slacktivate.slack package

Submodules

slacktivate.slack.classes module

This submodule provides a commong abstraction layer over the heterogeneous object types provided by the Slack API client and the Slack SCIM client modules.

class slacktivate.slack.classes.SlackGroup(group_id=None, display_name=None, group=None, resource=None)

Bases: object

property created
property display_name
property exists
classmethod from_any(value)
Parameters

value (Optional[Union[str, slack_scim.v1.group.Group, slack_scim.v1.users.Group]]) –

Return type

Optional[slacktivate.slack.classes.SlackGroup]

classmethod from_display_name(display_name)
Parameters

display_name (str) –

Return type

slacktivate.slack.classes.SlackGroup

classmethod from_group(group)
Parameters

group (Union[slack_scim.v1.group.Group, slack_scim.v1.users.Group]) –

Return type

slacktivate.slack.classes.SlackGroup

classmethod from_id(group_id)
Parameters

group_id (str) –

Return type

slacktivate.slack.classes.SlackGroup

classmethod from_string(string)
Parameters

string (str) –

Return type

slacktivate.slack.classes.SlackGroup

get_members_as_users()
Return type

Optional[List[slacktivate.slack.classes.SlackUser]]

property id
property member_ids
property members
refresh()
Return type

bool

class slacktivate.slack.classes.SlackGroupMember(*args, **kwargs)

Bases: dict

display: str
value: str
slacktivate.slack.classes.SlackGroupTypes

This is a type annotation to describe all the data types supported by the to_slack_group() method:

  1. a string (a Slack group ID or group display name as described in more detail in the documentation for SlackGroup.from_string()),

  2. a slack_scim.Group object, from the Slack API package,

  3. an existing SlackGroup object.

alias of Union[str, slack_scim.v1.group.Group, slack_scim.v1.users.Group, slacktivate.slack.classes.SlackGroup]

class slacktivate.slack.classes.SlackUser(user_id=None, username=None, email=None, user=None, resource=None)

Bases: object

This is a wrapper class to abstract the concept of Slack user across the various vendor-provided packages

property active
property email
property emails
property exists
classmethod from_any(value)
Parameters

value (Optional[Union[str, slack_scim.v1.user.User]]) –

Returns

Return type

Optional[slacktivate.slack.classes.SlackUser]

classmethod from_email(email)

Creates a SlackUser wrapper object, given an email address.

Note

This is an internal package method that does not do any validation, and can result in SlackUser representing non-existent users. Use the higher-level to_slack_user() method to do user validation.

Parameters

email (str) – A Slack user ID

Returns

A SlackUser object

Return type

slacktivate.slack.classes.SlackUser

classmethod from_id(user_id)

Creates a SlackUser wrapper object, given a Slack user ID.

Note

This is an internal package method that does not do any validation, and can result in SlackUser representing non-existent users. Use the higher-level to_slack_user() method to do user validation.

Parameters

user_id (str) – A Slack user ID

Returns

A SlackUser object

Return type

slacktivate.slack.classes.SlackUser

classmethod from_string(string)

Creates a SlackUser wrapper object, given a string that may represent either:

  1. a Slack user ID (alphanumeric string beginning by W or U as described in the Slack API documentation),

  2. an email (string with no spaces containing an @),

  3. or a Slack username.

Note

This is an internal package method that does not do any validation, and can result in SlackUser representing non-existent users. Use the higher-level to_slack_user() method to do user validation.

Parameters

string (str) – A string

Returns

A SlackUser object

Return type

slacktivate.slack.classes.SlackUser

classmethod from_user(user)

Creates a SlackUser wrapper object, given a non-null slack_scim.User object.

Parameters

user (slack_scim.v1.user.User) – A slack_scim.User object

Returns

A SlackUser object

Return type

slacktivate.slack.classes.SlackUser

classmethod from_username(username)

Creates a SlackUser wrapper object, given a Slack username.

Note

This is an internal package method that does not do any validation, and can result in SlackUser representing non-existent users. Use the higher-level to_slack_user() method to do user validation.

Parameters

username (str) – A Slack user ID

Returns

A SlackUser object

Return type

slacktivate.slack.classes.SlackUser

property fullname
property id
property image_url
refresh()
Return type

bool

property scim_obj
property username
slacktivate.slack.classes.SlackUserTypes

This is a type annotation to describe all the data types supported by the to_slack_user() method:

  1. a string (an email, or a Slack user ID or username as described in more detail in the documentation for SlackUser.from_string()),

  2. a slack_scim.User object, from the Slack API package,

  3. an existing SlackUser object.

alias of Union[str, slack_scim.v1.user.User, slacktivate.slack.classes.SlackUser]

slacktivate.slack.classes.lookup_group_by_display_name(display_name)
Parameters

display_name (str) –

Return type

Optional[slack_scim.v1.group.Group]

slacktivate.slack.classes.lookup_group_by_id(group_id)
Parameters

group_id (str) –

Return type

Optional[slack_scim.v1.group.Group]

slacktivate.slack.classes.lookup_user_by_email(email)

Returns the internal slack_scim.User object for a Slack user in the currently logged-in workspace, given one of that user’s emails; if the email does not correspond to an existing user, returns None. This query is live.

Parameters

email (str) – An email address

Returns

A slack_scim.User object or None

Return type

Optional[slack_scim.v1.user.User]

slacktivate.slack.classes.lookup_user_by_id(user_id)

Returns the internal slack_scim.User object for a Slack user in the currently logged-in workspace, given that user’s Slack ID; if the Slack user ID does not correspond to an existing user, returns None. This query is live.

Parameters

user_id (str) – A Slack user ID

Returns

A slack_scim.User object or None

Return type

Optional[slack_scim.v1.user.User]

slacktivate.slack.classes.lookup_user_by_username(username)

Returns the internal slack_scim.User object for a Slack user in the currently logged-in workspace, given that user’s username; if the username does not correspond to an existing user, returns None. This query is live.

Parameters

username (str) – A Slack username

Returns

A slack_scim.User object or None

Return type

Optional[slack_scim.v1.user.User]

slacktivate.slack.classes.to_slack_group(value, only_existing=True)
Parameters
Return type

Optional[slacktivate.slack.classes.SlackGroup]

slacktivate.slack.classes.to_slack_user(value, only_existing=True)
Parameters
Returns

Return type

Optional[slacktivate.slack.classes.SlackUser]

slacktivate.slack.clients module

This submodule

slacktivate.slack.clients.SLACK_TOKEN = '<SLACK TOKEN>'

In order to use the Slack SCIM API, you need to be an owner of the workspace, and obtain an API token with admin scope.

As explained in the official Slack SCIM API documentation, the easiest way to obtain a valid token for the purposes of SCIM provisioning is as follows:

  1. As a Workspace/Organization Owner, create a new app for your workspace (see here for the documentation).

  2. Add the admin OAuth scope to the “User Token Scopes” section.

  3. Install the app to your workspace (see here for the documentation).

  4. Use the generated token in the “OAuth & Permissions” tab (if you are provided with multiple tokens, use the “OAuth Access Token” not the “Bot User OAuth Access Token”).

Note that you can easily reinstall your app with different permissions if it turns out you did not select all the necessary permissions.

slacktivate.slack.clients.api(token=None, force_login=False, update_global=None)
Parameters
  • token (Optional[str]) –

  • force_login (bool) –

  • update_global (Optional[bool]) –

Return type

slack.web.client.WebClient

slacktivate.slack.clients.login(token=None, silent_error=False, update_global=True)

Returns a pair containing a logged-in Slack API and Slack SCIM API client.

Parameters
  • token (Optional[str]) – A valid Slack OAuth token (if none is provided, will try to obtain it from the environment)

  • silent_error (bool) – Flag whether to silently fail when no valid token is available or not

  • update_global (bool) – Flag whether to update the global clients with the result of this operation (useful to globally change which workspace is being affected by this library)

Returns

A pair containing a properly logged-in Slack API client and Slack SCIM API client

Return type

Tuple[slack.web.client.WebClient, slack_scim.v1.client.SCIMClient]

slacktivate.slack.clients.managed_api(token=None, patch_reply_exception=True)
Parameters
  • token (Optional[str]) –

  • patch_reply_exception (bool) –

Return type

AbstractContextManager[slack.web.client.WebClient]

slacktivate.slack.clients.managed_scim(token=None, patch_reply_exception=True)
Parameters
  • token (Optional[str]) –

  • patch_reply_exception (bool) –

Return type

AbstractContextManager[slack_scim.v1.client.SCIMClient]

slacktivate.slack.clients.scim(token=None, force_login=False, update_global=None)
Parameters
  • token (Optional[str]) –

  • force_login (bool) –

  • update_global (Optional[bool]) –

Return type

slack_scim.v1.client.SCIMClient

slacktivate.slack.exceptions module

class slacktivate.slack.exceptions.SlackExceptionHandler(client, patch_reply_exception=True)

Bases: contextlib.ExitStack

static wrap(client, patch_reply_exception=True)
Parameters
  • client (Union[slack_scim.v1.client.SCIMClient, slack.web.client.WebClient]) –

  • patch_reply_exception (bool) –

Return type

slacktivate.slack.exceptions.SlackExceptionHandler

slacktivate.slack.exceptions.handle_slack_errors(exc_val, exc_type=None, exc_tb=None)
Parameters
  • exc_val (Exception) –

  • exc_type (Optional[Type]) –

  • exc_tb (Optional[traceback]) –

Return type

bool

slacktivate.slack.methods module

This submodule provides an intermediate abstraction layer to the methods provided by the Slack API and Slack SCIM API. This layer handles certain errors (such as rate-limiting exceptions), uses the wrapper classes defined in slacktivate.slack.classes, and provides a coherent, predictable syntax to do typical, elementary administrative operations on the logged-in Slack workspace.

slacktivate.slack.methods.channel_create(name, is_private=False, return_id=True)
Parameters
  • name (str) –

  • is_private (bool) –

  • return_id (bool) –

Return type

Optional[Union[str, Dict[str, Any]]]

slacktivate.slack.methods.channels_list(by_id=False, only_name=False)
Parameters
  • by_id (bool) –

  • only_name (bool) –

Return type

Optional[Dict[str, Dict[str, Any]]]

slacktivate.slack.methods.conversation_member_ids(conversation_id)
Parameters

conversation_id (str) –

Return type

List[str]

slacktivate.slack.methods.group_create(display_name)
Parameters

display_name (str) –

Return type

Optional[slacktivate.slack.classes.SlackGroup]

slacktivate.slack.methods.group_ensure(display_name, user_ids=None, remove_unspecified_members=True)
Parameters
  • display_name (str) –

  • user_ids (Optional[List[str]]) –

  • remove_unspecified_members (bool) –

slacktivate.slack.methods.group_patch(group, changes)
Parameters
Return type

Optional[slacktivate.slack.classes.SlackGroup]

slacktivate.slack.methods.list_custom_profile_fields(index_by_label=False, silent_error=True)

Returns a dictionary of all the custom profile fields defined in the currently logged-in Slack workspace (custom fields are only available in Slack Plus and above plans).

By default, the dictionary is indexed by the fields internal ID:

{
    'Xf01AVK94ASU': {
        'id': 'Xf01AVK94ASU',
        'ordering': 0,
        'field_name': None,
        'label': 'Pronouns',
        'hint': 'E.g.: she/her/hers, he/him/his, they/them/theirs, ze/zim/zirs, ...',
        'type': 'text',
        'possible_values': None,
        'options': None,
        'is_hidden': False
    }
    ...
}

For more information, see Slack’s documentation of the API method.

Parameters
  • index_by_label (bool) – Flag to indicate whether the returned dictionary should be indexed by the label, rather than the ID

  • silent_error (bool) – Flag to indicate whether to silently suppress any unexpected error and return an empty dictionary in that case

Raises

If silent_error is False, may raise a slack.errors.SlackApiError

Returns

The dictionary mapping a field ID to the internal dictionary defining a custom Slack profile field

Return type

Dict[str, str]

slacktivate.slack.methods.make_user_dictionary(attributes, include_naming=True, include_image=True, include_fields=True)

Returns the payload to update a Slack user’s profile; this is an internal method, that is only useful to make calls directly to the Slack API client.

Parameters
  • attributes (dict) – A dictionary mapping the profile customized fields to their content for a given user

  • include_naming (bool) – Flag determining whether to include the naming attributes (such as name, displayName, nickName)

  • include_image (bool) – Flag determining whether to include the profile image

  • include_fields (bool) – Flag determining whether to include customized profile fields (as processed by the method make_user_extra_fields_dictionary())

Returns

A dictionary representing the payload to update a Slack user’s profile

Return type

Optional[dict]

slacktivate.slack.methods.make_user_extra_fields_dictionary(attributes)

Returns the payload to update a Slack user’s customized profile fields; this is an internal method, that is only useful to make calls directly to the Slack API client.

This method expects to provided a dictionary attributes, mapping the customized fields to the their value, such as:

{
    "Degree": "Ph.D.",
    "GitHub": "https://github.com/jlumbroso/",
}

Internally, a cache is maintained containing the result of a call to list_custom_profile_fields(), which allows this payload to be built by translating the labels into their corresponding field IDs.

The resulting payload might be:

{
    "Xf01957FNX4N": { "value": "Ph.D.", "alt":"" },
    "Xf019AHU8MJ9": { "value": "https://github.com/jlumbroso/", "alt":"" },
}
Parameters

attributes (dict) – A dictionary mapping the profile customized fields to their content for a given user

Returns

A dictionary representing the payload to update a Slack user’s customized profile fields

Return type

Dict[str, Any]

slacktivate.slack.methods.team_access_logs(before=None, count=None, user=None, users=None, page_shifting=True)
Parameters
slacktivate.slack.methods.user_activate(user)

Ensures an existing Slack user is active.

Parameters

user (slacktivate.slack.classes.SlackUserTypes) – A valid user object

Returns

True if the status of the user is active

Return type

bool

slacktivate.slack.methods.user_create(attributes)

Creates a new Slack user, based on the provided attributes, using Slack SCIM API provisioning.

Note

Only the userName and emails attributes are required to create a user.

Parameters

attributes (dict) – A (possibly nested) dictionary containing the attributes for the user to be created

Returns

A valid Slack user, if successful

Return type

Optional[slacktivate.slack.classes.SlackUser]

slacktivate.slack.methods.user_deactivate(user)

Ensures an existing Slack user is deactivate.

Parameters

user (slacktivate.slack.classes.SlackUserTypes) – A valid user object

Returns

True if the status of the user is active

Return type

bool

slacktivate.slack.methods.user_image_set(user, image_url)
Parameters
Return type

Optional[slacktivate.slack.classes.SlackUser]

slacktivate.slack.methods.user_patch(user, changes)

Patch an existing Slack user, as provided by the user parameter, with modifications provided in the changes parameter.

See also

See the Slack SCIM API documentation for an overview of the modifications that can be effected through this method with the dictionary passed through the changes parameter.

Parameters
Returns

The modified SlackUser if successful, None otherwise.

Return type

Optional[slacktivate.slack.classes.SlackUser]

slacktivate.slack.methods.user_profile_set(user, extra_fields)

Updates a Slack user’s customized profile fields.

Parameters
Returns

Return type

Optional[slacktivate.slack.classes.SlackUser]

slacktivate.slack.methods.user_set_active(user, active=True)

Activates (or deactivates) an existing Slack user.

Parameters
Returns

True if the status of the user was successfully changed

Return type

bool

slacktivate.slack.retry module

This submodule contains a few helper methods that provide a decorator slack_retry() that handles all the rate-limiting API exceptions that are raised by the Slack API and Slack SCIM API packages. This helps streamline the composition of more complex macros.

slacktivate.slack.retry.DEFAULT_SECONDS_TO_WAIT: int = 20

Default number of seconds to wait when a rate limiting exception is thrown by the Slack API or Slack SCIM API, but without a valid Retry-After header.

slacktivate.slack.retry.slack_do_we_give_up(err)
Parameters

err (Union[slack.errors.SlackApiError, slack_scim.v1.errors.SCIMApiError, Exception]) –

Return type

bool

slacktivate.slack.retry.slack_retry(target)
@slack_retry

This is a decorator to automatically handle the Slack vendor exceptions, slack.errors.SlackApiError and slack_scim.SCIMApiError when it is caused by a rate-limiting error (as described in the Slack API documentation and the Slack SCIM API documentation. When such an exception is thrown, this decorator will pause for an unspecified, random amount of time and retry the exact same method call.

See also

This functionality is powered by the backoff package (available on GitHub).

Module contents

This submodule contains all the code that interacts directly with the Slack API and Slack SCIM API official Python SDKs.