Welcome to discord.aio’s documentation!¶
See the reference documentation.
discord.aio¶
discord.aio is an asynchronous Discord API wrapper
Currently under very early development
Python 3.6+ only.
Documentation¶
You can find the module documentation here: documentation
Installation¶
With pip:¶
pip3 install discord.aio
From source:¶
git clone https://github.com/Ryozuki/discord.aio && cd discord.aio && pip3 install .
Local development¶
git clone https://github.com/Ryozuki/discord.aio
cd discord.aio && pip3 install -e .
Example bot¶
import asyncio
import os
import logging
from discordaio import DiscordBot
logging.basicConfig(
level='DEBUG', format='%(asctime)s - %(name)s - %(levelname)s: %(message)s')
logger = logging.getLogger('my_lovely_bot')
if __name__ == '__main__':
TOKEN = os.environ['DISCORD_TOKEN']
bot = DiscordBot(TOKEN)
@bot.event()
async def on_ready():
logger.info('Connected!')
logger.info(f'My username is {bot.user}')
@bot.event('on_message') # You can also use a custom function name.
async def foo_bar(message):
logger.info(f'{message.author}: {message.content}')
Here you can find a more extensive example.
TODO¶
- Add compression support
- Add bot shards support
- Handle ISO8601 timestamp
Your first bot¶
TODO: Do this
Events¶
Events¶
Event: on_ready¶
Raised when:
- The client is ready and connected.
Note: Before this event is raised, DiscordBot.user is filled with information.
@bot.event()
async def on_ready():
print('Connected!')
print(f'My username is {bot.user}')
Event: on_resumed¶
Raised when:
- A client has sent a resume payload to the gateway (for resuming existing sessions).
Event: on_invalid_session¶
Raised when:
- The gateway could not initialize a session after receiving an Opcode 2 Identify
- The gateway could not resume a previous session after receiving an Opcode 6 Resume
- The gateway has invalidated an active session and is requesting client action
Event Parameters:
resume
(bool): Indicates whether the client can resume.
Event: on_channel_create¶
Raised when:
- A new channel is created
Event Parameters:
channel
(Channel): The created channel
Event: on_channel_update¶
Raised when:
- A channel is updated
Event Parameters:
channel
(Channel): The updated channel
Event: on_channel_delete¶
Raised when:
- A channel is deleted
Event Parameters:
channel
(Channel): The deleted channel
Event: on_channel_pin¶
Raised when:
- A message is pinned or unpinned in a text channel.
Note: This is not raised when a pinned message is deleted.
Event Parameters:
channel_id
(int): The id of the channellast_pin_timestamp
(int): The time at which the most recent pinned message was pinned
Event: on_guild_create¶
Raised when:
- After the
on_ready
event, to fullfill the guild information. - When a Guild becomes available again to the client.
- When the current user joins a new Guild.
Event Parameters:
guild
(Guild): The guild
@bot.event()
async def on_guild_create(guild):
print(f'I\'m connected to {guild.name} guild, it got {len(guild.channels)} channels.')
Event: on_guild_delete¶
Raised when:
- A guild becomes unavailable during a guild outage
- The user leaves or is removed from a guild
- When the current user joins a new Guild.
Note: If the unavailable attribute is not set, the user was removed from the guild.
Event Parameters:
guild
(Guild): The guild
@bot.event()
async def on_guild_delete(guild):
print(f'{guild.name} went offline?')
if not guild.unavailable:
print(f'I got removed from {guild}!')
Event: on_guild_emojis_update¶
Raised when:
- When a guild’s emojis have been updated.
Event Parameters:
guild_id
(int): The guild idemojis
(list): A list of emojis
Event: on_guild_integrations_update¶
Raised when:
- When a guild integration is updated.
Event Parameters:
guild_id
(int): The guild id.
Event: on_guild_member_add¶
Raised when:
- When a new user joins a guild.
Event Parameters:
guild_id
(int): The guild id.member
(GuildMember): The user that joined.
Event: on_guild_member_remove¶
Raised when:
- A user is removed from a guild (leave/kick/ban).
Event Parameters:
guild_id
(int): The guild id.user
(User): The user that was removed/left.
Event: on_guild_member_update¶
Raised when:
- A guild member is updated
Event Parameters:
guild_id
(int): The guild id.roles
(list): User role ids.user
(User): The user.nick
(str): Nickname of the user in the guild.
Event: on_guild_members_chunk¶
Raised when:
- In response to Guild Request Members.
Event Parameters:
guild_id
(int): The guild id.members
(list): Set of guild members
Event: on_guild_role_create¶
Raised when:
- A guild role is created.
Event Parameters:
guild_id
(int): The guild id.role
(Role): The role created
Event: on_guild_role_update¶
Raised when:
- A guild role is updated.
Event Parameters:
guild_id
(int): The guild id.role
(Role): The role updated
Event: on_guild_role_delete¶
Raised when:
- A guild role is deleted.
Event Parameters:
guild_id
(int): The guild id.role_id
(int): The id of the deleted role
Event: on_ban¶
Raised when:
- A user is banned from a guild
Event Parameters:
guild_id
(int): The guild id.user
(User): The banned .
Event: on_ban_remove¶
Raised when:
- A user is unbanned from a guild
Event Parameters:
guild_id
(int): The guild id.user
(User): The unbanned user.
Event: on_message¶
Raised when:
- A user send a message to a channel
Event Parameters:
user_id
(int): The id of the user that started typing.channel_id
(int): The id of the channel where the action happened.timestamp
(int): The timestamp telling when it happened.
@bot.event()
async def on_message(message):
print(f'{message.author}: {message.content}')
Event: on_message_update¶
Raised when:
- A message is updated.
Note: Unlike creates, message updates may contain only a subset of the full message object payload (but will always contain an id and channel_id)
Event Parameters:
message
(ChannelMessage): The Channel message that has been updated
@bot.event()
async def on_message_create(message):
print(f'A message with id {message.id} has been updated.')
Event: on_message_delete¶
Raised when:
- A message is deleted.
Event Parameters:
id
(int): The id of the message.channel_id
(int): The id of the channel.
@bot.event()
async def on_message_delete(id, channel_id):
print(f'A message with id {id} has been deleted.')
Event: on_message_delete_bulk¶
Raised when:
- Multiple messages are deleted at once.
Event Parameters:
ids
(int): The ids of the messageschannel_id
(int): The id of the channel
@bot.event()
async def on_message_delete_bulk(ids, channel_id):
print(f'Multiple messages have been deleted')
Event: on_message_reaction_add¶
Raised when:
- A user adds a reaction to a message
Event Parameters:
user_id
(int): The id of the userchannel_id
(int): The id of the channelmessage_id
(int): The id of the messageemoji
(Emoji): The emoji used to react
@bot.event()
async def on_message_reaction_add(user_id, channel_id, message_id, emoji):
user = await bot.get_user(user_id)
print(f'{user} reacted to a message with {emoji.name}')
Event: on_message_reaction_remove¶
Raised when:
- A user removes a reaction from a message
Event Parameters:
user_id
(int): The id of the userchannel_id
(int): The id of the channelmessage_id
(int): The id of the messageemoji
(Emoji): The emoji used to react
@bot.event()
async def on_message_reaction_add(user_id, channel_id, message_id, emoji):
user = await bot.get_user(user_id)
print(f'{user} removed reaction {emoji.name} from a message.')
Event: on_message_reaction_remove_all¶
Raised when:
- A user explicitly removes all reactions from a message.
Event Parameters:
channel_id
(int): The id of the channelmessage_id
(int): The id of the message
Event: on_presence_update¶
Raised when:
- A user’s presence is updated for a guild.
Note: The user object within this event can be partial, the only field which must be set is the id field
Event Parameters:
user
(User): The user presence is being updated forroles
(list): Ids of the roles this user is ingame
(?Activity): Null, or the user’s current activityguild_id
(int): The guild idstatus
(str): Either “idle”, “dnd”, “online”, or “offline”
Event: on_typing_start¶
Raised when:
- A user starts typing in a channel
Event Parameters:
user_id
(int): The id of the user that started typing.channel_id
(int): The id of the channel where the action happened.timestamp
(int): The timestamp telling when it happened.
@bot.event()
async def on_typing_start(user_id, channel_id, timestamp):
user = await bot.get_user(user_id)
print(f'{user} started typing!')
Event: on_user_update¶
Raised when:
- Properties about the user change
Event Parameters:
user
(User): The user that has been updated
Event: on_voice_state_update¶
Raised when:
- Someone joins/leaves/moves voice channels.
Event Parameters:
voice_state
(VoiceState): The voice state object
Event: on_voice_server_update¶
Raised when:
- A guild’s voice server is updated.
- This is sent when initially connecting to voice, and when the current voice instance fails over to a new server.
Event Parameters:
token
(str): Voice connection token-guild_id
(int): The guild this voice server update is forendpoint
(str): The voice server host
Event: on_webhooks_update¶
Raised when:
- A guild’s voice server is updated.
- This is sent when initially connecting to voice, and when the current voice instance fails over to a new server.
Event Parameters:
guild_id
(int): Id of the guildchannel_id
(int): Id of the channel
discordaio
¶
discord.aio is an asynchronous Discord API wrapper for python 3.6+
Submodules¶
discordaio.activity
¶
Classes¶
Activity
: Represents a discord activityActivityParty
: Activity partyActivityTimestamps
: Activity timestampsActivityAssets
: Activity assets
-
class
discordaio.activity.
Activity
(name='', type=0, url='', timestamps=None, application_id=0, details='', state='', party=None, assets=None)[source]¶ Represents a discord activity
New in version 0.2.0.
-
timestamps
¶ Timestamps
– object unix timestamps for start and/or end of the game
-
party
¶ Party
– object information for the current party of the player
-
assets
¶ Assets
– object images for the presence and their hover texts
Inheritance
-
-
class
discordaio.activity.
ActivityParty
(id='', size=[])[source]¶ Activity party
New in version 0.2.0.
-
size
¶ list
ofint
– array of two integers (current_size, max_size), used to show the party’s current and maximum size
Inheritance
-
-
class
discordaio.activity.
ActivityTimestamps
(start=0, end=0)[source]¶ Activity timestamps
New in version 0.2.0.
Inheritance
discordaio.base
¶
discordaio.channel
¶
Contains all related Channel Discord objects
Classes¶
Channel
: Represents a guild or DM channel within Discord.ChannelMessage
: Represents a message sent in a channel within Discord.Overwrite
: Represents a Overwrite object.MessageActivity
: Represents a Message Activity.MessageApplication
: Represents a Message Application.Reaction
: Represents a Reaction.Embed
: Represents a discord EmbedEmbedThumbnail
: Represents a embed thumbnail objectEmbedVideo
: Represents a embed videoEmbedImage
: Represents a embed imageEmbedProvider
: Represents a embed providerEmbedAuthor
: Represents a embed authorEmbedFooter
: Represents a embed footerEmbedField
: Represents a embed fieldAttachment
: Represents a attachment
-
class
discordaio.channel.
Channel
(id=0, type=0, guild_id=0, position=0, permission_overwrites=[], name='', topic='', nsfw=False, last_message_id=0, bitrate=0, user_limit=0, recipients=[], icon='', owner_id=0, application_id=0, parent_id=0, last_pin_timestamp=None)[source]¶ Represents a guild or DM channel within Discord.
New in version 0.2.0.
-
permission_overwrites
¶ list
ofOverwrite
, optional – explicit permission overwrites for members and roles
-
last_message_id
¶ int
, optional – the id of the last message sent in this channel (may not point to an existing or valid message)
Inheritance
-
-
class
discordaio.channel.
ChannelMessage
(id=0, channel_id=0, author=None, content='', timestamp=None, edited_timestamp=None, tts=False, mention_everyone=False, mentions=[], mention_roles=[], attachments=[], embeds=[], reactions=[], nonce=0, pinned=False, webhook_id=0, type=0, activity=<discordaio.channel.MessageActivity object>, application=<discordaio.channel.MessageApplication object>)[source]¶ Represents a message sent in a channel within Discord.
New in version 0.2.0.
Note
The author object follows the structure of the
User
object, but is only a valid user in the case where the message is generated by a user or bot user. If the message is generated by aWebhook
, the author object corresponds to the webhook’s id, username, and avatar. You can tell if a message is generated by a webhook by checking for the webhook_id on the message object.user – object the author of this message (not guaranteed to be a valid user, see below)
-
attachments
¶ list
ofAttachment
– objects any attached files
-
activity
¶ MessageActivity – activity object sent with Rich Presence-related chat embeds
-
application
¶ MessageApplication – application object sent with Rich Presence-related chat embeds
Inheritance
-
class
discordaio.channel.
Overwrite
(id=0, type='', allow=0, deny=0)[source]¶ Represents a Overwrite object.
New in version 0.2.0.
Inheritance
-
class
discordaio.channel.
MessageActivity
(type=None, party_id='')[source]¶ Represents a Message Activity.
New in version 0.2.0.
Inheritance
-
class
discordaio.channel.
MessageApplication
(id=0, cover_image='', description='', icon='', name='')[source]¶ Represents a Message Application.
New in version 0.2.0.
Inheritance
-
class
discordaio.channel.
Reaction
(count=0, me=False, emoji=None)[source]¶ Represents a Reaction.
New in version 0.2.0.
Inheritance
-
class
discordaio.channel.
Embed
(title='', type='', description='', url='', timestamp=None, color=0, footer=<discordaio.channel.EmbedFooter object>, image=<discordaio.channel.EmbedImage object>, thumbnail=<discordaio.channel.EmbedThumbnail object>, video=<discordaio.channel.EmbedVideo object>, provider=<discordaio.channel.EmbedProvider object>, author=<discordaio.channel.EmbedAuthor object>, fields=[])[source]¶ Represents a discord Embed
New in version 0.2.0.
EmbedFooter
– footer information
-
image
¶ EmbedImage
– image information
-
thumbnail
¶ EmbedThumbnail
– thumbnail information
-
video
¶ EmbedVideo
– video information
-
provider
¶ EmbedProvider
– provider information
EmbedAuthor
– author information
-
fields
¶ list
ofEmbedField
– fields information
Inheritance
-
class
discordaio.channel.
EmbedThumbnail
(url='', proxy_url='', height=0, width=0)[source]¶ Represents a embed thumbnail object
New in version 0.2.0.
Inheritance
-
class
discordaio.channel.
EmbedVideo
(url='', height=0, width=0)[source]¶ Represents a embed video
New in version 0.2.0.
Inheritance
-
class
discordaio.channel.
EmbedImage
(url='', proxy_url='', height=0, width=0)[source]¶ Represents a embed image
New in version 0.2.0.
Inheritance
-
class
discordaio.channel.
EmbedProvider
(name='', url='')[source]¶ Represents a embed provider
New in version 0.2.0.
Inheritance
-
class
discordaio.channel.
EmbedAuthor
(name='', url='', icon_url='', proxy_icon_url='')[source]¶ Represents a embed author
New in version 0.2.0.
Inheritance
Represents a embed footer
New in version 0.2.0.
str
– footer text
str
– url of footer icon (only supports http(s) and attachments)
str
– a proxied url of footer icon
Inheritance
-
class
discordaio.channel.
EmbedField
(name='', value='', inline=False)[source]¶ Represents a embed field
New in version 0.2.0.
Inheritance
discordaio.client
¶
Classes¶
DiscordBot
: This class represents a discord bot object, it has many utility methods for making a bot.
-
class
discordaio.client.
DiscordBot
(token: str)[source]¶ This class represents a discord bot object, it has many utility methods for making a bot.
New in version 0.2.0.
-
http
¶ HTTPHandler
– Used for making http requests and websocket creation.
-
ws
¶ DiscordWebsocket
– The websocket used for communication
Inheritance
-
await
delete_channel
(channel_id: int) → discordaio.channel.Channel[source]¶ Deletes a channel.
Note
Delete a channel, or close a private message. Requires the ‘MANAGE_CHANNELS’ permission for the guild. Deleting a category does not delete its child channels; they will have their parent_id removed and a Channel Update Gateway event will fire for each of them. Returns a channel object on success. Fires a Channel Delete Gateway event.
New in version 0.2.0.
Parameters: channel_id ( int
) – The channel idReturns: The deleted channel Return type: Channel
-
event
(name: str = None)[source]¶ DiscordBot event decorator, uses the function’s name or the ‘name’ parameter to subscribe to a event
New in version 0.2.0.
-
await
get_channel
(channel_id: int) → discordaio.channel.Channel[source]¶ Gets a channel from it’s id
New in version 0.2.0.
Parameters: channel_id ( int
) – The channel idReturns: The channel Return type: Channel
-
await
get_dms
() → list[source]¶ Gets a list of dms.
New in version 0.2.0.
Returns: The DMs channels Return type: list
ofChannel
-
await
get_guild
(guild_id: int) → discordaio.guild.Guild[source]¶ Returns a Guild object from a guild id.
New in version 0.2.0.
Parameters: guild_id ( int
) – The guild idReturns: The requested guild Return type: Guild
-
await
get_guild_member
(guild: discordaio.guild.Guild, member_id: int) → discordaio.guild.GuildMember[source]¶ Gets a guild member info for the guild and the member id.
New in version 0.2.0.
Parameters: Returns: The guild member
Return type:
-
await
get_guild_members
(guild: discordaio.guild.Guild)[source]¶ Gets and fills the guild with the members info.
New in version 0.2.0.
Parameters: guild ( Guild
) – The guild to fill the members.
-
await
get_guilds
() → list[source]¶ Returns a list of guilds where the bot is in.
New in version 0.2.0.
-
await
get_self_user
() → discordaio.user.User[source]¶ Returns the bot user object. (it’s like get_user(‘@me’))
New in version 0.2.0.
-
await
get_user
(id: int) → discordaio.user.User[source]¶ Gets the user object from the given user id.
New in version 0.2.0.
Parameters: id ( int
) – The user idReturns: The requested user Return type: User
-
discordaio.constants
¶
Variables¶
-
discordaio.constants.
DISCORD_CDN
¶ str(object=’‘) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’. .. code-block:: guess
-
discordaio.constants.
DISCORD_API_URL
¶ str(object=’‘) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’. .. code-block:: guess
discordaio.emoji
¶
discordaio.enums
¶
Classes¶
MessageNotificationLevel
: An enumeration.ExplicitContentFilterLevel
: An enumeration.MFALevel
: An enumeration.VerificationLevel
: An enumeration.ChannelTypes
: An enumeration.MessageActivityTypes
: An enumeration.GatewayOpcodes
: An enumeration.
discordaio.exceptions
¶
Exceptions¶
WebSocketCreationError
: Common base class for all non-exit exceptions.EventTypeError
: Common base class for all non-exit exceptions.AuthorizationError
: Common base class for all non-exit exceptions.
discordaio.guild
¶
Classes¶
Guild
: Represents a guildGuildMember
: Represents a guild memberGuildEmbed
: Represents a guild embedIntegrationAccount
: Represents a integration accountIntegration
: Represents a integrationBan
: Represents a ban
-
class
discordaio.guild.
Guild
(id=0, name='', icon='', splash='', owner=False, owner_id=0, permissions=0, region='', afk_channel_id=0, afk_timeout=0, embed_enabled=False, embed_channel_id=0, verification_level=0, default_message_notifications=0, explicit_content_filter=0, roles=[], emojis=[], features=[], mfa_level=0, application_id=0, widget_enabled=False, widget_channel_id=0, system_channel_id=0, joined_at=None, large=None, unavailable=None, member_count=None, voice_states=None, members=[], channels=None, presences=None)[source]¶ Represents a guild
New in version 0.2.0.
Note
Guilds in Discord represent an isolated collection of users and channels, and are often referred to as “servers” in the UI.
-
permissions
¶ int
, optional – total permissions for the user in the guild (does not include channel overrides)
bool
, optional – is this guild unavailable
Inheritance
-
get_icon
() → str[source]¶ Returns the guild icon
New in version 0.2.0.
Returns: The icon link Return type: str
-
get_splash
()[source]¶ Returns the guild splash
New in version 0.2.0.
Returns: The splash link Return type: str
-
is_owner
(member: discordaio.guild.GuildMember) → bool[source]¶ Returns wether the guild member is the owner of the guild
New in version 0.2.0.
Parameters: member ( GuildMember
) – The memberReturns: True if it’s the owner, False otherwise. Return type: bool
-
-
class
discordaio.guild.
GuildMember
(user=<User Object: #, 0>, nick='', roles=[], joined_at=None, deaf=False, mute=False)[source]¶ Represents a guild member
New in version 0.2.0.
Inheritance
-
class
discordaio.guild.
GuildEmbed
(enabled=False, channel_id=0)[source]¶ Represents a guild embed
New in version 0.2.0.
Inheritance
-
class
discordaio.guild.
IntegrationAccount
(id='', name='')[source]¶ Represents a integration account
New in version 0.2.0.
Inheritance
discordaio.http
¶
discordaio.invite
¶
Classes¶
Invite
: Represents a code that when used, adds a user to a guild.InviteMetadata
: Represents the invite metadata
-
class
discordaio.invite.
Invite
(code='', guild=None, channel=None)[source]¶ Represents a code that when used, adds a user to a guild.
New in version 0.2.0.
Inheritance
discordaio.role
¶
discordaio.user
¶
Users in Discord are generally considered the base entity. Users can spawn across the entire platform, be members of guilds, participate in text and voice chat, and much more. Users are separated by a distinction of “bot” vs “normal.” Although they are similar, bot users are automated users that are “owned” by another user. Unlike normal users, bot users do not have a limitation on the number of Guilds they can be a part of.
Classes¶
User
: Represents a discord userUserConnection
: Represents a discord user connection
-
class
discordaio.user.
User
(id=0, username='', discriminator='', avatar='', bot=False, mfa_enabled=False, verified=False, email='')[source]¶ Represents a discord user
New in version 0.2.0.
Inheritance
discordaio.version
¶
Variables¶
-
discordaio.version.
__version__
¶ str(object=’‘) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’. .. code-block:: guess
‘0.2.1’
discordaio.voice
¶
Classes¶
VoiceState
: Used to represent a user’s voice connection status.VoiceRegion
: Attributes:
-
class
discordaio.voice.
VoiceState
(guild_id: typing.Union[int, NoneType] = None, channel_id: int = 0, user_id: int = 0, session_id: str = '', deaf=False, mute=False, self_deaf=False, self_mute=False, suppress=False)[source]¶ Used to represent a user’s voice connection status.
Inheritance
discordaio.webhook
¶
Webhooks are a low-effort way to post messages to channels in Discord. They do not require a bot user or authentication to use.
Classes¶
Webhook
: Used to represent a webhook.
discordaio.websocket
¶
Classes¶
DiscordWebsocket
: Class used for handling the websocket connection with the discord gateway
-
class
discordaio.websocket.
DiscordWebsocket
(http: discordaio.http.HTTPHandler = None, session_id: str = None, shards: list = [])[source]¶ Class used for handling the websocket connection with the discord gateway
New in version 0.2.0.
-
http
¶ HTTPHandler
– Used for sending http requests and session handling.
-
ws (
class:aiohttp.ClientWebSocketResponse``): The websocket
Inheritance
-