discordapi
Subpackages
Submodules
discordapi.channeldiscordapi.clientdiscordapi.commanddiscordapi.constdiscordapi.dictobjectdiscordapi.embeddiscordapi.exceptionsdiscordapi.filediscordapi.gatewaydiscordapi.guilddiscordapi.handlerdiscordapi.memberdiscordapi.messagediscordapi.oggdiscordapi.playerdiscordapi.ratelimitdiscordapi.userdiscordapi.utildiscordapi.voicediscordapi.websocket
Package Contents
Classes
Class which handles sending events to Discord. |
|
Handler to handle methods with defined methods. |
|
Object which automatically sets the attribute based on a dict object. |
|
Object which automatically sets the attribute based on a dict object. |
|
Object which automatically sets the attribute based on a dict object. |
|
Object which automatically sets the attribute based on a dict object. |
|
Object which automatically sets the attribute based on a dict object. |
|
Object which automatically sets the attribute based on a dict object. |
|
Object which automatically sets the attribute based on a dict object. |
|
Class which handles sending events to Discord. |
|
Handler to handle methods with defined methods. |
|
Handler to handle methods with defined methods. |
|
Object which automatically sets the attribute based on a dict object. |
|
Object which automatically sets the attribute based on a dict object. |
|
Represents file and name. |
|
Object which automatically sets the attribute based on a dict object. |
|
Base client for EventHandler. |
|
Handler to be used within terminal, or with a simple bot. |
|
Handler to handle methods with defined methods. |
|
Handler to assign functions per events with decorator. |
|
Handler that starts thread automatically per every events. |
|
Same as ThreadedMethodEventHandler, but decorator version. |
|
Object which automatically sets the attribute based on a dict object. |
|
Object which automatically sets the attribute based on a dict object. |
|
AudioSource providing the Opus packet to send to Voice server. |
|
AudioSource that utilizes FFMPEG commandline tool to play audio. |
|
Player to play AudioSource to given VoiceClient. |
|
AudioPlayer that disconnects right after the source finishes. |
|
AudioPlayer with audio queue implemented. |
|
Object which automatically sets the attribute based on a dict object. |
|
Base class for running WebSocket connection. |
Functions
|
Returns a channel object that has a corresponding type with given data. |
Attributes
- class discordapi.DiscordInteractionClient(token, command_manager=None, handler=None, event_parser=None, intents=32509, name='main')
Bases:
discordapi.client.DiscordClientClass which handles sending events to Discord.
- headers
Headers to be used when sending HTTP request.
- _activities
Activity objects used when sending UPDATE_PRESENCE event- This attribute is required as changing status resets the activities.
- ratelimit_handler
handler used to handle rate limit accordingly.
- Parameters
url – same as .url attribute
dispatcher – same as .dispatcher attribute
name – same as name argument in threading.Thread
- _set_command_manager(self, manager)
- __send_request(self, method, route, data=None, expected_code=None, raise_at_exc=True, baseurl=None, headers=None)
- get_global_commands(self)
- create_global_command(self, command)
- get_global_command(self, id_)
- edit_global_command(self, id_, command)
- delete_global_command(self, id_)
- bulk_global_commands(self, commands)
- get_guild_commands(self, guild)
- create_guild_command(self, guild, command)
- get_guild_command(self, guild, id_)
- edit_guild_command(self, guild, id_, command)
- delete_guild_command(self, guild, id_)
- bulk_guild_commands(self, guild, commands)
- get_guild_permissions(self, guild)
- get_command_permissions(self, guild, id_)
- edit_command_permissions(self, guild, id_, permissions)
- batch_command_permissions(self, guild, permissions)
- class discordapi.InteractionEventHandler(client=None)
Bases:
discordapi.handler.MethodEventHandlerHandler to handle methods with defined methods.
This handler calls .on_{lowercased event type} method when event issues. e.g. self.on_message_create method gets called when MESSAGE_CREATE fires. If the corresponding method has not defined, It does nothing.
The arguments handlers will receive is the same as .handle method.
Since this runs on a main client thread, running a time-consuming job will block other events from reaching the client, stopping the bot from functioning. Please start another thread for those jobs.
No method other than .handle comes predefined, You have to either inherit this method or assign functions as attributes to use this.
- on_interaction_create(self, obj)
- class discordapi.InteractionEventParser(client=None)
Bases:
discordapi.gateway.GatewayEventParser- on_interaction_create(self, payload)
- class discordapi.Context(client, data)
Bases:
discordapi.dictobject.DictObjectObject which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- __str__(self)
Return str(self).
- __repr__(self)
Return repr(self).
- class discordapi.Option(type_, name, desc, choices, required, opts=None)
- _json(self)
- classmethod from_command(cls, cmd)
- class discordapi.SubCommand(name, desc, *commands, default_permission=True)
Bases:
SlashCommand- run(self, ctx, **kwargs)
- class discordapi.SubCommandGroup(name, desc, *commands, default_permission=True)
Bases:
SubCommand
- class discordapi.SlashCommand(func, name, desc, options=[], default_permission=True, argcheck=True)
- classmethod create(cls, desc, options=[], default_permission=True, cmdname=None)
- execute(self, ctx, options, manager)
- _json(self)
- class discordapi.SlashCommandManager(client=None)
- _set_client(self, client)
- register(self, command)
- update(self)
- execute(self, ctx)
- respond(self, ctx, type_, message=None)
- edit(self, ctx, content=EMPTY, file=None, embeds=EMPTY, allowed_mentions=EMPTY, components=EMPTY)
- delete(self, ctx)
- discordapi.get_channel(client, data, guild=None)
Returns a channel object that has a corresponding type with given data.
Type is determined from ‘type’ key. If the object came from the proper source, its type should be integer. Exception occurs if it doesn’t.
This function only determines the correct subclass to make instance with. Rest of the initialization is done under __init__ from each classes.
- Parameters
client (DiscordClient) – DiscordClient object which a generated object will use.
data (dict) – Dictionary containing channel object returned from Discord.
guild (Guild) – Guild object for generated object to use. Can be ommited if the channel is not included in a guild.
- Returns
instance of Channel with corresponding type.
- Return type
- Raises
ValueError – Raised If the key ‘type’ is not included in data or not integer.
- class discordapi.Channel(client, data)
Bases:
discordapi.dictobject.DictObject
Object which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- modify(self, postdata)
- delete(self)
- get_messages(self, limit=EMPTY, around=EMPTY, before=EMPTY, after=EMPTY)
- get_message(self, id_)
- send(self, content=EMPTY, tts=EMPTY, file=None, embeds=None, embed=None, allowed_mentions=EMPTY, reply_to=None, components=EMPTY)
- edit_message(self, message, content=EMPTY, file=None, embeds=None, embed=None, flags=EMPTY, allowed_mentions=EMPTY, attachments=EMPTY, components=EMPTY)
- delete_message(self, message)
- delete_messages(self, messages)
- typing(self)
- get_pinned_messages(self)
- pin_message(self, message)
- unpin_message(self, message)
- react(self, message, emoji, urlencoded=False)
- delete_my_reaction(self, message, emoji, urlencoded=False)
- delete_others_reaction(self, message, emoji, user, urlencoded=False)
- get_reactions(self, message, emoji, limit=EMPTY, after=EMPTY, urlencoded=False)
- delete_all_reactions(self, message)
- delete_all_reactions_for_emoji(self, message, emoji, urlencoded=False)
- _send_request(self, method, route, data=None, expected_code=None, raise_at_exc=True, baseurl=None, headers=None)
- class discordapi.DMChannel(client, data)
Bases:
Channel
Object which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- class discordapi.GroupDMChannel(client, data)
Bases:
DMChannel
Object which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- modify(self, name=EMPTY, icon=None)
- class discordapi.GuildChannel(client, data, guild=None)
Bases:
Channel
Object which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- get_parent(self)
- edit_permission(self, id_, allow=EMPTY, deny=EMPTY, type=EMPTY)
- remove_permission(self, id_)
- get_invites(self)
- invite(self, max_age=86400, max_uses=0, temporary=False, unique=False, target_type=EMPTY, target_user_id=EMPTY, target_application_id=EMPTY)
- class discordapi.GuildTextChannel(client, data, guild=None)
Bases:
GuildChannel
Object which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- modify(self, name=EMPTY, position=EMPTY, topic=EMPTY, nsfw=EMPTY, rate_limit_per_user=EMPTY, permission_overwrites=EMPTY, parent_id=EMPTY)
- crosspost(self, message)
- follow_news_channel(self, id_)
- class discordapi.GuildVoiceChannel(client, data, guild=None)
Bases:
GuildChannel
Object which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- modify(self, name=EMPTY, position=EMPTY, bitrate=EMPTY, user_limit=EMPTY, permission_overwrites=EMPTY, parent_id=EMPTY, rtc_region=EMPTY, video_quality_mode=EMPTY)
- connect(self, mute=False, deaf=False, timeout=10)
Connects the bot to the voice channel.
This method will fire a Gateway event to initialize connection to the voice server, create DiscordVoiceClient object, add it to client.voice_clients and return the client. Please note that client would most likely not be ready to run when it gets returned- please check its availability using .is_ready method or .ready_to_run Event attribute. AudioPlayer will also check this.
- class discordapi.DiscordClient(token, handler=None, event_parser=None, intents=32509, name='main')
Bases:
discordapi.gateway.DiscordGatewayClass which handles sending events to Discord.
- headers
Headers to be used when sending HTTP request.
- _activities
Activity objects used when sending UPDATE_PRESENCE event- This attribute is required as changing status resets the activities.
- ratelimit_handler
handler used to handle rate limit accordingly.
- Parameters
url – same as .url attribute
dispatcher – same as .dispatcher attribute
name – same as name argument in threading.Thread
- get_guilds(self)
- get_guild(self, id_)
- get_channels(self)
- get_channel(self, id_)
- get_users(self)
- get_user(self, id_)
- update_presence(self, activities=None, status=None, afk=False, since=None)
Updates the presence- This includes its status and activities.
You can use this method to change the bot’s status, as well as its activities. Activities will be stored on ._activities attribute and will carry over other changes. If you want to reset the Activities, pass an empty list or tuple to activities argument.
- Parameters
activities – A list/tuple of array, or a single object of Activity object in dict type. This will be saved into ._activities attribute.
status – Status string. Possible values are; online, idle, dnd, invisible, offline.
- update_voice_state(self, guild_id, channel_id=None, mute=False, deaf=False)
- request_guild_member(self, guild_id, query='', limit=0, presences=EMPTY, user_ids=EMPTY, nonce=EMPTY)
- modify_user(self, username=EMPTY, avatar=EMPTY)
- leave_guild(self, guild)
- create_dm(self, user)
- get_connections(self)
- fetch_user(self, id_)
- fetch_channel(self, id_)
- create_guild(self, name, icon=None, verification_level=EMPTY, default_message_notifications=EMPTY, explicit_content_filter=EMPTY, roles=EMPTY, channels=EMPTY, afk_channel_id=EMPTY, afk_timeout=EMPTY, system_channel_id=EMPTY, system_channel_flags=EMPTY)
- fetch_guild(self, id_, with_counts=False)
Returns guild object.
This method sends request to HTTP API to fetch the object. Most of the time, this is probably not what you want. Try to find the guild in .guilds Attribute by calling client.guilds.get(guild_id).
- get_guild_preview(self, id_)
- send_request(self, method, route, data=None, expected_code=None, raise_at_exc=True, baseurl=API_URL, headers=None)
Sends HTTP API request.
It sends the request, parses result data, checks ratelimit, and returns result data in JSON format.
- Parameters
method – HTTP method to use- e.g. GET, POST, DELETE, etc…
route – API subdirectory to send request to. e.g. /channels/id
data – POST data to send to, as a dictionary, refer to urllib.request for details.
expected_code – HTTP return code to check for. If this code mismatches and raise_at_exc is true, This will raise DiscordHTTPError.
raise_at_exc – Whether or not to throw exception when urllib.request raises HTTPError or return code is not what we were expecting. If this is true, DiscordHTTPError will be raised.
baseurl – Base URL to construct full URL with. Defaluts to Discord API endpoint.
headers – Headers to use when sending requests. It contains User-Agent, Autorization, Content-Type by default. Should be used if Content-Type is not application/json .
- Returns
Dict made out of JSON object returned from API.
- Raises
DiscordHTTPError – Raised when HTTPError is raised, or unexpected code is returned
- _send_request(self, method, route, data=None, baseurl=API_URL, headers=None)
Returns Response object directly.
- Parameters
method – HTTP method to use- e.g. GET, POST, DELETE, etc…
route – API subdirectory to send request to. e.g. /channels/id
data – POST data to send to, as a dictionary, refer to urllib.request for details.
baseurl – Base URL to construct full URL with. Defaluts to Discord API endpoint.
headers – Headers to use when sending requests. It contains User-Agent, Autorization, Content-Type by default. Should be used if Content-Type is not application/json.
- Returns
A tuple of (Response, exc) where exc determines whether an exception was occured or not. If HTTPError was thrown, Response object would be a catched exception, but there’s no difference in its functionality.
- exception discordapi.CommandError(command, title, message)
Bases:
Exception
Common base class for all non-exit exceptions.
Initialize self. See help(type(self)) for accurate signature.
- class discordapi.CommandManager(client=None)
- _set_client(self, client)
- execute_cmd(self, cmdinput, message)
- class discordapi.EmbedCommandManager(client=None)
Bases:
CommandManager
- set_color(self, color)
- execute_cmd(self, cmdinput, message)
- class discordapi.CommandEventHandler(manager, prefix)
Bases:
discordapi.handler.MethodEventHandler
Handler to handle methods with defined methods.
This handler calls .on_{lowercased event type} method when event issues. e.g. self.on_message_create method gets called when MESSAGE_CREATE fires. If the corresponding method has not defined, It does nothing.
The arguments handlers will receive is the same as .handle method.
Since this runs on a main client thread, running a time-consuming job will block other events from reaching the client, stopping the bot from functioning. Please start another thread for those jobs.
No method other than .handle comes predefined, You have to either inherit this method or assign functions as attributes to use this.
- _set_manager(self, manager)
- on_message_create(self, message)
- class discordapi.ThreadedCommandEventHandler(manager, prefix)
Bases:
CommandEventHandler,discordapi.handler.ThreadedMethodEventHandler
Handler to handle methods with defined methods.
This handler calls .on_{lowercased event type} method when event issues. e.g. self.on_message_create method gets called when MESSAGE_CREATE fires. If the corresponding method has not defined, It does nothing.
The arguments handlers will receive is the same as .handle method.
Since this runs on a main client thread, running a time-consuming job will block other events from reaching the client, stopping the bot from functioning. Please start another thread for those jobs.
No method other than .handle comes predefined, You have to either inherit this method or assign functions as attributes to use this.
- discordapi.path
- discordapi.LIB_NAME = nicobot
- discordapi.LIB_VER
- discordapi.LIB_URL = https://github.com/KokoseiJ/NicoBot
- discordapi.GATEWAY_VER = 9
- discordapi.GATEWAY_URL
- discordapi.API_VER = 9
- discordapi.API_URL
- discordapi.CDN_URL = https://cdn.discordapp.com/
- discordapi.VOICE_VER = 4
- discordapi.EMPTY
- class discordapi.DictObject(data, keylist=[])
Object which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- _get_str(self, class_, id_, repr_=None)
- __str__(self)
Return str(self).
- __repr__(self)
Return repr(self).
- __eq__(self, other)
Return self==value.
- class discordapi.Embed(*args, **kwargs)
Bases:
discordapi.dictobject.DictObjectObject which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- set_thumbnail(self, url, height=None, width=None)
- add_field(self, name, value, inline=False)
- set_author(self, name, url=None, icon=None)
- exception discordapi.DiscordError
Bases:
ExceptionBase Exception for Discord Errors.
Initialize self. See help(type(self)) for accurate signature.
- exception discordapi.DiscordHTTPError(code, message, response)
Bases:
DiscordErrorException to be thrown when error occurs from Discord HTTP API.
- code
Error code specified by API.
- message
Message specified by API.
- response
http.cilent.HTTPResponse object containing the error
Initialize self. See help(type(self)) for accurate signature.
- class discordapi.File(obj=None)
Represents file and name.
This object could be constructed by either using a traditional constructor for simple usages, or using .from_path, .from_io, .from_bytes classmethods for explicity. Refer to each methods for detailed usage.
- name
string representing the filename. This could be different from the actual file this object is pointing to.
- path
An absolute path to the file. This could be None if the instance was constructed from BytesIO or bytes, in which case fileobj should not be None.
- fileobj
io object to the actual file content. This could be None if .read() method wasn’t called yet- in which case path should not be None.
Creates File object.
- Parameters
obj –
This could be str, BytesIO, bytes, bytearray or tuple/list. str will be assumed as a path to the file- while other types except tuple/list would be used as a file content itself.
if the type is tuple/list, it should be formatted as following: (filename, obj) where filename is str and obj is as explained.
if the type is BytesIO/bytes/bytearray and filename is not given, filename will be defaulted as “file”.
- Raises
ValueError – Raised if the argument doesn’t satisfy the requirements.
FileNotFoundError – Raised if obj was str and given path does not exist.
IsADirectoryError – Raised if obj was str and given path was a dir.
- classmethod from_path(cls, path, name=None)
Creates File object from path.
- Parameters
path – str object representing the filepath. It can be either relative or absolute.
name – str object representing the name.
- Raises
ValueError – Raised if the argument doesn’t satisfy the requirements.
FileNotFoundError – Raised if obj was str and given path does not exist.
IsADirectoryError – Raised if obj was str and given path was a dir.
- classmethod from_io(cls, name, io)
Creates File object from io.
- Parameters
name – str object representing the name.
io – BytesIO object representing the file to read.
- Raises
ValueError – Raised if the argument doesn’t satisfy the requirements.
FileNotFoundError – Raised if obj was str and given path does not exist.
IsADirectoryError – Raised if obj was str and given path was a dir.
- classmethod from_bytes(cls, name, byteobj)
Creates File object from bytes.
- Parameters
name – str object representing the name.
byteobj – bytes/bytearray object representing the file to read.
- Raises
ValueError – Raised if the argument doesn’t satisfy the requirements.
FileNotFoundError – Raised if obj was str and given path does not exist.
IsADirectoryError – Raised if obj was str and given path was a dir.
- get_name(self)
- read(self, *args, **kwargs)
- _prep_read(self)
- _from_path(self, path, name=None)
- _from_io(self, name, obj)
- _from_bytes(self, name, bytes)
- class discordapi.Guild(client, data)
Bases:
discordapi.dictobject.DictObjectObject which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- get_channels(self)
- get_channel(self, id_)
- get_members(self)
- get_preview(self)
- modify(self, name=EMPTY, region=EMPTY, verification_level=EMPTY, default_message_notifications=EMPTY, explicit_content_filter=EMPTY, afk_channel_id=EMPTY, afk_timeout=EMPTY, icon=None, owner_id=EMPTY, splash=EMPTY, discovery_splash=EMPTY, banner=EMPTY, system_channel_id=EMPTY, system_channel_flags=EMPTY, rules_channel_id=EMPTY, public_updates_channel_id=EMPTY, preferred_locale=EMPTY, features=EMPTY, description=EMPTY)
- delete(self)
- leave(self)
- fetch_channels(self)
- create_channel(self, name, type, topic=EMPTY, bitrate=EMPTY, user_limit=EMPTY, rate_limit_per_user=EMPTY, position=EMPTY, permission_overwrites=EMPTY, parent_id=EMPTY, nsfw=EMPTY)
- modify_channel_positions(self, params={})
- get_member(self, user)
- list_members(self, limit=EMPTY, after=EMPTY)
- search_members(self, query=EMPTY, limit=EMPTY)
- modify_member(self, member, nick=EMPTY, roles=EMPTY, mute=EMPTY, deaf=EMPTY, channel_id=EMPTY)
- change_my_nick(self, nick)
- add_role_to_member(self, member, role)
- remove_role_from_member(self, member, role)
- kick(self, member)
- get_bans(self)
- get_ban(self, member)
- ban(self, member)
- remove_ban(self, member)
- get_roles(self)
- create_role(self, name, permission=EMPTY, color=EMPTY, hoist=EMPTY, mentionable=EMPTY)
- modify_role_position(self, params)
- modify_guild_role(self, role, name=EMPTY, permissions=EMPTY, color=EMPTY, hoist=EMPTY, mentionable=EMPTY)
- delete_role(self, role)
- get_voice_regions(self)
- get_invites(self)
- _send_request(self, method, route, data=None, expected_code=None, raise_at_exc=True, baseurl=None, headers=None)
- class discordapi.EventHandler(client=None)
Base client for EventHandler.
- self.client
- set_client(self, client)
Sets client to be used.
Required to provide client-side interface and contexts to handlers.
- abstract handle(self, event, obj)
Handler function to handle the event.
This method handles the event fired by the Gateway. Since this runs on a main client thread, running a time-consuming job will block other events from reaching the client, stopping the bot from functioning. Please start another thread for those jobs.
This method should be implemented by the inherited class.
- Parameters
event – str indicating the type of this event. comes in ALL_CAPS.
obj – Corresponding type of object for the event. Possible types are: Channel/Guild/Member/Message/dict. Check DiscordGateway._event_parser method to see how things are handled.
- class discordapi.GeneratorEventHandler(client=None)
Bases:
EventHandlerHandler to be used within terminal, or with a simple bot.
This handler provides a new way to handle events- by using a generator. By iterating through .event_generator method with for loop, You can receive events without declaring additional functions, which is suitable for simple usages.
- event_queue
Queue object storing events.
- handle(self, event, obj)
Handler function to handle the event.
This method handles the event fired by the Gateway. Since this runs on a main client thread, running a time-consuming job will block other events from reaching the client, stopping the bot from functioning. Please start another thread for those jobs.
This method should be implemented by the inherited class.
- Parameters
event – str indicating the type of this event. comes in ALL_CAPS.
obj – Corresponding type of object for the event. Possible types are: Channel/Guild/Member/Message/dict. Check DiscordGateway._event_parser method to see how things are handled.
- event_generator(self)
Generator yielding events.
Yielded data will be in a tuple of (event, obj)- where event is the type of the object and obj is the object itself. Same as .handle args.
This generator could be used like this:
for event, obj in handler.event_generator(): print(f"{event}: {obj}")
or, in the interpreter: like this:
>>> gen = handler.event_generator() >>> event, obj = next(gen) >>> print(f"{event}: {obj}") >>> # Rinse and repeat
Additionally, This generator silences KeyboardInterrupt exception.
- class discordapi.MethodEventHandler(client=None)
Bases:
EventHandlerHandler to handle methods with defined methods.
This handler calls .on_{lowercased event type} method when event issues. e.g. self.on_message_create method gets called when MESSAGE_CREATE fires. If the corresponding method has not defined, It does nothing.
The arguments handlers will receive is the same as .handle method.
Since this runs on a main client thread, running a time-consuming job will block other events from reaching the client, stopping the bot from functioning. Please start another thread for those jobs.
No method other than .handle comes predefined, You have to either inherit this method or assign functions as attributes to use this.
- handle(self, event, obj)
Handler function to handle the event.
This method handles the event fired by the Gateway. Since this runs on a main client thread, running a time-consuming job will block other events from reaching the client, stopping the bot from functioning. Please start another thread for those jobs.
This method should be implemented by the inherited class.
- Parameters
event – str indicating the type of this event. comes in ALL_CAPS.
obj – Corresponding type of object for the event. Possible types are: Channel/Guild/Member/Message/dict. Check DiscordGateway._event_parser method to see how things are handled.
- class discordapi.DecoratorEventHandler(client=None)
Bases:
EventHandler
Handler to assign functions per events with decorator.
It lets you assign individual handlers per events using decorator, similar to how other libraries such as Discord.py and Telethon works.
You can use @handler.on(“event_name”) to assign the handler.
function to be assigned should receive a single arguments- the object returned from the gateway. Handler is being provided in a second argument as a purpose of giving context.
Other than decorator, This handler behaves similar to MethodEventHandler.
- handle(self, event, obj)
Handler function to handle the event.
This method handles the event fired by the Gateway. Since this runs on a main client thread, running a time-consuming job will block other events from reaching the client, stopping the bot from functioning. Please start another thread for those jobs.
This method should be implemented by the inherited class.
- Parameters
event – str indicating the type of this event. comes in ALL_CAPS.
obj – Corresponding type of object for the event. Possible types are: Channel/Guild/Member/Message/dict. Check DiscordGateway._event_parser method to see how things are handled.
- on(self, event)
- class discordapi.ThreadedMethodEventHandler(client=None)
Bases:
MethodEventHandlerHandler that starts thread automatically per every events.
Since handler runs on a main client thread, time-consuming actions will block other events from reaching, stopping the bot from functioning. this handler will counter that problem by starting a new thread for every events being fired.
This is a basic implementation with no limits or safety measures being placed whatsoever, and could be critical to performance. I recommend implementing your own handler with appropriate safety measures in place.
- handle(self, event, obj)
Handler function to handle the event.
This method handles the event fired by the Gateway. Since this runs on a main client thread, running a time-consuming job will block other events from reaching the client, stopping the bot from functioning. Please start another thread for those jobs.
This method should be implemented by the inherited class.
- Parameters
event – str indicating the type of this event. comes in ALL_CAPS.
obj – Corresponding type of object for the event. Possible types are: Channel/Guild/Member/Message/dict. Check DiscordGateway._event_parser method to see how things are handled.
- class discordapi.ThreadedDecoratorEventHandler(client=None)
Bases:
DecoratorEventHandler
Same as ThreadedMethodEventHandler, but decorator version.
Refer to ThreadMethodEventHandler for details, those cautions apply here too.
- handle(self, event, obj)
Handler function to handle the event.
This method handles the event fired by the Gateway. Since this runs on a main client thread, running a time-consuming job will block other events from reaching the client, stopping the bot from functioning. Please start another thread for those jobs.
This method should be implemented by the inherited class.
- Parameters
event – str indicating the type of this event. comes in ALL_CAPS.
obj – Corresponding type of object for the event. Possible types are: Channel/Guild/Member/Message/dict. Check DiscordGateway._event_parser method to see how things are handled.
- class discordapi.Member(client, guild, data)
Bases:
discordapi.dictobject.DictObjectObject which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- modify(self, nick=EMPTY, roles=EMPTY, mute=EMPTY, deaf=EMPTY, channel_id=EMPTY)
- add_role(self, role)
- remove_role(self, role)
- kick(self)
- ban(self)
- __str__(self)
Return str(self).
- class discordapi.Message(client, data)
Bases:
discordapi.dictobject.DictObjectObject which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- crosspost(self)
- react(self, emoji, urlencoded=False)
- delete_my_reaction(self, emoji, urlencoded=False)
- delete_others_reaction(self, emoji, user, urlencoded=False)
- get_reactions(self, emoji, limit=EMPTY, after=EMPTY, urlencoded=False)
- delete_all_reactions(self)
- delete_all_reactions_for_emoji(self, emoji, urlencoded=False)
- edit(self, content=EMPTY, file=None, embeds=EMPTY, flags=EMPTY, allowed_mentions=EMPTY, attachments=EMPTY, components=EMPTY)
- delete(self)
- pin(self)
- unpin(self)
- __str__(self)
Return str(self).
- class discordapi.AudioSource
AudioSource providing the Opus packet to send to Voice server.
- prepare(self)
Preparation to do before the song plays.
This method gets called before it starts playing. You can e.g. download the audio file, spawn a process, connect to remote server, etc etc.
Whether to override this method or not is your choice.
- abstract read(self)
Method that returns a packet of Opus audio stream to be sent.
Return empty value (b’’) if the audio stream has finished.
Each packet contains around 20ms worth of data. If you’re sending Opus data stored in Ogg container(which is also what FFMPEG uses), You can extract each packets from it and return it right away.
This method should be implemented by the inherited class.
- cleanup(self)
Method to clean things after audio stops playing.
This method gets called after the audio stops. You can e.g. remove the used audio file, kill the used process, etc etc.
Whether to override this method or not is your choice.
- class discordapi.FFMPEGAudioSource(filename, inputargs=None, outputargs=None, ffmpeg='ffmpeg')
Bases:
AudioSource
AudioSource that utilizes FFMPEG commandline tool to play audio.
This class requires ffmpeg to be installed on the system.
Initialize the ffmpeg settings.
- Parameters
filename – Input file to process. gets passed straight into -i.
inputargs – Options to be used in input stream.
outputargs – Options to be used in output stream.
ffmpeg – directory to the binary. defaults to “ffmpeg”.
- prepare(self)
Starts FFMPEG process and initializes Ogg parser.
- read(self)
Method that returns a packet of Opus audio stream to be sent.
Return empty value (b’’) if the audio stream has finished.
Each packet contains around 20ms worth of data. If you’re sending Opus data stored in Ogg container(which is also what FFMPEG uses), You can extract each packets from it and return it right away.
This method should be implemented by the inherited class.
- cleanup(self)
Method to clean things after audio stops playing.
This method gets called after the audio stops. You can e.g. remove the used audio file, kill the used process, etc etc.
Whether to override this method or not is your choice.
- class discordapi.AudioPlayer(client=None, source=None, callback=None)
Bases:
discordapi.util.StoppableThread
Player to play AudioSource to given VoiceClient.
This player is designed to be managed separately from the voice client. it will keep on running after the source finishes playing or client stops. you can also change which client to play to, if you want.
This player inherits StoppableThread, will run on a separate thread, and is able to be stopped by calling .stop method.
- client
DiscordVoiceClient to play to.
- source
Source to play with.
- callback
Function to be called after the source finishes.
- _resumed
Event indicating if the player has been paused or not.
- _ready
Event indicating if the player is ready to play.
- _sent_silence
bool indicating if the five frame of silence has been played after the player pauses playing.
- loop
Integer tracking how many packets have been sent so far, to determine when to send the next packet.
- start_time
Integer indicating when the transmission has started, to determine when to send the next packet.
Initializes player.
- Parameters
client – Client to play to.
source – Source to play with.
callback – A function to be called after the song finishes playing. this function receives a single argument which is player object.
- set_client(self, client)
Sets client. Also checks if client is in the right type.
- set_source(self, source)
Sets source. Also checks if source is in the right type.
- set_callback(self, callback)
Sets callback. Also checks if callback is in the right type.
- play(self, source=None)
Starts playing the source.
It can set the source if provided. This method will refuse playing if either client or source is not set.
- stop(self)
- pause(self)
- resume(self)
- _prepare_play(self)
Initializes needed attributes to start playing.
- run(self)
Method representing the thread’s activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
- _send_and_wait(self, data)
- _source_is_finished(self)
- class discordapi.SingleAudioPlayer(client=None, source=None, callback=None)
Bases:
AudioPlayer
AudioPlayer that disconnects right after the source finishes.
Initializes player.
- Parameters
client – Client to play to.
source – Source to play with.
callback – A function to be called after the song finishes playing. this function receives a single argument which is player object.
- _source_is_finished(self)
- class discordapi.QueuedAudioPlayer(client=None, source=None, callback=None)
Bases:
AudioPlayer
AudioPlayer with audio queue implemented.
player keeps on playing until the queue gets empty. .play method can be called again to resume playing.
Initializes player.
- Parameters
client – Client to play to.
source – Source to play with.
callback – A function to be called after the song finishes playing. this function receives a single argument which is player object.
- set_source(self, source)
Sets source. Also checks if source is in the right type.
- add_to_queue(self, source)
Adds list of source to the queue. can be used with single object.
- _update_source(self)
- play(self, source=None)
Starts playing the source.
It can set the source if provided. This method will refuse playing if either client or source is not set.
- _source_is_finished(self)
- class discordapi.RateLimitHandler
- register_bucket(self, route, bucket)
- uniformize_route(self, route)
- get_route(self, route)
- update(self, route, data)
- check_global(self)
- get_data(self, route)
- check(self, route)
- wait_until(self, until)
- class discordapi.User(client, data)
Bases:
discordapi.dictobject.DictObjectObject which automatically sets the attribute based on a dict object.
- _json
The original dict object in which the class was constructed from.
Constructs the class from the data.
This automatically sets the attributes from the dict. additionally, keys in keylist will be set as an attribute with the value of None when the attribute doesn’t exist- this is to ensure that it won’t overwrite the existing keys when running __init__ in already initialized instance.
- dm(self)
- __str__(self)
Return str(self).
- class discordapi.DiscordVoiceClient(client, endpoint, token, session_id, server_id)
Bases:
discordapi.websocket.WebSocketThreadBase class for running WebSocket connection.
It has .do_heartbeat, .init_connection, .cleanup method to be overriden by inherited client, for defining desired behaviour depending on clients.
This class inherits from Thread, and is running as a separate thread. To start the client, you have to invoke .start method as you would with typical threads.
- url
URL of the gateway for this client to connect to.
- dispatcher
Handler to be called when the event has been received. It should recieve a single argument with type of dict.
- ready_to_run
Event object indicating if the event is ready to be used. This event must be set manually by the inherited class.
- _sock
internal WebSocket object to be used to communicate with gateway.
- heartbeat_thread
Thread where .do_heartbeat method runs. This thread runs throughout the lifetime of this thread, so .do_heartbeat should be written with continuability in mind.
- init_thread
Thread where init_thread method runs. It runs in thread so that ._event_loop method could run parellelly. This thread is expected to run quick and quit shortly after.
- Parameters
url – same as .url attribute
dispatcher – same as .dispatcher attribute
name – same as name argument in threading.Thread
- IDENTIFY = 0
- SELECT_PROTOCOL = 1
- READY = 2
- HEARTBEAT = 3
- SESSION_DESCRIPTION = 4
- SPEAKING = 5
- HEARTBEAT_ACK = 6
- RESUME = 7
- HELLO = 8
- RESUMED = 9
- CLIENT_DISCONNECT = 13
- _set_info(self, endpoint, token, session_id, server_id=None)
- reapply_info(self, endpoint, token, session_id, server_id=None)
- get_channel(self)
- speak(self, speaking=1)
Send SPEAKING event to the gateway.
- Parameters
speaking – either bool or integer. True indicates speaking, False indicates that the client is no longer speaking. integer value should be the flag value to be used. Default value is 1.
- disconnect(self)
- _send_voice(self, data)
- xsalsa20_poly1305(self, header, data)
- init_connection(self)
Method to be run when websocket connection establishes.
This method is expected to run shortly, if a problem occurs during the procedure, run .reconnect method which will reestablish the connection.
This method should be implemented by the inherited client.
- send_identify(self)
- ip_discovery(self)
- send_udp(self, data)
- send_protocol(self)
- do_heartbeat(self)
Method to be run when websocket connection establishes.
This method runs throughout the main thread’s lifetime, so you should consider that while overriding the method.
This method should be implemented by the inherited class.
- send_heartbeat(self)
- _get_payload(self, op, d=None, **data)
- cleanup(self)
Method to be called after the client disconnects.
This method exists to reset the attributes when needed. if not, you can just leave this method as is.
Whether to override this method or not is your choice.
- _dispatcher(self, data)
- discordapi.__version__