Commands Object

Note

This commands object is an extention of basic-client.

Usage..

from slack import commands

client = commands.Client(..., prefix="!")

@client.command(name="msg")
async def message(ctx: commands.Context, *args):
    await ctx.channel.send("message received!")

@client.command()
async def ping(ctx: commands.Context, *args):
    await ctx.channel.send("pong!")

If commands was start your prefix and the command was registered, dispatch command-function.

Bot

This class need…

  • user-token.

  • bot-token.

  • app-token.

  • prefix.

Prefix is a string for command occur. If you don’t need this, you put prefix=””

class slack.commands.Bot

This is slack.Client’s subclass.

New in version 1.2.0.

Parameters:
  • user_token (str) – The your-self token. It must be start ‘xoxp-…’

  • bot_token (str) – The bot token. It must be start ‘xoxb-…’

  • token (Optional[str]) –

    App-level token. It is startwith ‘xapp-…’

    Changed in version 1.4.0: To optional.

  • _logger (Logger.Logger) –

    Logger object.

    New in version 1.4.0.

  • prefix (str) – Command-prefix.

@command(name=None)

Register command of your client-object.

Parameters:

name (str) – command name. If you don’t set, use function name.

@event
event is a decorator that takes a coroutine function and sets

it as an attribute of the class it’s decorating.

Parameters:

coro (Coro) – The coroutine function to be decorated.

Return type:

The coro function itself.

property channel_manager: _ChannelManager
Channels manager.

versionadded:: 1.4.5

Return type:

_ChannelManager

property channels: list[Channel]

List of channels.

Return type:

list[Channel]

await close() None

Close connection.

property commands: dict[str, Command]

Return all commands

New in version 1.4.0.

Return type:

Dict[:class:`str, Command]

await connect(ws_url: str) None

connect to slack-API

Parameters:

ws_url (str) –

get_command(name: str, /) Command | None

Get registered command from name

New in version 1.4.0.

Parameters:

name (str) –

Return type:

Optional[Command]

is_closed() bool

It returns a boolean value.

Returns:

The return value is a boolean value.

Return type:

bool

await login() None

Login as bot with websocket. Get teams, channels and member data.

property members: list[Member]

List of members.

Return type:

list[Member]

await on_error(event_name, exc: Exception, *args, **kwargs) None

It prints the name of the event that raised the exception, the name of the exception, and the name of the class that the event is in.

Parameters:
  • event_name – The name of the event that was raised.

  • exc (Exception) – The exception that was raised.

run() None

A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use start() coroutine or connect() + login(). Roughly Equivalent to:

try:
    loop.run_until_complete(start(*args, **kwargs))
except KeyboardInterrupt:
    loop.run_until_complete(close())
    # cancel all tasks lingering
finally:
    loop.close()

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.

await start() None

start connection.

property team_manager: _TeamManager
Teams manager.

versionadded:: 1.4.5

Return type:

_TeamManager

property teams: list[Team]

List of teams.

Return type:

list[Team]

wait_for(event: str, check: Callable[[...], bool] | None = None, timeout: float | None = None)

This function is a coroutine

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The timeout parameter is passed onto asyncio.wait_for(). By default, it does not time out. Note that this does propagate the asyncio.TimeoutError for you in case of timeout and is provided for ease of use.

Parameters:
  • event (str) – The event name, similar to the event reference, but without the on_ prefix, to wait for.

  • check (Optional[Callable[…, bool]]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.

  • timeout (Optional[float]) – The number of seconds to wait before timing out and raising asyncio.TimeoutError.

Returns:

Returns no arguments, a single argument, or a tuple of multiple arguments that mirrors the parameters passed in the event reference.

Return type:

Any

Raises:

asyncio.TimeoutError – Raised if a timeout is provided and reached.

Examples

Waiting for a user reply:

@bot.event
async def on_message(message):
    if message.content.startswith('$greet'):
        channel = message.channel
        await channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await bot.wait_for('message', check=check)
        await channel.send(f'Hello {msg.author}!')

Waiting for a thumbs up reaction from the message author:

@bot.event
async def on_message(message):
    if message.content.startswith('$thumb'):
        channel = message.channel
        await channel.send('Send me that 👍 reaction, mate')

        def check(reaction, user):
            return user == message.author

        try:
            reaction, user = await bot.wait_for('channel_create', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('👎')
        else:
            await channel.send('👍')

Context

class slack.commands.Context

A context is a message that is sent to a handler

client
Type:

Bot

message

Message object of context.

Type:

Message

message_id

Context ID (equals message ID)

Type:

str

id

Context channel ID

Type:

str

prefix

Message prefix.

Type:

str

await archive() None

This function is a coroutine This channel archive as user.

property channel: Channel

Returns context channel.

Returns:

Context channel.

Return type:

Channel

await delete() DeletedMessage

Delete context message.

Returns:

Data of deleted message.

Return type:

DeletedMessage

property everyone: str

New in version 1.4.0.

Return type:

str

Retrieve a permalink URL for a specific extant message.

New in version 1.4.5.

Parameters:

message (Message) – Message for which you want to get a permalink.

Returns:

Message permalink.

Return type:

str

await get_scheduled_messages(limit: int | None = None, latest: datetime | int | float | None = None, oldest: datetime | int | float | None = None) list[ScheduledMessage | None]

Examples

Examples

messages = await channel.get_scheduled_messages():
for message in messages:
    print(message.content)
Parameters:
  • limit (Optional[int]) –

  • latest (Optional[int, float, datetime]) –

  • oldest (Optional[int, float, datetime]) –

Return type:

List[Optional[ScheduledMessage]]

property here: str

New in version 1.4.0.

Return type:

str

await history() list[Message]

Examples

Examples

async for message in channel.history():
    print(message.content)
await send(text: str | None = None, view: ViewFrame | None = None, as_user: bool = False) Message

This function is a coroutine

It sends a message to a channel.

Changed in version 1.4.0: Add view parameter.

Parameters:
  • text (Optional[str]) – The text of the message to send.

  • view (Optional[ViewFrame]) – The viewframe contain blocks of the message to send.

  • as_user (str) –

    Is message send by user or not.

    New in version 1.4.2.

Raises:

InvalidArgumentException – Raise when text and view are in param.

Returns:

A Message object.

Return type:

Message

await send_ephemeral(text: str, member: Member) datetime

This function is a coroutine Send Ephemeral message.

New in version 1.4.0.

Parameters:
  • text (str) – The text of the message to send.

  • member (Member) – send member.

Returns:

Message posted time.

Return type:

datetime

await send_file(attachment: Attachment) File

This function occur sending file.

Parameters:

attachment (Attachment) – Your file to send.

Returns:

Sended data of file.

Return type:

File

await send_schedule(text: str, date: datetime | int | float) Message

This function is sending scheduled message with UNIX timestamp.

New in version 1.4.2.

Parameters:
  • text (str) – Message content.

  • date (Optional[datetime,:class:intfloat]) – Timestamp when scheduled message sending.

Returns:

Message object.

Return type:

Message

property team: Team

Return context team.

Returns:

Context team.

Return type:

Team

Command

Note

If raise exception in commands object, it will go to on_command_error(ctx, err) event.

Attributes
class slack.commands.Command

It’s a class that represents a command

New in version 1.2.0.

name

Comman name.

Type:

str

property callback: Callable

It returns a function that is stored in the object

Returns:

The function itself.

Return type:

Callable