aslack package

Submodules

aslack.core module

Core API wrapper functionality, adapted from Flash Services.

class aslack.core.Service(*_, **kwargs)[source]

Bases: object

Abstract base class for API wrapper services.

REQUIRED = set()

set – The service’s required configuration keys.

ROOT = ''

str – The root URL for the API.

headers

Get the headers for the service requests.

Returns:The header mapping.
Return type:dict
url_builder(endpoint, *, root=None, params=None, url_params=None)[source]

Create a URL for the specified endpoint.

Parameters:
  • endpoint (str) – The API endpoint to access.
  • root – (str, optional): The root URL for the service API.
  • params – (dict, optional): The values for format into the created URL (defaults to None).
  • url_params – (dict, optional): Parameters to add to the end of the URL (defaults to None).
Returns:

The resulting URL.

Return type:

str

class aslack.core.TokenAuthMixin(*, api_token, **kwargs)[source]

Bases: object

Mix-in class for implementing token authentication.

Parameters:api_token (str) – A valid API token.
TOKEN_ENV_VAR = None

str – The environment variable holding the token.

classmethod from_env()[source]

Create a service instance from an environment variable.

class aslack.core.UrlParamMixin(*, api_token, **kwargs)[source]

Bases: aslack.core.TokenAuthMixin

Mix-in class for implementing URL parameter authentication.

AUTH_PARAM = None

str – The name of the URL parameter.

url_builder(endpoint, params=None, url_params=None)[source]

Add authentication URL parameter.

aslack.slack_api module

Access to the base Slack Web API.

aslack.slack_api.ALL

object – Marker for cases where all child methods should be deleted by api_subclass_factory().

class aslack.slack_api.SlackApi(*, api_token, **kwargs)[source]

Bases: aslack.core.UrlParamMixin, aslack.core.Service

Class to handle interaction with Slack’s API.

API_METHODS

dict – The API methods defined by Slack.

execute_method(method, **params)[source]

Execute a specified Slack Web API method.

Parameters:
  • method (str) – The name of the method.
  • **params (dict) – Any additional parameters required.
Returns:

The JSON data from the response.

Return type:

dict

Raises:
  • aiohttp.web_exceptions.HTTPException – If the HTTP request returns a code other than 200 (OK).
  • SlackApiError – If the Slack API is reached but the response contains an error message.
classmethod method_exists(method)[source]

Whether a given method exists in the known API.

Parameters:method (str) – The name of the method.
Returns:Whether the method is in the known API.
Return type:bool
exception aslack.slack_api.SlackApiError(err_msg, *args)[source]

Bases: aslack.utils.FriendlyError

Wrapper exception for error messages in the response JSON.

EXPECTED_ERRORS = {'migration_in_progress': 'Team is being migrated between servers.', 'account_inactive': 'Authentication token is for a deleted user or team.', 'invalid_auth': 'Invalid authentication token.', 'not_authed': 'No authentication token provided.'}

Friendly messages for expected Slack API errors.

aslack.slack_api.api_subclass_factory(name, docstring, remove_methods, base=<class 'aslack.slack_api.SlackApi'>)[source]

Create an API subclass with fewer methods than its base class.

Parameters:
  • name (str) – The name of the new class.
  • docstring (str) – The docstring for the new class.
  • remove_methods (dict) – The methods to remove from the base class’s API_METHODS for the subclass. The key is the name of the root method (e.g. 'auth' for 'auth.test', the value is either a tuple of child method names (e.g. ('test',)) or, if all children should be removed, the special value ALL.
  • base (type, optional) – The base class (defaults to SlackApi).
Returns:

The new subclass.

Return type:

type

Raises:

KeyError – If the method wasn’t in the superclass.

aslack.slack_bot module

A Slack bot using the real-time messaging API.

class aslack.slack_bot.bot.SlackBot(id_, user, api)[source]

Bases: object

Base class Slack bot.

Parameters:
  • id (str) – The bot’s Slack ID.
  • user (str) – The bot’s friendly name.
  • api (SlackApi) – The Slack API wrapper.
address_as

str – The text that appears at the start of messages addressed to this bot (e.g. '<@user>: ').

full_name

str – The name of the bot as it appears in messages about the bot (e.g. '<@user>').

socket

aiohttp.web.WebSocketResponse – The web socket to respond on.

API_AUTH_ENDPOINT

str – Test endpoint for API authorisation.

INSTRUCTIONS

str – Message to give the user when they request instructions.

MESSAGE_FILTERS

list – Default filters for incoming messages

RTM_HANDSHAKE

dict – Expected handshake message from RTM API.

RTM_START_ENDPOINT

str – Start endpoint for real-time messaging.

VERSION

str – Version string to show to the user (if not overridden, will show the aSlack version).

classmethod from_api_token(token=None, api_cls=<class 'abc.SlackBotApi'>)[source]

Create a new instance from the API token.

Parameters:
  • token (str, optional) – The bot’s API token (defaults to None, which means looking in the environment).
  • api_cls (type, optional) – The class to create as the api argument for API access (defaults to aslack.slack_api.SlackBotApi).
Returns:

The new instance.

Return type:

SlackBot

handle_message(message, filters)[source]

Handle an incoming message appropriately.

Parameters:
  • message (aiohttp.websocket.Message) – The incoming message to handle.
  • filters (list) – The filters to apply to incoming messages.
join_rtm(filters=None)[source]

Join the real-time messaging service.

Parameters:filters (dict, optional) – Dictionary mapping message filters to the functions they should dispatch to. Use a collections.OrderedDict if precedence is important; only one filter, the first match, will be applied to each message.
message_is_to_me(data)[source]

If you send a message directly to me

message_mentions_me(data)[source]

If you send a message that mentions me

Generic message handling functionality.

class aslack.slack_bot.handler.BotMessageHandler(bot)[source]

Bases: aslack.slack_bot.handler.MessageHandler

Base class for handlers of messages about the current bot.

Parameters:bot (SlackBot) – The current bot.
PHRASE

str – The phrase to match.

class aslack.slack_bot.handler.MessageHandler(*_)[source]

Bases: object

Base class for message handlers.

Parameters:*_ (tuple) – Arbitrary positional arguments.
description()[source]

A user-friendly description of the handler.

Returns:The handler’s description.
Return type:str
matches(data)[source]

Whether the handler should handle the current message.

Parameters:data – The data representing the current message.
Returns:Whether it should be handled.
Return type:bool

aslack.utils module

Utility functionality.

exception aslack.utils.FriendlyError(err_msg, *args)[source]

Bases: Exception

Exception with friendlier error messages.

Notes

The err_msg is resolved in EXPECTED_ERRORS, or passed through as-is if not found there.

Parameters:
  • err_msg (str) – The error message to attempt to resolve.
  • *args (tuple) – Any additional positional arguments.
EXPECTED_ERRORS = {}

Friendly messages for expected errors.

aslack.utils.raise_for_status(response)[source]

Raise an appropriate error for a given response.

Parameters:response (aiohttp.ClientResponse) – The API response.
Raises:aiohttp.web_exceptions.HTTPException – The appropriate error for the response’s status.
aslack.utils.truncate(text, max_len=350, end='...')[source]

Truncate the supplied text for display.

Parameters:
  • text (str) – The text to truncate.
  • max_len (int, optional) – The maximum length of the text before truncation (defaults to 350 characters).
  • end (str, optional) – The ending to use to show that the text was truncated (defaults to '...').
Returns:

The truncated text.

Return type:

str

Examples

halliwell

Example aSlack bot to give you information on movies.

class examples.halliwell.ActorOverlapQueryHandler(bot)[source]

Bases: aslack.slack_bot.handler.BotMessageHandler

Handles queries about movies with the same group of actors.

If you send me a message asking ‘actors in’ with a quoted list of movies I will find movies featuring all of those actors.

class examples.halliwell.Halliwell(id_, user, api, tmdb_client=None)[source]

Bases: aslack.slack_bot.bot.SlackBot

The filmgoer’s companion.

Parameters:
class examples.halliwell.MovieOverlapQueryHandler(bot)[source]

Bases: aslack.slack_bot.handler.BotMessageHandler

Handles queries about actors in the same group of movies.

If you send me a message asking ‘movies with’ with a quoted list of actors I will find movies featuring all of those actors.

class examples.halliwell.MovieQueryHandler(bot)[source]

Bases: aslack.slack_bot.handler.BotMessageHandler

Handles queries about specific movies.

If you send me a message starting with the word ‘movie’ I will tell you about that movie.

class examples.halliwell.PersonQueryHandler(bot)[source]

Bases: aslack.slack_bot.handler.BotMessageHandler

Handles queries about specific people.

If you send me a message starting with the word ‘person’ I will tell you about that person.

examples.halliwell.QUOTED = re.compile('"([^"]+)"')

Regular expression to extract quoted text.