slack-sansio documentation

40
slack-sansio Documentation Pyslackers Jul 25, 2019

Upload: others

Post on 25-Oct-2021

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: slack-sansio Documentation

slack-sansio Documentation

Pyslackers

Jul 25, 2019

Page 2: slack-sansio Documentation
Page 3: slack-sansio Documentation

Contents

1 I/O Implementations 3

2 Installation 5

3 Examples 7

4 Methods 9

5 Navigation 11

Python Module Index 33

Index 35

i

Page 4: slack-sansio Documentation

ii

Page 5: slack-sansio Documentation

slack-sansio Documentation

This project aims to provide a simple library that abstract the slack API details.

Many slack libraries already exist for Python but none oriented towards asynchronous usage. While working on Sirbot-a-lot we figured the slack client could be useful for the community and decided to take it out and create this library.We also choose to take a sans-I/O approach to allow reusability for other asynchronous frameworks.

Contents 1

Page 6: slack-sansio Documentation

slack-sansio Documentation

2 Contents

Page 7: slack-sansio Documentation

CHAPTER 1

I/O Implementations

Most people would want to use one of these implementations directly. For those that have an HTTP library which isnot supported this library provide the base tools to ease the use of the Slack API.

• Synchronous with request.

• Asyncio with aiohttp.

1.1 In development

• Curio with asks.

• Trio with asks.

3

Page 8: slack-sansio Documentation

slack-sansio Documentation

4 Chapter 1. I/O Implementations

Page 9: slack-sansio Documentation

CHAPTER 2

Installation

slack-sansio is on PyPI

$ pip3 install slack-sansio # No extra requirements

Due to it’s sans-I/O approach extra requirements are needed for each implementations. You can install them with:

$ pip3 install slack-sansio[requests] # requests implementation extra requirements$ pip3 install slack-sansio[aiohttp] # aiohttp implementation extra requirements$ pip3 install slack-sansio[curio] # curio implementation extra requirements$ pip3 install slack-sansio[trio] # trio implementation extra requirements$ pip3 install slack-sansio[treq] # treq implementation extra requirements$ pip3 install slack-sansio[full] # all implementations extra requirements

5

Page 10: slack-sansio Documentation

slack-sansio Documentation

6 Chapter 2. Installation

Page 11: slack-sansio Documentation

CHAPTER 3

Examples

Examples are dependant of the implementations and can be found on the documentation of each implementation.

• Requests examples

• Aiohttp examples

• Curio examples

• Trio examples

7

Page 12: slack-sansio Documentation

slack-sansio Documentation

8 Chapter 3. Examples

Page 13: slack-sansio Documentation

CHAPTER 4

Methods

For ease of use the library provide an enum.Enum of all the slack API methods.

slack.methodsalias of slack.methods.Methods

class slack.methods.MethodsEnumeration of available slack methods.

Provides iterkey and itermod for SlackAPI.iter().

9

Page 14: slack-sansio Documentation

slack-sansio Documentation

10 Chapter 4. Methods

Page 15: slack-sansio Documentation

CHAPTER 5

Navigation

5.1 slack.events - Events

class slack.events.Event(raw_event: collections.abc.MutableMapping, metadata: Op-tional[collections.abc.MutableMapping] = None)

MutableMapping representing a slack event coming from the RTM API or the Event API.

metadataMetadata dispatched with the event when using the Event API (see slack event API documentation)

clone()→ slack.events.EventClone the event

Returns slack.events.Event

classmethod from_http(raw_body: collections.abc.MutableMapping, verification_token:Optional[str] = None, team_id: Optional[str] = None) →slack.events.Event

Create an event with data coming from the HTTP Event API.

If the event type is a message a slack.events.Message is returned.

Parameters

• raw_body – Decoded body of the Event API request

• verification_token – Slack verification token used to verify the request came fromslack

• team_id – Verify the event is for the correct team

Returns slack.events.Event or slack.events.Message

Raises slack.exceptions.FailedVerification – when verification_token orteam_id does not match the incoming event’s.

classmethod from_rtm(raw_event: collections.abc.MutableMapping)→ slack.events.EventCreate an event with data coming from the RTM API.

11

Page 16: slack-sansio Documentation

slack-sansio Documentation

If the event type is a message a slack.events.Message is returned.

Parameters raw_event – JSON decoded data from the RTM API

Returns slack.events.Event or slack.events.Message

class slack.events.EventRouterWhen receiving an event from the RTM API or the slack API it is useful to have a routing mechanisms for dis-patching event to individual function/coroutine. This class provide such mechanisms for any slack.events.Event.

dispatch(event: slack.events.Event)→ Iterator[Any]Yields handlers matching the routing of the incoming slack.events.Event.

Parameters event – slack.events.Event

Yields handler

register(event_type: str, handler: Any, **detail)→ NoneRegister a new handler for a specific slack.events.Event type (See slack event types documentationfor a list of event types).

The arbitrary keyword argument is used as a key/value pair to compare against what is in the incomingslack.events.Event

Parameters

• event_type – Event type the handler is interested in

• handler – Callback

• **detail – Additional key for routing

class slack.events.Message(msg: Optional[collections.abc.MutableMapping] = None, metadata:Optional[collections.abc.MutableMapping] = None)

Type of slack.events.Event corresponding to a message event type

response(in_thread: Optional[bool] = None)→ slack.events.MessageCreate a response message.

Depending on the incoming message the response can be in a thread. By default the response follow wherethe incoming message was posted.

Parameters in_thread (boolean) – Overwrite the threading behaviour

Returns a new slack.event.Message

serialize()→ dictSerialize the message for sending to slack API

Returns serialized message

class slack.events.MessageRouterWhen receiving an event of type message from the RTM API or the slack API it is useful to have a routingmechanisms for dispatching the message to individual function/coroutine. This class provide such mechanismsfor any slack.events.Message.

The routing is based on regex pattern matching of the message text and the receiving channel.

dispatch(message: slack.events.Message)→ Iterator[Any]Yields handlers matching the routing of the incoming slack.events.Message

Parameters message – slack.events.Message

Yields handler

12 Chapter 5. Navigation

Page 17: slack-sansio Documentation

slack-sansio Documentation

register(pattern: str, handler: Any, flags: int = 0, channel: str = ’*’, subtype: Optional[str] = None)→ None

Register a new handler for a specific slack.events.Message.

The routing is based on regex pattern matching the message text and the incoming slack channel.

Parameters

• pattern – Regex pattern matching the message text.

• handler – Callback

• flags – Regex flags.

• channel – Slack channel ID. Use * for any.

• subtype – Message subtype

5.2 slack.commands - Commands

class slack.commands.Command(raw_command: MutableMapping[KT, VT], verification_token: Op-tional[str] = None, team_id: Optional[str] = None)

MutableMapping representing a slack slash command.

Parameters raw_command – Decoded body of the webhook HTTP request

Raises slack.exceptions.FailedVerification – when verification_token or team_iddoes not match the incoming command’s

class slack.commands.RouterWhen creating slash command for your applications each one can have a custom webhook url. For ease ofconfiguration this class provide a routing mechanisms based on the command so that each command can definethe same webhook url.

dispatch(command: slack.commands.Command)→ Iterator[Any]Yields handlers matching the incoming slack.actions.Command.

Parameters command – slack.actions.Command

Yields handler

register(command: str, handler: Any)Register a new handler for a specific slash command

Parameters

• command – Slash command

• handler – Callback

5.3 slack.actions - Actions

class slack.actions.Action(raw_action: MutableMapping[KT, VT], verification_token: Op-tional[str] = None, team_id: Optional[str] = None)

MutableMapping representing a response to an interactive message, a dialog submission or a message action.

Parameters

• raw_action – Decoded body of the HTTP request

5.2. slack.commands - Commands 13

Page 18: slack-sansio Documentation

slack-sansio Documentation

• verification_token – Slack verification token used to verify the request came fromslack

• team_id – Verify the event is for the correct team

Raises slack.exceptions.FailedVerification – when verification_token or team_iddoes not match the incoming event’s

class slack.actions.RouterWhen creating a slack applications you can only set one action url. This provide a routing mechanism for theincoming actions, based on their callback_id and the action name, to one or more handlers.

dispatch(action: slack.actions.Action)→ AnyYields handlers matching the incoming slack.actions.Action callback_id or action_id.

Parameters action – slack.actions.Action

Yields handler

register(callback_id: str, handler: Any, name: str = ’*’)→ NoneRegister a new handler for a specific slack.actions.Action callback_id. Optional routing basedon the action name too.

The name argument is useful for actions of type interactive_message to provide a different handler foreach individual action.

Parameters

• callback_id – Callback_id the handler is interested in

• handler – Callback

• name – Name of the action (optional).

register_block_action(block_id: str, handler: Any, action_id: str = ’*’)→ NoneRegister a new handler for a block-based slack.actions.Action. Internally uses the base registermethod for actual registration.

Optionally provides routing based on a specific action_id if present.

Parameters

• block_id – The action block_id the handler is interested in

• handler – Callback

• action_id – specific action_id for the action (optional)

register_dialog_submission(callback_id: str, handler: Any)Registers a new handler for a dialog_submission slack.actions.Action.

Internally calls the base register method for actual registration.

Parameters

• callback_id – Callback_id the handler is interested in

• handler – Callback

register_interactive_message(callback_id: str, handler: Any, name: str = ’*’)→ NoneRegister a new handler for a specific slack.actions.Action callback_id. Optional routing basedon the action name too.

The name argument is useful for actions of type interactive_message to provide a different handler foreach individual action.

Internally calls the base register method for actual registration.

14 Chapter 5. Navigation

Page 19: slack-sansio Documentation

slack-sansio Documentation

Parameters

• callback_id – Callback_id the handler is interested in

• handler – Callback

• name – Name of the action (optional).

exception slack.actions.UnknownActionType(action: slack.actions.Action)Raised for incoming action with unknown type

actionThe incoming action

5.4 slack.io.abc - Abstract Base Class

class slack.io.abc.SlackAPI(*, token: str, headers: Optional[MutableMapping[KT, VT]] = None)abstract base class abstracting the HTTP library used to call Slack API. Built with the functions of slack.sansio.

Parameters

• session – HTTP session

• token – Slack API token

• headers – Default headers for all request

async-for iter(url: Union[str, slack.methods.Methods], data: Optional[MutableMapping[KT,VT]] = None, headers: Optional[MutableMapping[KT, VT]] = None, *, limit:int = 200, iterkey: Optional[str] = None, itermode: Optional[str] = None, mini-mum_time: Optional[int] = None, as_json: Optional[bool] = None)→ AsyncIter-ator[dict]

Iterate over a slack API method supporting pagination

When using slack.methods the request is made as_json if available

Parameters

• url – slack.methods or url string

• data – JSON encodable MutableMapping

• headers –

• limit – Maximum number of results to return per call.

• iterkey – Key in response data to iterate over (required for url string).

• itermode – Iteration mode (required for url string) (one of cursor, page or timeline)

• minimum_time – Minimum elapsed time (in seconds) between two calls to the SlackAPI (default to 0). If not reached the client will sleep for the remaining time.

• as_json – Post JSON to the slack API

Returns Async iterator over response_data[key]

async-for rtm(url: Optional[str] = None, bot_id: Optional[str] = None) → AsyncItera-tor[slack.events.Event]

Iterate over event from the RTM API

Parameters

• url – Websocket connection url

5.4. slack.io.abc - Abstract Base Class 15

Page 20: slack-sansio Documentation

slack-sansio Documentation

• bot_id – Connecting bot ID

Returns slack.events.Event or slack.events.Message

coroutine query(url: Union[str, slack.methods.Methods], data: Optional[MutableMapping[KT,VT]] = None, headers: Optional[MutableMapping[KT, VT]] = None, as_json:Optional[bool] = None)→ dict

Query the slack API

When using slack.methods the request is made as_json if available

Parameters

• url – slack.methods or url string

• data – JSON encodable MutableMapping

• headers – Custom headers

• as_json – Post JSON to the slack API

Returns dictionary of slack API response data

5.5 slack.io.requests - Requests implementation

5.5.1 Examples

Query

import osimport sysimport pprintimport logging

import requestsimport slackfrom slack.io.requests import SlackAPI

logging.basicConfig(level=logging.INFO)LOG = logging.getLogger(__name__)

def query(client):data = client.query(slack.methods.AUTH_TEST)pprint.pprint(data)

if __name__ == "__main__":

if len(sys.argv) > 1:TOKEN = sys.argv[1]

else:TOKEN = os.environ.get("SLACK_TOKEN")

if not TOKEN:raise ValueError("No slack token provided !")

session = requests.session()

(continues on next page)

16 Chapter 5. Navigation

Page 21: slack-sansio Documentation

slack-sansio Documentation

(continued from previous page)

slack_client = SlackAPI(token=TOKEN, session=session)query(slack_client)

Iterate

import osimport sysimport pprintimport logging

import requestsimport slackfrom slack.io.requests import SlackAPI

logging.basicConfig(level=logging.INFO)LOG = logging.getLogger(__name__)

def iterate(client):

for channel in client.iter(slack.methods.CHANNELS_LIST, limit=2):pprint.pprint(channel)

if __name__ == "__main__":

if len(sys.argv) > 1:TOKEN = sys.argv[1]

else:TOKEN = os.environ.get("SLACK_TOKEN")

if not TOKEN:raise ValueError("No slack token provided !")

session = requests.session()slack_client = SlackAPI(token=TOKEN, session=session)iterate(slack_client)

RTM

import osimport sysimport pprintimport logging

import requestsimport slackfrom slack.events import Messagefrom slack.io.requests import SlackAPI

logging.basicConfig(level=logging.INFO)LOG = logging.getLogger(__name__)

(continues on next page)

5.5. slack.io.requests - Requests implementation 17

Page 22: slack-sansio Documentation

slack-sansio Documentation

(continued from previous page)

def rtm(client):

for event in client.rtm():pprint.pprint(event)

if isinstance(event, Message):respond_to_message(event, client)

def respond_to_message(message, client):response = message.response()response["text"] = "Hello world !"client.query(slack.methods.CHAT_POST_MESSAGE, data=response.serialize())

if __name__ == "__main__":

if len(sys.argv) > 1:TOKEN = sys.argv[1]

else:TOKEN = os.environ.get("SLACK_TOKEN")

if not TOKEN:raise ValueError("No slack token provided !")

session = requests.session()slack_client = SlackAPI(token=TOKEN, session=session)rtm(slack_client)

5.6 slack.io.aiohttp - Aiohttp implementation

5.6.1 Examples

Query

import osimport sysimport pprintimport asyncioimport logging

import aiohttpimport slackfrom slack.io.aiohttp import SlackAPI

logging.basicConfig(level=logging.INFO)LOG = logging.getLogger(__name__)

async def query(client):

data = await client.query(slack.methods.AUTH_TEST)

(continues on next page)

18 Chapter 5. Navigation

Page 23: slack-sansio Documentation

slack-sansio Documentation

(continued from previous page)

pprint.pprint(data)

if __name__ == "__main__":

if len(sys.argv) > 1:TOKEN = sys.argv[1]

else:TOKEN = os.environ.get("SLACK_TOKEN")

if not TOKEN:raise ValueError("No slack token provided !")

loop = asyncio.get_event_loop()session = aiohttp.ClientSession(loop=loop)slack_client = SlackAPI(token=TOKEN, session=session)

try:loop.run_until_complete(query(slack_client))

except KeyboardInterrupt:pass

loop.run_until_complete(session.close())

Iterate

import osimport sysimport pprintimport asyncioimport logging

import aiohttpimport slackfrom slack.io.aiohttp import SlackAPI

logging.basicConfig(level=logging.INFO)LOG = logging.getLogger(__name__)

async def iterate(client):

async for channel in client.iter(slack.methods.CHANNELS_LIST, limit=4):pprint.pprint(channel)

if __name__ == "__main__":

if len(sys.argv) > 1:TOKEN = sys.argv[1]

else:TOKEN = os.environ.get("SLACK_TOKEN")

if not TOKEN:raise ValueError("No slack token provided !")

(continues on next page)

5.6. slack.io.aiohttp - Aiohttp implementation 19

Page 24: slack-sansio Documentation

slack-sansio Documentation

(continued from previous page)

loop = asyncio.get_event_loop()session = aiohttp.ClientSession(loop=loop)slack_client = SlackAPI(token=TOKEN, session=session)

try:loop.run_until_complete(iterate(slack_client))

except KeyboardInterrupt:pass

loop.run_until_complete(session.close())

RTM

import osimport sysimport pprintimport asyncioimport logging

import aiohttpimport slackfrom slack.events import Messagefrom slack.io.aiohttp import SlackAPI

logging.basicConfig(level=logging.INFO)LOG = logging.getLogger(__name__)

async def rtm(client):

async for event in client.rtm():pprint.pprint(event)

if isinstance(event, Message):asyncio.ensure_future(respond_to_message(event, client))

async def respond_to_message(message, client):response = message.response()response["text"] = "Hello world !"await client.query(slack.methods.CHAT_POST_MESSAGE, data=response.serialize())

if __name__ == "__main__":

if len(sys.argv) > 1:TOKEN = sys.argv[1]

else:TOKEN = os.environ.get("SLACK_TOKEN")

if not TOKEN:raise ValueError("No slack token provided !")

loop = asyncio.get_event_loop()(continues on next page)

20 Chapter 5. Navigation

Page 25: slack-sansio Documentation

slack-sansio Documentation

(continued from previous page)

session = aiohttp.ClientSession(loop=loop)slack_client = SlackAPI(token=TOKEN, session=session)

try:loop.run_until_complete(rtm(slack_client))

except KeyboardInterrupt:pass

loop.run_until_complete(session.close())

5.7 slack.io.curio - Curio implementation

5.7.1 Examples

Query

import osimport sysimport pprintimport logging

import asksimport curioimport slackfrom slack.io.curio import SlackAPI

logging.basicConfig(level=logging.INFO)LOG = logging.getLogger(__name__)

async def query(client):

data = await client.query(slack.methods.AUTH_TEST)pprint.pprint(data)

if __name__ == "__main__":

if len(sys.argv) > 1:TOKEN = sys.argv[1]

else:TOKEN = os.environ.get("SLACK_TOKEN")

if not TOKEN:raise ValueError("No slack token provided !")

session = asks.Session()slack_client = SlackAPI(token=TOKEN, session=session)curio.run(query(slack_client))

5.7. slack.io.curio - Curio implementation 21

Page 26: slack-sansio Documentation

slack-sansio Documentation

Iterate

import osimport sysimport pprintimport logging

import asksimport curioimport slackfrom slack.io.curio import SlackAPI

logging.basicConfig(level=logging.INFO)LOG = logging.getLogger(__name__)

async def iterate(client):

async for channel in client.iter(slack.methods.CHANNELS_LIST, limit=4):pprint.pprint(channel)

if __name__ == "__main__":

if len(sys.argv) > 1:TOKEN = sys.argv[1]

else:TOKEN = os.environ.get("SLACK_TOKEN")

if not TOKEN:raise ValueError("No slack token provided !")

session = asks.Session()slack_client = SlackAPI(token=TOKEN, session=session)curio.run(iterate(slack_client))

5.8 slack.io.trio - Trio implementation

5.8.1 Examples

Query

import osimport sysimport pprintimport logging

import asksimport trioimport slackfrom slack.io.curio import SlackAPI

logging.basicConfig(level=logging.INFO)LOG = logging.getLogger(__name__)

(continues on next page)

22 Chapter 5. Navigation

Page 27: slack-sansio Documentation

slack-sansio Documentation

(continued from previous page)

async def query(client):

data = await client.query(slack.methods.AUTH_TEST)pprint.pprint(data)

if __name__ == "__main__":

if len(sys.argv) > 1:TOKEN = sys.argv[1]

else:TOKEN = os.environ.get("SLACK_TOKEN")

if not TOKEN:raise ValueError("No slack token provided !")

session = asks.Session()slack_client = SlackAPI(token=TOKEN, session=session)trio.run(query, slack_client)

Iterate

import osimport sysimport pprintimport logging

import asksimport trioimport slackfrom slack.io.curio import SlackAPI

logging.basicConfig(level=logging.INFO)LOG = logging.getLogger(__name__)

async def iterate(client):

async for channel in client.iter(slack.methods.CHANNELS_LIST, limit=4):pprint.pprint(channel)

if __name__ == "__main__":

if len(sys.argv) > 1:TOKEN = sys.argv[1]

else:TOKEN = os.environ.get("SLACK_TOKEN")

if not TOKEN:raise ValueError("No slack token provided !")

session = asks.Session()(continues on next page)

5.8. slack.io.trio - Trio implementation 23

Page 28: slack-sansio Documentation

slack-sansio Documentation

(continued from previous page)

slack_client = SlackAPI(token=TOKEN, session=session)trio.run(iterate, slack_client)

5.9 slack.sansio - Sans-I/O helpers

Collection of functions for sending and decoding request to or from the slack API

slack.sansio.ITERMODE = ('cursor', 'page', 'timeline')Supported pagination mode

slack.sansio.RECONNECT_EVENTS = ('team_migration_started', 'goodbye')Events type preceding a disconnection

slack.sansio.SKIP_EVENTS = ('reconnect_url',)Events that do not need to be dispatched

slack.sansio.decode_body(headers: MutableMapping[KT, VT], body: bytes)→ dictDecode the response body

For ‘application/json’ content-type load the body as a dictionary

Parameters

• headers – Response headers

• body – Response body

Returns decoded body

slack.sansio.decode_iter_request(data: dict)→ Union[str, int, None]Decode incoming response from an iteration request

Parameters data – Response data

Returns Next itervalue

slack.sansio.decode_response(status: int, headers: MutableMapping[KT, VT], body: bytes) →dict

Decode incoming response

Parameters

• status – Response status

• headers – Response headers

• body – Response body

Returns Response data

slack.sansio.discard_event(event: slack.events.Event, bot_id: str = None)→ boolCheck if the incoming event needs to be discarded

Parameters

• event – Incoming slack.events.Event

• bot_id – Id of connected bot

Returns boolean

24 Chapter 5. Navigation

Page 29: slack-sansio Documentation

slack-sansio Documentation

slack.sansio.find_iteration(url: Union[slack.methods.Methods, str], itermode: Optional[str] =None, iterkey: Optional[str] = None)→ Tuple[str, str]

Find iteration mode and iteration key for a given slack.methods

Parameters

• url – slack.methods or string url

• itermode – Custom iteration mode

• iterkey – Custom iteration key

Returns tuple (itermode, iterkey)

slack.sansio.need_reconnect(event: slack.events.Event)→ boolCheck if RTM needs reconnecting

Parameters event – Incoming slack.events.Event

Returns boolean

slack.sansio.parse_content_type(headers: MutableMapping[KT, VT]) → Tuple[Optional[str],str]

Find content-type and encoding of the response

Parameters headers – Response headers

Returns tuple (content-type, encoding)

slack.sansio.prepare_iter_request(url: Union[slack.methods.Methods, str], data: Muta-bleMapping[KT, VT], *, iterkey: Optional[str] = None,itermode: Optional[str] = None, limit: int = 200,itervalue: Union[str, int, None] = None) → Tu-ple[MutableMapping[KT, VT], str, str]

Prepare outgoing iteration request

Parameters

• url – slack.methods item or string of url

• data – Outgoing data

• limit – Maximum number of results to return per call.

• iterkey – Key in response data to iterate over (required for url string).

• itermode – Iteration mode (required for url string) (one of cursor, page or timeline)

• itervalue – Value for current iteration (cursor hash, page or timestamp depending onthe itermode)

Returns tuple (data, iterkey, itermode)

slack.sansio.prepare_request(url: Union[str, slack.methods.Methods], data: Op-tional[MutableMapping[KT, VT]], headers: Op-tional[MutableMapping[KT, VT]], global_headers: MutableMap-ping[KT, VT], token: str, as_json: Optional[bool] = None) →Tuple[str, Union[str, MutableMapping[KT, VT]], MutableMap-ping[KT, VT]]

Prepare outgoing request

Create url, headers, add token to the body and if needed json encode it

Parameters

• url – slack.methods item or string of url

5.9. slack.sansio - Sans-I/O helpers 25

Page 30: slack-sansio Documentation

slack-sansio Documentation

• data – Outgoing data

• headers – Custom headers

• global_headers – Global headers

• token – Slack API token

• as_json – Post JSON to the slack API

Returns tuple (url, body, headers)

slack.sansio.raise_for_api_error(headers: MutableMapping[KT, VT], data: MutableMap-ping[KT, VT])→ None

Check request response for Slack API error

Parameters

• headers – Response headers

• data – Response data

Raises slack.exceptions.SlackAPIError

slack.sansio.raise_for_status(status: int, headers: MutableMapping[KT, VT], data: Muta-bleMapping[KT, VT])→ None

Check request response status

Parameters

• status – Response status

• headers – Response headers

• data – Response data

Raises

• slack.exceptions.RateLimited – For 429 status code

• slack.exceptions:HTTPException

slack.sansio.validate_request_signature(body: str, headers: MutableMapping[KT, VT],signing_secret: str)→ None

Validate incoming request signature using the application signing secret.

Contrary to the team_id and verification_token verification this method is not called byslack-sansio when creating object from incoming HTTP request. Because the body of the request needs tobe provided as text and not decoded as json beforehand.

Parameters

• body – Raw request body

• headers – Request headers

• signing_secret – Application signing_secret

Raise: slack.exceptions.InvalidSlackSignature: when provided and calculated signature donot match slack.exceptions.InvalidTimestamp: when incoming request timestamp is morethan 5 minutes old

26 Chapter 5. Navigation

Page 31: slack-sansio Documentation

slack-sansio Documentation

5.10 slack.exceptions - Exceptions

exception slack.exceptions.FailedVerification(token: str, team_id: str)Bases: slack.exceptions.InvalidRequest

Raised when incoming data from Slack webhooks fail verification

tokenToken that failed verification

team_idTeam id that failed verification

exception slack.exceptions.HTTPException(status: int, headers: MutableMapping[KT, VT],data: MutableMapping[KT, VT])

Bases: Exception

Raised on non 200 status code

headersResponse headers

dataResponse data

statusResponse status

exception slack.exceptions.InvalidRequestBases: Exception

Base class for all exception raised due to an invalid verification

exception slack.exceptions.InvalidSlackSignature(slack_signature: str, calcu-lated_signature: str)

Bases: slack.exceptions.InvalidRequest

Raised when the incoming request fails signature check

slack_signatureSignature sent by slack

calculated_singatureCalculated signature

exception slack.exceptions.InvalidTimestamp(timestamp: float)Bases: slack.exceptions.InvalidRequest

Raised when the incoming request is too old

timestampTimestamp of the incoming request

exception slack.exceptions.RateLimited(retry_after: int, error: str, status: int, headers: Mu-tableMapping[KT, VT], data: MutableMapping[KT,VT])

Bases: slack.exceptions.HTTPException, slack.exceptions.SlackAPIError

Raised when rate limited.

retry_afterTimestamp when the rate limitation ends

5.10. slack.exceptions - Exceptions 27

Page 32: slack-sansio Documentation

slack-sansio Documentation

exception slack.exceptions.SlackAPIError(error: str, headers: MutableMapping[KT, VT],data: MutableMapping[KT, VT])

Bases: Exception

Raised for errors return by the Slack API

headersResponse headers

dataResponse data

errorSlack API error

5.11 slack.tests.plugin - Pytest fixtures

Slack-sansio provide a pytest plugin with some fixtures to facilitate testing of the slack API.

5.11.1 Installation

To load the plugin add the snippet below to your conftest.py.

pytest_plugins = "slack.tests.plugin",

5.11.2 Available fixtures

slack.tests.plugin.slack_event()Fixture returning data sent by the slack event API.

This fixture can be parametrized to return one or more available event from slack.tests.data.Eventsand slack.tests.data.Messages.

@pytest.mark.parametrize("slack_event", ("channel_deleted", "simple"),→˓indirect=True)def test_events(slack_event):

assert slack_event["event"]["type"] in ("channel_deleted", "message")

To only get slack.tests.data.Messages members you can parametrize the test that way:

@pytest.mark.parametrize("slack_event", {**slack.tests.data.Messages.__members__}, indirect=True

)def test_messages(slack_event):

assert slack_event["event"]["type"] == "message"

slack.tests.plugin.slack_action()Fixture returning data sent by the slack API when using an interactive message or dialog.

This fixture can be parametrized to return one or more available action from slack.tests.data.InteractiveMessage or slack.tests.data.DialogSubmission.

28 Chapter 5. Navigation

Page 33: slack-sansio Documentation

slack-sansio Documentation

@pytest.mark.parametrize("slack_action", ("button_ok", "button_cancel"),→˓indirect=True)def test_actions(slack_action):

action = slack.actions.Action.from_http(slack_action)assert action["type"] == "interactive_message"

slack.tests.plugin.slack_command()Fixture returning data sent by the slack API when using a slash command.

This fixture can be parametrized to return one or more available command from slack.tests.data.Commands.

@pytest.mark.parametrize("slack_command", ("text", "no_text"), indirect=True)def test_commands(slack_command):

command = slack.commands.Command(slack_command)assert command["command"] == "/test"

slack.tests.plugin.slack_client()Fixture returning a fake slack client.

By default the client return to any request:

• status: 200

• body: {'ok': True}

• headers: {'content-type': 'application/json; charset=utf-8'}

Parametrize a reponse:

@[email protected](

"slack_client", ({"body": {"ok": True, "hello": "world"}},), indirect=True)async def test_client_custom_body(slack_client):

data = await slack_client.query(slack.methods.AUTH_TEST)assert data == {"ok": True, "hello": "world"}

The body parameter of a request can be a string corresponding to one of the methods available in slack.tests.data.Methods.

@[email protected]("slack_client", ({"body": "auth_test"},), indirect=True)async def test_client_body(slack_client):

data = await slack_client.query(slack.methods.AUTH_TEST)assert data["team"] == "TestTeam Workspace"

Parametrize multiple responses:

@[email protected]("slack_client", ({"status": [200, 500]},), indirect=True)

(continues on next page)

5.11. slack.tests.plugin - Pytest fixtures 29

Page 34: slack-sansio Documentation

slack-sansio Documentation

(continued from previous page)

async def test_client_status(slack_client):

await slack_client.query(slack.methods.AUTH_TEST)

with pytest.raises(slack.exceptions.HTTPException):await slack_client.query(slack.methods.AUTH_TEST)

@[email protected](

"slack_client", ({"body": ["channels_iter", "channels"]},), indirect=True)async def test_client_iter(slack_client):

async for channel in slack_client.iter(slack.methods.CHANNELS_LIST):print(channel)

Parametrize multiple run:

@[email protected](

"slack_client,ok",(({"status": 200}, True), ({"status": 500}, False)),indirect=["slack_client"],

)async def test_client_multiple_run(slack_client, ok):

if ok:await slack_client.query(slack.methods.AUTH_TEST)

else:with pytest.raises(slack.exceptions.HTTPException):

await slack_client.query(slack.methods.AUTH_TEST)

5.11.3 Available data

class slack.tests.data.EventsList of available event for testing

• channel_deleted

• pin_added

• reaction_added

class slack.tests.data.MessagesList of available message for testing

• simple

• snippet

• shared

• threaded

30 Chapter 5. Navigation

Page 35: slack-sansio Documentation

slack-sansio Documentation

• bot

• bot_edit

• attachment

• edit

• edit_threaded

• mention

• none_text

• channel_topic

class slack.tests.data.CommandsList of available command for testing

• text

• no_text

class slack.tests.data.InteractiveMessageList of available interactive message action for testing

• button_ok

• button_cancel

class slack.tests.data.DialogSubmissionList of available dialog submission action for testing

• dialog_submission

class slack.tests.data.MethodsList of available methods for testing

• channels

• channels_iter (channels with a cursor)

• users

• users_iter (users with a cursor)

• users_info

• auth_test

• rtm_connect

5.11. slack.tests.plugin - Pytest fixtures 31

Page 36: slack-sansio Documentation

slack-sansio Documentation

32 Chapter 5. Navigation

Page 37: slack-sansio Documentation

Python Module Index

sslack.actions, 13slack.commands, 13slack.events, 11slack.exceptions, 27slack.io.abc, 15slack.io.aiohttp, 18slack.io.curio, 21slack.io.requests, 16slack.io.trio, 22slack.methods, 9slack.sansio, 24

33

Page 38: slack-sansio Documentation

slack-sansio Documentation

34 Python Module Index

Page 39: slack-sansio Documentation

Index

AAction (class in slack.actions), 13action (slack.actions.UnknownActionType attribute),

15

Ccalculated_singature

(slack.exceptions.InvalidSlackSignature at-tribute), 27

clone() (slack.events.Event method), 11Command (class in slack.commands), 13Commands (class in slack.tests.data), 31

Ddata (slack.exceptions.HTTPException attribute), 27data (slack.exceptions.SlackAPIError attribute), 28decode_body() (in module slack.sansio), 24decode_iter_request() (in module slack.sansio),

24decode_response() (in module slack.sansio), 24DialogSubmission (class in slack.tests.data), 31discard_event() (in module slack.sansio), 24dispatch() (slack.actions.Router method), 14dispatch() (slack.commands.Router method), 13dispatch() (slack.events.EventRouter method), 12dispatch() (slack.events.MessageRouter method), 12

Eerror (slack.exceptions.SlackAPIError attribute), 28Event (class in slack.events), 11EventRouter (class in slack.events), 12Events (class in slack.tests.data), 30

FFailedVerification, 27find_iteration() (in module slack.sansio), 24from_http() (slack.events.Event class method), 11from_rtm() (slack.events.Event class method), 11

Hheaders (slack.exceptions.HTTPException attribute),

27headers (slack.exceptions.SlackAPIError attribute), 28HTTPException, 27

IInteractiveMessage (class in slack.tests.data), 31InvalidRequest, 27InvalidSlackSignature, 27InvalidTimestamp, 27iter() (slack.io.abc.SlackAPI method), 15ITERMODE (in module slack.sansio), 24

MMessage (class in slack.events), 12MessageRouter (class in slack.events), 12Messages (class in slack.tests.data), 30metadata (slack.events.Event attribute), 11Methods (class in slack.methods), 9Methods (class in slack.tests.data), 31

Nneed_reconnect() (in module slack.sansio), 25

Pparse_content_type() (in module slack.sansio),

25prepare_iter_request() (in module

slack.sansio), 25prepare_request() (in module slack.sansio), 25

Qquery() (slack.io.abc.SlackAPI method), 16

Rraise_for_api_error() (in module slack.sansio),

26raise_for_status() (in module slack.sansio), 26

35

Page 40: slack-sansio Documentation

slack-sansio Documentation

RateLimited, 27RECONNECT_EVENTS (in module slack.sansio), 24register() (slack.actions.Router method), 14register() (slack.commands.Router method), 13register() (slack.events.EventRouter method), 12register() (slack.events.MessageRouter method), 12register_block_action() (slack.actions.Router

method), 14register_dialog_submission()

(slack.actions.Router method), 14register_interactive_message()

(slack.actions.Router method), 14response() (slack.events.Message method), 12retry_after (slack.exceptions.RateLimited attribute),

27Router (class in slack.actions), 14Router (class in slack.commands), 13rtm() (slack.io.abc.SlackAPI method), 15

Sserialize() (slack.events.Message method), 12SKIP_EVENTS (in module slack.sansio), 24slack.actions (module), 13slack.commands (module), 13slack.events (module), 11slack.exceptions (module), 27slack.io.abc (module), 15slack.io.aiohttp (module), 18slack.io.curio (module), 21slack.io.requests (module), 16slack.io.trio (module), 22slack.methods (module), 9slack.sansio (module), 24slack.tests.plugin.slack_action() (built-

in function), 28slack.tests.plugin.slack_client() (built-

in function), 29slack.tests.plugin.slack_command()

(built-in function), 29slack.tests.plugin.slack_event() (built-in

function), 28slack_signature (slack.exceptions.InvalidSlackSignature

attribute), 27SlackAPI (class in slack.io.abc), 15SlackAPIError, 27status (slack.exceptions.HTTPException attribute), 27

Tteam_id (slack.exceptions.FailedVerification attribute),

27timestamp (slack.exceptions.InvalidTimestamp at-

tribute), 27token (slack.exceptions.FailedVerification attribute), 27

UUnknownActionType, 15

Vvalidate_request_signature() (in module

slack.sansio), 26

36 Index