Clients

The following section documents everything related to clients. Clients in this library are primary way to make bots and interact with Stoat API.

Clients

Client

class stoat.Client(*, token='', bot=True, cache=UNDEFINED, cdn_base=None, cdn_client=None, http_base=None, http=None, parser=None, shard=None, state=None, request_user_settings=None, websocket_base=None)[source]

A Stoat client.

@listen(event=None, /)[source]

Register an event listener.

There is an alias for this called on().

Examples

Ping Pong:

@client.listen()
async def on_message_create(event: stoat.MessageCreateEvent):
    message = event.message
    if message.content == '!ping':
        await message.reply('pong!')

# It returns :class:`EventSubscription`, so you can do ``on_message_create.remove()``
Parameters:

event (Optional[Type[EventT]]) – The event to listen to.

@on(event=None, /)[source]

Register an event listener.

This is an alias of listen().

Examples

Ping Pong:

@client.on()
async def on_message_create(event: stoat.MessageCreateEvent):
    message = event.message
    if message.content == '!ping':
        await message.reply('pong!')

# It returns :class:`EventSubscription`, so you can do ``on_message_create.remove()``
Parameters:

event (Optional[Type[EventT]]) – The event to listen to.

await on_user_error(event, /)[source]

Handles user errors that came from handlers. You can get current exception being raised via sys.exc_info().

By default, this logs exception.

await on_library_error(shard, payload, exc, /)[source]

Handles library errors. By default, this logs exception.

Note

This won’t be called if handling Ready will raise an exception as it is fatal.

dispatch(event, /)[source]

Dispatches an event.

Examples

Dispatch an event when someone sends silent message:

from attrs import define, field
import stoat

# ...

@define(slots=True)
class SilentMessageEvent(stoat.BaseEvent):
    message: stoat.Message = field(repr=True, kw_only=True)


@client.on(stoat.MessageCreateEvent)
async def on_message_create(event):
    message = event.message
    if message.flags.suppress_notifications:
        event = SilentMessageEvent(message=message)

        # Block until event gets fully handled (run hooks, calling event handlers, cache received data).
        await client.dispatch(event)

        # Note, that `dispatch` returns `asyncio.Task`, as such you may just do `client.dispatch(event)`.
Parameters:

event (BaseEvent) – The event to dispatch.

Returns:

The asyncio task.

Return type:

asyncio.Task

subscribe(event, /, callback)[source]

Subscribes to event.

Parameters:
  • event (Type[EventT]) – The type of the event.

  • callback (MaybeAwaitableFunc[[EventT], None]) – The callback for the event.

wait_for(event, /, *, check=None, count=1, timeout=None, manual_process=False, stop_dispatching_on_success=True)[source]

This function is a coroutine.

Waits for a WebSocket event to be dispatched.

This could be used to wait for an 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 timeout. Note that this does propagate the asyncio.TimeoutError for you in case of timeout and is provided for ease of use.

This function returns the first event that meets the requirements.

Examples

Waiting for an user reply:

@client.on(stoat.MessageCreateEvent)
async def on_message_create(event):
    message = event.message
    if message.content.startswith('$greet'):
        channel = message.channel
        await channel.send('Say hello!')

        def check(event):
            return event.message.content == 'hello' and event.message.channel.id == channel.id

        msg = await client.wait_for(stoat.MessageCreateEvent, check=check)
        await channel.send(f'Hello {msg.author}!')

Waiting for a thumbs up reaction from the message author:

@client.on(stoat.MessageCreateEvent)
async def on_message_create(event):
    message = event.message
    if message.content.startswith('$thumb'):
        channel = message.channel
        await channel.send('Send me that 👍 reaction, mate')

        def check(event):
            return event.user_id == message.author.id and event.emoji == '👍'

        try:
            await client.wait_for(stoat.MessageReactEvent, timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('👎')
        else:
            await channel.send('👍')
Parameters:
  • event (Type[EventT]) – The event to wait for.

  • check (Optional[Callable[[EventT], bool]]) – A predicate to check what to wait for.

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

  • manual_process (bool) – Whether to not process the event at all when it gets dispatched. Defaults to False.

  • stop_dispatching_on_success (bool) – Whether to stop dispatching when event arrives. Defaults to True.

Raises:
Returns:

The subscription. This can be await’ed.

Return type:

Union[TemporarySubscription, TemporarySubscriptionList]

all_subscriptions()[source]

List[EventSubscription[BaseEvent]]: Returns all event subscriptions.

subscriptions_for(event, /, *, include_subclasses=False)[source]

List[EventSubscription[EventT]]: Returns the subscriptions for event.

Parameters:
  • event (Type[EventT]) – The event to get subscriptions to.

  • include_subclasses (bool) – Whether to include subclassed events. Defaults to False.

subscriptions_count_for(event, /, *, include_subclasses=False)[source]

int: Returns the subscriptions for event.

Parameters:
  • event (Type[EventT]) – The event to get subscription count to.

  • include_subclasses (class:bool) – Whether to include subclassed events. Defaults to False.

property me[source]

The currently logged in user. None if not logged in.

Type:

Optional[OwnUser]

property user[source]

The currently logged in user. None if not logged in.

Alias to me.

Type:

Optional[OwnUser]

property saved_notes[source]

The Saved Notes channel.

Type:

Optional[SavedMessagesChannel]

property http[source]

The HTTP client.

Type:

HTTPClient

property shard[source]

The Stoat WebSocket client.

Type:

Shard

property state[source]

The controller for all entities and components.

Type:

State

property channels[source]

Mapping of cached channels.

Type:

Mapping[str, Channel]

property emojis[source]

Mapping of cached emojis.

Type:

Mapping[str, Emoji]

property members[source]

Mapping of cached server members.

Type:

Mapping[str, Mapping[str, Member]]

property read_states[source]

Mapping of cached read states.

Type:

Mapping[str, ReadState]

property servers[source]

Mapping of cached servers.

Type:

Mapping[str, Server]

property users[source]

Mapping of cached users.

Type:

Mapping[str, User]

property voice_states[source]

Mapping of cached voice states.

Type:

Mapping[str, ChannelVoiceStateContainer]

property dm_channel_ids[source]

Mapping of user IDs to cached DM channel IDs.

Type:

Mapping[str, str]

property dm_channels[source]

Mapping of user IDs to cached DM channels.

Type:

Mapping[str, DMChannel]

property private_channels[source]

Mapping of channel IDs to private channels.

Type:

Mapping[str, Union[DMChannel, GroupChannel]]

property ordered_private_channels_old[source]

The list of private channels in Revite order.

Type:

List[Union[DMChannel, GroupChannel]]

property ordered_private_channels[source]

The list of private channels in new client’s order.

Type:

List[Union[DMChannel, GroupChannel]]

get_channel(channel_id, /, *, partial=False)[source]

Retrieves a channel from cache.

Parameters:
  • channel_id (str) – The channel ID.

  • partial (bool) – Whether to return PartialMessageable instead of None if server was not found.

Returns:

The channel or None if not found.

Return type:

Optional[Union[Channel, PartialMessageable]]

await fetch_channel(channel_id, /, *, http_overrides=None)[source]

This function is a coroutine.

Fetch a Channel with the specified ID.

You must have view_channel to do this.

This is shortcut to stoat.HTTPClient.get_channel().

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to view the channel.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

Returns:

The retrieved channel.

Return type:

Channel

get_emoji(emoji_id, /)[source]

Retrieves an emoji from cache.

Parameters:

emoji_id (str) – The emoji ID.

Returns:

The emoji or None if not found.

Return type:

Optional[Emoji]

await fetch_emoji(emoji_id, /, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves a custom emoji.

This is shortcut to stoat.HTTPClient.get_emoji().

Parameters:
Raises:

NotFound – Possible values for type:

Value

Reason

NotFound

The emoji was not found.

Returns:

The retrieved emoji.

Return type:

Emoji

get_read_state(channel_id, /)[source]

Retrieves a read state from cache.

Parameters:

channel_id (str) – The channel ID of read state.

Returns:

The read state or None if not found.

Return type:

Optional[ReadState]

get_server(server_id, /, *, partial=False)[source]

Retrieves a server from cache.

Parameters:
  • server_id (str) – The server ID.

  • partial (bool) – Whether to return BaseServer instead of None if server was not found.

Returns:

The server or None if not found.

Return type:

Optional[Union[Server, BaseServer]]

await fetch_server(server_id, *, http_overrides=None, populate_channels=None)[source]

This function is a coroutine.

Retrieves a Server.

This is shortcut to stoat.HTTPClient.get_server().

Parameters:
  • server (ULIDOr[BaseServer]) – The server to retrieve.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • populate_channels (Optional[bool]) – Whether to populate channels.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

Returns:

The retrieved server.

Return type:

stoat.Server

get_user(user_id, /, *, partial=False)[source]

Retrieves an user from cache.

Parameters:
  • user_id (str) – The user ID.

  • partial (bool) – Whether to return BaseUser instead of None if server was not found.

Returns:

The user or None if not found.

Return type:

Optional[Union[User, BaseUser]]

await fetch_user(user_id, /, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves an user from API. This is shortcut to stoat.HTTPClient.get_user().

Parameters:
  • user_id (str) – The user ID.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Returns:

The user.

Return type:

User

property settings[source]

The current user settings.

Type:

UserSettings

property system[source]

The Stoat sentinel user.

Type:

User

await setup_hook()[source]

This function is a coroutine.

A hook that is called when client starts up.

await start()[source]

This function is a coroutine.

Starts up the client.

Calls setup_hook() before connecting.

await close(*, http=True, cleanup_websocket=True)[source]

This function is a coroutine.

Closes all HTTP sessions, and WebSocket connections.

Parameters:
  • http (bool) – Whether to clean up HTTP sessions.

  • cleanup_websocket (bool) – Whether to clean up WebSocket.

run(token='', *, bot=UNDEFINED, log_handler=UNDEFINED, log_formatter=UNDEFINED, log_level=UNDEFINED, root_logger=False, asyncio_debug=False, cleanup=True)[source]

A blocking call that abstracts away the event loop initialization from you.

If you want more control over the event loop then this function should not be used. Use start() coroutine.

This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing None to the log_handler parameter.

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.

Parameters:
  • log_handler (Optional[logging.Handler]) –

    The log handler to use for the library’s logger. If this is None then the library will not set up anything logging related. Logging will still work if None is passed, though it is your responsibility to set it up.

    The default log handler if not provided is logging.StreamHandler.

  • log_formatter (logging.Formatter) – The formatter to use with the given log handler. If not provided then it defaults to a color based logging formatter (if available).

  • log_level (int) – The default log level for the library’s logger. This is only applied if the log_handler parameter is not None. Defaults to logging.INFO.

  • root_logger (bool) –

    Whether to set up the root logger rather than the library logger. By default, only the library logger ('stoat') is set up. If this is set to True then the root logger is set up as well.

    Defaults to False.

  • asyncio_debug (bool) –

    Whether to run with asyncio debug mode enabled or not.

    Defaults to False.

  • cleanup (bool) –

    Whether to close aiohttp sessions or not.

    Defaults to True.

await create_group(name, *, http_overrides=None, description=None, icon=None, recipients=None, nsfw=None)[source]

This function is a coroutine.

Creates a new group.

Fires PrivateChannelCreateEvent for the current user and all specified recipients.

Note

This can only be used by non-bot accounts.

Parameters:
  • name (str) – The group name. Must be between 1 and 32 characters long.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • description (Optional[str]) – The group description. Can be only up to 1024 characters.

  • icon (Optional[ResolvableResource]) – The group’s icon.

  • recipients (Optional[List[ULIDOr[BaseUser]]]) – The users to create the group with, only up to 49 users. You must be friends with these users.

  • nsfw (Optional[bool]) – To mark the group as NSFW or not.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    GroupTooLarge

    The group exceeded maximum count of recipients.

    MissingPermission

    You do not have the proper permissions to add the recipient.

    NotFriends

    You’re not friends with the users you want to create group with.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    One of recipients was not found, or the provided file for icon was not found.

  • InternalServerError – Possible values for type:

Returns:

The new group.

Return type:

GroupChannel

await create_server(name, *, http_overrides=None, description=None, nsfw=None)[source]

This function is a coroutine.

Create a new server.

Fires ServerCreateEvent for the current user.

Note

This can only be used by non-bot accounts.

Parameters:
  • name (str) – The server name. Must be between 1 and 32 characters long.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • description (Optional[str]) – The server description. Can be only up to 1024 characters.

  • nsfw (Optional[bool]) – Whether this server is age-restricted.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    IsBot

    The current token belongs to bot account.

    TooManyChannels

    The instance was incorrectly configured. (?)

    TooManyServers

    You’re in too many servers than the instance allows.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • InternalServerError – Possible values for type:

Returns:

The created server.

Return type:

Server

ClientEventHandler

class stoat.ClientEventHandler(client)[source]

The default event handler for the client.

client

The client the event handler is for.

Type:

Client

state

The client’s state.

Type:

State

dispatch

Alias for Client.dispatch().

Type:

Callable[[BaseEvent], :class:``asyncio.Task`]

handlers

The handlers.

Type:

Dict[str, Callable[…, MaybeAwaitable[None]]]

Parameters:

client (Client) – The client.

await handle_bulk(shard, payload, /)[source]

Handle Bulk WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_authenticated(shard, payload, /)[source]

Handle Authenticated WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_logout(shard, payload, /)[source]

Handle Logout WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_ready(shard, payload, /)[source]

Handle Ready WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_message(shard, payload, /)[source]

Handle Message WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_message_update(shard, payload, /)[source]

Handle MessageUpdate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_message_append(shard, payload, /)[source]

Handle MessageAppend WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_message_delete(shard, payload, /)[source]

Handle MessageDelete WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_message_react(shard, payload, /)[source]

Handle MessageReact WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_message_unreact(shard, payload, /)[source]

Handle MessageUnreact WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_message_remove_reaction(shard, payload, /)[source]

Handle MessageRemoveReaction WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_bulk_message_delete(shard, payload, /)[source]

Handle BulkMessageDelete WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_server_create(shard, payload, /)[source]

Handle ServerCreate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_server_update(shard, payload, /)[source]

Handle ServerUpdate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_server_delete(shard, payload, /)[source]

Handle ServerDelete WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_server_member_join(shard, payload, /)[source]

Handle ServerMemberJoin WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_server_member_update(shard, payload, /)[source]

Handle ServerMemberUpdate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_server_member_leave(shard, payload, /)[source]

Handle ServerMemberLeave WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_server_role_update(shard, payload, /)[source]

Handle ServerRoleUpdate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_server_role_delete(shard, payload, /)[source]

Handle ServerRoleDelete WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_server_role_ranks_update(shard, payload, /)[source]

Handle ServerRoleRanksUpdate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_user_update(shard, payload, /)[source]

Handle UserUpdate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_user_relationship(shard, payload, /)[source]

Handle UserRelationship WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_user_settings_update(shard, payload, /)[source]

Handle UserSettingsUpdate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_user_platform_wipe(shard, payload, /)[source]

Handle UserPlatformWipe WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_emoji_create(shard, payload, /)[source]

Handle EmojiCreate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_emoji_delete(shard, payload, /)[source]

Handle EmojiDelete WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_report_create(shard, payload, /)[source]

Handle ReportCreate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_channel_create(shard, payload, /)[source]

Handle ChannelCreate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_channel_update(shard, payload, /)[source]

Handle ChannelUpdate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_channel_delete(shard, payload, /)[source]

Handle ChannelDelete WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_channel_group_join(shard, payload, /)[source]

Handle ChannelGroupJoin WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_channel_group_leave(shard, payload, /)[source]

Handle ChannelGroupLeave WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_channel_start_typing(shard, payload, /)[source]

Handle ChannelStartTyping WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_channel_stop_typing(shard, payload, /)[source]

Handle ChannelStopTyping WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_message_start_editing(shard, payload, /)[source]

Handle MessageStartEditing WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_message_stop_editing(shard, payload, /)[source]

Handle MessageStopEditing WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_channel_ack(shard, payload, /)[source]

Handle ChannelAck WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_webhook_create(shard, payload, /)[source]

Handle WebhookCreate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_webhook_update(shard, payload, /)[source]

Handle WebhookUpdate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_webhook_delete(shard, payload, /)[source]

Handle WebhookDelete WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_auth(shard, payload, /)[source]

Handle Auth WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_voice_channel_join(shard, payload, /)[source]

Handle VoiceChannelJoin WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_voice_channel_leave(shard, payload, /)[source]

Handle VoiceChannelLeave WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_voice_channel_move(shard, payload, /)[source]

Handle VoiceChannelMove WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_user_voice_state_update(shard, payload, /)[source]

Handle UserVoiceStateUpdate WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_user_move_voice_channel(shard, payload, /)[source]

Handle UserMoveVoiceChannel WebSocket event.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

await handle(shard, payload, /)[source]

Handle a WebSocket event, depending on value of type in payload.

Parameters:
  • shard (Shard) – The shard the event arrived on.

  • payload (Dict[str, Any]) – The event payload.

handle_raw(shard, payload, /)[source]

Handles dispatched event.

Parameters:
  • shard (Shard) – The shard that received the event.

  • payload (Dict[str, Any]) – The received event payload.

before_connect(shard, /)[source]

Called before connecting to Stoat.

after_connect(shard, socket, /)[source]

Called when successfully connected to Stoat WebSocket.

Parameters:

socket (HTTPWebSocket) – The connected WebSocket.

EventSubscription

Attributes
Methods
class stoat.EventSubscription[source]

Represents an event subscription.

client

The client that this subscription is tied to.

Type:

Client

id

The ID of the subscription.

Type:

int

callback

The callback.

Type:

MaybeAwaitableFunc[[EventT], None]

remove()[source]

Removes the event subscription.

TemporarySubscription

Methods
class stoat.TemporarySubscription[source]

Represents a temporary event subscription.

cancel()[source]

Cancels the subscription.

TemporarySubscriptionList

Methods
class stoat.TemporarySubscriptionList[source]

Represents a temporary subscription on multiple events.

cancel()[source]

Cancels the subscription.

HTTPOverrideOptions

Methods
class stoat.HTTPOverrideOptions(**kwargs)[source]

Represents overrides for outgoing HTTP request.

All parameters are optional.

The attributes are same as parameters, but may be not present if not set.

Parameters:
  • accept_json (bool) – Whether to explicitly receive JSON or not.

  • adapter (HTTPAdapter) – The adapter to use when sending a HTTP request.

  • base_url (str) – The base API url to use when sending a HTTP request.

  • bot (UndefinedOr[bool]) – Whether the authentication token belongs to bot account. Defaults to HTTPClient.bot.

  • cookie (UndefinedOr[str]) – The cookies to use when performing a request.

  • headers (MultiMapping[str]) – The headers.

  • idempotency_key (Optional[str]) – The idempotency key.

  • json (UndefinedOr[Any]) – The JSON payload to pass in.

  • mfa_ticket (Optional[str]) – The MFA ticket to pass in headers.

  • oauth2 (bool) – Whether the authentication token is an OAuth2 access token. Defaults to HTTPClient.oauth2.

  • token (UndefinedOr[Optional[str]]) – The token to use when requesting the route.

  • user_agent (UndefinedOr[str]) – The user agent to use for HTTP request. Defaults to HTTPClient.user_agent.

populate(**kwargs)[source]

Populate overrides.

update(**kwargs)[source]

Updates overrides.

Parameters:

**kwargs – The parameters to update overrides with.

Returns:

The overrides for chaining.

Return type:

Self

HTTPClient

Methods
class stoat.HTTPClient(token=None, *, adapter=None, base=None, bot=True, cookie=None, max_retries=None, oauth2=False, rate_limiter=UNDEFINED, state, user_agent=None)[source]

Represents a HTTP client sending HTTP requests to the Stoat API.

bot

Whether the token belongs to bot account.

Type:

bool

cookie

The cookie used to make requests. If cf_clearance cookie is present, then it’s used to prevent HTML pages when service is down.

Type:

str

max_retries

How many times to retry requests that received 429 or 502 HTTP status code.

Type:

int

oauth2

Whether the token is an OAuth2 access token.

Type:

bool

rate_limiter

The rate limiter in use.

Type:

Optional[RateLimiter]

state

The state.

Type:

State

token

The token in use. May be empty if not started.

Type:

str

user_agent

The HTTP user agent used when making requests.

Type:

str

await accept_friend_request(user, *, http_overrides=None)[source]

This function is a coroutine.

Accept another user’s friend request.

Fires UserRelationshipUpdateEvent for the current user and user you accepted friend request from.

Note

This can only be used by non-bot accounts.

Parameters:
  • user (ULIDOr[BaseUser]) – The user to accept friend request from.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    IsBot

    Either the current user or user you tried to accept friend request from are bot accounts.

    TooManyPendingFriendRequests

    You sent too many outgoing friend requests.

  • NoEffect – You tried to accept friend request from yourself.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    BlockedOther

    The user you tried to accept friend request from have blocked you.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The user was not found.

  • Conflict – Possible values for type:

    Value

    Reason

    AlreadyFriends

    You’re already friends with user you tried to accept friend request from.

    AlreadySentRequest

    You already sent friend request to this user.

    Blocked

    You have blocked the user you tried to accept friend request from.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The user you accepted friend request from.

Return type:

User

await accept_invite(code, /, *, http_overrides=None)[source]

This function is a coroutine.

Accepts an invite.

Fires either PrivateChannelCreateEvent or ServerCreateEvent for the current user, and fires either GroupRecipientAddEvent or ServerMemberJoinEvent, and MessageCreateEvent (optional in server context), both for all group recipients/server members.

Note

This can only be used by non-bot accounts.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    IsBot

    The current token belongs to bot account.

    TooManyServers

    You’re participating in too many servers.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    Banned

    You’re banned from server.

    GroupTooLarge

    The group exceeded maximum count of recipients.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The invite/channel/server was not found.

  • Conflict – Possible values for type:

    Value

    Reason

    AlreadyInGroup

    The user is already in group.

    AlreadyInServer

    The user is already in server.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The joined server or group.

Return type:

Union[Server, GroupChannel]

await acknowledge_message(channel, message, *, http_overrides=None)[source]

This function is a coroutine.

Marks a message as read.

You must have view_channel to do this.

Fires MessageAckEvent for the current user.

Note

This can only be used by non-bot accounts.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to view the message.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

await acknowledge_policy_changes(*, http_overrides=None)[source]

This function is a coroutine.

Acknowledges pending policy changes.

Added in version 1.2.

Note

This is not supposed to be used by bot accounts.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
await add_group_recipient(channel, /, user, *, http_overrides=None)[source]

This function is a coroutine.

Adds another user to the group.

You must have create_invites to do this.

Fires PrivateChannelCreateEvent for added recipient, and GroupRecipientAddEvent for rest of group recipients.

Note

This can only be used by non-bot accounts.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    The target channel is not group.

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    GroupTooLarge

    The group exceeded maximum count of recipients.

    MissingPermission

    You do not have the proper permissions to add the recipient.

    NotFriends

    You’re not friends with the user you want to add.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel or user were not found.

  • Conflict – Possible values for type:

    Value

    Reason

    AlreadyInGroup

    The user is already in group.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

add_headers(headers, route, /, *, accept_json=True, bot=UNDEFINED, cookie=UNDEFINED, idempotency_key=None, json_body=False, mfa_ticket=None, oauth2=UNDEFINED, overrides=None, token=UNDEFINED, user_agent=UNDEFINED)[source]

Populate headers.

Parameters:
  • headers (CIMultiDict[Any]) – The headers to populate.

  • route (CompiledRoute) – The route.

  • accept_json (bool) – Whether to explicitly receive JSON or not. Defaults to True.

  • bot (UndefinedOr[bool]) – Whether the authentication token belongs to bot account. Defaults to bot.

  • cookie (UndefinedOr[str]) – The cookies to use when performing a request.

  • idempotency_key (Optional[str]) – The idempotency key.

  • json_body (bool) – Whether the request body is JSON.

  • mfa_ticket (Optional[str]) – The MFA ticket to pass in headers.

  • oauth2 (UndefinedOr[bool]) – Whether the token is an OAuth2 access token. Defaults to oauth2.

  • overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • token (UndefinedOr[Optional[str]]) – The token to use when requesting the route.

  • user_agent (UndefinedOr[str]) – The user agent to use for HTTP request. Defaults to user_agent.

Returns:

None if no asynchronous code is required to be executed. An awaitable object otherwise.

Return type:

MaybeAwaitable[None]

await add_reaction_to_message(channel, message, emoji, *, http_overrides=None)[source]

This function is a coroutine.

React to a given message.

You must have react to do this.

Fires MessageReactEvent for all users who can see target channel.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    One of these:

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to react.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/message/custom emoji was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

attach(state=None, /)[source]

Attach this HTTP client to state.

Parameters:

state (Optional[State]) – The state to attach this HTTP client to. Defaults to state if set is None.

Returns:

This HTTP client for chaining.

Return type:

Self

await authorize(client, *, http_overrides=None, scopes, redirect_uri, response_type=('code', 'code'), state=None, code_challenge=None, code_challenge_method=None)[source]

This function is a coroutine.

Authorizes the bot.

Note

This can only be used by non-bot accounts.

Added in version 1.2.

Parameters:
  • client (ULIDOr[BaseBot]) – The bot to authorize.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • scopes (List[Union[OAuth2Scope, str]]) – A list of scopes to authorize.

  • redirect_uri (str) – The URI to redirect to after authorizing the bot.

  • response_type (OAuth2ResponseType) –

    The response type. Defaults to code.

    This specifies what will be received in code parameter in returned URI.

  • state (Optional[str]) –

    The state. Must be between 44 and 127 characters if provided.

    This cannot be specified if response_type is set to code.

  • code_challenge (Optional[str]) – The code challenge.

  • code_challenge_method (Optional[OAuth2CodeChallengeMethod]) – The method of generating OAuth2 code challenge.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    One of these:

    • The bot did not had OAuth2 set up.

    • One of requested scopes is invalid.

    • You tried to request scope that bot does not have access to.

    • Provided redirect URI was not whitelisted.

    • No scope was provided.

    • One of state, code_challenge or code_challenge_method is provided

    and response_type was code. - The provided code challenge was invalid. - The state violated length constraints described above. This won’t be thrown if response_type is not code. - An OAuth2 token was directly requested and the bot was not a public client.

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The bot was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

    InternalError

    Somehow something went wrong during authorizing the bot.

Returns:

The redirect URI with code querystring parameter.

Return type:

str

await ban(server, user, *, http_overrides=None, reason=None)[source]

This function is a coroutine.

Bans an user from the server.

You must have ban_members to do this.

May fire ServerMemberRemoveEvent for banned user and all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server.

  • user (Union[str, BaseUser, BaseMember]) – The user to ban from the server.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • reason (Optional[str]) – The ban reason. Can be only up to 1024 characters long.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CannotRemoveYourself

    You tried to ban yourself.

    FailedValidation

    The payload was invalid.

    InvalidOperation

    You tried to ban server owner.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    NotElevated

    Rank of your top role is higher than rank of top role of user you’re trying to ban.

    MissingPermission

    You do not have the proper permissions to ban members.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/user was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The created ban.

Return type:

Ban

property base[source]

The base URL used for API requests.

Type:

str

await block_user(user, /, *, http_overrides=None)[source]

This function is a coroutine.

Blocks an user.

Fires UserRelationshipUpdateEvent for the current user and blocked user.

Note

This is not supposed to be used by bot accounts.

Parameters:
Raises:
  • NoEffect – You tried to block yourself or someone that you already had blocked.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The user was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The blocked user.

Return type:

User

await bulk_edit_role_ranks(server, ranks, *, http_overrides=None)[source]

This function is a coroutine.

Edits ranks of all roles in bulk.

You must have manage_roles to do this.

Fires ServerRoleRanksUpdateEvent for all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server.

  • ranks (List[ULIDOr[BaseRole]]) –

    A list of roles that should be reordered, where their position in list represents their new rank.

    For example, we have following roles:

    • Owner

    • Administrator

    • Moderator

    • Member

    Passing [member_role_id, moderator_role_id, administrator_role_id, owner_role_id] would result in following hierachy:

    • Member has rank=3

    • Moderator has rank=2

    • Administrator has rank=1

    • Owner has rank=0

    Must contain all roles.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • HTTPException – Possible values for type:

    Value

    InvalidOperation

    One of server roles was not specified in ranks parameter.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    NotElevated

    Rank of your top role is higher than rank of roles you were trying to edit rank of.

    MissingPermission

    You do not have the proper permissions to edit role ranks.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/role was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The server with updated role ranks.

Return type:

Server

await change_email(*, http_overrides=None, email, current_password)[source]

This function is a coroutine.

Sends an email message to change email of current account.

Note

This can only be used by non-bot accounts.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • email (str) – The new email for current account.

  • current_password (str) – The current account password.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    IncorrectData

    The email was invalid.

  • Unauthorized – Possible values for type:

    Value

    Reason

    DisallowedContactSupport

    You’re probably doing something you shouldn’t be.

    InvalidCredentials

    The provided password is incorrect.

    InvalidSession

    The current user token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    EmailFailed

    Failed to send message about changing email.

    InternalError

    Somehow something went wrong during changing email.

await change_password(*, http_overrides=None, new_password, current_password)[source]

This function is a coroutine.

Change the current account password.

Note

This can only be used by non-bot accounts.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • new_password (str) – The new password for this account. Must be at least 8 characters.

  • current_password (str) – The current account password.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CompromisedPassword

    The new password was compromised.

    ShortPassword

    The new password was less than 8 characters long.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidCredentials

    The provided current password is incorrect.

    InvalidSession

    The current user token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    InternalError

    Somehow something went wrong during changing password.

await change_username(*, http_overrides=None, username, current_password)[source]

This function is a coroutine.

Change your username.

Fires UserUpdateEvent for all users who are subscribed to you.

Note

This can only be used by non-bot accounts.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • username (str) – The new username. Must be between 2 and 32 characters and not contain whitespace characters.

  • current_password (str) – The current account password. Must be between 8 and 1024 characters.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidCredentials

    The provided password was incorrect.

    InvalidSession

    The current bot/user token is invalid.

  • Conflict – Possible values for type:

    Value

    Reason

    UsernameTaken

    The username was taken.

  • Ratelimited – Possible values for type:

    Value

    Reason

    DiscriminatorChangeRatelimited

    You was changing username too fast.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly updated user.

Return type:

OwnUser

await cleanup()[source]

This function is a coroutine.

Closes the HTTP session.

await clear_reactions(channel, message, *, http_overrides=None)[source]

This function is a coroutine.

Removes all the reactions from the message.

You must have manage_messages to do this.

Fires MessageUpdateEvent with empty reactions for all users who can see target channel.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to remove all the reactions.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel or message was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await close_channel(channel, silent=None, *, http_overrides=None)[source]

This function is a coroutine.

Deletes a server channel, leaves a group or closes a group.

You must have view_channel to do this. If target channel is server channel, manage_channels is also required.

For DMs, fires ChannelUpdateEvent for the current user and DM recipient. For groups, if the current user is group owner, fires PrivateChannelDeleteEvent for all group recipients (including group owner), otherwise PrivateChannelDeleteEvent is fired for the current user, and GroupRecipientRemoveEvent is fired for rest of group recipients. For server channels, ServerChannelDeleteEvent is fired for all users who could see target channel, and ServerUpdateEvent for all server members.

Parameters:
  • channel (ULIDOr[BaseChannel]) – The channel to close.

  • silent (Optional[bool]) – Whether to not send message when leaving.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to view and/or delete the channel.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await complete_onboarding(username, *, http_overrides=None)[source]

This function is a coroutine.

Complete onboarding by setting up an username, and allow connections to WebSocket.

Parameters:
  • username (str) – The username to use. Must be between 2 and 32 characters and not contain whitespace characters.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    InvalidUsername

    The username is invalid.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    AlreadyOnboarded

    You already completed onboarding.

  • Conflict – Possible values for type:

    Value

    Reason

    UsernameTaken

    The username was taken.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The updated user.

Return type:

OwnUser

await confirm_account_deletion(*, http_overrides=None, token)[source]

This function is a coroutine.

Schedule an account for deletion by confirming the received token.

Fires LogoutEvent for the current user.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • token (str) – The deletion token received.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidToken

    The deletion token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    EmailFailed

    Failed to send mail about changing email.

    InternalError

    Somehow something went wrong during changing email.

await confirm_password_reset(token, *, http_overrides=None, new_password, remove_sessions=None)[source]

This function is a coroutine.

Confirms password reset and change the password.

Parameters:
  • token (str) – The password reset token.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • new_password (str) – The new password for the account. Must be at least 8 characters.

  • remove_sessions (Optional[bool]) – Whether to logout all sessions.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CompromisedPassword

    The provided password was compromised.

    ShortPassword

    The provided password was less than 8 characters long.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidToken

    The provided password reset token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    InternalError

    Somehow something went wrong during confirming password reset.

await create_bot(name, *, http_overrides=None)[source]

This function is a coroutine.

Creates a new Stoat bot.

Note

This can only be used by non-bot accounts.

Parameters:
  • name (str) – The bot name. Must be between 2 and 32 characters and not contain whitespace characters.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The bot’s name exceeded length or contained whitespace.

    InvalidUsername

    The bot’s name had forbidden characters/substrings.

    IsBot

    The current token belongs to bot account.

    ReachedMaximumBots

    The current user has too many bots.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Conflict – Possible values for type:

    Value

    Reason

    UsernameTaken

    The bot user name was taken.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The created bot.

Return type:

Bot

await create_channel_invite(channel, *, http_overrides=None)[source]

This function is a coroutine.

Creates an invite to channel. The destination channel must be a group or server channel.

Note

This can only be used by non-bot accounts.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    The target channel is not group or server channel.

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to create invites in channel.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The target channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The invite that was created.

Return type:

Invite

await create_group(name, *, http_overrides=None, description=None, icon=None, recipients=None, nsfw=None)[source]

This function is a coroutine.

Creates a new group.

Fires PrivateChannelCreateEvent for the current user and all specified recipients.

Note

This can only be used by non-bot accounts.

Parameters:
  • name (str) – The group name. Must be between 1 and 32 characters long.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • description (Optional[str]) – The group description. Can be only up to 1024 characters.

  • icon (Optional[ResolvableResource]) – The group’s icon.

  • recipients (Optional[List[ULIDOr[BaseUser]]]) – The users to create the group with, only up to 49 users. You must be friends with these users.

  • nsfw (Optional[bool]) – To mark the group as NSFW or not.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    GroupTooLarge

    The group exceeded maximum count of recipients.

    MissingPermission

    You do not have the proper permissions to add the recipient.

    NotFriends

    You’re not friends with the users you want to create group with.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    One of recipients was not found, or the provided file for icon was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The new group.

Return type:

GroupChannel

await create_password_ticket(password, *, http_overrides=None, mfa_ticket=None, authenticated=None)[source]

This function is a coroutine.

Creates a new MFA password ticket, or validate an existing one.

Parameters:
  • password (str) – The current account password.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • mfa_ticket (Optional[str]) – The token of existing MFA ticket to validate, if applicable.

  • authenticated (bool) – Whether to create a new MFA password ticket or not.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    DisallowedMFAMethod

    The account has MFA set up.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidCredentials

    The provided password is incorrect.

    InvalidToken

    You was not authenticated nor provided mfa_ticket parameter.

  • NotFound – Possible values for type:

    Value

    Reason

    UnknownUser

    The account was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    OperationFailed

    You was authenticated but provided mfa_ticket parameter.

Returns:

The MFA ticket created.

Return type:

MFATicket

await create_recovery_code_ticket(recovery_code, *, http_overrides=None, mfa_ticket=None, authenticated=None)[source]

This function is a coroutine.

Creates a new MFA recovery code ticket, or validate an existing one.

Parameters:
  • recovery_code (str) – The recovery code in format xxxx-yyyy.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • mfa_ticket (Optional[str]) – The token of existing MFA ticket to validate, if applicable.

  • authenticated (bool) – Whether to create a new MFA password ticket or not.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    DisallowedMFAMethod

    The account has MFA set up.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidToken

    One of these:

    • You was not authenticated nor provided mfa_ticket parameter.

    • The provided recovery code is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    UnknownUser

    The account was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    OperationFailed

    You was authenticated but provided mfa_ticket parameter.

Returns:

The MFA ticket created.

Return type:

MFATicket

await create_role(server, *, http_overrides=None, name, rank=None)[source]

This function is a coroutine.

Creates a new server role.

You must have manage_roles to do this.

Fires RawServerRoleUpdateEvent for all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server to create role in.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • name (str) – The role name. Must be between 1 and 32 characters long.

  • rank (Optional[int]) – The ranking position. The smaller value is, the more role takes priority.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    TooManyRoles

    The server has too many roles than allowed on this instance.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    NotElevated

    Rank of your top role is higher than rank of role you’re trying to create.

    MissingPermission

    You do not have the proper permissions to create role in this server.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/role was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The role created in server.

Return type:

Role

await create_server(name, *, http_overrides=None, description=None, nsfw=None)[source]

This function is a coroutine.

Create a new server.

Fires ServerCreateEvent for the current user.

Note

This can only be used by non-bot accounts.

Parameters:
  • name (str) – The server name. Must be between 1 and 32 characters long.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • description (Optional[str]) – The server description. Can be only up to 1024 characters.

  • nsfw (Optional[bool]) – Whether this server is age-restricted.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    IsBot

    The current token belongs to bot account.

    TooManyChannels

    The instance was incorrectly configured. (?)

    TooManyServers

    You’re in too many servers than the instance allows.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The created server.

Return type:

Server

await create_server_category(server, title, *, http_overrides=None, channels)[source]

This function is a coroutine.

Create a new category within server.

You must have manage_channels to do this.

Fires ServerUpdateEvent for all server members.

Added in version 1.2.

Parameters:
  • server (ULIDOr[BaseServer]) – The server to create category in.

  • title (str) – The category name. Must be between 1 and 32 characters.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • channels (List[ULIDOr[ServerChannel]]) – The channel’s IDs inside this category.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    TooManyCategories

    The server has too many categories than allowed on this instance.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to create categories.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The category created in server.

Return type:

Category

await create_server_channel(server, *, http_overrides=None, type=None, name, description=None, nsfw=None, voice=None)[source]

This function is a coroutine.

Create a new text or voice channel within server.

You must have manage_channels to do this.

Fires ServerChannelCreateEvent for all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server to create channel in.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • type (Optional[ChannelType]) – The channel type. Defaults to text if not provided.

  • name (str) – The channel name. Must be between 1 and 32 characters.

  • description (Optional[str]) – The channel description. Can be only up to 1024 characters.

  • nsfw (Optional[bool]) – To mark channel as NSFW or not.

  • voice (Optional[ChannelVoiceMetadata]) –

    The voice-specific metadata for this channel.

    Added in version 1.2.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    TooManyChannels

    The server has too many channels than allowed on this instance.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to create channels in server.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The channel created in server.

Return type:

ServerChannel

await create_server_emoji(server, *, http_overrides=None, name, nsfw=None, image)[source]

This function is a coroutine.

Creates an emoji in server.

You must have manage_customization to do this.

Fires EmojiCreateEvent for all server members.

Note

Prior to API v0.8.4, this could only be used by non-bot accounts.

Parameters:
  • server (ULIDOr[BaseServer]) – The server to create emoji in.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • name (str) – The emoji name. Must be between 1 and 32 chars long. Can only contain ASCII digits, underscore and lowercase letters.

  • nsfw (Optional[bool]) – Whether the emoji is NSFW or not. Defaults to False.

  • image (ResolvableResource) – The emoji data.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    IsBot

    The current token belongs to bot account. Only applicable to instances running API whose version is lower than v0.8.3.

    TooManyEmoji

    The server has too many emojis than allowed on this instance.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to create emojis in server.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/file was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The created emoji.

Return type:

ServerEmoji

await create_totp_ticket(totp_code, *, http_overrides=None, mfa_ticket=None, authenticated=None)[source]

This function is a coroutine.

Creates a new MFA password ticket, or validate an existing one.

Parameters:
  • totp_code (str) – The TOTP code, in format 123456.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • mfa_ticket (Optional[str]) – The token of existing MFA ticket to validate, if applicable.

  • authenticated (bool) – Whether to create a new MFA password ticket or not.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    DisallowedMFAMethod

    The account does not have MFA set up.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidCredentials

    The provided password is incorrect.

    InvalidToken

    You was not authenticated nor provided mfa_ticket parameter.

  • NotFound – Possible values for type:

    Value

    Reason

    UnknownUser

    The account was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    OperationFailed

    You was authenticated and provided mfa_ticket parameter.

Returns:

The MFA ticket created.

Return type:

MFATicket

await create_webhook(channel, *, http_overrides=None, name, avatar=None)[source]

This function is a coroutine.

Creates a webhook which 3rd party platforms can use to send.

You must have manage_webhooks permission to do this.

Fires WebhookCreateEvent for all users who can see target channel.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    The channel was not type of group or text.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to create a webhook.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/file was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The created webhook.

Return type:

Webhook

await delete_account(*, http_overrides=None, mfa_ticket)[source]

This function is a coroutine.

Schedules account deletion.

Note

This can only be used by non-bot accounts.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • mfa_ticket (str) – The valid MFA ticket token.

Raises:
  • Forbidden – Possible values for type:

    Value

    Reason

    InvalidToken

    The provided MFA ticket token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    EmailFailed

    Failed to send message about scheduling account deletion.

    InternalError

    Somehow something went wrong during scheduling account deletion.

await delete_bot(bot, /, *, http_overrides=None)[source]

This function is a coroutine.

Deletes a bot.

Fires UserUpdateEvent for all users who are subscribed to bot user.

Note

This can only be used by non-bot accounts.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The bot was not found, or the current user does not own bot.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await delete_emoji(emoji, *, http_overrides=None)[source]

This function is a coroutine.

Deletes an emoji.

You must have manage_customization to do this if you do not own the emoji, unless it was detached (already deleted).

May fire EmojiDeleteEvent for all server members.

Note

If deleting detached emoji, this will successfully return.

Note

Prior to API v0.8.4, this could only be used by non-bot accounts.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    IsBot

    The current token belongs to bot account. Only applicable to instances running API whose version is lower than v0.8.3.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to delete an emoji.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The emoji/server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await delete_invite(code, /, *, http_overrides=None)[source]

This function is a coroutine.

Deletes an invite.

You must have manage_server if deleting server invite.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to delete this invite.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The invite was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await delete_message(channel, message, *, http_overrides=None)[source]

This function is a coroutine.

Deletes the message in a channel.

You must have manage_messages to do this if message is not yours.

Fires MessageDeleteEvent for all users who can see target channel.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to delete the message.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel or message was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await delete_messages(channel, messages, *, http_overrides=None)[source]

This function is a coroutine.

Deletes multiple messages.

You must have manage_messages to do this regardless whether you authored the message or not.

Fires MessageDeleteBulkEvent for all users who can see target channel.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    One of provided message IDs was invalid or message was at least 1 week old.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to delete messages.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The target channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await delete_role(server, role, *, http_overrides=None)[source]

This function is a coroutine.

Deletes a server role.

You must have manage_roles to do this.

Fires ServerRoleDeleteEvent for all server members.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    NotElevated

    Rank of your top role is higher than rank of role you’re trying to delete.

    MissingPermission

    You do not have the proper permissions to delete role.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/role was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await delete_server(server, /, *, http_overrides=None)[source]

This function is a coroutine.

Deletes a server if owner, or leaves otherwise.

Fires ServerDeleteEvent (if owner) or ServerMemberRemoveEvent for all server members.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await delete_server_category(server, category, *, http_overrides=None)[source]

This function is a coroutine.

Deletes a category in server.

You must have manage_channels to do this.

Fires ServerUpdateEvent for all server members.

Added in version 1.2.

Parameters:
  • server (ULIDOr[BaseServer]) – The server the category is in.

  • category (ULIDOr[Category]) – The category to delete.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    TooManyCategories

    The server has too many categories than allowed on this instance.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to delete categories.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

    UnknownCategory

    The category was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await delete_webhook(webhook, *, http_overrides=None, token=None)[source]

This function is a coroutine.

Deletes a webhook.

If webhook token wasn’t given, the library will attempt delete webhook with current bot/user token.

You must have manage_webhooks to do this if token parameter is None or missing.

Fires WebhookDeleteEvent for all users who can see webhook channel.

Parameters:
  • webhook (ULIDOr[BaseWebhook]) – The webhook to delete.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • token (Optional[str]) – The webhook token.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

    NotAuthenticated

    The webhook token is invalid. Only applicable when token is provided.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The webhook was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await deny_friend_request(user, *, http_overrides=None)[source]

This function is a coroutine.

Denies another user’s friend request.

Fires UserRelationshipUpdateEvent for the current user and user you denide friend request from.

Note

This can only be used by non-bot accounts.

Parameters:
  • user (ULIDOr[BaseUser]) – The user to deny friend request from.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    IsBot

    Either the current user or user you tried to deny friend request from are bot accounts.

  • NoEffect – You tried to deny friend request from user you had no friend request sent from/to.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The user was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The user you denied friend request from.

Return type:

User

await disable_account(*, http_overrides=None, mfa_ticket)[source]

This function is a coroutine.

Disable an account.

Fires LogoutEvent for the current user.

Note

This can only be used by non-bot accounts.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • mfa_ticket (str) – The valid MFA ticket token.

Raises:
  • Forbidden – Possible values for type:

    Value

    Reason

    InvalidToken

    The provided MFA ticket token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    InternalError

    Somehow something went wrong during disabling account.

await disable_totp_mfa(*, http_overrides=None, mfa_ticket)[source]

This function is a coroutine.

Disables TOTP-based MFA for this account.

Note

This can only be used by non-bot accounts.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • mfa_ticket (str) – The valid MFA ticket token.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

    InvalidToken

    The provided MFA ticket token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    InternalError

    Somehow something went wrong during disabling TOTP-based MFA.

await edit_bot(bot, *, http_overrides=None, name=UNDEFINED, public=UNDEFINED, analytics=UNDEFINED, interactions_url=UNDEFINED, oauth2=UNDEFINED, reset_oauth2_client_secret=False, reset_token=False)[source]

This function is a coroutine.

Edits the bot.

Fires UserUpdateEvent for all users who are subscribed to bot user.

Parameters:
  • bot (ULIDOr[BaseBot]) – The bot to edit.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • name (UndefinedOr[str]) – The new bot name. Must be between 2 and 32 characters and not contain whitespace characters.

  • public (UndefinedOr[bool]) – Whether the bot should be public (could be invited by anyone).

  • analytics (UndefinedOr[bool]) – Whether to allow Stoat collect analytics about the bot.

  • interactions_url (UndefinedOr[Optional[str]]) – The new bot interactions URL. For now, this parameter is reserved and does not do anything.

  • oauth2 (UndefinedOr[Optional[BotOAuth2Edit]]) – The new bot’s OAuth2 settings.

  • reset_oauth2_client_secret (bool) – Whether to reset bot’s OAuth2 client secret. The new client secret can be accessed via BotOAuth2.secret.

  • reset_token (bool) – Whether to reset bot token. The new token can be accessed via Bot.token.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The bot’s name exceeded length or contained whitespace.

    InvalidUsername

    The bot’s name had forbidden characters/substrings.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The bot was not found, or the current user does not own bot.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The updated bot.

Return type:

Bot

await edit_channel(channel, *, http_overrides=None, name=UNDEFINED, description=UNDEFINED, owner=UNDEFINED, icon=UNDEFINED, nsfw=UNDEFINED, archived=UNDEFINED, voice=UNDEFINED, default_permissions=UNDEFINED)[source]

This function is a coroutine.

Edits the channel.

You must have manage_channels to do this.

Fires ChannelUpdateEvent for all users who still can see target channel, optionally ServerChannelCreateEvent for all users who now can see target server channel, and optionally ChannelDeleteEvent for users who no longer can see target server channel.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    InvalidOperation

    The target channel was not group/text/voice channel.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to edit the channel.

    NotOwner

    You do not own the group.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

    NotInGroup

    The new owner was not in group.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly updated channel.

Return type:

Channel

await edit_member(server, member, *, http_overrides=None, nick=UNDEFINED, avatar=UNDEFINED, roles=UNDEFINED, timeout=UNDEFINED, can_publish=UNDEFINED, can_receive=UNDEFINED, voice=UNDEFINED)[source]

This function is a coroutine.

Edits a member.

Fires ServerMemberUpdateEvent for all server members, and optionally fires multiple/single ServerChannelCreateEvent / ChannelDeleteEvent events for target member if roles parameter is provided.

For Livekit instances:

Parameters:
  • server (BaseServer) – The server.

  • member (Union[str, BaseUser, BaseMember]) – The member.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • nick (UndefinedOr[Optional[str]]) –

    The member’s new nick. Use None to remove the nickname.

    To provide this, you must have manage_nicknames if changing other member’s nick. Otherwise, change_nickname is required instead.

  • avatar (UndefinedOr[Optional[ResolvableResource]]) –

    The member’s new avatar. Use None to remove the avatar.

    You can only change your own server avatar.

    You must have change_avatar to provide this.

  • roles (UndefinedOr[Optional[List[ULIDOr[BaseRole]]]]) –

    The member’s new list of roles. This replaces the roles.

    You must have assign_roles to provide this.

  • timeout (UndefinedOr[Optional[Union[datetime, timedelta, float, int]]]) –

    The duration/date the member’s timeout should expire, or None to remove the timeout.

    This must be a timezone-aware datetime object. Consider using stoat.utils.utcnow().

    If the member has timeout_members, this will throw a NonElevated error.

    You must have timeout_members to provide this.

  • can_publish (UndefinedOr[Optional[bool]]) –

    Whether the member should send voice data.

    You must have mute_members to provide this.

  • can_receive (UndefinedOr[Optional[bool]]) –

    Whether the member should receive voice data.

    You must have deafen_members to provide this.

  • voice (UndefinedOr[Optional[ULIDOr[Union[TextChannel, VoiceChannel]]]]) –

    The voice channel to move the member to.

    You must have move_members to provide this.

    Changed in version 1.3: Members can be kicked from the current voice channel.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CannotTimeoutYourself

    You tried to time out yourself.

    LivekitUnavailable

    The voice server is unavailable. Only applicable to instances using Livekit.

    NotAVoiceChannel

    The channel passed in voice parameter was not voice-like channel. Only applicable to instances using Livekit.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    IsElevated

    The member has timeout_members, and as such cannot be timed out.

    MissingPermission

    You do not have the proper permissions to edit this member.

    NotElevated

    Ranking of one of roles you tried to add is lower than ranking of your top role.

  • NotFound – Possible values for type:

    Value

    Reason

    InvalidRole

    One of provided roles passed in roles parameter was not found.

    NotFound

    The server/member was not found.

    UnknownChannel

    The channel passed in voice parameter was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

    InternalError

    Somehow something went wrong during editing member.

Returns:

The newly updated member.

Return type:

Member

await edit_message(channel, message, *, http_overrides=None, content=UNDEFINED, embeds=UNDEFINED)[source]

This function is a coroutine.

Edits a message in channel.

Fires MessageUpdateEvent and optionally MessageAppendEvent, both for all users who can see target channel.

Parameters:
  • channel (ULIDOr[TextableChannel]) – The channel the message is in.

  • message (ULIDOr[BaseMessage]) – The message to edit.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • content (UndefinedOr[str]) – The new content to replace the message with. Must be between 1 and 2000 characters long.

  • embeds (UndefinedOr[List[SendableEmbed]]) –

    The new embeds to replace the original with. Must be a maximum of 10. To remove all embeds [] should be passed.

    You must have send_embeds to provide this.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    PayloadTooLarge

    The message was too large.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    CannotEditMessage

    The message you tried to edit isn’t yours.

    MissingPermission

    You do not have the proper permissions to send messages.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/message/file was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly edited message.

Return type:

Message

await edit_my_user(*, http_overrides=None, display_name=UNDEFINED, avatar=UNDEFINED, status=UNDEFINED, profile=UNDEFINED, badges=UNDEFINED, flags=UNDEFINED)[source]

This function is a coroutine.

Edits the current user.

Fires UserUpdateEvent for all users who are subscribed to you.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • display_name (UndefinedOr[Optional[str]]) – The new display name. Must be between 2 and 32 characters and not contain zero width space, newline or carriage return characters.

  • avatar (UndefinedOr[Optional[ResolvableResource]]) – The new avatar. Could be None to remove avatar.

  • status (UndefinedOr[UserStatusEdit]) – The new user status.

  • profile (UndefinedOr[UserProfileEdit]) – The new user profile data. This is applied as a partial.

  • badges (UndefinedOr[UserBadges]) – The new user badges. You must be privileged user to provide this.

  • flags (UndefinedOr[UserFlags]) – The new user flags. You must be privileged user to provide this.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    NotPrivileged

    You tried to edit fields that require you to be privileged.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly updated authenticated user.

Return type:

OwnUser

await edit_role(server, role, *, http_overrides=None, name=UNDEFINED, color=UNDEFINED, hoist=UNDEFINED, rank=UNDEFINED)[source]

This function is a coroutine.

Edits a role.

You must have manage_roles to do this.

Fires RawServerRoleUpdateEvent for all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server the role in.

  • role (ULIDOr[BaseRole]) – The role to edit.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • name (UndefinedOr[str]) – The new role name. Must be between 1 and 32 characters long.

  • color (UndefinedOr[Optional[str]]) – The new role color. Must be a valid CSS color.

  • hoist (UndefinedOr[bool]) – Whether this role should be displayed separately.

  • rank (UndefinedOr[int]) –

    The new ranking position. The smaller value is, the more role takes priority.

    Deprecated since version 1.2: Use bulk_edit_role_ranks() instead.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    NotElevated

    One of these:

    • Rank of your top role is higher than rank of role you’re trying to edit.

    • Rank of your top role is higher than rank you’re trying to set for this role.

    MissingPermission

    You do not have the proper permissions to edit role.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/role was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly updated role.

Return type:

Role

await edit_server(server, *, http_overrides=None, mfa_ticket=None, name=UNDEFINED, description=UNDEFINED, icon=UNDEFINED, banner=UNDEFINED, categories=UNDEFINED, system_messages=UNDEFINED, flags=UNDEFINED, discoverable=UNDEFINED, analytics=UNDEFINED, owner=UNDEFINED)[source]

This function is a coroutine.

Edits a server.

To provide any of parameters below (except for categories, discoverable and flags), you must have manage_server.

Fires ServerUpdateEvent for all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server to edit.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • mfa_ticket (Optional[str]) – The valid MFA ticket token. Must be provided if owner is provided as well.

  • name (UndefinedOr[str]) – The new server name. Must be between 1 and 32 characters long.

  • description (UndefinedOr[Optional[str]]) – The new server description. Can be only up to 1024 characters.

  • icon (UndefinedOr[Optional[ResolvableResource]]) – The new server icon.

  • banner (UndefinedOr[Optional[ResolvableResource]]) – The new server banner.

  • categories (UndefinedOr[Optional[List[Category]]]) –

    The new server categories structure.

    You must have manage_channels.

    Deprecated since version 1.2: Due to categories rework in API v0.8.5, this parameter will be ignored on newer API versions, and was deprecated in favor of these dedicated methods:

  • system_messages (UndefinedOr[Optional[SystemMessageChannels]]) – The new system message channels configuration.

  • flags (UndefinedOr[ServerFlags]) – The new server flags. You must be a privileged user to provide this.

  • discoverable (UndefinedOr[bool]) –

    Whether this server is public and should show up on Stoat Discover.

    The new server flags. You must be a privileged user to provide this.

  • analytics (UndefinedOr[bool]) –

    Whether analytics should be collected for this server. Must be enabled in order to show up on Stoat Discover.

  • owner (UndefinedOr[Union[str, BaseUser, BaseMember]]) –

    The member to transfer ownership to.

    You must own the server, or be a privileged user to provide this.

    The target user must be not a bot.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    InvalidOperation

    One of these:

    • More than 2 categories had same channel.

    • You tried to transfer ownership to bot.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidCredentials

    The provided MFA ticket was invalid.

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to edit server details.

    NotOwner

    You provided owner parameter but you do not own the server or are not a privileged user.

    NotPrivileged

    You provided discoverable or flags parameters but you are not a privileged user.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    One of these:

    • The server was not found.

    • One of channels in one of provided categories was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly updated server.

Return type:

Server

await edit_server_category(server, category, *, http_overrides=None, title=UNDEFINED, channels=UNDEFINED, default_permissions=UNDEFINED)[source]

This function is a coroutine.

Edits a category in server.

You must have manage_channels to do this.

Fires ServerUpdateEvent for all server members.

Added in version 1.2.

Parameters:
  • server (ULIDOr[BaseServer]) – The server the category is in.

  • category (ULIDOr[Category]) – The category to edit.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • title (UndefinedOr[str]) – The new category title.

  • channels (UndefinedOr[List[ULIDOr[ServerChannel]]]) – The channel’s IDs inside this category.

  • default_permissions (UndefinedOr[None]) – To remove default permissions or not.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    TooManyCategories

    The server has too many categories than allowed on this instance.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to edit categories.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/ban was not found.

    UnknownCategory

    The category was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly updated category.

Return type:

Category

await edit_session(session, *, http_overrides=None, friendly_name)[source]

This function is a coroutine.

Edits a session.

Parameters:
  • session (ULIDOr[PartialSession]) – The session to edit.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • friendly_name (str) – The new user-friendly client name. Because of Authifier limitation, this is not UndefinedOr.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    One of these:

    • The current user token is invalid.

    • The session you tried to edit didn’t belong to your account.

  • NotFound – Possible values for type:

    Value

    Reason

    UnknownUser

    The session was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

Returns:

The newly updated session.

Return type:

PartialSession

await edit_user(user, *, http_overrides=None, display_name=UNDEFINED, avatar=UNDEFINED, status=UNDEFINED, profile=UNDEFINED, badges=UNDEFINED, flags=UNDEFINED)[source]

This function is a coroutine.

Edits an user.

Fires UserUpdateEvent for all users who are subscribed to target user.

Parameters:
  • user (ULIDOr[BaseUser]) – The user to edit.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • display_name (UndefinedOr[Optional[str]]) – The new display name. Must be between 2 and 32 characters and not contain zero width space, newline or carriage return characters.

  • avatar (UndefinedOr[Optional[ResolvableResource]]) – The new avatar. Could be None to remove avatar.

  • status (UndefinedOr[UserStatusEdit]) – The new user status.

  • profile (UndefinedOr[UserProfileEdit]) – The new user profile data. This is applied as a partial.

  • badges (UndefinedOr[UserBadges]) – The new user badges. You must be privileged user to provide this.

  • flags (UndefinedOr[UserFlags]) – The new user flags. You must be privileged user to provide this.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    NotPrivileged

    You tried to edit fields that require you to be privileged, or tried to edit bot you do not own.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly updated user.

Return type:

User

await edit_user_settings(partial, edited_at=None, *, http_overrides=None)[source]

This function is a coroutine.

Edits the current user settings.

Fires UserSettingsUpdateEvent for the current user.

Note

This is not supposed to be used by bot accounts.

Parameters:
  • partial (Dict[str, str]) – The dict to merge into the current user settings.

  • edited_at (Optional[Union[datetime, int]]) – The revision.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
await edit_webhook(webhook, *, http_overrides=None, token=None, name=UNDEFINED, avatar=UNDEFINED, permissions=UNDEFINED)[source]

This function is a coroutine.

Edits a webhook.

If webhook token wasn’t given, the library will attempt edit webhook with current bot/user token.

You must have manage_webhooks to do this if token parameter is None or missing.

Fires WebhookUpdateEvent for all users who can see webhook channel.

Parameters:
  • webhook (ULIDOr[BaseWebhook]) – The webhook to edit.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • token (Optional[str]) – The webhook token.

  • name (UndefinedOr[str]) – The new webhook name. Must be between 1 and 32 chars long.

  • avatar (UndefinedOr[Optional[ResolvableResource]]) – The new webhook avatar.

  • permissions (UndefinedOr[Permissions]) – The new webhook permissions.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

    NotAuthenticated

    The webhook token is invalid. Only applicable when token is provided.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The webhook/file was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly updated webhook.

Return type:

Webhook

await enable_totp_mfa(response, /, *, http_overrides=None)[source]

This function is a coroutine.

Enables TOTP-based MFA for this account.

Note

This can only be used by non-bot accounts.

Parameters:
  • response (MFAResponse) – The password, TOTP or recovery code to verify. Currently can be only ByTOTP.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

    InvalidToken

    The provided TOTP code is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    InternalError

    Somehow something went wrong during enabling TOTP-based MFA.

    OperationFailed

    Something went wrong.

await exchange_token(*, http_overrides=None, client, client_secret=None, code=None, refresh_token=None, grant_type, code_verifier=None)[source]

This function is a coroutine.

Exchanges an access token, or refresh an existing one.

Added in version 1.2.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • client (ULIDOr[BaseBot]) – The bot to exchange token for.

  • client_secret (Optional[str]) – The client secret. Required if grant_type is authorization_code.

  • grant_type (OAuth2GrantType) – The grant type. Only authorization_code is currently supported.

  • code (Optional[str]) – The code to exchange.

  • refresh_token (Optional[str]) – The refresh token to exchange access token from.

  • code_verifier (Optional[str]) – The code verifier.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    One of these:

    • The provided “code” was an access token.

    • grant_type was set to implicit.

  • Unauthorized – Possible values for type:

    Value

    Reason

    NotAuthenticated

    One of these:

    • The code was tamped.

    • The provided client secret did not match bot’s client secret.

    • The code does not belong to provided client.

    • The code expired.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The bot was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    InternalError

    Somehow something went wrong during authorizing the bot.

Returns:

The OAuth2 access token.

Return type:

OAuth2AccessToken

await execute_webhook(webhook, token, content=None, *, http_overrides=None, nonce=None, attachments=None, replies=None, embeds=None, masquerade=None, interactions=None, silent=None, mention_everyone=None, mention_online=None)[source]

This function is a coroutine.

Executes a webhook.

The webhook must have send_messages to do this.

If message mentions “@everyone” or “@online”, the webhook must have mention_everyone to do that.

If message mentions any roles, the webhook must have mention_roles to do that.

Fires MessageCreateEvent and optionally MessageAppendEvent, both for all users who can see target channel.

Parameters:
  • webhook (ULIDOr[BaseWebhook]) – The webhook to execute.

  • token (str) – The webhook token.

  • content (Optional[str]) – The message content.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • nonce (Optional[str]) – The message nonce.

  • attachments (Optional[List[ResolvableResource]]) –

    The attachments to send the message with.

    Webhook must have upload_files to provide this.

  • replies (Optional[List[Union[Reply, ULIDOr[BaseMessage]]]]) – The message replies.

  • embeds (Optional[List[SendableEmbed]]) –

    The embeds to send the message with.

    Webhook must have send_embeds to provide this.

  • masquerade (Optional[MessageMasquerade]) –

    The masquerade for the message.

    Webhook must have use_masquerade to provide this.

    If MessageMasquerade.color is provided, manage_roles is also required.

  • interactions (Optional[MessageInteractions]) –

    The message interactions.

    If MessageInteractions.reactions is provided, react is required.

  • silent (Optional[bool]) – Whether to suppress notifications or not.

  • mention_everyone (Optional[bool]) – Whether to mention all users who can see the channel. This cannot be mixed with mention_online parameter.

  • mention_online (Optional[bool]) – Whether to mention all users who are online and can see the channel. This cannot be mixed with mention_everyone parameter.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    EmptyMessage

    The message was empty.

    FailedValidation

    The payload was invalid.

    InvalidFlagValue

    Both mention_everyone and mention_online were True.

    InvalidOperation

    The passed nonce was already used. One of MessageInteractions.reactions elements was invalid.

    InvalidProperty

    MessageInteractions.restrict_reactions was True but MessageInteractions.reactions was empty.

    PayloadTooLarge

    The message was too large.

    TooManyAttachments

    You provided more attachments than allowed on this instance.

    TooManyEmbeds

    You provided more embeds than allowed on this instance.

    TooManyReplies

    You were replying to more messages than was allowed on this instance.

  • Unauthorized – Possible values for type:

    Value

    Reason

    NotAuthenticated

    The webhook token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    The webhook do not have the proper permissions to send messages.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/file/reply/webhook was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

    InternalError

    Somehow something went wrong during message creation.

Returns:

The message that was sent.

Return type:

Message

await generate_recovery_codes(*, http_overrides=None, mfa_ticket)[source]

This function is a coroutine.

Regenerates recovery codes for this account.

Note

This can only be used by non-bot accounts.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • mfa_ticket (str) – The valid MFA ticket token.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

    InvalidToken

    The provided MFA ticket token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    InternalError

    Somehow something went wrong during regenerating recovery codes.

Returns:

The regenerated recovery codes.

Return type:

List[str]

await generate_totp_secret(*, http_overrides=None, mfa_ticket)[source]

This function is a coroutine.

Generates a TOTP secret.

Note

This can only be used by non-bot accounts.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • mfa_ticket (str) – The valid MFA ticket token.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

    InvalidToken

    The provided MFA ticket token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    InternalError

    Somehow something went wrong during enabling TOTP-based MFA.

    OperationFailed

    Something went wrong.

Returns:

The TOTP secret.

Return type:

str

await get_account(*, http_overrides=None)[source]

This function is a coroutine.

Retrieve account information.

Note

This can only be used by non-bot accounts.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    InternalError

    Somehow something went wrong during retrieving account.

Returns:

The retrieved account.

Return type:

PartialAccount

await get_authorized_bots(*, http_overrides=None)[source]

This function is a coroutine.

Retrieve bots that you have authorized.

Added in version 1.2.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
await get_bans(server, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves all bans on a server.

You must have ban_members to do this.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to retrieve all bans.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/ban was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The ban entries.

Return type:

List[Ban]

await get_bot(bot, /, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves the bot with the given ID.

The bot must be owned by you.

Note

This can only be used by non-bot accounts.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The bot was not found, or the current user does not own bot.

Returns:

The retrieved bot.

Return type:

Bot

await get_channel(channel, /, *, http_overrides=None)[source]

This function is a coroutine.

Fetch a Channel with the specified ID.

You must have view_channel to do this.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to view the channel.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

Returns:

The retrieved channel.

Return type:

Channel

await get_channel_webhooks(channel, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves all webhooks in a channel.

You must have manage_webhooks permission to do this.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to view webhooks that belong to this channel.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The webhooks for this channel.

Return type:

List[Webhook]

await get_default_avatar(user, *, http_overrides=None)[source]

This function is a coroutine.

Return a default user avatar based on the given ID.

Parameters:
  • user (ULIDOr[BaseUser]) – The user to retrieve default avatar of.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Returns:

The image in PNG format.

Return type:

bytes

await get_emoji(emoji, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves a custom emoji.

Parameters:
Raises:

NotFound – Possible values for type:

Value

Reason

NotFound

The emoji was not found.

Returns:

The retrieved emoji.

Return type:

Emoji

await get_group_recipients(channel, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves all recipients who are part of this group.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    The target channel is not group.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to view the group.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The target channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The group recipients.

Return type:

List[User]

await get_invite(code, /, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves an invite.

Parameters:
Raises:

NotFound – Possible values for type:

Value

Reason

NotFound

The invite/server/user was not found.

Returns:

The invite retrieved.

Return type:

PublicInvite

await get_me(*, http_overrides=None)[source]

This function is a coroutine.

Retrieves your user data.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:

Unauthorized – Possible values for type:

Value

Reason

InvalidSession

The current bot/user token is invalid.

Returns:

The retrieved user.

Return type:

OwnUser

await get_member(server, member, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves a member.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The retrieved member.

Return type:

Member

await get_member_list(server, *, http_overrides=None, exclude_offline=None)[source]

This function is a coroutine.

Retrieves server member list.

Parameters:
  • server (ULIDOr[BaseServer]) – The server.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • exclude_offline (Optional[bool]) – Whether to exclude offline users.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The member list.

Return type:

MemberList

await get_members(server, *, http_overrides=None, exclude_offline=None)[source]

This function is a coroutine.

Retrieves all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • exclude_offline (Optional[bool]) – Whether to exclude offline users.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The retrieved members.

Return type:

List[Member]

await get_message(channel, message, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves a message.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to view the channel.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/message was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The retrieved message.

Return type:

Message

await get_messages(channel, *, http_overrides=None, limit=None, before=None, after=None, sort=None, nearby=None, populate_users=None)[source]

This function is a coroutine.

Retrieve message history of a textable channel.

You must have read_message_history to do this.

Parameters:
  • channel (ULIDOr[TextableChannel]) – The channel to retrieve messages from.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • limit (Optional[int]) –

    The maximum number of messages to get. Must be between 1 and 100. Defaults to 50.

    If nearby is provided, then this is (limit + 2).

  • before (Optional[ULIDOr[BaseMessage]]) – The message before which messages should be fetched.

  • after (Optional[ULIDOr[BaseMessage]]) – The message after which messages should be fetched.

  • sort (Optional[MessageSort]) – The message sort direction. Defaults to MessageSort.latest

  • nearby (Optional[ULIDOr[BaseMessage]]) –

    The message to search around.

    Providing this parameter will discard before, after and sort parameters.

    It will also take half of limit rounded as the limits to each side. It also fetches the message specified.

  • populate_users (bool) – Whether to populate user (and member, if server channel) objects.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to read the message history.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The messages retrieved.

Return type:

List[Message]

await get_mfa_methods(*, http_overrides=None)[source]

This function is a coroutine.

Retrieves available MFA methods.

Note

This can only be used by non-bot accounts.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    InternalError

    Somehow something went wrong during retrieving available MFA methods.

Returns:

The available MFA methods.

Return type:

List[MFAMethod]

await get_mutuals_with(user, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves a list of mutual friends and servers with another user.

You must have view_profile to do this.

Parameters:
  • user (ULIDOr[BaseUser]) – The user to retrieve mutuals with.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    You tried to retrieve mutuals with yourself.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The user was not found.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingUserPermission

    You do not have the proper permissions to view user profile.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The found mutuals.

Return type:

Mutuals

await get_owned_bots(*, http_overrides=None)[source]

This function is a coroutine.

Retrieves all bots owned by you.

Note

This can only be used by non-bot accounts.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
Returns:

The owned bots.

Return type:

List[Bot]

await get_possible_oauth2_authorization(client, *, http_overrides=None, scopes, redirect_uri, response_type=('code', 'code'), state=None, code_challenge=None, code_challenge_method=None)[source]

This function is a coroutine.

Retrieve information about possible OAuth2 authorization.

Added in version 1.2.

Parameters:
  • client (ULIDOr[BaseBot]) – The bot to retrieve possible OAuth2 authorization for.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • scopes (List[Union[OAuth2Scope, str]]) – A list of scopes.

  • redirect_uri (str) – The redirect URI.

  • response_type (OAuth2ResponseType) – The response type. Defaults to code.

  • state (Optional[str]) – The state.

  • code_challenge (Optional[str]) – The code challenge.

  • code_challenge_method (Optional[OAuth2CodeChallengeMethod]) – The method of generating OAuth2 code challenge.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    One of these:

    • The bot did not had OAuth2 set up.

    • Provided redirect URI was not whitelisted.

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The bot was not found.

Returns:

The retrieved possible OAuth2 authorization.

Return type:

PossibleOAuth2Authorization

await get_private_channels(*, http_overrides=None)[source]

This function is a coroutine.

Retrieves all opened DMs, groups the current user in, and “Saved Notes” channel.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
Returns:

The private channels.

Return type:

List[Union[SavedMessagesChannel, DMChannel, GroupChannel]]

await get_public_bot(bot, /, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves the public bot with the given ID.

Note

This can only be used by non-bot accounts.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The bot was not found, or the current user does not own bot.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The retrieved bot.

Return type:

PublicBot

await get_read_states(*, http_overrides=None)[source]

This function is a coroutine.

Retrieves read states for all channels the current user in.

Note

This is not supposed to be used by bot accounts.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
Returns:

The channel read states.

Return type:

List[ReadState]

await get_recovery_codes(*, http_overrides=None, mfa_ticket)[source]

This function is a coroutine.

Retrieve recovery codes.

Note

This can only be used by non-bot accounts.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • mfa_ticket (str) – The valid MFA ticket token.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

    InvalidToken

    The provided MFA ticket token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    InternalError

    Somehow something went wrong during retrieving recovery codes.

Returns:

The retrieved recovery codes.

Return type:

List[str]

await get_role(server, role, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves a server role.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/role was not found.

Returns:

The retrieved role.

Return type:

Role

await get_server(server, *, http_overrides=None, populate_channels=None)[source]

This function is a coroutine.

Retrieves a Server.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

Returns:

The retrieved server.

Return type:

Server

await get_server_emojis(server, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves all custom ServerEmoji’s that belong to a server.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The retrieved emojis.

Return type:

List[ServerEmoji]

await get_server_invites(server, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves all invites that belong to a server.

You must have manage_server to do this.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to retrieve server invites.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The retrieved invites.

Return type:

List[ServerInvite]

await get_servers(*, http_overrides=None, populate_channels=None)[source]

This function is a coroutine.

Retrieves the list of Server's the user is in.

Added in version 1.2.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

Returns:

The retrieved servers.

Return type:

List[Server]

await get_sessions(*, http_overrides=None)[source]

This function is a coroutine.

Retrieves all sessions associated with this account.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

Returns:

The sessions.

Return type:

List[PartialSession]

await get_user(user, /, *, http_overrides=None)[source]

This function is a coroutine.

Retrieve user’s information.

You must have access to do this.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingUserPermission

    You do not have the proper permissions to view access user data.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The user was not found.

Returns:

The retrieved user.

Return type:

User

await get_user_flags(user, /, *, http_overrides=None)[source]

This function is a coroutine.

Retrieves flags for user.

Parameters:
  • user (ULIDOr[BaseUser]) – The user to retrieve flags for.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Returns:

The retrieved flags.

Return type:

UserFlags

await get_user_profile(user, *, http_overrides=None)[source]

This function is a coroutine.

Retrieve profile of an user.

You must have view_profile to do this.

Parameters:
  • user (ULIDOr[BaseUser]) – The user to retrieve profile of.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingUserPermission

    You do not have the proper permissions to view user profile.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The user was not found.

Returns:

The retrieved user profile.

Return type:

UserProfile

await get_user_settings(keys=None, *, http_overrides=None)[source]

This function is a coroutine.

Retrieve user settings.

Note

This is not supposed to be used by bot accounts.

Parameters:
  • keys (Optional[List[str]]) – The keys of user settings to retrieve. To retrieve all user settings, pass None or empty list.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
Returns:

The partial user settings with provided keys.

Return type:

UserSettings

await get_webhook(webhook, *, http_overrides=None, token=None)[source]

This function is a coroutine.

Retrieves a webhook.

If webhook token wasn’t given, the library will attempt get webhook with bot/user token.

You must have manage_webhooks to do this.

Note

Due to Stoat limitation, the webhook avatar information will be partial if no token is provided. Fields are guaranteed to be non-zero/non-empty are id and user_id.

Parameters:
  • webhook (ULIDOr[BaseWebhook]) – The webhook to retrieve.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • token (Optional[str]) – The webhook token.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

    NotAuthenticated

    The webhook token is invalid. Only applicable when token is provided.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to retrieve this webhook.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The webhook was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The retrieved webhook.

Return type:

Webhook

await invite_bot(bot, *, http_overrides=None, server=None, group=None)[source]

This function is a coroutine.

Invites a bot to a server or group.

Specifying both ``server`` and ``group`` parameters (or no parameters at all) will lead to an exception.

If destination is a server, you must have manage_server to do this, otherwise create_invites is required.

For groups, fires PrivateChannelCreateEvent for bot, GroupRecipientAddEvent and MessageCreateEvent for all group recipients. For servers, fires ServerCreateEvent for bot, ServerMemberJoinEvent and MessageCreateEvent for all server members.

Note

This can only be used by non-bot accounts.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    The target channel was not actually a group channel.

    IsBot

    The current token belongs to bot account.

  • Forbidden – Possible values for type:

    Value

    Reason

    Banned

    The bot was banned in target server.

    BotIsPrivate

    You do not own the bot to add it.

    GroupTooLarge

    The group exceeded maximum count of recipients.

    MissingPermission

    You do not have the proper permissions to add bots.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The bot/group/server was not found.

  • Conflict – Possible values for type:

    Value

    Reason

    AlreadyInGroup

    The bot is already in group.

    AlreadyInServer

    The bot is already in server.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

  • TypeError – You specified server and group parameters, or passed no parameters.

await join_call(channel, *, http_overrides=None, node=UNDEFINED, force_disconnect=UNDEFINED, recipients=UNDEFINED)[source]

This function is a coroutine.

Asks the voice server for a token to join the call.

You must have connect to do this.

For Livekit instances, fires MessageCreateEvent and VoiceChannelJoinEvent / VoiceChannelMoveEvent for all users who can see target channel.

Parameters:
  • channel (ULIDOr[Union[DMChannel, GroupChannel, TextChannel, VoiceChannel]]) –

    The channel to join a call in.

    If current instance uses legacy voice server (determined by whether InstanceFeaturesConfig.livekit_voice is False), then a channel with type of text cannot be passed and will raise HTTPException with CannotJoinCall type.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • node (UndefinedOr[Optional[str]]) –

    The node’s name to use for starting a call.

    If None or UNDEFINED, the currently assigned channel node will be used.

    If channel has no node assigned, you should discover existing voice nodes via query_node() (on official instances, you generally currently should use worldwide). Otherwise, this will throw an UnknownNode error.

    Added in version 1.2.

  • force_disconnect (UndefinedOr[Optional[bool]]) –

    Whether to force disconnect any other existing voice connections. Useful for disconnecting on another device and joining on a new.

    Added in version 1.2.

  • recipients (UndefinedOr[Optional[List[ULIDOr[BaseUser]]]]) –

    A list of users which should be notified of the call starting. Only used when the user is the first one connected.

    Added in version 1.2.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    AlreadyConnected

    The current user was already connected to this voice channel.

    CannotJoinCall

    The channel was type of saved_messages (or if instance uses legacy voice server, text).

    InvalidOperation

    The voice server is unavailable.

    LivekitUnavailable

    The voice server is unavailable. Only applicable to instances using Livekit.

    NotConnected

    The current user was already connected to other voice channel.

    NotAVoiceChannel

    The channel was not a voice channel. Only applicable to instances using Livekit.

    UnknownNode

    The server could not discover a voice node.

    VosoUnavailable

    The voice server is unavailable. Not applicable to instances using Livekit.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to join a call.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

    InternalError

    Somehow something went during retrieving token.

Returns:

The token for authenticating with the voice server, and node WebSocket URL (can be empty if instance does not use Livekit).

Return type:

Tuple[str, str]

await kick_member(server, member, *, http_overrides=None)[source]

This function is a coroutine.

Kicks a member from the server.

Fires ServerMemberRemoveEvent for kicked user and all server members.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CannotRemoveYourself

    You tried to kick yourself.

    InvalidOperation

    You tried to kick server owner.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    NotElevated

    Rank of your top role is higher than rank of top role of user you’re trying to ban.

    MissingPermission

    You do not have the proper permissions to ban members.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/user was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await leave_server(server, /, *, http_overrides=None, silent=None)[source]

This function is a coroutine.

Leaves a server if not owner, or deletes otherwise.

Fires ServerMemberRemoveEvent or ServerDeleteEvent (if owner) for all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server to leave.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • silent (Optional[bool]) – Whether to silently leave server or not.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await login_with_email(email, password, *, http_overrides=None, friendly_name=None)[source]

This function is a coroutine.

Logs in to an account using email and password.

Parameters:
  • email (str) – The email.

  • password (str) – The password. Must be at least 8 characters.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • friendly_name (Optional[str]) – The user-friendly client name.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CompromisedPassword

    The password was compromised.

    ShortPassword

    The password was less than 8 characters long.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidCredentials

    The provided password was incorrect.

  • Forbidden – Possible values for type:

    Value

    Reason

    LockedOut

    The account was locked out.

    UnverifiedAccount

    The account you tried to log into is currently unverified.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

Returns:

The login response.

Return type:

LoginResult

await login_with_mfa(ticket, by=None, *, http_overrides=None, friendly_name=None)[source]

This function is a coroutine.

Complete MFA login flow.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    DisallowedMFAMethod

    You tried to use disallowed MFA verification method.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidCredentials

    The provided password (in by parameter) was incorrect.

    InvalidToken

    One of these:

    • The provided MFA ticket token is invalid.

    • The provided TOTP, or recovery code is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    LockedOut

    The account was locked out.

    UnverifiedAccount

    The account you tried to log into is currently unverified.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

Returns:

The session if successfully logged in, or AccountDisabled containing user ID associated with the account.

Return type:

Union[Session, AccountDisabled]

await logout(*, http_overrides=None)[source]

This function is a coroutine.

Deletes the current session.

Fires SessionDeleteEvent for the current session.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

await mark_server_as_read(server, /, *, http_overrides=None)[source]

This function is a coroutine.

Marks all channels in a server as read.

Note

This can only be used by non-bot accounts.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await mfa_status(*, http_overrides=None)[source]

This function is a coroutine.

Retrieves MFA status.

Note

This can only be used by non-bot accounts.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    InternalError

    Somehow something went wrong during retrieving recovery codes.

Returns:

The MFA status.

Return type:

MFAStatus

await onboarding_status(*, http_overrides=None)[source]

This function is a coroutine.

Determines whether the current session requires to complete onboarding.

You may skip calling this if you’re restoring from an existing session.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:

Unauthorized – Possible values for type:

Value

Reason

InvalidSession

The current user token is invalid.

Returns:

Whether the onboarding is completed.

Return type:

bool

await open_dm(user, *, http_overrides=None)[source]

This function is a coroutine.

Retrieve a DM (or create if it doesn’t exist) with another user.

If target is current user, a SavedMessagesChannel is always returned.

You must have send_messages to do this.

May fire PrivateChannelCreateEvent for the current user and user you opened DM with.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The user was not found.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingUserPermission

    You do not have the proper permissions to open DM with this user.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The private channel.

Return type:

Union[SavedMessagesChannel, DMChannel]

await pin_message(channel, message, *, http_overrides=None)[source]

This function is a coroutine.

Pins a message.

You must have manage_messages to do this, unless the channel is DMChannel.

Fires MessageUpdateEvent and MessageCreateEvent, both for all users who can see target channel.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    AlreadyPinned

    The message was already pinned.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to pin the message.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/message was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await push_subscribe(*, http_overrides=None, endpoint, p256dh, auth)[source]

This function is a coroutine.

Create a new Web Push subscription. If a subscription already exists on this session, it will be removed.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

await query_members_by_name(server, query, *, http_overrides=None)[source]

This function is a coroutine.

Query members by a given name.

Warning

This API is not stable and may be removed in the future.

Parameters:
  • server (ULIDOr[BaseServer]) – The server.

  • query (str) – The query to search members for.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The members matched.

Return type:

List[Member]

await query_node(*, http_overrides=None)[source]

This function is a coroutine.

Retrieves the instance information.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:

InternalServerError – The internal configuration is invalid.

Returns:

The instance.

Return type:

Instance

await raw_request(route, *, accept_json=True, bot=UNDEFINED, cookie=UNDEFINED, http_overrides=None, idempotency_key=None, json=UNDEFINED, mfa_ticket=None, token=UNDEFINED, user_agent=UNDEFINED, **kwargs)[source]

This function is a coroutine.

Perform a HTTP request, with ratelimiting and errors handling.

Parameters:
  • route (CompiledRoute) – The route.

  • accept_json (bool) – Whether to explicitly receive JSON or not. Defaults to True.

  • bot (UndefinedOr[bool]) – Whether the authentication token belongs to bot account. Defaults to bot.

  • cookie (UndefinedOr[str]) – The cookies to use when performing a request.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • idempotency_key (Optional[str]) – The idempotency key.

  • json (UndefinedOr[Any]) – The JSON payload to pass in.

  • mfa_ticket (Optional[str]) – The MFA ticket to pass in headers.

  • token (UndefinedOr[Optional[str]]) – The token to use when requesting the route.

  • user_agent (UndefinedOr[str]) – The user agent to use for HTTP request. Defaults to user_agent.

  • **kwargs – The keyword arguments to pass to send_request().

Raises:

HTTPException – Something went wrong during request.

Returns:

The HTTP response.

Return type:

HTTPResponse

await register(email, password, *, http_overrides=None, invite=None, captcha=None)[source]

This function is a coroutine.

Registers a new account.

Danger

This function has high rate of abuse on official instance. Proceed carefully with caution.

Parameters:
  • email (str) – The account email.

  • password (str) – The account password. Must be at least 8 characters.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • invite (Optional[str]) – The instance invite code.

  • captcha (Optional[str]) – The CAPTCHA solution.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    BlockedByShield

    Your request was blocked by Authifier Shield. Try adjusting your HTTP headers to be more human-like, have not flagged IP, and good email. Optionally, use a HTTP client that impersonates browser TLS fingerprint.

    CaptchaFailed

    The CAPTCHA solution was invalid.

    CompromisedPassword

    The provided password was compromised.

    IncorrectData

    The email was invalid.

    InvalidInvite

    The provided instance invite was not found.

    MissingInvite

    The instance requires an invite to register, but you did not provide it.

    ShortPassword

    The provided password was less than 8 characters long.

  • Unauthorized – Possible values for type:

    Value

    Reason

    DisallowedContactSupport

    You’re probably doing something you shouldn’t be.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    EmailFailed

    Failed to send mail for confirming account creation.

    InternalError

    Somehow something went wrong during account creation.

    OperationFailed

    Email verification was not set up on this instance.

await remove_friend(user, *, http_overrides=None)[source]

This function is a coroutine.

Removes the user from friend list.

Fires UserRelationshipUpdateEvent for the current user and user you removed from friend list.

Note

This can only be used by non-bot accounts.

Parameters:
  • user (ULIDOr[BaseUser]) – The user to remove from friend list.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    IsBot

    Either the current user or user you tried to deny friend request from are bot accounts.

  • NoEffect – You tried to deny friend request from user you had no friend request sent from/to.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The user was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The user you removed from friend list.

Return type:

User

await remove_group_recipient(channel, user, *, http_overrides=None)[source]

This function is a coroutine.

Removes a recipient from the group.

Fires PrivateChannelDeleteEvent for removed recipient, and GroupRecipientRemoveEvent for rest of group recipients.

Note

This can only be used by non-bot accounts.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CannotRemoveYourself

    You tried to remove yourself from the group.

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not own the target group.

    NotFriends

    You’re not friends with the users you want to create group with.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The target group was not found.

    NotInGroup

    The recipient you wanted to remove was not in group.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await remove_reactions_from_message(channel, message, emoji, *, http_overrides=None, user=None, remove_all=None)[source]

This function is a coroutine.

Remove your own, someone else’s or all of a given reaction.

You must have react to do this.

Fires MessageClearReactionEvent if remove_all is True or MessageUnreactEvent, for all users who can see target channel.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to remove reaction.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    One of these:

    • The channel was not found.

    • The message was not found.

    • The user provided did not react.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await report_message(message, reason, *, http_overrides=None, additional_context=None)[source]

This function is a coroutine.

Report a message to the instance moderation team.

Fires ReportCreateEvent internally (but not fired over WebSocket).

Note

This can only be used by non-bot accounts.

Parameters:
  • message (ULIDOr[BaseMessage]) –

    The message to report.

    Internally, 15 messages around provided message will be snapshotted for context. All attachments of provided message are snapshotted as well.

  • reason (ContentReportReason) – The reason for reporting.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • additional_context (Optional[str]) – The additional context for moderation team. Can be only up to 1000 characters.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CannotReportYourself

    You tried to report your own message.

    FailedValidation

    The payload was invalid.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The message was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await report_server(server, reason, *, http_overrides=None, additional_context=None)[source]

This function is a coroutine.

Report a server to the instance moderation team.

Fires ReportCreateEvent internally (but not fired over WebSocket).

Note

This can only be used by non-bot accounts.

Parameters:
  • server (ULIDOr[BaseServer]) – The server to report.

  • reason (ContentReportReason) – The reason for reporting.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • additional_context (Optional[str]) – The additional context for moderation team. Can be only up to 1000 characters.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CannotReportYourself

    You tried to report your own server.

    FailedValidation

    The payload was invalid.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await report_user(user, reason, *, http_overrides=None, additional_context=None, message_context=None)[source]

This function is a coroutine.

Report an user to the instance moderation team.

Fires ReportCreateEvent internally (but not fired over WebSocket).

Note

This can only be used by non-bot accounts.

Parameters:
  • user (ULIDOr[BaseUser]) – The user to report.

  • reason (UserReportReason) – The reason for reporting user.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • additional_context (Optional[str]) – The additional context for moderation team. Can be only up to 1000 characters.

  • message_context (Optional[ULIDOr[BaseMessage]]) –

    The message context.

    Internally, 15 messages around provided message will be snapshotted for context. All attachments of provided message are snapshotted as well.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CannotReportYourself

    You tried to report yourself.

    FailedValidation

    The payload was invalid.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The user/message was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await request(route, *, accept_json=True, bot=UNDEFINED, http_overrides=None, idempotency_key=None, json=UNDEFINED, log=True, mfa_ticket=None, token=UNDEFINED, user_agent=UNDEFINED, **kwargs)[source]

This function is a coroutine.

Perform a HTTP request, with ratelimiting and errors handling.

Parameters:
  • route (CompiledRoute) – The route.

  • accept_json (bool) – Whether to explicitly receive JSON or not. Defaults to True.

  • bot (UndefinedOr[bool]) – Whether the authentication token belongs to bot account. Defaults to bot.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • idempotency_key (Optional[str]) – The idempotency key.

  • json (UndefinedOr[Any]) – The JSON payload to pass in.

  • log (bool) – Whether to log successful response or not. This option is intended to avoid console spam caused by routes like GET /servers/{server_id}/members. Defaults to True.

  • mfa_ticket (Optional[str]) – The MFA ticket to pass in headers.

  • token (UndefinedOr[Optional[str]]) – The token to use when requesting the route.

  • user_agent (UndefinedOr[str]) – The user agent to use for HTTP request. Defaults to user_agent.

  • **kwargs – The keyword arguments to pass to send_request().

Raises:

HTTPException – Something went wrong during request.

Returns:

The parsed JSON response or nothing.

Return type:

Any

await resend_verification(*, http_overrides=None, email, captcha=None)[source]

This function is a coroutine.

Resend account creation verification email.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • email (str) – The email associated with the account.

  • captcha (Optional[str]) – The CAPTCHA solution.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CaptchaFailed

    The CAPTCHA solution was invalid.

  • Unauthorized – Possible values for type:

    Value

    Reason

    DisallowedContactSupport

    You’re probably doing something you shouldn’t be.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    EmailFailed

    Failed to send mail about confirming password reset.

    OperationFailed

    Email verification was not set up on this instance.

    InternalError

    Somehow something went wrong during confirming password reset.

await revoke_all_sessions(*, http_overrides=None, revoke_self=None)[source]

This function is a coroutine.

Deletes all active sessions, optionally including current one.

Fires SessionDeleteAllEvent for the all sessions (may include current session if revoke_self is True).

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • revoke_self (Optional[bool]) – Whether to revoke current session or not.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

await revoke_oauth2_authorization(bot, *, http_overrides=None)[source]

This function is a coroutine.

Revokes the OAuth2 authorization.

Added in version 1.2.

Parameters:
  • bot (Union[BaseBot, OAuth2Authorization, str]) – The bot to deauthorize, OAuth2 authorization to remove, or ID of the bot to deauthorize.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    The token was already revoked.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The OAuth2 authorization was deleted.

Returns:

The revoked OAuth2 authorization.

Return type:

OAuth2Authorization

await revoke_oauth2_token(token=None, *, http_overrides=None)[source]

This function is a coroutine.

Revokes the OAuth2 token.

Added in version 1.2.

Parameters:
  • token (Optional[str]) – The token to revoke. Defaults to the current one.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    The token was not an access/refresh token, or the token was already revoked.

  • Unauthorized – Possible values for type:

    Value

    Reason

    NotAuthenticated

    The token was invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The OAuth2 authorization was deleted.

Returns:

The revoked OAuth2 authorization.

Return type:

OAuth2Authorization

await revoke_session(session, /, *, http_overrides=None)[source]

This function is a coroutine.

Deletes a specific active session.

Fires SessionDeleteEvent for the provided session.

Parameters:
Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

    InvalidToken

    The provided session did not belong to your account.

  • NotFound – Possible values for type:

    Value

    Reason

    UnknownUser

    The provided session was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

await search_for_messages(channel, query=None, *, http_overrides=None, pinned=None, limit=None, before=None, after=None, sort=None, populate_users=None)[source]

This function is a coroutine.

Searches for messages.

For query and pinned, only one parameter can be provided, otherwise a HTTPException will be thrown with InvalidOperation type.

You must have read_message_history to do this.

Note

This can only be used by non-bot accounts.

Parameters:
  • channel (ULIDOr[TextableChannel]) – The channel to search in.

  • query (Optional[str]) – The full-text search query. See MongoDB documentation for more information.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • pinned (Optional[bool]) – Whether to search for (un-)pinned messages or not.

  • limit (Optional[int]) –

    The maximum number of messages to get. Must be between 1 and 100. Defaults to 50.

    If nearby is provided, then this is (limit + 2).

  • before (Optional[ULIDOr[BaseMessage]]) – The message before which messages should be fetched.

  • after (Optional[ULIDOr[BaseMessage]]) – The message after which messages should be fetched.

  • sort (Optional[MessageSort]) – The message sort direction. Defaults to MessageSort.latest

  • nearby (Optional[ULIDOr[BaseMessage]]) –

    The message to search around.

    Providing this parameter will discard before, after and sort parameters.

    It will also take half of limit rounded as the limits to each side. It also fetches the message specified.

  • populate_users (bool) – Whether to populate user (and member, if server channel) objects.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    FailedValidation

    One of before, after or nearby parameters were invalid IDs.

    InvalidOperation

    You provided both query and pinned parameters.

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to search messages.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The messages matched.

Return type:

List[Message]

await send_friend_request(username, discriminator=None, *, http_overrides=None)[source]

This function is a coroutine.

Sends a friend request to another user.

Fires UserRelationshipUpdateEvent for the current user and user you sent friend request to.

Note

This can only be used by non-bot accounts.

Parameters:
  • username (str) – The username and optionally discriminator combo separated by #.

  • discriminator (Optional[str]) – The user’s discriminator.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidProperty

    You did not provide a discriminator.

    IsBot

    Either the current user or user you tried to accept friend request from are bot accounts.

    TooManyPendingFriendRequests

    You sent too many outgoing friend requests.

  • NoEffect – You tried to accept friend request from yourself.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    BlockedOther

    The user you tried to send friend request to have blocked you.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The user was not found.

  • Conflict – Possible values for type:

    Value

    Reason

    AlreadyFriends

    You’re already friends with user you tried to send friend request to.

    AlreadySentRequest

    You already sent friend request to this user.

    Blocked

    You have blocked the user you tried to send friend request to.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The user you sent friend request to.

Return type:

User

await send_message(channel, content=None, *, http_overrides=None, nonce=None, attachments=None, replies=None, embeds=None, masquerade=None, interactions=None, silent=None, mention_everyone=None, mention_online=None)[source]

This function is a coroutine.

Sends a message to the given channel.

You must have send_messages to do this.

If message mentions “@everyone” or “@online”, you must have mention_everyone to do that.

If message mentions any roles, you must have mention_roles to do that.

Fires MessageCreateEvent and optionally MessageAppendEvent, both for all users who can see target channel.

Parameters:
  • channel (ULIDOr[TextableChannel]) – The destination channel.

  • content (Optional[str]) – The message content.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • nonce (Optional[str]) – The message nonce.

  • attachments (Optional[List[ResolvableResource]]) –

    The attachments to send the message with.

    You must have upload_files to provide this.

  • replies (Optional[List[Union[Reply, ULIDOr[BaseMessage]]]]) – The message replies.

  • embeds (Optional[List[SendableEmbed]]) –

    The embeds to send the message with.

    You must have send_embeds to provide this.

  • masquerade (Optional[MessageMasquerade]) –

    The masquerade for the message.

    You must have use_masquerade to provide this.

    If MessageMasquerade.color is provided, manage_roles is also required.

  • interactions (Optional[MessageInteractions]) –

    The message interactions.

    If MessageInteractions.reactions is provided, react is required.

  • silent (Optional[bool]) – Whether to suppress notifications or not.

  • mention_everyone (Optional[bool]) –

    Whether to mention all users who can see the channel. This cannot be mixed with mention_online parameter.

    Note

    User accounts cannot set this to True.

  • mention_online (Optional[bool]) –

    Whether to mention all users who are online and can see the channel. This cannot be mixed with mention_everyone parameter.

    Note

    User accounts cannot set this to True.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    EmptyMessage

    The message was empty.

    FailedValidation

    The payload was invalid.

    InvalidFlagValue

    Both mention_everyone and mention_online were True.

    InvalidOperation

    The passed nonce was already used. One of MessageInteractions.reactions elements was invalid.

    InvalidProperty

    MessageInteractions.restrict_reactions was True but MessageInteractions.reactions was empty.

    IsBot

    The current token belongs to bot account.

    IsNotBot

    The current token belongs to user account.

    PayloadTooLarge

    The message was too large.

    TooManyAttachments

    You provided more attachments than allowed on this instance.

    TooManyEmbeds

    You provided more embeds than allowed on this instance.

    TooManyReplies

    You were replying to more messages than was allowed on this instance.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to send messages.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/file/reply was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

    InternalError

    Somehow something went wrong during message creation.

Returns:

The message that was sent.

Return type:

Message

await send_password_reset(*, http_overrides=None, email, captcha=None)[source]

This function is a coroutine.

Send an email to reset account password.

Parameters:
  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • email (str) – The email associated with the account.

  • captcha (Optional[str]) – The CAPTCHA verification code.

Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    CaptchaFailed

    The CAPTCHA solution was invalid.

  • Unauthorized – Possible values for type:

    Value

    Reason

    DisallowedContactSupport

    You’re probably doing something you shouldn’t be.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

    EmailFailed

    Failed to send mail for password reset.

    OperationFailed

    Email verification was not set up on this instance.

await send_request(method, url, *, headers, overrides=None, **kwargs)[source]

Perform an actual HTTP request.

This is different from raw_request() as latter performs complete error and ratelimit handling.

Parameters:
  • method (str) – The HTTP method.

  • url (str) – The URL to send HTTP request to.

  • headers (CIMultiDict[Any]) – The HTTP headers.

  • overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • **kwargs – The keyword arguments to pass to HTTPAdapter.request().

Returns:

The response.

Return type:

HTTPResponse

await set_category_permissions_for_role(server, category, role, *, http_overrides=None, allow=<Permissions: 0>, deny=<Permissions: 0>)[source]

This function is a coroutine.

Sets permissions for the specified category.

You must have manage_permissions to do this.

Fires ServerUpdateEvent for all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server.

  • category (ULIDOr[Category]) – The category.

  • role (ULIDOr[BaseRole]) – The role.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • allow (Permissions) – The permissions to allow for the specified role.

  • deny (Permissions) – The permissions to deny for the specified role.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    CannotGiveMissingPermissions

    Your new provided permissions contained permissions you didn’t have.

    NotElevated

    Rank of your top role is higher than rank of role you’re trying to set override for.

    MissingPermission

    You do not have the proper permissions to edit permissions for this category.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/role was not found.

    UnknownCategory

    The category was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly updated category with new permissions.

Return type:

Category

await set_channel_permissions_for_role(channel, role, *, http_overrides=None, allow=<Permissions: 0>, deny=<Permissions: 0>)[source]

This function is a coroutine.

Sets permissions for the specified role in a channel.

You must have manage_permissions to do this.

The provided channel must be a ServerChannel.

Fires ChannelUpdateEvent for all users who still see target channel, ServerChannelCreateEvent for all users who now can see target channel, and ChannelDeleteEvent for users who no longer can see target channel.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    The provided channel was not server channel.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    CannotGiveMissingPermissions

    Your new provided permissions contained permissions you didn’t have.

    NotElevated

    Rank of your top role is higher than rank of role you’re trying to set override for.

    MissingPermission

    You do not have the proper permissions to edit overrides for this channel.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/server/role was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The updated server channel with new permissions.

Return type:

ServerChannel

await set_default_category_permissions(server, category, *, http_overrides=None, allow=<Permissions: 0>, deny=<Permissions: 0>)[source]

This function is a coroutine.

Sets default permissions for everyone in a category.

You must have manage_permissions to do this.

Fires ServerUpdateEvent for all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server the category is in.

  • category (ULIDOr[Category]) – The category to set default permissions for.

  • permissions (Permissions) – The new permissions.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    CannotGiveMissingPermissions

    Your new provided permissions contained permissions you didn’t have.

    MissingPermission

    You do not have the proper permissions to edit default permissions for this server.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly updated server.

Return type:

Server

await set_default_channel_permissions(channel, permissions, *, http_overrides=None)[source]

This function is a coroutine.

Sets default permissions for everyone in a channel.

You must have manage_permissions to do this.

Channel must be a GroupChannel, or ServerChannel.

Fires ChannelUpdateEvent for all users who still see target channel, and for server channels, ServerChannelCreateEvent for all users who now can see target channel, and ChannelDeleteEvent is fired for users who no longer can see target channel.

Parameters:
Raises:
  • HTTPException – Possible values for type:

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    CannotGiveMissingPermissions

    Your new provided permissions contained permissions you didn’t have.

    MissingPermission

    You do not have the proper permissions to edit default permissions for this channel.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The updated group/server channel with new permissions.

Return type:

Union[GroupChannel, ServerChannel]

await set_default_server_permissions(server, permissions, *, http_overrides=None)[source]

This function is a coroutine.

Sets default permissions for everyone in a server.

You must have manage_permissions to do this.

Fires ServerUpdateEvent for all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server to set default permissions for.

  • permissions (Permissions) – The new permissions.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    CannotGiveMissingPermissions

    Your new provided permissions contained permissions you didn’t have.

    MissingPermission

    You do not have the proper permissions to edit default permissions for this server.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The newly updated server.

Return type:

Server

await set_server_permissions_for_role(server, role, *, http_overrides=None, allow=<Permissions: 0>, deny=<Permissions: 0>)[source]

This function is a coroutine.

Sets permissions for the specified server role.

You must have manage_permissions to do this.

Fires RawServerRoleUpdateEvent for all server members.

Parameters:
  • server (ULIDOr[BaseServer]) – The server.

  • role (ULIDOr[BaseRole]) – The role.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

  • allow (Permissions) – The permissions to allow for the specified role.

  • deny (Permissions) – The permissions to deny for the specified role.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    CannotGiveMissingPermissions

    Your new provided permissions contained permissions you didn’t have.

    NotElevated

    Rank of your top role is higher than rank of role you’re trying to set override for.

    MissingPermission

    You do not have the proper permissions to edit permissions for this role.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/role was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The updated server with new permissions.

Return type:

Server

await stop_ringing(channel, user, *, http_overrides=None)[source]

This function is a coroutine.

Stops ringing a specific user in a private call.

The channel must be a DM or group.

Added in version 1.2.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    InvalidOperation

    The channel was not type of private or group.

    LivekitUnavailable

    The voice server is unavailable.

    NotConnected

    The user wasn’t connected to voice channel.

  • NoEffect – The channel was a server channel.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/user was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

    InternalError

    Somehow something went wrong during stopping ringing.

await unban(server, user, *, http_overrides=None)[source]

This function is a coroutine.

Unbans an user from the server.

You must have ban_members to do this.

Parameters:
  • server (ULIDOr[BaseServer]) – The server.

  • user (ULIDOr[BaseUser]) – The user to unban from the server.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to unban members.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server/ban was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await unblock_user(user, *, http_overrides=None)[source]

This function is a coroutine.

Unblocks an user.

Fires UserRelationshipUpdateEvent for the current user and unblocked user.

Note

This is not supposed to be used by bot accounts.

Parameters:
Raises:
  • NoEffect – You tried to block yourself or someone that you didn’t had blocked.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The user was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

    InternalError

    Somehow something went wrong during unblocking user.

Returns:

The unblocked user.

Return type:

User

await unpin_message(channel, message, *, http_overrides=None)[source]

This function is a coroutine.

Unpins a message.

You must have manage_messages to do this, unless the channel is DMChannel.

Fires MessageUpdateEvent and MessageCreateEvent, both for all users who can see target channel.

Parameters:
Raises:
  • HTTPException – Possible values for type:

    Value

    Reason

    NotPinned

    The message was not pinned.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to unpin the message.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/message was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

await unsubscribe(*, http_overrides=None)[source]

This function is a coroutine.

Remove the Web Push subscription associated with the current session.

Parameters:

http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current user token is invalid.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    operation, with_

url_for(route, /)[source]

Returns URL for route.

Parameters:

route (CompiledRoute) – The route.

Returns:

The URL for the route.

Return type:

str

await verify_email(code, *, http_overrides=None)[source]

This function is a coroutine.

Verify an email address.

Parameters:
  • code (str) – The code from email.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:
Returns:

The MFA ticket.

Return type:

Optional[MFATicket]

with_credentials(token, *, bot=True, oauth2=False)[source]

Modifies HTTP client credentials.

Parameters:
  • token (str) – The authentication token.

  • bot (bool) – Whether the token belongs to bot account or not. Defaults to True.

  • oauth2 (bool) – Whether the token is an OAuth2 access token. Defaults to False.

HTTPAdapter

class stoat.HTTPAdapter[source]

Represents a HTTP adapter.

await startup()[source]

Sets up adapter.

await close()[source]

Release all underlying resources.

abstractmethod await request(method, url, *, headers, **kwargs)[source]

Perform an actual HTTP request.

Note

You should not perform Stoat API error and ratelimit handling in this method if you’re overriding it.

Parameters:
  • method (str) – The HTTP method.

  • url (str) – The URL to send HTTP request to.

  • headers (CIMultiDict[Any]) – The HTTP headers.

  • **kwargs

    The keyword arguments to pass to requester function.

    Usually these are passed:

    • form

    • json

    • params

    • proxy

    • proxy_auth

Returns:

The response.

Return type:

HTTPResponse

abstractmethod await websocket(url, *, headers, **kwargs)[source]

Creates a WebSocket connection.

Note

You should perform basic WebSocket handshake validation in this method if you’re overriding it.

However you should not validate frames sent by Stoat itself.

Parameters:
  • url (str) – The URL to create WebSocket connection to.

  • headers (CIMultiDict[Any]) – The HTTP headers.

  • **kwargs

    The keyword arguments to pass to requester function.

    Usually these are passed:

    • proxy

    • proxy_auth

Returns:

The response.

Return type:

HTTPWebSocket

abstractmethod is_close_frame(frame, /)[source]

bool: Returns whether the provided frame is a CLOSE/CLOSED/CLOSING frame.

abstractmethod is_error_frame(frame, /)[source]

bool: Returns whether the provided frame is an ERROR pseudo-frame.

abstractmethod is_binary_frame(frame, /)[source]

bool: Returns whether the provided frame is a BINARY frame.

abstractmethod is_text_frame(frame, /)[source]

bool: Returns whether the provided frame is a TEXT frame.

abstractmethod payload_from_frame(frame, /)[source]

Any: Returns frame payload.

AIOHTTPAdapter

class stoat.AIOHTTPAdapter(*, session=None)[source]

Represents a HTTP adapter using aiohttp.ClientSession.

This inherits from HTTPAdapter.

await get_session()[source]

aiohttp.ClientSession: The HTTP session.

await close()[source]

Release all underlying resources.

await request(method, url, *, headers, **kwargs)[source]

Perform an actual HTTP request.

Note

You should not perform Stoat API error and ratelimit handling in this method if you’re overriding it.

Parameters:
  • method (str) – The HTTP method.

  • url (str) – The URL to send HTTP request to.

  • headers (CIMultiDict[Any]) – The HTTP headers.

  • **kwargs – The keyword arguments to pass to aiohttp.ClientSession.request().

Returns:

The response.

Return type:

AIOHTTPResponseWrapper

await websocket(url, *, headers, **kwargs)[source]

Creates a WebSocket connection.

Note

You should perform basic WebSocket handshake validation in this method if you’re overriding it.

However you should not validate frames sent by Stoat itself.

Parameters:
  • url (str) – The URL to create WebSocket connection to.

  • headers (CIMultiDict[Any]) – The HTTP headers.

  • **kwargs

    The keyword arguments to pass to requester function.

    Usually these are passed:

    • proxy

    • proxy_auth

Returns:

The response.

Return type:

HTTPWebSocket

is_close_frame(frame, /)[source]

bool: Returns whether the provided frame is a close frame.

is_error_frame(frame, /)[source]

bool: Returns whether the provided frame is an ERROR pseudo-frame.

is_binary_frame(frame, /)[source]

bool: Returns whether the provided frame is a BINARY frame.

is_text_frame(frame, /)[source]

bool: Returns whether the provided frame is a TEXT frame.

payload_from_frame(frame, /)[source]

Any: Returns frame payload.

convert_form(form, /)[source]

Converts agnostic HTTPForm to aiohttp.FormData.

Added in version 1.2.

HTTPResponse

Methods
class stoat.HTTPResponse(*args, **kwargs)[source]

A HTTP response.

property method[source]

The HTTP request method.

Type:

str

property status[source]

The HTTP response status code.

Type:

int

property headers[source]

The response headers.

Type:

MultiMapping[str]

property closed[source]

Whether the request resources were released.

Type:

bool

property url[source]

The request URL.

Type:

yarl.URL

close()[source]

Release request resources.

await read()[source]

bytes: Read the response body.

await text(encoding=None, errors='strict')[source]

str: Read the response body as string.

AIOHTTPResponseWrapper

Methods
class stoat.AIOHTTPResponseWrapper(underlying, /)[source]

A wrapper around aiohttp.ClientResponse.

property method[source]

The HTTP request method.

Type:

str

property status[source]

The HTTP response status code.

Type:

int

property headers[source]

The response headers.

Type:

MultiMapping[str]

property closed[source]

Whether the request resources were released.

Type:

bool

property url[source]

The request URL.

Type:

yarl.URL

close()[source]

Release request resources.

await read()[source]

bytes: Read the response body.

await text(encoding=None, errors='strict')[source]

str: Read the response body as string.

HTTPWebSocket

class stoat.HTTPWebSocket(*args, **kwargs)[source]

A HTTP WebSocket connection.

HTTPForm

Methods
class stoat.HTTPForm(fields=None, *, charset=None, quote_fields=True)[source]

Represents a form.

This is constructed by the library and meant to be converted to form consumable by underlying HTTP backend.

Added in version 1.2.

add_field(name, value, *, content_type=None, filename=None)[source]

Adds a field.

Route

Methods
class stoat.routes.Route(method, path, /, *, ratelimit_key_template=UNDEFINED)[source]

Represents Stoat API route.

compile(**args)[source]

Compiles route.

CompiledRoute

class stoat.routes.CompiledRoute(route, /, **args)[source]

Represents compiled Stoat API route.

RateLimit

Methods
class stoat.RateLimit[source]
abstractmethod await block()[source]

If necessary, this method must calculate delay and sleep.

abstractmethod is_expired()[source]

bool: Whether the ratelimit is expired.

abstractmethod on_response(route, response, /)[source]

Called when any response from Stoat API is received.

This has same note as RateLimiter.on_response().

This is called only if bucket was already present and ratelimiter wants to resync data.

RateLimitBlocker

Methods
class stoat.RateLimitBlocker[source]
await decrement()[source]

Decrements pending requests counter.

await increment()[source]

Increments pending requests counter.

RateLimiter

class stoat.RateLimiter[source]
abstractmethod fetch_blocker_for(route, path, /)[source]

RateLimitBlocker: Returns request blocker.

abstractmethod fetch_ratelimit_for(route, path, /)[source]

Optional[RateLimit]: Must return ratelimit information, if available.

abstractmethod on_bucket_update(response, route, old_bucket, new_bucket, /)[source]

Called when route updates it’s bucket key.

The default implementation will remove old bucket from internal mapping.

Parameters:
  • response (HTTPResponse) – The response.

  • route (CompiledRoute) – The route.

  • old_bucket (str) – The old bucket key.

  • new_bucket (str) – The new bucket key.

abstractmethod await on_response(route, path, response, /)[source]

Called when any response from Stoat API is received.

Note

This is always called, even when request fails for other reasons like failed validation, invalid token, something not found, etc.

DefaultRateLimit

Methods
class stoat.DefaultRateLimit(rate_limiter, bucket, /, *, remaining, reset_after)[source]
await block()[source]

If necessary, this method must calculate delay and sleep.

is_expired()[source]

bool: Whether the ratelimit is expired.

on_response(route, response, /)[source]

Called when any response from Stoat API is received.

This has same note as RateLimiter.on_response().

This is called only if bucket was already present and ratelimiter wants to resync data.

DefaultRateLimitBlocker

Methods
class stoat.DefaultRateLimitBlocker[source]
await decrement()[source]

Decrements pending requests counter.

await increment()[source]

Increments pending requests counter.

DefaultRateLimiter

class stoat.DefaultRateLimiter(*, no_concurrent_block=False, no_expired_ratelimit_remove=False)[source]
fetch_blocker_for(route, path, /)[source]

RateLimitBlocker: Returns request blocker.

fetch_ratelimit_for(route, path, /)[source]

Optional[RateLimit]: Must return ratelimit information, if available.

get_ratelimit_key_for(route, /)[source]

Gets ratelimit key for this compiled route.

By default this just calls routes.CompiledRoute.build_ratelimit_key().

Parameters:

route (CompiledRoute) – The route to fetch ratelimit key for.

Returns:

The ratelimit key.

Return type:

str

on_bucket_update(response, route, old_bucket, new_bucket, /)[source]

Called when route updates it’s bucket key.

The default implementation will remove old bucket from internal mapping.

Parameters:
  • response (HTTPResponse) – The response.

  • route (CompiledRoute) – The route.

  • old_bucket (str) – The old bucket key.

  • new_bucket (str) – The new bucket key.

await on_response(route, path, response, /)[source]

Called when any response from Stoat API is received.

Note

This is always called, even when request fails for other reasons like failed validation, invalid token, something not found, etc.

try_remove_expired_ratelimits()[source]

Tries to remove expired ratelimits.