Как узнать права комнаты discord python

от admin

how do I check if a user has a specific role in discord

ktzr's user avatar

Member does not have a .has_role() method, you can however get a list of all their roles using .roles .

To see if a user has a given role we can use role in user.roles .

Note: ctx.message.guild.roles use to be ctx.message.server.roles . Updated due to API change.

ktzr's user avatar

Personally I use this:

So as you can see

role = discord.utils.get(ctx.guild.roles, name="Muted") this variable locates the Muted role in the server

and this will remove the role from the user

    The Overflow Blog
Linked
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.13.43306

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Как я могу проверить, имеет ли мой бот Python Discord необходимые разрешения?

Я создал служебного бота, который помогает регистрировать сообщения и переносить каналы с одного сервера на другой. Мне нужно было проверить, есть ли у него необходимые разрешения для выполнения своих команд, но следующий код не работает (я использую @client.event и не хочу использовать @bot.command ) Вот мой код проверки прав:

Это выше не работает, я получаю следующую ошибку при тестировании с соответствующими условиями:

Как узнать права комнаты discord python

This is the documentation for discord.py, a library for Python to aid in creating applications that utilise the Discord API.

Prerequisites¶

discord.py works with Python 3.5.3 or higher. Support for earlier versions of Python is not provided. Python 2.7 or lower is not supported. Python 3.4 or lower is not supported due to one of the dependencies ( aiohttp ) not supporting Python 3.4.

Installing¶

You can get the library directly from PyPI:

If you are using Windows, then the following should be used instead:

To get voice support, you should use discord.py[voice] instead of discord.py , e.g.

On Linux environments, installing voice requires getting the following dependencies:

For a Debian-based system, the following command will get these dependencies:

Remember to check your permissions!

Virtual Environments¶

Sometimes you want to keep libraries from polluting system installs or use a different version of libraries than the ones installed on the system. You might also not have permissions to install libraries system-wide. For this purpose, the standard library as of Python 3.3 comes with a concept called “Virtual Environment”s to help maintain these separate versions.

API Reference¶

The following section outlines the API of discord.py.

This module uses the Python logging module to log diagnostic and errors in an output independent way. If the logging module is not configured, these logs will not be output anywhere. See Setting Up Logging for more information on how to set up and use the logging module with discord.py.

Version Related Info¶

There are two main ways to query version information about the library.

A named tuple that is similar to sys.version_info.

Just like sys.version_info the valid values for releaselevel are ‘alpha’, ‘beta’, ‘candidate’ and ‘final’.

A string representation of the version. e.g. ‘0.10.0-alpha0’ .

Client¶

Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the Client .

  • max_messages (Optional[int]) – The maximum number of messages to store in messages . This defaults to 5000. Passing in None or a value less than 100 will use the default instead of the passed in value.
  • loop (Optional[event loop] ) – The event loop to use for asynchronous operations. Defaults to None , in which case the default event loop is used via asyncio.get_event_loop() .
  • cache_auth (Optional[bool]) – Indicates if login() should cache the authentication tokens. Defaults to True . The method in which the cache is written is done by writing to disk to a temporary directory.
  • connector (aiohttp.BaseConnector) – The connector to use for connection pooling. Useful for proxies, e.g. with a ProxyConnector.
  • shard_id (Optional[int]) – Integer starting at 0 and less than shard_count.
  • shard_count (Optional[int]) – The total number of shards.

Optional[ User ] – Represents the connected client. None if not logged in.

iterable of VoiceClient – Represents a list of voice connections. To connect to voice use join_voice_channel() . To query the voice connection state use is_voice_connected() .

iterable of Server – The servers that the connected client is a member of.

iterable of PrivateChannel – The private channels that the connected client is participating on.

A deque of Message that the client has received from all servers and private messages. The number of messages stored in this deque is controlled by the max_messages parameter.

The email used to login. This is only set if login is successful, otherwise it’s None.

The websocket gateway the client is currently connected to. Could be None.

The event loop that the client uses for HTTP requests and websocket operations.

The default error handler provided by the client.

By default this prints to sys.stderr however it could be overridden to have a different implementation. Check discord.on_error() for more details.

Logs in the client with the specified credentials.

This function can be used in two different ways.

More than 2 parameters or less than 1 parameter raises a TypeError .

bot (bool) – Keyword argument that specifies if the account logging on is a bot token or not. Only useful for logging in with a static token. Ignored for the email and password combo. Defaults to True .

    – The wrong credentials are passed. – An unknown HTTP related error occurred, usually when it isn’t 200 or the known incorrect credentials passing status code.
  • TypeError – The incorrect number of parameters is passed.

Logs out of Discord and closes all connections.

Creates a websocket connection and lets the websocket listen to messages from discord.

    – If the gateway to connect to discord is not found. Usually if this is thrown then there is a discord API outage. – The websocket connection has been terminated.

Closes the connection to discord.

A shorthand coroutine for login() + connect() .

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

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

Roughly Equivalent to:

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.

bool – Indicates if the client has logged in successfully.

bool – Indicates if the websocket connection is closed.

Returns a Channel or PrivateChannel with the following ID. If not found, returns None.

Returns a Server with the given ID. If not found, returns None.

Returns a generator with every Emoji the client can see.

A generator that retrieves every Channel the client can ‘access’.

This is equivalent to:

Just because you receive a Channel does not mean that you can communicate in said channel. Channel.permissions_for() should be used for that.

Returns a generator with every Member the client can see.

This is equivalent to:

This coroutine waits until the client is all ready. This could be considered another way of asking for discord.on_ready() except meant for your own background tasks.

This coroutine waits until the client is logged on successfully. This is different from waiting until the client’s state is all ready. For that check discord.on_ready() and wait_until_ready() .

wait_for_message ( timeout=None, *, author=None, channel=None, content=None, check=None ) ¶

Waits for a message reply from Discord. This could be seen as another discord.on_message() event outside of the actual event. This could also be used for follow-ups and easier user interactions.

The keyword arguments passed into this function are combined using the logical and operator. The check keyword argument can be used to pass in more complicated checks and must be a regular function (not a coroutine).

The timeout parameter is passed into asyncio.wait_for. By default, it does not timeout. Instead of throwing asyncio.TimeoutError the coroutine catches the exception and returns None instead of a Message .

If the check predicate throws an exception, then the exception is propagated.

This function returns the first message that meets the requirements.

Asking for a follow-up question:

Advanced filters using check :

  • timeout (float) – The number of seconds to wait before returning None .
  • author ( Member or User ) – The author the message must be from.
  • channel ( Channel or PrivateChannel or Object ) – The channel the message must be from.
  • content (str) – The exact content the message must have.
  • check (function) – A predicate for other complicated checks. The predicate must take a Message as its only parameter.

The message that you requested for.

Waits for a message reaction from Discord. This is similar to wait_for_message() and could be seen as another on_reaction_add() event outside of the actual event. This could be used for follow up situations.

Similar to wait_for_message() , the keyword arguments are combined using logical AND operator. The check keyword argument can be used to pass in more complicated checks and must a regular function taking in two arguments, (reaction, user) . It must not be a coroutine.

The timeout parameter is passed into asyncio.wait_for. By default, it does not timeout. Instead of throwing asyncio.TimeoutError the coroutine catches the exception and returns None instead of a the (reaction, user) tuple.

If the check predicate throws an exception, then the exception is propagated.

The emoji parameter can be either a Emoji , a str representing an emoji, or a sequence of either type. If the emoji parameter is a sequence then the first reaction emoji that is in the list is returned. If None is passed then the first reaction emoji used is returned.

This function returns the first reaction that meets the requirements.

Checking for reaction emoji regardless of skin tone:

  • timeout (float) – The number of seconds to wait before returning None .
  • user ( Member or User ) – The user the reaction must be from.
  • emoji (str or Emoji or sequence) – The emoji that we are waiting to react with.
  • message ( Message ) – The message that we want the reaction to be from.
  • check (function) – A predicate for other complicated checks. The predicate must take (reaction, user) as its two parameters, which reaction being a Reaction and user being either a User or a Member .

A namedtuple with attributes reaction and user similar to on_reaction_add() .

A decorator that registers an event to listen to.

You can find more info about the events on the documentation below .

The events must be a coroutine, if not, ClientException is raised.

Using the basic event() decorator:

Saving characters by using the async_event() decorator:

A shorthand decorator for asyncio.coroutine + event() .

Starts a private message with the user. This allows you to send_message() to the user.

This method should rarely be called as send_message() does it automatically for you.

user ( User ) – The user to start the private message with.

    – The request failed. – The user argument was not of User .

Add a reaction to the given message.

The message must be a Message that exists. emoji may be a unicode emoji, or a custom server Emoji .

  • message ( Message ) – The message to react to.
  • emoji ( Emoji or str) – The emoji to react with.
    – Adding the reaction failed. – You do not have the proper permissions to react to the message. – The message or emoji you specified was not found. – The message or emoji parameter is invalid.

Remove a reaction by the member from the given message.

If member != server.me, you need Manage Messages to remove the reaction.

The message must be a Message that exists. emoji may be a unicode emoji, or a custom server Emoji .

  • message ( Message ) – The message.
  • emoji ( Emoji or str) – The emoji to remove.
  • member ( Member ) – The member for which to delete the reaction.
    – Removing the reaction failed. – You do not have the proper permissions to remove the reaction. – The message or emoji you specified was not found. – The message or emoji parameter is invalid.

Get the users that added a reaction to a message.

  • reaction ( Reaction ) – The reaction to retrieve users for.
  • limit (int) – The maximum number of results to return.
  • after ( Member or Object ) – For pagination, reactions are sorted by member.
    – Getting the users for the reaction failed. – The message or emoji you specified was not found. – The reaction parameter is invalid.

Removes all the reactions from a given message.

You need Manage Messages permission to use this.

message ( Message ) – The message to remove all reactions from.

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

Sends a message to the destination given with the content given.

The destination could be a Channel , PrivateChannel or Server . For convenience it could also be a User . If it’s a User or PrivateChannel then it sends the message via private message, otherwise it sends the message to the channel. If the destination is a Server then it’s equivalent to calling Server.default_channel and sending it there.

If it is a Object instance then it is assumed to be the destination ID. The destination ID is a channel so passing in a user ID will not be a valid destination.

Changed in version 0.9.0: str being allowed was removed and replaced with Object .

The content must be a type that can convert to a string through str(content) . If the content is set to None (the default), then the embed parameter must be provided.

If the embed parameter is provided, it must be of type Embed and it must be a rich embed type.

  • destination – The location to send the message.
  • content – The content of the message to send. If this is missing, then the embed parameter must be present.
  • tts (bool) – Indicates if the message should be sent using text-to-speech.
  • embed ( Embed ) – The rich embed for the content.
    – Sending the message failed. – You do not have the proper permissions to send the message. – The destination was not found and hence is invalid. – The destination parameter is invalid.

Sending a regular message:

Sending a TTS message:

Sending an embed message:

Returns: The message that was sent.
Return type: Message

send_typing ( destination ) ¶

Send a typing status to the destination.

Typing status will go away after 10 seconds, or after a message is sent.

The destination parameter follows the same rules as send_message() .

Parameters: destination – The location to send the typing update.

send_file ( destination, fp, *, filename=None, content=None, tts=False ) ¶

Sends a message to the destination given with the file given.

The destination parameter follows the same rules as send_message() .

The fp parameter should be either a string denoting the location for a file or a file-like object. The file-like object passed is not closed at the end of execution. You are responsible for closing it yourself.

If the file-like object passed is opened via open then the modes ‘rb’ should be used.

The filename parameter is the filename of the file. If this is not given then it defaults to fp.name or if fp is a string then the filename will default to the string given. You can overwrite this value by passing this in.

  • destination – The location to send the message.
  • fp – The file-like object or file path to send.
  • filename (str) – The filename of the file. Defaults to fp.name if it’s available.
  • content – The content of the message to send along with the file. This is forced into a string by a str(content) call.
  • tts (bool) – If the content of the message should be sent with TTS enabled.

HTTPException – Sending the file failed.

The message sent.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the proper permissions to do so.

message ( Message ) – The message to delete.

    – You do not have proper permissions to delete the message. – Deleting the message failed.

Deletes a list of messages. This is similar to delete_message() except it bulk deletes multiple messages.

The channel to check where the message is deleted from is handled via the first element of the iterable’s .channel.id attributes. If the channel is not consistent throughout the entire sequence, then an HTTPException will be raised.

Usable only by bot accounts.

messages (iterable of Message ) – An iterable of messages denoting which ones to bulk delete.

    – The number of messages to delete is less than 2 or more than 100. – You do not have proper permissions to delete the messages or you’re not using a bot account. – Deleting the messages failed.

Purges a list of messages that meet the criteria given by the predicate check . If a check is not provided then all messages are deleted without discrimination.

You must have Manage Messages permission to delete messages even if they are your own. The Read Message History permission is also needed to retrieve message history.

Usable only by bot accounts.

  • channel ( Channel ) – The channel to purge from.
  • limit (int) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.
  • check (predicate) – The function used to check if a message should be deleted. It must take a Message as its sole parameter.
  • before ( Message or datetime ) – The message or date before which all deleted messages must be. If a date is provided it must be a timezone-naive datetime representing UTC time.
  • after ( Message or datetime ) – The message or date after which all deleted messages must be. If a date is provided it must be a timezone-naive datetime representing UTC time.
  • around ( Message or datetime ) – The message or date around which all deleted messages must be. If a date is provided it must be a timezone-naive datetime representing UTC time.
    – You do not have proper permissions to do the actions required or you’re not using a bot account. – Purging the messages failed.

Deleting bot’s messages

Returns: The list of messages that were deleted.
Return type: list

edit_message ( message, new_content=None, *, embed=None ) ¶

Edits a Message with the new message content.

The new_content must be able to be transformed into a string via str(new_content) .

If the new_content is not provided, then embed must be provided, which must be of type Embed .

The Message object is not directly modified afterwards until the corresponding WebSocket event is received.

  • message ( Message ) – The message to edit.
  • new_content – The new content to replace the message with.
  • embed ( Embed ) – The new embed to replace the original embed with.

HTTPException – Editing the message failed.

The new edited message.

Retrieves a single Message from a Channel .

This can only be used by bot accounts.

  • channel ( Channel or PrivateChannel ) – The text channel to retrieve the message from.
  • id (str) – The message ID to look for.

The message asked for.

    – The specified channel or message was not found. – You do not have the permissions required to get a message. – Retrieving the message failed.

Pins a message. You must have Manage Messages permissions to do this in a non-private channel context.

message ( Message ) – The message to pin.

    – You do not have permissions to pin the message. – The message or channel was not found. – Pinning the message failed, probably due to the channel having more than 50 pinned messages.

Unpins a message. You must have Manage Messages permissions to do this in a non-private channel context.

message ( Message ) – The message to unpin.

    – You do not have permissions to unpin the message. – The message or channel was not found. – Unpinning the message failed.

Returns a list of Message that are currently pinned for the specified Channel or PrivateChannel .

channel ( Channel or PrivateChannel ) – The channel to look through pins for.

    – The channel was not found. – Retrieving the pinned messages failed.

This coroutine returns a generator that obtains logs from a specified channel.

  • channel ( Channel or PrivateChannel ) – The channel to obtain the logs from.
  • limit (int) – The number of messages to retrieve.
  • before ( Message or datetime ) – The message or date before which all returned messages must be. If a date is provided it must be a timezone-naive datetime representing UTC time.
  • after ( Message or datetime ) – The message or date after which all returned messages must be. If a date is provided it must be a timezone-naive datetime representing UTC time.
  • around ( Message or datetime ) – The message or date around which all returned messages must be. If a date is provided it must be a timezone-naive datetime representing UTC time.
    – You do not have permissions to get channel logs. – The channel you are requesting for doesn’t exist. – The request to get logs failed.

Message – The message with the message data parsed.

Python 3.5 Usage

Requests previously offline members from the server to be filled up into the Server.members cache. This function is usually not called.

When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the server is larger than 250. You can check if a server is large if Server.large is True .

Parameters: server ( Server or iterable) – The server to request offline members for. If this parameter is a iterable then it is interpreted as an iterator of servers to request offline members for.

kick ( member ) ¶

Kicks a Member from the server they belong to.

This function kicks the Member based on the server it belongs to, which is accessed via Member.server . So you must have the proper permissions in that server.

member ( Member ) – The member to kick from their server.

    – You do not have the proper permissions to kick. – Kicking failed.

Bans a Member from the server they belong to.

This function bans the Member based on the server it belongs to, which is accessed via Member.server . So you must have the proper permissions in that server.

  • member ( Member ) – The member to ban from their server.
  • delete_message_days (int) – The number of days worth of messages to delete from the user in the server. The minimum is 0 and the maximum is 7.
    – You do not have the proper permissions to ban. – Banning failed.

Unbans a User from the server they are banned from.

  • server ( Server ) – The server to unban the user from.
  • user ( User ) – The user to unban.
    – You do not have the proper permissions to unban. – Unbanning failed.

Server mutes or deafens a specific Member .

This function mutes or un-deafens the Member based on the server it belongs to, which is accessed via Member.server . So you must have the proper permissions in that server.

  • member ( Member ) – The member to unban from their server.
  • mute (Optional[bool]) – Indicates if the member should be server muted or un-muted.
  • deafen (Optional[bool]) – Indicates if the member should be server deafened or un-deafened.
    – You do not have the proper permissions to deafen or mute. – The operation failed.

Edits the current profile of the client.

If a bot account is used then the password field is optional, otherwise it is required.

The Client.user object is not modified directly afterwards until the corresponding WebSocket event is received.

To upload an avatar, a bytes-like object must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via open(‘some_filename’, ‘rb’) and the bytes-like object is given through the use of fp.read() .

The only image formats supported for uploading is JPEG and PNG.

  • password (str) – The current password for the client’s account. Not used for bot accounts.
  • new_password (str) – The new password you wish to change to.
  • email (str) – The new email you wish to change to.
  • username (str) – The new username you wish to change to.
  • avatar (bytes) – A bytes-like object representing the image to upload. Could be None to denote no avatar.
    – Editing your profile failed. – Wrong image format passed for avatar . – Password is required for non-bot accounts.

Changes the client’s status.

The game parameter is a Game object (not a string) that represents a game being played currently.

The idle parameter is a boolean parameter that indicates whether the client should go idle or not.

Deprecated since version v0.13.0: Use change_presence() instead.

  • game (Optional[ Game ]) – The game being played. None if no game is being played.
  • idle (bool) – Indicates if the client should go idle.

InvalidArgument – If the game parameter is not Game or None.

Changes the client’s presence.

The game parameter is a Game object (not a string) that represents a game being played currently.

  • game (Optional[ Game ]) – The game being played. None if no game is being played.
  • status (Optional[ Status ]) – Indicates what status to change to. If None, then Status.online is used.
  • afk (bool) – Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying.

InvalidArgument – If the game parameter is not Game or None.

Changes a member’s nickname.

You must have the proper permissions to change someone’s (or your own) nickname.

  • member ( Member ) – The member to change the nickname for.
  • nickname (Optional[str]) – The nickname to change it to. None to remove the nickname.
    – You do not have permissions to change the nickname. – Changing the nickname failed.

You must have the proper permissions to edit the channel.

To move the channel’s position use move_channel() instead.

The Channel object is not directly modified afterwards until the corresponding WebSocket event is received.

  • channel ( Channel ) – The channel to update.
  • name (str) – The new channel name.
  • topic (str) – The new channel’s topic.
  • bitrate (int) – The new channel’s bitrate. Voice only.
  • user_limit (int) – The new channel’s user limit. Voice only.
    – You do not have permissions to edit the channel. – Editing the channel failed.

Moves the specified Channel to the given position in the GUI. Note that voice channels and text channels have different position values.

The Channel object is not directly modified afterwards until the corresponding WebSocket event is received.

Object instances do not work with this function.

  • channel ( Channel ) – The channel to change positions of.
  • position (int) – The position to insert the channel to.
    – If position is less than 0 or greater than the number of channels. – You do not have permissions to change channel order. – If moving the channel failed, or you are of too low rank to move the channel.

Creates a Channel in the specified Server .

Note that you need the proper permissions to create the channel.

The overwrites argument list can be used to create a ‘secret’ channel upon creation. A namedtuple of ChannelPermissions is exposed to create a channel-specific permission overwrite in a more self-documenting matter. You can also use a regular tuple of (target, overwrite) where the overwrite expected has to be of type PermissionOverwrite .

Creating a voice channel:

Creating a ‘secret’ text channel:

Or in a more ‘compact’ way:

  • server ( Server ) – The server to create the channel in.
  • name (str) – The channel’s name.
  • type ( ChannelType ) – The type of channel to create. Defaults to ChannelType.text .
  • overwrites – An argument list of channel specific overwrites to apply on the channel on creation. Useful for creating ‘secret’ channels.
    – You do not have the proper permissions to create the channel. – The server specified was not found. – Creating the channel failed. – The permission overwrite array is not in proper form.

The channel that was just created. This channel is different than the one that will be added in cache.

In order to delete the channel, the client must have the proper permissions in the server the channel belongs to.

channel ( Channel ) – The channel to delete.

    – You do not have proper permissions to delete the channel. – The specified channel was not found. – Deleting the channel failed.

You cannot leave the server that you own, you must delete it instead via delete_server() .

Parameters: server ( Server ) – The server to leave.
Raises: HTTPException – If leaving the server failed.

delete_server ( server ) ¶

Deletes a Server . You must be the server owner to delete the server.

server ( Server ) – The server to delete.

    – If deleting the server failed. – You do not have permissions to delete the server.

Bot accounts generally are not allowed to create servers. See Discord’s official documentation for more info.

  • name (str) – The name of the server.
  • region ( ServerRegion ) – The region for the voice communication server. Defaults to ServerRegion.us_west .
  • icon (bytes) – The bytes-like object representing the icon. See edit_profile() for more details on what is expected.
    – Server creation failed. – Invalid icon image format given. Must be PNG or JPG.

The server created. This is not the same server that is added to cache.

You must have the proper permissions to edit the server.

The Server object is not directly modified afterwards until the corresponding WebSocket event is received.

  • server ( Server ) – The server to edit.
  • name (str) – The new name of the server.
  • icon (bytes) – A bytes-like object representing the icon. See edit_profile() for more details. Could be None to denote no icon.
  • splash (bytes) – A bytes-like object representing the invite splash. See edit_profile() for more details. Could be None to denote no invite splash. Only available for partnered servers with INVITE_SPLASH feature.
  • region ( ServerRegion ) – The new region for the server’s voice communication.
  • afk_channel (Optional[ Channel ]) – The new channel that is the AFK channel. Could be None for no AFK channel.
  • afk_timeout (int) – The number of seconds until someone is moved to the AFK channel.
  • owner ( Member ) – The new owner of the server to transfer ownership to. Note that you must be owner of the server to do this.
  • verification_level ( VerificationLevel ) – The new verification level for the server.
    – You do not have permissions to edit the server. – The server you are trying to edit does not exist. – Editing the server failed. – The image format passed in to icon is invalid. It must be PNG or JPG. This is also raised if you are not the owner of the server and request an ownership transfer.
Читать:
Почему на жестком диске меньше памяти чем заявлено

Retrieves all the User s that are banned from the specified server.

You must have proper permissions to get this information.

server ( Server ) – The server to get ban information from.

    – You do not have proper permissions to get the information. – An error occurred while fetching the information.

A list of User that have been banned.

Prunes a Server from its inactive members.

The inactive members are denoted if they have not logged on in days number of days and they have no roles.

You must have the “Kick Members” permission to use this.

To check how many members you would prune without actually pruning, see the estimate_pruned_members() function.

  • server ( Server ) – The server to prune from.
  • days (int) – The number of days before counting as inactive.
    – You do not have permissions to prune members. – An error occurred while pruning members. – An integer was not passed for days .

The number of members pruned.

Similar to prune_members() except instead of actually pruning members, it returns how many members it would prune from the server had it been called.

  • server ( Server ) – The server to estimate a prune from.
  • days (int) – The number of days before counting as inactive.
    – You do not have permissions to prune members. – An error occurred while fetching the prune members estimate. – An integer was not passed for days .

The number of members estimated to be pruned.

Creates a custom Emoji for a Server .

This endpoint is only allowed for user bots or white listed bots. If this is done by a user bot then this is a local emoji that can only be used inside that server.

There is currently a limit of 50 local emotes per server.

  • server ( Server ) – The server to add the emoji to.
  • name (str) – The emoji name. Must be at least 2 characters.
  • image (bytes) – The bytes-like object representing the image data to use. Only JPG and PNG images are supported.

The created emoji.

    – You are not allowed to create emojis. – An error occurred creating an emoji.

Deletes a custom Emoji from a Server .

This follows the same rules as create_custom_emoji() .

emoji ( Emoji ) – The emoji to delete.

    – You are not allowed to delete emojis. – An error occurred deleting the emoji.
  • emoji ( Emoji ) – The emoji to edit.
  • name (str) – The new emoji name.
    – You are not allowed to edit emojis. – An error occurred editing the emoji.

Creates an invite for the destination which could be either a Server or Channel .

  • destination – The Server or Channel to create the invite to.
  • max_age (int) – How long the invite should last. If it’s 0 then the invite doesn’t expire. Defaults to 0.
  • max_uses (int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to 0.
  • temporary (bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.
  • unique (bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

HTTPException – Invite creation failed.

The invite that was created.

Gets a Invite from a discord.gg URL or ID.

If the invite is for a server you have not joined, the server and channel attributes of the returned invite will be Object with the names patched in.

url (str) – The discord invite ID or URL (must be a discord.gg URL).

    – The invite has expired or is invalid. – Getting the invite failed.

The invite from the URL/ID.

Returns a list of all active instant invites from a Server .

You must have proper permissions to get this information.

server ( Server ) – The server to get invites from.

    – You do not have proper permissions to get the information. – An error occurred while fetching the information.

The list of invites that are currently active.

Accepts an Invite , URL or ID to an invite.

The URL must be a discord.gg URL. e.g. “http://discord.gg/codehere”. An ID for the invite is just the “codehere” portion of the invite URL.

invite – The Invite or URL to an invite to accept.

    – Accepting the invite failed. – The invite is invalid or expired. – You are a bot user and cannot use this endpoint.

Revokes an Invite , URL, or ID to an invite.

The invite parameter follows the same rules as accept_invite() .

invite – The invite to revoke.

    – You do not have permissions to revoke invites. – The invite is invalid or expired. – Revoking the invite failed.

Moves the specified Role to the given position in the Server .

The Role object is not directly modified afterwards until the corresponding WebSocket event is received.

  • server ( Server ) – The server the role belongs to.
  • role ( Role ) – The role to edit.
  • position (int) – The position to insert the role to.
    – If position is 0, or role is server.default_role – You do not have permissions to change role order. – If moving the role failed, or you are of too low rank to move the role.

Edits the specified Role for the entire Server .

The Role object is not directly modified afterwards until the corresponding WebSocket event is received.

All fields except server and role are optional. To change the position of a role, use move_role() instead.

Changed in version 0.8.0: Editing now uses keyword arguments instead of editing the Role object directly.

  • server ( Server ) – The server the role belongs to.
  • role ( Role ) – The role to edit.
  • name (str) – The new role name to change to.
  • permissions ( Permissions ) – The new permissions to change to.
  • colour ( Colour ) – The new colour to change to. (aliased to color as well)
  • hoist (bool) – Indicates if the role should be shown separately in the online list.
  • mentionable (bool) – Indicates if the role should be mentionable by others.
    – You do not have permissions to change the role. – Editing the role failed.

Deletes the specified Role for the entire Server .

  • server ( Server ) – The server the role belongs to.
  • role ( Role ) – The role to delete.
    – You do not have permissions to delete the role. – Deleting the role failed.

Gives the specified Member a number of Role s.

You must have the proper permissions to use this function.

The Member object is not directly modified afterwards until the corresponding WebSocket event is received.

  • member ( Member ) – The member to give roles to.
  • *roles – An argument list of Role s to give the member.
    – You do not have permissions to add roles. – Adding roles failed.

Removes the Role s from the Member .

You must have the proper permissions to use this function.

The Member object is not directly modified afterwards until the corresponding WebSocket event is received.

  • member ( Member ) – The member to revoke roles from.
  • *roles – An argument list of Role s to revoke the member.
    – You do not have permissions to revoke roles. – Removing roles failed.

Replaces the Member ’s roles.

You must have the proper permissions to use this function.

This function replaces all roles that the member has. For example if the member has roles [a, b, c] and the call is client.replace_roles(member, d, e, c) then the member has the roles [d, e, c] .

The Member object is not directly modified afterwards until the corresponding WebSocket event is received.

  • member ( Member ) – The member to replace roles from.
  • *roles – An argument list of Role s to replace the roles with.
    – You do not have permissions to revoke roles. – Removing roles failed.

This function is similar to edit_role in both the fields taken and exceptions thrown.

Returns: The newly created role. This not the same role that is stored in cache.
Return type: Role

edit_channel_permissions ( channel, target, overwrite=None ) ¶

Sets the channel specific permission overwrites for a target in the specified Channel .

The target parameter should either be a Member or a Role that belongs to the channel’s server.

You must have the proper permissions to do this.

Setting allow and deny:

  • channel ( Channel ) – The channel to give the specific permissions for.
  • target – The Member or Role to overwrite permissions for.
  • overwrite ( PermissionOverwrite ) – The permissions to allow and deny to the target.
    – You do not have permissions to edit channel specific permissions. – The channel specified was not found. – Editing channel specific permissions failed. – The overwrite parameter was not of type PermissionOverwrite or the target type was not Role or Member .

Removes a channel specific permission overwrites for a target in the specified Channel .

The target parameter follows the same rules as edit_channel_permissions() .

You must have the proper permissions to do this.

  • channel ( Channel ) – The channel to give the specific permissions for.
  • target – The Member or Role to overwrite permissions for.
    – You do not have permissions to delete channel specific permissions. – The channel specified was not found. – Deleting channel specific permissions failed.

Moves a Member to a different voice channel.

You must have proper permissions to do this.

You cannot pass in a Object instead of a Channel object in this function.

  • member ( Member ) – The member to move to another voice channel.
  • channel ( Channel ) – The voice channel to move the member to.
    – The channel provided is not a voice channel. – Moving the member failed. – You do not have permissions to move the member.

Joins a voice channel and creates a VoiceClient to establish your connection to the voice server.

After this function is successfully called, voice is set to the returned VoiceClient .

channel ( Channel ) – The voice channel to join to.

    – The channel was not a voice channel.
  • asyncio.TimeoutError – Could not connect to the voice channel in time. – You are already connected to a voice channel.
  • OpusNotLoaded – The opus library has not been loaded.

A voice client that is fully connected to the voice server.

Indicates if we are currently connected to a voice channel in the specified server.

Parameters: server ( Server ) – The server to query if we’re connected to it.

voice_client_in ( server ) ¶

Returns the voice client associated with a server.

If no voice client is found then None is returned.

Parameters: server ( Server ) – The server to query if we have a voice client for.
Returns: The voice client associated with the server.
Return type: VoiceClient

group_call_in ( channel ) ¶

Returns the GroupCall associated with a private channel.

If no group call is found then None is returned.

Parameters: channel ( PrivateChannel ) – The group private channel to query the group call for.
Returns: The group call.
Return type: Optional[ GroupCall ]

application_info ( ) ¶

Retrieve’s the bot’s application information.

Returns: A namedtuple representing the application info.
Return type: AppInfo
Raises: HTTPException – Retrieving the information failed somehow.

get_user_info ( user_id ) ¶

Retrieves a User based on their ID. This can only be used by bot accounts. You do not have to share any servers with the user to get this information, however many operations do require that you do.

user_id (str) – The user’s ID to fetch from.

The user you requested.

    – A user with this ID does not exist. – Fetching the user failed.

Voice¶

Represents a Discord voice connection.

This client is created solely through Client.join_voice_channel() and its only purpose is to transmit voice.

In order to play audio, you must have loaded the opus library through opus.load_opus() .

If you don’t do this then the library will not be able to transmit audio.

str – The voice connection session ID.

str – The voice connection token.

User – The user connected to voice.

str – The endpoint we are connecting to.

Channel – The voice channel connected to.

Server – The server the voice channel is connected to. Shorthand for channel.server .

The event loop that the voice client is running on.

This function is a coroutine. Reads from the voice websocket while connected.

Disconnects all connections to the voice client.

In order to reconnect, you must create another voice client using Client.join_voice_channel() .

Moves you to a different voice channel.

Object instances do not work with this function.

Parameters: channel ( Channel ) – The channel to move to. Must be a voice channel.
Raises: InvalidArgument – Not a voice channel.

is_connected ( ) ¶

bool : Indicates if the voice client is connected to voice.

create_ffmpeg_player ( filename, *, use_avconv=False, pipe=False, stderr=None, options=None, before_options=None, headers=None, after=None ) ¶

Creates a stream player for ffmpeg that launches in a separate thread to play audio.

The ffmpeg player launches a subprocess of ffmpeg to a specific filename and then plays that file.

You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.

The operations that can be done on the player are the same as those in create_stream_player() .

  • filename – The filename that ffmpeg will take and convert to PCM bytes. If pipe is True then this is a file-like object that is passed to the stdin of ffmpeg .
  • use_avconv (bool) – Use avconv instead of ffmpeg .
  • pipe (bool) – If true, denotes that filename parameter will be passed to the stdin of ffmpeg.
  • stderr – A file-like object or subprocess.PIPE to pass to the Popen constructor.
  • options (str) – Extra command line flags to pass to ffmpeg after the -i flag.
  • before_options (str) – Command line flags to pass to ffmpeg before the -i flag.
  • headers (dict) – HTTP headers dictionary to pass to -headers command line option
  • after (callable) – The finalizer that is called after the stream is done being played. All exceptions the finalizer throws are silently discarded.

ClientException – Popen failed to due to an error in ffmpeg or avconv .

A stream player with specific operations. See create_stream_player() .

Creates a stream player for youtube or other services that launches in a separate thread to play the audio.

The player uses the youtube_dl python library to get the information required to get audio from the URL. Since this uses an external library, you must install it yourself. You can do so by calling pip install youtube_dl .

You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.

The operations that can be done on the player are the same as those in create_stream_player() . The player has been augmented and enhanced to have some info extracted from the URL. If youtube-dl fails to extract the information then the attribute is None . The yt , url , and download_url attributes are always available.

Operation Description
player.yt The YoutubeDL <ytdl> instance.
player.url The URL that is currently playing.
player.download_url The URL that is currently being downloaded to ffmpeg.
player.title The title of the audio stream.
player.description The description of the audio stream.
player.uploader The uploader of the audio stream.
player.upload_date A datetime.date object of when the stream was uploaded.
player.duration The duration of the audio in seconds.
player.likes How many likes the audio stream has.
player.dislikes How many dislikes the audio stream has.
player.is_live Checks if the audio stream is currently livestreaming.
player.views How many views the audio stream has.
  • url (str) – The URL that youtube_dl will take and download audio to pass to ffmpeg or avconv to convert to PCM bytes.
  • ytdl_options (dict) – A dictionary of options to pass into the YoutubeDL instance. See the documentation for more details.
  • **kwargs – The rest of the keyword arguments are forwarded to create_ffmpeg_player() .

ClientException – Popen failure from either ffmpeg / avconv .

An augmented StreamPlayer that uses ffmpeg. See create_stream_player() for base operations.

Sets the encoder options for the OpusEncoder.

Calling this after you create a stream player via create_ffmpeg_player() or create_stream_player() has no effect.

  • sample_rate (int) – Sets the sample rate of the OpusEncoder. The unit is in Hz.
  • channels (int) – Sets the number of channels for the OpusEncoder. 2 for stereo, 1 for mono.

InvalidArgument – The values provided are invalid.

Creates a stream player that launches in a separate thread to play audio.

The stream player assumes that stream.read is a valid function that returns a bytes-like object.

The finalizer, after is called after the stream has been exhausted or an error occurred (see below).

The following operations are valid on the StreamPlayer object:

Operation Description
player.start() Starts the audio stream.
player.stop() Stops the audio stream.
player.is_done() Returns a bool indicating if the stream is done.
player.is_playing() Returns a bool indicating if the stream is playing.
player.pause() Pauses the audio stream.
player.resume() Resumes the audio stream.
player.volume Allows you to set the volume of the stream. 1.0 is equivalent to 100% and 0.0 is equal to 0%. The maximum the volume can be set to is 2.0 for 200%.
player.error The exception that stopped the player. If no error happened, then this returns None.

The stream must have the same sampling rate as the encoder and the same number of channels. The defaults are 48000 Hz and 2 channels. You could change the encoder options by using encoder_options() but this must be called before this function.

If an error happens while the player is running, the exception is caught and the player is then stopped. The caught exception could then be retrieved via player.error . When the player is stopped in this matter, the finalizer under after is called.

  • stream – The stream object to read from.
  • after – The finalizer that is called after the stream is exhausted. All exceptions it throws are silently discarded. This function can have either no parameters or a single parameter taking in the current player.

A stream player with the operations noted above.

Sends an audio packet composed of the data.

You must be connected to play audio.

  • data (bytes) – The bytes-like object denoting PCM or Opus voice data.
  • encode (bool) – Indicates if data should be encoded into Opus.
    – You are not connected.
  • OpusError – Encoding the data failed.

Opus Library¶

Loads the libopus shared library for use with voice.

If this function is not called then the library uses the function ctypes.util.find_library and then loads that one if available.

Not loading a library leads to voice not working.

This function propagates the exceptions thrown.

The bitness of the library must match the bitness of your python interpreter. If the library is 64-bit then your python interpreter must be 64-bit as well. Usually if there’s a mismatch in bitness then the load will throw an exception.

On Windows, the .dll extension is not necessary. However, on Linux the full extension is required to load the library, e.g. libopus.so.1 . On Linux however, find library will usually find the library automatically without you having to call this.

Parameters: name (str) – The filename of the shared library.

discord.opus. is_loaded ( ) ¶

Function to check if opus lib is successfully loaded either via the ctypes.util.find_library call of load_opus() .

This must return True for voice to work.

Returns: Indicates if the opus library has been loaded.
Return type: bool

Event Reference¶

This page outlines the different types of events listened by Client .

There are two ways to register an event, the first way is through the use of Client.event() . The second way is through subclassing Client and overriding the specific events. For example:

If an event handler raises an exception, on_error() will be called to handle it, which defaults to print a traceback and ignore the exception.

All the events must be a coroutine. If they aren’t, then you might get unexpected errors. In order to turn a function into a coroutine they must either be decorated with @asyncio.coroutine or in Python 3.5+ be defined using the async def declaration.

The following two functions are examples of coroutine functions:

Since this can be a potentially common mistake, there is a helper decorator, Client.async_event() to convert a basic function into a coroutine and an event at the same time. Note that it is not necessary if you use async def .

New in version 0.7.0: Subclassing to listen to events.

Called when the client is done preparing the data received from Discord. Usually after login is successful and the Client.servers and co. are filled up.

This function is not guaranteed to be the first event called. Likewise, this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.

Called when the client has resumed a session.

Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will supress the default action of printing the traceback.

The information of the exception rasied and the exception itself can be retreived with a standard call to sys.exc_info() .

If you want exception to propogate out of the Client class you can define an on_error handler consisting of a single empty raise statement. Exceptions raised by on_error will not be handled in any way by Client .

  • event – The name of the event that raised the exception.
  • args – The positional arguments for the event that raised the exception.
  • kwargs – The keyword arguments for the event that raised the execption.

Called when a message is created and sent to a server.

Parameters: message – A Message of the current message.

discord. on_socket_raw_receive ( msg ) ¶

Called whenever a message is received from the websocket, before it’s processed.This event is always dispatched when a message is received and the passed data is not processed in any way.

This is only really useful for grabbing the websocket stream and debugging purposes.

This is only for the messages received from the client websocket. The voice websocket will not trigger this event.

Parameters: msg – The message passed in from the websocket library. Could be bytes for a binary message or str for a regular message.

discord. on_socket_raw_send ( payload ) ¶

Called whenever a send operation is done on the websocket before the message is sent. The passed parameter is the message that is to sent to the websocket.

This is only really useful for grabbing the websocket stream and debugging purposes.

This is only for the messages received from the client websocket. The voice websocket will not trigger this event.

Parameters: payload – The message that is about to be passed on to the websocket library. It can be bytes to denote a binary message or str to denote a regular text message.

discord. on_message_delete ( message ) ¶

Called when a message is deleted. If the message is not found in the Client.messages cache, then these events will not be called. This happens if the message is too old or the client is participating in high traffic servers. To fix this, increase the max_messages option of Client .

Parameters: message – A Message of the deleted message.

discord. on_message_edit ( before, after ) ¶

Called when a message receives an update event. If the message is not found in the Client.messages cache, then these events will not be called. This happens if the message is too old or the client is participating in high traffic servers. To fix this, increase the max_messages option of Client .

The following non-exhaustive cases trigger this event:

  • A message has been pinned or unpinned.
  • The message content has been changed.
  • The message has received an embed.
    • For performance reasons, the embed server does not do this in a “consistent” manner.
    • before – A Message of the previous version of the message.
    • after – A Message of the current version of the message.

    Called when a message has a reaction added to it. Similar to on_message_edit, if the message is not found in the Client.messages cache, then this event will not be called.

    To get the message being reacted, access it via Reaction.message .

    • reaction – A Reaction showing the current state of the reaction.
    • user – A User or Member of the user who added the reaction.

    Called when a message has a reaction removed from it. Similar to on_message_edit, if the message is not found in the Client.messages cache, then this event will not be called.

    To get the message being reacted, access it via Reaction.message .

    • reaction – A Reaction showing the current state of the reaction.
    • user – A User or Member of the user who removed the reaction.

    Called when a message has all its reactions removed from it. Similar to on_message_edit, if the message is not found in the Client.messages cache, then this event will not be called.

    • message – The Message that had its reactions cleared.
    • reactions – A list of Reaction s that were removed.

    Called whenever a channel is removed or added from a server.

    Note that you can get the server from Channel.server . on_channel_create() could also pass in a PrivateChannel depending on the value of Channel.is_private .

    Parameters: channel – The Channel that got added or deleted.

    discord. on_channel_update ( before, after ) ¶

    Called whenever a channel is updated. e.g. changed name, topic, permissions.

    • before – The Channel that got updated with the old info.
    • after – The Channel that got updated with the updated info.

    Called when a Member leaves or joins a Server .

    Parameters: member – The Member that joined or left.

    discord. on_member_update ( before, after ) ¶

    Called when a Member updates their profile.

    This is called when one or more of the following things change:

    • status
    • game playing
    • avatar
    • nickname
    • roles
    • before – The Member that updated their profile with the old info.
    • after – The Member that updated their profile with the updated info.

    Called when a Server is either created by the Client or when the Client joins a server.

    Parameters: server – The class: Server that was joined.

    discord. on_server_remove ( server ) ¶

    Called when a Server is removed from the Client .

    This happens through, but not limited to, these circumstances:

    • The client got banned.
    • The client got kicked.
    • The client left the server.
    • The client or the server owner deleted the server.

    In order for this event to be invoked then the Client must have been part of the server to begin with. (i.e. it is part of Client.servers )

    Parameters: server – The Server that got removed.

    discord. on_server_update ( before, after ) ¶

    Called when a Server updates, for example:

    • Changed name
    • Changed AFK channel
    • Changed AFK timeout
    • etc
    • before – The Server prior to being updated.
    • after – The Server after being updated.

    Called when a Server creates or deletes a new Role .

    To get the server it belongs to, use Role.server .

    Parameters: role – The Role that was created or deleted.

    discord. on_server_role_update ( before, after ) ¶

    Called when a Role is changed server-wide.

    • before – The Role that updated with the old info.
    • after – The Role that updated with the updated info.

    Called when a Server adds or removes Emoji .

    • before – A list of Emoji before the update.
    • after – A list of Emoji after the update.

    Called when a server becomes available or unavailable. The server must have existed in the Client.servers cache.

    Parameters: server – The Server that has changed availability.

    discord. on_voice_state_update ( before, after ) ¶

    Called when a Member changes their voice state.

    The following, but not limited to, examples illustrate when this event is called:

    • A member joins a voice room.
    • A member leaves a voice room.
    • A member is muted or deafened by their own accord.
    • A member is muted or deafened by a server administrator.
    • before – The Member whose voice state changed prior to the changes.
    • after – The Member whose voice state changed after the changes.

    Called when a Member gets banned from a Server .

    You can access the server that the member got banned from via Member.server .

    Parameters: member – The member that got banned.

    discord. on_member_unban ( server, user ) ¶

    Called when a User gets unbanned from a Server .

    • server – The server the user got unbanned from.
    • user – The user that got unbanned.

    Called when someone begins typing a message.

    The channel parameter could either be a PrivateChannel or a Channel . If channel is a PrivateChannel then the user parameter is a User , otherwise it is a Member .

    • channel – The location where the typing originated from.
    • user – The user that started typing.
    • when – A datetime.datetime object representing when typing started.

    Called when someone joins or leaves a group, i.e. a PrivateChannel with a PrivateChannel.type of ChannelType.group .

    • channel – The group that the user joined or left.
    • user – The user that joined or left.

    Utility Functions¶

    A helper to return the first element found in the sequence that meets the predicate. For example:

    would find the first Member whose name is ‘Mighty’ and return it. If an entry is not found, then None is returned.

    This is different from filter due to the fact it stops the moment it finds a valid entry.

    • predicate – A function that returns a boolean-like result.
    • seq (iterable) – The iterable to search through.

    A helper that returns the first element in the iterable that meets all the traits passed in attrs . This is an alternative for discord.utils.find() .

    When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

    To have a nested attribute search (i.e. search by x.y ) then pass in x__y as the keyword argument.

    If nothing is found that matches the attributes passed, then None is returned.

Related Posts