Client Objects

Bots

Methods
class discord.Bot(description=None, *args, **options)[kaynak]

Represents a discord bot.

This class is a subclass of discord.Client and as a result anything that you can do with a discord.Client you can do with this bot.

This class also subclasses ApplicationCommandMixin to provide the functionality to manage commands.

Added in version 2.0.

description

The content prefixed into the default help message.

Type:

str

owner_id

The user ID that owns the bot. If this is not set and is then queried via is_owner() then it is fetched automatically using application_info(), returning the application owner.

Type:

Optional[int]

owner_ids

The user IDs that owns the bot. This is similar to owner_id. If this is not set and the application is team based, then it is fetched automatically using application_info(), returning all non read-only team members. For performance reasons it is recommended to use a set for the collection. You cannot set both owner_id and owner_ids.

Added in version 1.3.

Type:

Optional[Collection[int]]

debug_guilds

Guild IDs of guilds to use for testing commands. The bot will not create any global commands if debug guild IDs are passed.

Added in version 2.0.

Type:

Optional[List[int]]

auto_sync_commands

Whether to automatically sync slash commands. This will call sync_commands() in discord.on_connect(), and in process_application_commands if the command is not found. Defaults to True.

Added in version 2.0.

Type:

bool

default_command_contexts

The default context types that the bot will use for commands. Defaults to a set containing InteractionContextType.guild, InteractionContextType.bot_dm, and InteractionContextType.private_channel.

Added in version 2.6.

Type:

Collection[InteractionContextType]

default_command_integration_types

The default integration types that the bot will use for commands. Defaults to a set containing IntegrationType.guild_install.

Added in version 2.6.

Type:

Collection[IntegrationType]]

@command(**kwargs)

An alias for application_command().

Not

This decorator is overridden by discord.ext.commands.Bot.

Added in version 2.0.

Dönüşler:

A decorator that converts the provided function into an ApplicationCommand, adds it to the bot, and returns it.

Dönüş türü:

Callable[…, ApplicationCommand]

@event(coro)

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, TypeError is raised.

Not

This replaces any default handlers. Developers are encouraged to use listen() for adding additional handlers instead of event() unless default method replacement is intended.

Harekete geçirir:

TypeError – The coroutine passed is not actually a coroutine.

Örnek

@client.event
async def on_ready():
    print('Ready!')
Parametreler:

coro (TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]]))

Dönüş türü:

TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])

@message_command(*, checks=..., cog=..., contexts=..., cooldown=..., default_member_permissions=..., guild_ids=..., guild_only=..., integration_types=..., name=..., name_localizations=..., nsfw=..., **kwargs)

A shortcut decorator for adding a message command to the bot. This is equivalent to using application_command(), providing the MessageCommand class.

Added in version 2.0.

Dönüşler:

A decorator that converts the provided function into a MessageCommand, adds it to the bot, and returns it.

Dönüş türü:

Callable[..., MessageCommand]

Parametreler:
@slash_command(*, checks=..., cog=..., contexts=..., cooldown=..., default_member_permissions=..., description=..., description_localizations=..., guild_ids=..., guild_only=..., integration_types=..., name=..., name_localizations=..., nsfw=..., options=..., parent=..., **kwargs)

A shortcut decorator for adding a slash command to the bot. This is equivalent to using application_command(), providing the SlashCommand class.

Added in version 2.0.

Dönüşler:

A decorator that converts the provided function into a SlashCommand, adds it to the bot, and returns it.

Dönüş türü:

Callable[..., SlashCommand]

Parametreler:
@user_command(*, checks=..., cog=..., contexts=..., cooldown=..., default_member_permissions=..., guild_ids=..., guild_only=..., integration_types=..., name=..., name_localizations=..., nsfw=..., **kwargs)

A shortcut decorator for adding a user command to the bot. This is equivalent to using application_command(), providing the UserCommand class.

Added in version 2.0.

Dönüşler:

A decorator that converts the provided function into a UserCommand, adds it to the bot, and returns it.

Dönüş türü:

Callable[..., UserCommand]

Parametreler:
@listen(name=..., once=False)

A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as on_ready()

The functions being listened to must be a coroutine.

Harekete geçirir:
  • TypeError – The function being listened to is not a coroutine.

  • ValueError – The name (event name) does not start with on_.

Örnek

@client.listen()
async def on_message(message):
    print('one')

# in some other file...

@client.listen('on_message')
async def my_message(message):
    print('two')

# listen to the first event only
@client.listen('on_ready', once=True)
async def on_ready():
    print('ready!')

Would print one and two in an unspecified order.

Parametreler:
Dönüş türü:

Callable[[TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])], TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])]

property activity: Activity | Game | CustomActivity | Streaming | Spotify | None

The activity being used upon logging in.

Dönüş türü:

Optional[BaseActivity]

add_application_command(command)

Adds an ApplicationCommand into the internal list of commands.

This is usually not called, instead the command() or other shortcut decorators are used instead.

Added in version 2.0.

Parametreler:

command (ApplicationCommand) – The command to add.

Dönüş türü:

None

add_check(func, *, call_once=False)

Adds a global check to the bot. This is the non-decorator interface to check() and check_once().

Parametreler:
  • func – The function that was used as a global check.

  • call_once (bool) – If the function should only be called once per Bot.invoke() call.

Dönüş türü:

None

add_cog(cog, *, override=False)

Adds a “cog” to the bot.

A cog is a class that has its own event listeners and commands.

2.0 sürümünde değişti: ClientException is raised when a cog with the same name is already loaded.

Parametreler:
  • cog (Cog) – The cog to register to the bot.

  • override (bool) –

    If a previously loaded cog with the same name should be ejected instead of raising an error.

    Added in version 2.0.

Harekete geçirir:
Dönüş türü:

None

add_listener(func, name=...)

The non decorator alternative to listen().

Parametreler:
Harekete geçirir:
  • TypeError – The func parameter is not a coroutine function.

  • ValueError – The name (event name) does not start with on_.

Dönüş türü:

None

Örnek

async def on_ready(): pass
async def my_message(message): pass

client.add_listener(on_ready)
client.add_listener(my_message, 'on_message')
add_view(view, *, message_id=None)

Registers a BaseView for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

Added in version 2.0.

Parametreler:
  • view (BaseView) – The view to register for dispatching.

  • message_id (int | None) – The message ID that the view is attached to. This is currently used to refresh the view’s state during message update events. If not given then message update events are not propagated for the view.

Harekete geçirir:
  • TypeError – A view was not passed.

  • ValueError – The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided custom_id.

Dönüş türü:

None

after_invoke(coro)

A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a Context.

Not

Similar to before_invoke(), this is not called unless checks and argument parsing procedures succeed. This hook is, however, always called regardless of the internal command callback raising an error (i.e. CommandInvokeError). This makes it ideal for clean-up scenarios.

Parametreler:

coro (coroutine) – The coroutine to register as the post-invoke hook.

Harekete geçirir:

TypeError – The coroutine passed is not actually a coroutine.

property allowed_mentions: AllowedMentions | None

The allowed mention configuration.

Added in version 1.4.

property app_emojis: list[AppEmoji]

The AppEmoji that the connected client has.

Not

This is only available if cache_app_emojis is True.

application_command(*, cls=<class 'discord.commands.core.SlashCommand'>, checks=..., cog=..., contexts=..., cooldown=..., default_member_permissions=..., description=..., description_localizations=..., guild_ids=..., guild_only=..., integration_types=..., name=..., name_localizations=..., nsfw=..., options=..., parent=..., **kwargs)

A shortcut decorator that converts the provided function into an application command via command() and adds it to the internal command list via add_application_command().

Added in version 2.0.

Parametreler:
Dönüşler:

A decorator that converts the provided function into an ApplicationCommand, adds it to the bot, and returns it.

Dönüş türü:

Callable[..., TypeVar(C, bound= MessageCommand | SlashCommand | UserCommand)]

property application_flags: ApplicationFlags

The client’s application flags.

Added in version 2.0.

property application_id: int | None

The client’s application ID.

If this is not passed via __init__ then this is retrieved through the gateway when an event contains the data. Usually after on_connect() is called.

Added in version 2.0.

await application_info()

This function is a coroutine.

Retrieves the bot’s application information.

Dönüşler:

The bot’s application information.

Dönüş türü:

AppInfo

Harekete geçirir:

HTTPException – Retrieving the information failed somehow.

await before_identify_hook(shard_id, *, initial=False)

This function is a coroutine.

A hook that is called before IDENTIFYing a session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients.

The default implementation sleeps for 5 seconds.

Added in version 1.4.

Parametreler:
  • shard_id (int | None) – The shard ID that requested being IDENTIFY’d

  • initial (bool) – Whether this IDENTIFY is the first initial IDENTIFY.

Dönüş türü:

None

before_invoke(coro)

A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a Context.

Not

The before_invoke() and after_invoke() hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called.

Parametreler:

coro (coroutine) – The coroutine to register as the pre-invoke hook.

Harekete geçirir:

TypeError – The coroutine passed is not actually a coroutine.

property cached_messages: Sequence[Message]

Read-only list of messages the connected client has cached.

Added in version 1.1.

await change_presence(*, activity=None, status=None)

This function is a coroutine.

Changes the client’s presence.

Parametreler:
  • activity (BaseActivity | None) – The activity being done. None if no currently active activity is done.

  • status (Status | None) – Indicates what status to change to. If None, then Status.online is used.

Harekete geçirir:

InvalidArgument – If the activity parameter is not the proper type.

Örnek

game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)

2.0 sürümünde değişti: Removed the afk keyword-only parameter.

check(func)

A decorator that adds a global check to the bot. A global check is similar to a check() that is applied on a per-command basis except it is run before any command checks have been verified and applies to every command the bot has.

Not

This function can either be a regular function or a coroutine. Similar to a command check(), this takes a single parameter of type Context and can only raise exceptions inherited from ApplicationCommandError.

Örnek

@bot.check
def check_commands(ctx):
    return ctx.command.qualified_name in allowed_commands
check_once(func)

A decorator that adds a “call once” global check to the bot. Unlike regular global checks, this one is called only once per Bot.invoke() call. Regular global checks are called whenever a command is called or Command.can_run() is called. This type of check bypasses that and ensures that it’s called only once, even inside the default help command.

Not

When using this function the Context sent to a group subcommand may only parse the parent command and not the subcommands due to it being invoked once per Bot.invoke() call.

Not

This function can either be a regular function or a coroutine. Similar to a command check(), this takes a single parameter of type Context and can only raise exceptions inherited from ApplicationCommandError.

Örnek

@bot.check_once
def whitelist(ctx):
    return ctx.message.author.id in my_whitelist
clear()

Clears the internal state of the bot.

After this, the bot can be considered “re-opened”, i.e. is_closed() and is_ready() both return False along with the bot’s internal cache cleared.

Dönüş türü:

None

await close()

This function is a coroutine.

Closes the connection to Discord.

Dönüş türü:

None

property cogs: Mapping[str, Cog]

A read-only mapping of cog name to cog.

await connect(*, reconnect=True)

This function is a coroutine.

Creates a WebSocket connection and lets the WebSocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.

Parametreler:

reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).

Harekete geçirir:
  • GatewayNotFound – The gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.

  • ConnectionClosed – The WebSocket connection has been terminated.

Dönüş türü:

None

await create_dm(user)

This function is a coroutine.

Creates a DMChannel with this user.

This should be rarely called, as this is done transparently for most people.

Added in version 2.0.

Parametreler:

user (Snowflake) – The user to create a DM with.

Dönüşler:

The channel that was created.

Dönüş türü:

DMChannel

await create_emoji(*, name, image)

This function is a coroutine.

Creates a custom AppEmoji for the application.

There is currently a limit of 2000 emojis per application.

Parametreler:
  • 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, PNG and GIF images are supported.

Harekete geçirir:

HTTPException – An error occurred creating an emoji.

Dönüşler:

The created emoji.

Dönüş türü:

AppEmoji

create_group(name, description=None, guild_ids=None, **kwargs)

A shortcut method that creates a slash command group with no subcommands and adds it to the internal command list via add_application_command().

Added in version 2.0.

Parametreler:
  • name (str) – The name of the group to create.

  • description (str | None) – The description of the group to create.

  • guild_ids (list[int] | None) – A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command if None is passed.

  • kwargs – Any additional keyword arguments to pass to SlashCommandGroup.

Dönüşler:

The slash command group that was created.

Dönüş türü:

SlashCommandGroup

await delete_emoji(emoji)

This function is a coroutine.

Deletes the custom AppEmoji from the application.

Parametreler:

emoji (Snowflake) – The emoji you are deleting.

Harekete geçirir:

HTTPException – An error occurred deleting the emoji.

Dönüş türü:

None

await delete_invite(invite)

This function is a coroutine.

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

You must have the manage_channels permission in the associated guild to do this.

Parametreler:

invite (Invite | str) – The invite to revoke.

Harekete geçirir:
  • Forbidden – You do not have permissions to revoke invites.

  • NotFound – The invite is invalid or expired.

  • HTTPException – Revoking the invite failed.

Dönüş türü:

None

property emojis: list[GuildEmoji | AppEmoji]

The emojis that the connected client has.

Not

This only includes the application’s emojis if cache_app_emojis is True.

entitlements(user=None, skus=None, before=None, after=None, limit=100, guild=None, exclude_ended=False)

Returns an AsyncIterator that enables fetching the application’s entitlements.

Added in version 2.6.

Parametreler:
  • user (Snowflake | None) – Limit the fetched entitlements to entitlements owned by this user.

  • skus (list[Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.

  • before (Snowflake | datetime | None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • limit (int | None) – The number of entitlements to retrieve. If None, retrieves every entitlement, which may be slow. Defaults to 100.

  • guild (Snowflake | None) – Limit the fetched entitlements to entitlements owned by this guild.

  • exclude_ended (bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults to False.

Getiriler:

Entitlement – The application’s entitlements.

Harekete geçirir:

HTTPException – Retrieving the entitlements failed.

Dönüş türü:

EntitlementIterator

Örnekler

Usage

async for entitlement in client.entitlements():
    print(entitlement.user_id)

Flattening into a list

entitlements = await user.entitlements().flatten()

All parameters are optional.

property extensions: Mapping[str, ModuleType]

A read-only mapping of extension name to extension.

await fetch_application(application_id, /)

This function is a coroutine. Retrieves a PartialAppInfo from an application ID.

Parametreler:

application_id (int) – The application ID to retrieve information from.

Dönüşler:

The application information.

Dönüş türü:

PartialAppInfo

Harekete geçirir:
  • NotFound – An application with this ID does not exist.

  • HTTPException – Retrieving the application failed.

await fetch_channel(channel_id, /)

This function is a coroutine.

Retrieves a abc.GuildChannel, abc.PrivateChannel, or Thread with the specified ID.

Not

This method is an API call. For general usage, consider get_channel() instead.

Added in version 1.2.

Dönüşler:

The channel from the ID.

Dönüş türü:

GuildChannel | PrivateChannel | Thread

Harekete geçirir:
  • InvalidData – An unknown channel type was received from Discord.

  • HTTPException – Retrieving the channel failed.

  • NotFound – Invalid Channel ID.

  • Forbidden – You do not have permission to fetch this channel.

Parametreler:

channel_id (int)

await fetch_default_sounds()

This function is a coroutine.

Fetches the bot’s default sounds.

Added in version 2.7.

Dönüşler:

The bot’s default sounds.

Dönüş türü:

list[SoundboardSound]

await fetch_emoji(emoji_id, /)

This function is a coroutine.

Retrieves a custom AppEmoji from the application.

Parametreler:

emoji_id (int) – The emoji’s ID.

Dönüşler:

The retrieved emoji.

Dönüş türü:

AppEmoji

Harekete geçirir:
  • NotFound – The emoji requested could not be found.

  • HTTPException – An error occurred fetching the emoji.

await fetch_emojis()

This function is a coroutine.

Retrieves all custom AppEmojis from the application.

Harekete geçirir:

HTTPException – An error occurred fetching the emojis.

Dönüşler:

The retrieved emojis.

Dönüş türü:

list[AppEmoji]

await fetch_guild(guild_id, /, *, with_counts=True)

This function is a coroutine.

Retrieves a Guild from an ID.

Not

Using this, you will not receive Guild.channels, Guild.members, Member.activity and Member.voice per Member.

Not

This method is an API call. For general usage, consider get_guild() instead.

Parametreler:
Dönüşler:

The guild from the ID.

Dönüş türü:

Guild

Harekete geçirir:
fetch_guilds(*, limit=100, before=None, after=None, with_counts=True)

Retrieves an AsyncIterator that enables receiving your guilds.

Not

Using this, you will only receive Guild.owner, Guild.icon, Guild.id, and Guild.name per Guild.

Not

This method is an API call. For general usage, consider guilds instead.

Parametreler:
  • limit (int | None) – The number of guilds to retrieve. If None, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 100.

  • before (Snowflake | datetime) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • with_counts (bool) – Whether to include member count information in guilds. This fills the Guild.approximate_member_count and Guild.approximate_presence_count fields. Defaults to True.

Getiriler:

Guild – The guild with the guild data parsed.

Harekete geçirir:

HTTPException – Getting the guilds failed.

Dönüş türü:

GuildIterator

Örnekler

Usage

async for guild in client.fetch_guilds(limit=150):
    print(guild.name)

Flattening into a list

guilds = await client.fetch_guilds(limit=150).flatten()
# guilds is now a list of Guild...

All parameters are optional.

await fetch_invite(url, *, with_counts=True, with_expiration=True, event_id=None)

This function is a coroutine.

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

Not

If the invite is for a guild you have not joined, the guild and channel attributes of the returned Invite will be PartialInviteGuild and PartialInviteChannel respectively.

Parametreler:
Dönüşler:

The invite from the URL/ID.

Dönüş türü:

Invite

Harekete geçirir:
await fetch_premium_sticker_packs()

This function is a coroutine.

Retrieves all available premium sticker packs.

Added in version 2.0.

Dönüşler:

All available premium sticker packs.

Dönüş türü:

list[StickerPack]

Harekete geçirir:

HTTPException – Retrieving the sticker packs failed.

await fetch_role_connection_metadata_records()

This function is a coroutine.

Fetches the bot’s role connection metadata records.

Added in version 2.4.

Dönüşler:

The bot’s role connection metadata records.

Dönüş türü:

list[ApplicationRoleConnectionMetadata]

await fetch_skus()

This function is a coroutine.

Fetches the bot’s SKUs.

Added in version 2.5.

Dönüşler:

The bot’s SKUs.

Dönüş türü:

list[SKU]

await fetch_stage_instance(channel_id, /)

This function is a coroutine.

Gets a StageInstance for a stage channel id.

Added in version 2.0.

Parametreler:

channel_id (int) – The stage channel ID.

Dönüşler:

The stage instance from the stage channel ID.

Dönüş türü:

StageInstance

Harekete geçirir:
  • NotFound – The stage instance or channel could not be found.

  • HTTPException – Getting the stage instance failed.

await fetch_sticker(sticker_id, /)

This function is a coroutine.

Retrieves a Sticker with the specified ID.

Added in version 2.0.

Dönüşler:

The sticker you requested.

Dönüş türü:

StandardSticker | GuildSticker

Harekete geçirir:
Parametreler:

sticker_id (int)

await fetch_template(code)

This function is a coroutine.

Gets a Template from a discord.new URL or code.

Parametreler:

code (Template | str) – The Discord Template Code or URL (must be a discord.new URL).

Dönüşler:

The template from the URL/code.

Dönüş türü:

Template

Harekete geçirir:
await fetch_user(user_id, /)

This function is a coroutine.

Retrieves a User based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Not

This method is an API call. If you have discord.Intents.members and member cache enabled, consider get_user() instead.

Parametreler:

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

Dönüşler:

The user you requested.

Dönüş türü:

User

Harekete geçirir:
await fetch_webhook(webhook_id, /)

This function is a coroutine.

Retrieves a Webhook with the specified ID.

Dönüşler:

The webhook you requested.

Dönüş türü:

Webhook

Harekete geçirir:
Parametreler:

webhook_id (int)

await fetch_widget(guild_id, /)

This function is a coroutine.

Gets a Widget from a guild ID.

Not

The guild must have the widget enabled to get this information.

Parametreler:

guild_id (int) – The ID of the guild.

Dönüşler:

The guild’s widget.

Dönüş türü:

Widget

Harekete geçirir:
get_all_channels()

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

This is equivalent to:

for guild in client.guilds:
    for channel in guild.channels:
        yield channel

Not

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

Getiriler:

abc.GuildChannel – A channel the client can ‘access’.

Dönüş türü:

Generator[GuildChannel, None, None]

get_all_members()

Returns a generator with every Member the client can see.

This is equivalent to:

for guild in client.guilds:
    for member in guild.members:
        yield member
Getiriler:

Member – A member the client can see.

Dönüş türü:

Generator[Member, None, None]

get_application_command(name, guild_ids=None, type=<class 'discord.commands.core.ApplicationCommand'>)

Get an ApplicationCommand from the internal list of commands.

Added in version 2.0.

Parametreler:
Dönüşler:

The command that was requested. If not found, returns None.

Dönüş türü:

ApplicationCommand | None

await get_application_context(interaction, cls=<class 'discord.commands.context.ApplicationContext'>)

This function is a coroutine.

Returns the invocation context from the interaction.

This is a more low-level counter-part for process_application_commands() to allow users more fine-grained control over the processing.

Parametreler:
  • interaction (Interaction) – The interaction to get the invocation context from.

  • cls (Any) – The factory class that will be used to create the context. By default, this is ApplicationContext. Should a custom class be provided, it must be similar enough to ApplicationContext's interface.

Dönüşler:

The invocation context. The type of this can change via the cls parameter.

Dönüş türü:

ApplicationContext

await get_autocomplete_context(interaction, cls=<class 'discord.commands.context.AutocompleteContext'>)

This function is a coroutine.

Returns the autocomplete context from the interaction.

This is a more low-level counter-part for process_application_commands() to allow users more fine-grained control over the processing.

Parametreler:
  • interaction (Interaction) – The interaction to get the invocation context from.

  • cls (Any) – The factory class that will be used to create the context. By default, this is AutocompleteContext. Should a custom class be provided, it must be similar enough to AutocompleteContext's interface.

Dönüşler:

The autocomplete context. The type of this can change via the cls parameter.

Dönüş türü:

AutocompleteContext

get_channel(id, /)

Returns a channel or thread with the given ID.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The returned channel or None if not found.

Dönüş türü:

GuildChannel | Thread | PrivateChannel | None

get_cog(name)

Gets the cog instance requested.

If the cog is not found, None is returned instead.

Parametreler:

name (str) – The name of the cog you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified.

Dönüşler:

The cog that was requested. If not found, returns None.

Dönüş türü:

Cog | None

property get_command

Shortcut for get_application_command().

Not

Overridden in ext.commands.Bot.

Added in version 2.0.

await get_desynced_commands(guild_id=None, prefetched=None)

This function is a coroutine.

Gets the list of commands that are desynced from discord. If guild_id is specified, it will only return guild commands that are desynced from said guild, else it will return global commands.

Not

This function is meant to be used internally, and should only be used if you want to override the default command registration behavior.

Added in version 2.0.

Parametreler:
  • guild_id (int | None) – The guild id to get the desynced commands for, else global commands if unspecified.

  • prefetched (list[ApplicationCommand] | None) – If you already fetched the commands, you can pass them here to be used. Not recommended for typical usage.

Dönüşler:

A list of the desynced commands. Each will come with at least the cmd and action keys, which respectively contain the command and the action to perform. Other keys may also be present depending on the action, including id.

Dönüş türü:

list[dict[str, Any]]

get_emoji(id, /)

Returns an emoji with the given ID.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The custom emoji or None if not found.

Dönüş türü:

GuildEmoji | AppEmoji | None

get_guild(id, /)

Returns a guild with the given ID.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The guild or None if not found.

Dönüş türü:

Guild | None

get_message(id, /)

Returns a message the given ID.

This is useful if you have a message_id but don’t want to do an API call to access the message.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The returned message or None if not found.

Dönüş türü:

Message | None

await get_or_fetch(object_type, object_id, default=None)

Shortcut method to get data from an object either by returning the cached version, or if it does not exist, attempting to fetch it from the API.

Parametreler:
  • object_type (type[TypeVar(_FETCHABLE, bound= VoiceChannel | TextChannel | ForumChannel | StageChannel | CategoryChannel | Thread | Member | User | Guild | Role | GuildEmoji | AppEmoji)]) – Type of object to fetch or get.

  • object_id (int | None) – ID of object to get. If None, returns default if provided, else None.

  • default (TypeVar(_D)) – A default to return instead of raising if fetch fails.

  • self (Client)

Dönüşler:

The object if found, or default if provided when not found.

Dönüş türü:

TypeVar(_FETCHABLE, bound= VoiceChannel | TextChannel | ForumChannel | StageChannel | CategoryChannel | Thread | Member | User | Guild | Role | GuildEmoji | AppEmoji) | TypeVar(_D) | None

Harekete geçirir:
  • TypeError – Raised when required parameters are missing or invalid types are provided.

  • InvalidArgument – Raised when an unsupported or incompatible object type is used.

await get_or_fetch_user(id, /)

This function is a coroutine.

Looks up a user in the user cache or fetches if not found.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The user or None if not found.

Dönüş türü:

User | None

get_partial_messageable(id, *, type=None)

Returns a partial messageable with the given channel ID.

This is useful if you have a channel_id but don’t want to do an API call to send messages to it.

Added in version 2.0.

Parametreler:
  • id (int) – The channel ID to create a partial messageable for.

  • type (ChannelType | None) – The underlying channel type for the partial messageable.

Dönüşler:

The partial messageable

Dönüş türü:

PartialMessageable

get_poll(id, /)

Returns a poll attached to the given message ID.

Parametreler:

id (int) – The message ID of the poll to search for.

Dönüşler:

The poll or None if not found.

Dönüş türü:

Poll | None

get_sound(sound_id)

Gets a Sound from the bot’s sound cache.

Added in version 2.7.

Parametreler:

sound_id (int) – The ID of the sound to get.

Dönüşler:

The sound with the given ID.

Dönüş türü:

SoundboardSound | None

get_stage_instance(id, /)

Returns a stage instance with the given stage channel ID.

Added in version 2.0.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The stage instance or None if not found.

Dönüş türü:

StageInstance | None

get_sticker(id, /)

Returns a guild sticker with the given ID.

Added in version 2.0.

Not

To retrieve standard stickers, use fetch_sticker(). or fetch_premium_sticker_packs().

Dönüşler:

The sticker or None if not found.

Dönüş türü:

GuildSticker | None

Parametreler:

id (int)

get_user(id, /)

Returns a user with the given ID.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The user or None if not found.

Dönüş türü:

User | None

group(name=None, description=None, guild_ids=None)

A shortcut decorator that initializes the provided subclass of SlashCommandGroup and adds it to the internal command list via add_application_command().

Added in version 2.0.

Parametreler:
  • name (str | None) – The name of the group to create. This will resolve to the name of the decorated class if None is passed.

  • description (str | None) – The description of the group to create.

  • guild_ids (list[int] | None) – A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command if None is passed.

Dönüşler:

The slash command group that was created.

Dönüş türü:

Callable[[type[SlashCommandGroup]], SlashCommandGroup]

property guild_emojis: list[GuildEmoji]

The GuildEmoji that the connected client has.

property guilds: list[Guild]

The guilds that the connected client is a member of.

property intents: Intents

The intents configured for this connection.

Added in version 1.5.

await invoke_application_command(ctx)

This function is a coroutine.

Invokes the application command given under the invocation context and handles all the internal event dispatch mechanisms.

Parametreler:

ctx (ApplicationContext) – The invocation context to invoke.

Dönüş türü:

None

is_closed()

Indicates if the WebSocket connection is closed.

Dönüş türü:

bool

await is_owner(user)

This function is a coroutine.

Checks if a User or Member is the owner of this bot.

If an owner_id is not set, it is fetched automatically through the use of application_info(), returning the application owner, or all non read-only team members.

1.3 sürümünde değişti: The function also checks if the application is team-owned if owner_ids is not set.

Parametreler:

user (User | Member) – The user to check for.

Dönüşler:

Whether the user is the owner.

Dönüş türü:

bool

is_ready()

Specifies if the client’s internal cache is ready for use.

Dönüş türü:

bool

is_ws_ratelimited()

Whether the WebSocket is currently rate limited.

This can be useful to know when deciding whether you should query members using HTTP or via the gateway.

Added in version 1.6.

Dönüş türü:

bool

property latency: float

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. If no websocket is present, this returns nan, and if no heartbeat has been received yet, this returns float('inf').

This could be referred to as the Discord WebSocket protocol latency.

load_extension(name, *, package=None, recursive=False, store=False)

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, setup defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the bot.

The extension passed can either be the direct name of a file within the current working directory or a folder that contains multiple extensions.

Parametreler:
  • name (str) – The extension or folder name to load. It must be dot separated like regular Python imports if accessing a submodule. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g .foo.test. Defaults to None.

    Added in version 1.7.

  • recursive (Optional[bool]) –

    If subdirectories under the given head directory should be recursively loaded. Defaults to False.

    Added in version 2.0.

  • store (Optional[bool]) –

    If exceptions should be stored or raised. If set to True, all exceptions encountered will be stored in a returned dictionary as a load status. If set to False, if any exceptions are encountered they will be raised and the bot will be closed. If no exceptions are encountered, a list of loaded extension names will be returned. Defaults to False.

    Added in version 2.0.

Dönüşler:

If the store parameter is set to True, a dictionary will be returned that contains keys to represent the loaded extension names. The values bound to each key can either be an exception that occurred when loading that extension or a True boolean representing a successful load. If the store parameter is set to False, either a list containing a list of loaded extensions or nothing due to an encountered exception.

Dönüş türü:

dict[str, Exception | bool] | list[str] | None

Harekete geçirir:
  • ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • ExtensionAlreadyLoaded – The extension is already loaded.

  • NoEntryPointError – The extension does not have a setup function.

  • ExtensionFailed – The extension or its setup function had an execution error.

load_extensions(*names, package=None, recursive=False, store=False)

Loads multiple extensions at once.

This method simplifies the process of loading multiple extensions by handling the looping of load_extension.

Parametreler:
  • names (str) – The extension or folder names to load. It must be dot separated like regular Python imports if accessing a submodule. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g .foo.test. Defaults to None.

    Added in version 1.7.

  • recursive (Optional[bool]) –

    If subdirectories under the given head directory should be recursively loaded. Defaults to False.

    Added in version 2.0.

  • store (Optional[bool]) –

    If exceptions should be stored or raised. If set to True, all exceptions encountered will be stored in a returned dictionary as a load status. If set to False, if any exceptions are encountered they will be raised and the bot will be closed. If no exceptions are encountered, a list of loaded extension names will be returned. Defaults to False.

    Added in version 2.0.

Dönüşler:

If the store parameter is set to True, a dictionary will be returned that contains keys to represent the loaded extension names. The values bound to each key can either be an exception that occurred when loading that extension or a True boolean representing a successful load. If the store parameter is set to False, either a list containing names of loaded extensions or nothing due to an encountered exception.

Dönüş türü:

dict[str, Exception | bool] | list[str] | None

Harekete geçirir:
  • ExtensionNotFound – A given extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • ExtensionAlreadyLoaded – A given extension is already loaded.

  • NoEntryPointError – A given extension does not have a setup function.

  • ExtensionFailed – A given extension or its setup function had an execution error.

await login(token)

This function is a coroutine.

Logs in the client with the specified credentials.

Parametreler:

token (str) – The authentication token. Do not prefix this token with anything as the library will do it for you.

Harekete geçirir:
  • TypeError – The token was in invalid type.

  • LoginFailure – The wrong credentials are passed.

  • HTTPException – An unknown HTTP related error occurred, usually when it isn’t 200 or the known incorrect credentials passing status code.

Dönüş türü:

None

await on_application_command_error(context, exception)

This function is a coroutine.

The default command error handler provided by the bot.

By default, this prints to sys.stderr however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.

Parametreler:
Dönüş türü:

None

await on_error(event_method, *args, **kwargs)

This function is a coroutine.

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 on_error() for more details.

Parametreler:
Dönüş türü:

None

await on_modal_error(error, interaction)

This function is a coroutine.

The default modal error handler provided by the client. The default implementation prints the traceback to stderr.

This only fires for a modal if you did not define its on_error().

Parametreler:
  • error (Exception) – The exception that was raised.

  • interaction (Interaction) – The interaction that was received.

Dönüş türü:

None

await on_view_error(error, item, interaction)

This function is a coroutine.

The default view error handler provided by the client.

This only fires for a view if you did not define its on_error().

Parametreler:
  • error (Exception) – The exception that was raised.

  • item (ViewItem) – The item that the user interacted with.

  • interaction (Interaction) – The interaction that was received.

Dönüş türü:

None

property persistent_views: Sequence[BaseView]

A sequence of persistent views added to the client.

Added in version 2.0.

property polls: list[Poll]

The polls that the connected client has.

Added in version 2.6.

property private_channels: list[PrivateChannel]

The private channels that the connected client is participating on.

Not

This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels.

await process_application_commands(interaction, auto_sync=None)

This function is a coroutine.

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the on_interaction() event. If you choose to override the on_interaction() event, then you should invoke this coroutine as well.

This function finds a registered command matching the interaction id from application commands and invokes it. If no matching command was found, it replies to the interaction with a default message.

Added in version 2.0.

Parametreler:
  • interaction (Interaction) – The interaction to process

  • auto_sync (bool | None) – Whether to automatically sync and unregister the command if it is not found in the internal cache. This will invoke the sync_commands() method on the context of the command, either globally or per-guild, based on the type of the command, respectively. Defaults to Bot.auto_sync_commands.

Dönüş türü:

None

await register_command(command, force=True, guild_ids=None)

This function is a coroutine.

Registers a command. If the command has guild_ids set, or if the guild_ids parameter is passed, the command will be registered as a guild command for those guilds.

Parametreler:
  • command (ApplicationCommand) – The command to register.

  • force (bool) – Whether to force the command to be registered. If this is set to False, the command will only be registered if it seems to already be registered and up to date with our internal cache. Defaults to True.

  • guild_ids (list[int] | None) – A list of guild ids to register the command for. If this is not set, the command’s ApplicationCommand.guild_ids attribute will be used.

Dönüşler:

The command that was registered

Dönüş türü:

None

await register_commands(commands=None, guild_id=None, method='bulk', force=False, delete_existing=True)

This function is a coroutine.

Register a list of commands.

Added in version 2.0.

Parametreler:
  • commands (list[ApplicationCommand] | None) – A list of commands to register. If this is not set (None), then all commands will be registered.

  • guild_id (int | None) – If this is set, the commands will be registered as a guild command for the respective guild. If it is not set, the commands will be registered according to their ApplicationCommand.guild_ids attribute.

  • method (Literal['individual', 'bulk', 'auto']) – The method to use when registering the commands. If this is set to “individual”, then each command will be registered individually. If this is set to “bulk”, then all commands will be registered in bulk. If this is set to “auto”, then the method will be determined automatically. Defaults to “bulk”.

  • force (bool) – Registers the commands regardless of the state of the command on Discord. This uses one less API call, but can result in hitting rate limits more often. Defaults to False.

  • delete_existing (bool) – Whether to delete existing commands that are not in the list of commands to register. Defaults to True.

Dönüş türü:

list[ApplicationCommand]

reload_extension(name, *, package=None)

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a unload_extension() followed by a load_extension() except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll back to the prior working state.

Parametreler:
  • name (str) – The extension name to reload. It must be dot separated like regular Python imports if accessing a submodule. e.g. foo.test if you want to import foo/test.py.

  • package (str | None) –

    The package name to resolve relative imports with. This is required when reloading an extension using a relative path, e.g .foo.test. Defaults to None.

    Added in version 1.7.

Harekete geçirir:
  • ExtensionNotLoaded – The extension was not loaded.

  • ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • NoEntryPointError – The extension does not have a setup function.

  • ExtensionFailed – The extension setup function had an execution error.

Dönüş türü:

None

remove_application_command(command)

Remove an ApplicationCommand from the internal list of commands.

Added in version 2.0.

Parametreler:

command (ApplicationCommand) – The command to remove.

Dönüşler:

The command that was removed. If the command has not been added, None is returned instead.

Dönüş türü:

ApplicationCommand | None

remove_check(func, *, call_once=False)

Removes a global check from the bot. This function is idempotent and will not raise an exception if the function is not in the global checks.

Parametreler:
  • func – The function to remove from the global checks.

  • call_once (bool) – If the function was added with call_once=True in the Bot.add_check() call or using check_once().

Dönüş türü:

None

remove_cog(name)

Removes a cog from the bot and returns it.

All registered commands and event listeners that the cog has registered will be removed as well.

If no cog is found then this method has no effect.

Parametreler:

name (str) – The name of the cog to remove.

Dönüşler:

The cog that was removed. None if not found.

Dönüş türü:

Cog | None

remove_listener(func, name=...)

Removes a listener from the pool of listeners.

Parametreler:
  • func (TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])) – The function that was used as a listener to remove.

  • name (str) – The name of the event we want to remove. Defaults to func.__name__.

Dönüş türü:

None

run(*args, **kwargs)

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

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

Roughly Equivalent to:

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

Uyarı

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.

Parametreler:
Dönüş türü:

None

slash_group(name=None, description=None, guild_ids=None)

A shortcut decorator that initializes the provided subclass of SlashCommandGroup and adds it to the internal command list via add_application_command().

Added in version 2.0.

Parametreler:
  • name (str | None) – The name of the group to create. This will resolve to the name of the decorated class if None is passed.

  • description (str | None) – The description of the group to create.

  • guild_ids (list[int] | None) – A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command if None is passed.

Dönüşler:

The slash command group that was created.

Dönüş türü:

Callable[[type[SlashCommandGroup]], SlashCommandGroup]

property sounds: list[SoundboardSound]

A list of all the sounds the bot can see.

Added in version 2.7.

await start(token, *, reconnect=True)

This function is a coroutine.

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

Harekete geçirir:

TypeError – An unexpected keyword argument was received.

Parametreler:
Dönüş türü:

None

property status: Status

The status being used upon logging on to Discord.

property stickers: list[GuildSticker]

The stickers that the connected client has.

Added in version 2.0.

property store_url: str

The URL that leads to the application’s store page for monetization.

Added in version 2.6.

Type:

str

await sync_commands(commands=None, method='bulk', force=False, guild_ids=None, register_guild_commands=True, check_guilds=[], delete_existing=True)

This function is a coroutine.

Registers all commands that have been added through add_application_command(). This method cleans up all commands over the API and should sync them with the internal cache of commands. It attempts to register the commands in the most efficient way possible, unless force is set to True, in which case it will always register all commands.

By default, this coroutine is called inside the on_connect() event. If you choose to override the on_connect() event, then you should invoke this coroutine as well such as the following:

@bot.event
async def on_connect():
    if bot.auto_sync_commands:
        await bot.sync_commands()
    print(f"{bot.user.name} connected.")

Not

If you remove all guild commands from a particular guild, the library may not be able to detect and update the commands accordingly, as it would have to individually check for each guild. To force the library to unregister a guild’s commands, call this function with commands=[] and guild_ids=[guild_id].

Added in version 2.0.

Parametreler:
  • commands (list[ApplicationCommand] | None) – A list of commands to register. If this is not set (None), then all commands will be registered.

  • method (Literal['individual', 'bulk', 'auto']) – The method to use when registering the commands. If this is set to “individual”, then each command will be registered individually. If this is set to “bulk”, then all commands will be registered in bulk. If this is set to “auto”, then the method will be determined automatically. Defaults to “bulk”.

  • force (bool) – Registers the commands regardless of the state of the command on Discord. This uses one less API call, but can result in hitting rate limits more often. Defaults to False.

  • guild_ids (list[int] | None) – A list of guild ids to register the commands for. If this is not set, the commands’ guild_ids attribute will be used.

  • register_guild_commands (bool) – Whether to register guild commands. Defaults to True.

  • check_guilds (list[int] | None) – A list of guilds ids to check for commands to unregister, since the bot would otherwise have to check all guilds. Unlike guild_ids, this does not alter the commands’ guild_ids attribute, instead it adds the guild ids to a list of guilds to sync commands for. If register_guild_commands is set to False, then this parameter is ignored.

  • delete_existing (bool) – Whether to delete existing commands that are not in the list of commands to register. Defaults to True.

Dönüş türü:

None

unload_extension(name, *, package=None)

Unloads an extension.

When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported.

The extension can provide an optional global function, teardown, to do miscellaneous clean-up if necessary. This function takes a single parameter, the bot, similar to setup from load_extension().

Parametreler:
  • name (str) – The extension name to unload. It must be dot separated like regular Python imports if accessing a submodule. e.g. foo.test if you want to import foo/test.py.

  • package (str | None) –

    The package name to resolve relative imports with. This is required when unloading an extension using a relative path, e.g .foo.test. Defaults to None.

    Added in version 1.7.

Harekete geçirir:
Dönüş türü:

None

await update_role_connection_metadata_records(*role_connection_metadata)

This function is a coroutine.

Updates the bot’s role connection metadata records.

Added in version 2.4.

Parametreler:

*role_connection_metadata (ApplicationRoleConnectionMetadata) – The new metadata records to send to Discord.

Dönüşler:

The updated role connection metadata records.

Dönüş türü:

list[ApplicationRoleConnectionMetadata]

property user: ClientUser | None

Represents the connected client. None if not logged in.

property users: list[User]

Returns a list of all the users the bot can see.

property voice_clients: list[VoiceProtocol[Self]]

Represents a list of voice connections.

These are usually VoiceClient instances.

wait_for(event, *, check=None, timeout=None)

This function is a coroutine.

Waits for a WebSocket event to be dispatched.

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

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

In case the event returns multiple arguments, a tuple containing those arguments is returned instead. Please check the documentation for a list of events and their parameters.

This function returns the first event that meets the requirements.

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

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

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

Dönüşler:

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

Dönüş türü:

Any

Harekete geçirir:

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

Örnekler

Waiting for a user reply:

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

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

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

Waiting for a thumbs up reaction from the message author:

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

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '👍'

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

This function is a coroutine.

Waits until the client’s internal cache is all ready.

Dönüş türü:

None

walk_application_commands()

An iterator that recursively walks through all application commands and subcommands.

Getiriler:

ApplicationCommand – An application command from the internal list of application commands.

Dönüş türü:

Generator[ApplicationCommand, None, None]

class discord.AutoShardedBot(description=None, *args, **options)[kaynak]

This is similar to Bot except that it is inherited from discord.AutoShardedClient instead.

Added in version 2.0.

Clients

class discord.Client(*, loop=None, **options)[kaynak]

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.

Parametreler:
  • max_messages (Optional[int]) –

    The maximum number of messages to store in the internal message cache. This defaults to 1000. Passing in None disables the message cache.

    1.3 sürümünde değişti: Allow disabling the message cache and change the default size to 1000.

  • loop (AbstractEventLoop | None) – The asyncio.AbstractEventLoop to use for asynchronous operations. Defaults to None, in which case the default event loop is used via asyncio.get_event_loop() if it exists or one is created via asyncio.new_event_loop().

  • connector (Optional[aiohttp.BaseConnector]) – The connector to use for connection pooling.

  • proxy (Optional[str]) – Proxy URL.

  • proxy_auth (Optional[aiohttp.BasicAuth]) – An object that represents proxy HTTP Basic Authorization.

  • shard_id (Optional[int]) – Integer starting at 0 and less than shard_count.

  • shard_count (Optional[int]) – The total number of shards.

  • application_id (int) – The client’s application ID.

  • intents (Intents) –

    The intents that you want to enable for the session. This is a way of disabling and enabling certain gateway events from triggering and being sent. If not given, defaults to a regularly constructed Intents class.

    Added in version 1.5.

  • member_cache_flags (MemberCacheFlags) –

    Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible with the currently selected intents.

    Added in version 1.5.

  • chunk_guilds_at_startup (bool) –

    Indicates if on_ready() should be delayed to chunk all guilds at start-up if necessary. This operation is incredibly slow for large amounts of guilds. The default is True if Intents.members is True.

    Added in version 1.5.

  • status (Optional[Status]) – A status to start your presence with upon logging on to Discord.

  • activity (Optional[BaseActivity]) – An activity to start your presence with upon logging on to Discord.

  • allowed_mentions (Optional[AllowedMentions]) –

    Control how the client handles mentions by default on every message sent.

    Added in version 1.4.

  • heartbeat_timeout (float) – The maximum numbers of seconds before timing out and restarting the WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if processing the initial packets take too long to the point of disconnecting you. The default timeout is 60 seconds.

  • guild_ready_timeout (float) –

    The maximum number of seconds to wait for the GUILD_CREATE stream to end before preparing the member cache and firing READY. The default timeout is 2 seconds.

    Added in version 1.4.

  • assume_unsync_clock (bool) –

    Whether to assume the system clock is unsynced. This applies to the ratelimit handling code. If this is set to True, the default, then the library uses the time to reset a rate limit bucket given by Discord. If this is False then your system clock is used to calculate how long to sleep for. If this is set to False it is recommended to sync your system clock to Google’s NTP server.

    Added in version 1.3.

  • enable_debug_events (bool) –

    Whether to enable events that are useful only for debugging gateway related information.

    Right now this involves on_socket_raw_receive() and on_socket_raw_send(). If this is False then those events will not be dispatched (due to performance considerations). To enable these events, this must be set to True. Defaults to False.

    Added in version 2.0.

  • cache_app_emojis (bool) –

    Whether to automatically fetch and cache the application’s emojis on startup and when fetching. Defaults to False.

    Uyarı

    There are no events related to application emojis - if any are created/deleted on the Developer Dashboard while the client is running, the cache will not be updated until you manually run fetch_emojis().

    Added in version 2.7.

  • cache_default_sounds (bool) –

    Whether to automatically fetch and cache the default soundboard sounds on startup. Defaults to True.

    Added in version 2.8.

ws

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

loop

The event loop that the client uses for asynchronous operations.

Type:

asyncio.AbstractEventLoop

Parametreler:

options (Any)

@event(coro)[kaynak]

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, TypeError is raised.

Not

This replaces any default handlers. Developers are encouraged to use listen() for adding additional handlers instead of event() unless default method replacement is intended.

Harekete geçirir:

TypeError – The coroutine passed is not actually a coroutine.

Örnek

@client.event
async def on_ready():
    print('Ready!')
Parametreler:

coro (TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]]))

Dönüş türü:

TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])

async for ... in fetch_guilds(*, limit=100, before=None, after=None, with_counts=True)[kaynak]

Retrieves an AsyncIterator that enables receiving your guilds.

Not

Using this, you will only receive Guild.owner, Guild.icon, Guild.id, and Guild.name per Guild.

Not

This method is an API call. For general usage, consider guilds instead.

Parametreler:
  • limit (int | None) – The number of guilds to retrieve. If None, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 100.

  • before (Snowflake | datetime) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • with_counts (bool) – Whether to include member count information in guilds. This fills the Guild.approximate_member_count and Guild.approximate_presence_count fields. Defaults to True.

Getiriler:

Guild – The guild with the guild data parsed.

Harekete geçirir:

HTTPException – Getting the guilds failed.

Dönüş türü:

GuildIterator

Örnekler

Usage

async for guild in client.fetch_guilds(limit=150):
    print(guild.name)

Flattening into a list

guilds = await client.fetch_guilds(limit=150).flatten()
# guilds is now a list of Guild...

All parameters are optional.

@listen(name=..., once=False)[kaynak]

A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as on_ready()

The functions being listened to must be a coroutine.

Harekete geçirir:
  • TypeError – The function being listened to is not a coroutine.

  • ValueError – The name (event name) does not start with on_.

Örnek

@client.listen()
async def on_message(message):
    print('one')

# in some other file...

@client.listen('on_message')
async def my_message(message):
    print('two')

# listen to the first event only
@client.listen('on_ready', once=True)
async def on_ready():
    print('ready!')

Would print one and two in an unspecified order.

Parametreler:
Dönüş türü:

Callable[[TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])], TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])]

property latency: float

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. If no websocket is present, this returns nan, and if no heartbeat has been received yet, this returns float('inf').

This could be referred to as the Discord WebSocket protocol latency.

is_ws_ratelimited()[kaynak]

Whether the WebSocket is currently rate limited.

This can be useful to know when deciding whether you should query members using HTTP or via the gateway.

Added in version 1.6.

Dönüş türü:

bool

property user: ClientUser | None

Represents the connected client. None if not logged in.

property guilds: list[Guild]

The guilds that the connected client is a member of.

property emojis: list[GuildEmoji | AppEmoji]

The emojis that the connected client has.

Not

This only includes the application’s emojis if cache_app_emojis is True.

property guild_emojis: list[GuildEmoji]

The GuildEmoji that the connected client has.

property app_emojis: list[AppEmoji]

The AppEmoji that the connected client has.

Not

This is only available if cache_app_emojis is True.

property stickers: list[GuildSticker]

The stickers that the connected client has.

Added in version 2.0.

property polls: list[Poll]

The polls that the connected client has.

Added in version 2.6.

property cached_messages: Sequence[Message]

Read-only list of messages the connected client has cached.

Added in version 1.1.

property private_channels: list[PrivateChannel]

The private channels that the connected client is participating on.

Not

This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels.

property voice_clients: list[VoiceProtocol[Self]]

Represents a list of voice connections.

These are usually VoiceClient instances.

property application_id: int | None

The client’s application ID.

If this is not passed via __init__ then this is retrieved through the gateway when an event contains the data. Usually after on_connect() is called.

Added in version 2.0.

property application_flags: ApplicationFlags

The client’s application flags.

Added in version 2.0.

is_ready()[kaynak]

Specifies if the client’s internal cache is ready for use.

Dönüş türü:

bool

await on_error(event_method, *args, **kwargs)[kaynak]

This function is a coroutine.

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 on_error() for more details.

Parametreler:
Dönüş türü:

None

await on_view_error(error, item, interaction)[kaynak]

This function is a coroutine.

The default view error handler provided by the client.

This only fires for a view if you did not define its on_error().

Parametreler:
  • error (Exception) – The exception that was raised.

  • item (ViewItem) – The item that the user interacted with.

  • interaction (Interaction) – The interaction that was received.

Dönüş türü:

None

await on_modal_error(error, interaction)[kaynak]

This function is a coroutine.

The default modal error handler provided by the client. The default implementation prints the traceback to stderr.

This only fires for a modal if you did not define its on_error().

Parametreler:
  • error (Exception) – The exception that was raised.

  • interaction (Interaction) – The interaction that was received.

Dönüş türü:

None

await before_identify_hook(shard_id, *, initial=False)[kaynak]

This function is a coroutine.

A hook that is called before IDENTIFYing a session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients.

The default implementation sleeps for 5 seconds.

Added in version 1.4.

Parametreler:
  • shard_id (int | None) – The shard ID that requested being IDENTIFY’d

  • initial (bool) – Whether this IDENTIFY is the first initial IDENTIFY.

Dönüş türü:

None

await login(token)[kaynak]

This function is a coroutine.

Logs in the client with the specified credentials.

Parametreler:

token (str) – The authentication token. Do not prefix this token with anything as the library will do it for you.

Harekete geçirir:
  • TypeError – The token was in invalid type.

  • LoginFailure – The wrong credentials are passed.

  • HTTPException – An unknown HTTP related error occurred, usually when it isn’t 200 or the known incorrect credentials passing status code.

Dönüş türü:

None

await connect(*, reconnect=True)[kaynak]

This function is a coroutine.

Creates a WebSocket connection and lets the WebSocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.

Parametreler:

reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).

Harekete geçirir:
  • GatewayNotFound – The gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.

  • ConnectionClosed – The WebSocket connection has been terminated.

Dönüş türü:

None

await close()[kaynak]

This function is a coroutine.

Closes the connection to Discord.

Dönüş türü:

None

clear()[kaynak]

Clears the internal state of the bot.

After this, the bot can be considered “re-opened”, i.e. is_closed() and is_ready() both return False along with the bot’s internal cache cleared.

Dönüş türü:

None

await start(token, *, reconnect=True)[kaynak]

This function is a coroutine.

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

Harekete geçirir:

TypeError – An unexpected keyword argument was received.

Parametreler:
Dönüş türü:

None

run(*args, **kwargs)[kaynak]

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

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

Roughly Equivalent to:

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

Uyarı

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.

Parametreler:
Dönüş türü:

None

is_closed()[kaynak]

Indicates if the WebSocket connection is closed.

Dönüş türü:

bool

property activity: Activity | Game | CustomActivity | Streaming | Spotify | None

The activity being used upon logging in.

Dönüş türü:

Optional[BaseActivity]

property status: Status

The status being used upon logging on to Discord.

property allowed_mentions: AllowedMentions | None

The allowed mention configuration.

Added in version 1.4.

property intents: Intents

The intents configured for this connection.

Added in version 1.5.

property users: list[User]

Returns a list of all the users the bot can see.

await fetch_application(application_id, /)[kaynak]

This function is a coroutine. Retrieves a PartialAppInfo from an application ID.

Parametreler:

application_id (int) – The application ID to retrieve information from.

Dönüşler:

The application information.

Dönüş türü:

PartialAppInfo

Harekete geçirir:
  • NotFound – An application with this ID does not exist.

  • HTTPException – Retrieving the application failed.

get_channel(id, /)[kaynak]

Returns a channel or thread with the given ID.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The returned channel or None if not found.

Dönüş türü:

GuildChannel | Thread | PrivateChannel | None

get_message(id, /)[kaynak]

Returns a message the given ID.

This is useful if you have a message_id but don’t want to do an API call to access the message.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The returned message or None if not found.

Dönüş türü:

Message | None

get_partial_messageable(id, *, type=None)[kaynak]

Returns a partial messageable with the given channel ID.

This is useful if you have a channel_id but don’t want to do an API call to send messages to it.

Added in version 2.0.

Parametreler:
  • id (int) – The channel ID to create a partial messageable for.

  • type (ChannelType | None) – The underlying channel type for the partial messageable.

Dönüşler:

The partial messageable

Dönüş türü:

PartialMessageable

get_stage_instance(id, /)[kaynak]

Returns a stage instance with the given stage channel ID.

Added in version 2.0.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The stage instance or None if not found.

Dönüş türü:

StageInstance | None

get_guild(id, /)[kaynak]

Returns a guild with the given ID.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The guild or None if not found.

Dönüş türü:

Guild | None

get_user(id, /)[kaynak]

Returns a user with the given ID.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The user or None if not found.

Dönüş türü:

User | None

get_emoji(id, /)[kaynak]

Returns an emoji with the given ID.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The custom emoji or None if not found.

Dönüş türü:

GuildEmoji | AppEmoji | None

get_sticker(id, /)[kaynak]

Returns a guild sticker with the given ID.

Added in version 2.0.

Not

To retrieve standard stickers, use fetch_sticker(). or fetch_premium_sticker_packs().

Dönüşler:

The sticker or None if not found.

Dönüş türü:

GuildSticker | None

Parametreler:

id (int)

get_poll(id, /)[kaynak]

Returns a poll attached to the given message ID.

Parametreler:

id (int) – The message ID of the poll to search for.

Dönüşler:

The poll or None if not found.

Dönüş türü:

Poll | None

get_all_channels()[kaynak]

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

This is equivalent to:

for guild in client.guilds:
    for channel in guild.channels:
        yield channel

Not

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

Getiriler:

abc.GuildChannel – A channel the client can ‘access’.

Dönüş türü:

Generator[GuildChannel, None, None]

get_all_members()[kaynak]

Returns a generator with every Member the client can see.

This is equivalent to:

for guild in client.guilds:
    for member in guild.members:
        yield member
Getiriler:

Member – A member the client can see.

Dönüş türü:

Generator[Member, None, None]

await get_or_fetch_user(id, /)[kaynak]

This function is a coroutine.

Looks up a user in the user cache or fetches if not found.

Parametreler:

id (int) – The ID to search for.

Dönüşler:

The user or None if not found.

Dönüş türü:

User | None

await get_or_fetch(object_type, object_id, default=None)[kaynak]

Shortcut method to get data from an object either by returning the cached version, or if it does not exist, attempting to fetch it from the API.

Parametreler:
  • object_type (type[TypeVar(_FETCHABLE, bound= VoiceChannel | TextChannel | ForumChannel | StageChannel | CategoryChannel | Thread | Member | User | Guild | Role | GuildEmoji | AppEmoji)]) – Type of object to fetch or get.

  • object_id (int | None) – ID of object to get. If None, returns default if provided, else None.

  • default (TypeVar(_D)) – A default to return instead of raising if fetch fails.

  • self (Client)

Dönüşler:

The object if found, or default if provided when not found.

Dönüş türü:

TypeVar(_FETCHABLE, bound= VoiceChannel | TextChannel | ForumChannel | StageChannel | CategoryChannel | Thread | Member | User | Guild | Role | GuildEmoji | AppEmoji) | TypeVar(_D) | None

Harekete geçirir:
  • TypeError – Raised when required parameters are missing or invalid types are provided.

  • InvalidArgument – Raised when an unsupported or incompatible object type is used.

await wait_until_ready()[kaynak]

This function is a coroutine.

Waits until the client’s internal cache is all ready.

Dönüş türü:

None

wait_for(event, *, check=None, timeout=None)[kaynak]

This function is a coroutine.

Waits for a WebSocket event to be dispatched.

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

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

In case the event returns multiple arguments, a tuple containing those arguments is returned instead. Please check the documentation for a list of events and their parameters.

This function returns the first event that meets the requirements.

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

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

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

Dönüşler:

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

Dönüş türü:

Any

Harekete geçirir:

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

Örnekler

Waiting for a user reply:

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

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

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

Waiting for a thumbs up reaction from the message author:

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

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '👍'

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('👎')
        else:
            await channel.send('👍')
add_listener(func, name=...)[kaynak]

The non decorator alternative to listen().

Parametreler:
Harekete geçirir:
  • TypeError – The func parameter is not a coroutine function.

  • ValueError – The name (event name) does not start with on_.

Dönüş türü:

None

Örnek

async def on_ready(): pass
async def my_message(message): pass

client.add_listener(on_ready)
client.add_listener(my_message, 'on_message')
remove_listener(func, name=...)[kaynak]

Removes a listener from the pool of listeners.

Parametreler:
  • func (TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])) – The function that was used as a listener to remove.

  • name (str) – The name of the event we want to remove. Defaults to func.__name__.

Dönüş türü:

None

await change_presence(*, activity=None, status=None)[kaynak]

This function is a coroutine.

Changes the client’s presence.

Parametreler:
  • activity (BaseActivity | None) – The activity being done. None if no currently active activity is done.

  • status (Status | None) – Indicates what status to change to. If None, then Status.online is used.

Harekete geçirir:

InvalidArgument – If the activity parameter is not the proper type.

Örnek

game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)

2.0 sürümünde değişti: Removed the afk keyword-only parameter.

await fetch_template(code)[kaynak]

This function is a coroutine.

Gets a Template from a discord.new URL or code.

Parametreler:

code (Template | str) – The Discord Template Code or URL (must be a discord.new URL).

Dönüşler:

The template from the URL/code.

Dönüş türü:

Template

Harekete geçirir:
await fetch_guild(guild_id, /, *, with_counts=True)[kaynak]

This function is a coroutine.

Retrieves a Guild from an ID.

Not

Using this, you will not receive Guild.channels, Guild.members, Member.activity and Member.voice per Member.

Not

This method is an API call. For general usage, consider get_guild() instead.

Parametreler:
Dönüşler:

The guild from the ID.

Dönüş türü:

Guild

Harekete geçirir:
await fetch_stage_instance(channel_id, /)[kaynak]

This function is a coroutine.

Gets a StageInstance for a stage channel id.

Added in version 2.0.

Parametreler:

channel_id (int) – The stage channel ID.

Dönüşler:

The stage instance from the stage channel ID.

Dönüş türü:

StageInstance

Harekete geçirir:
  • NotFound – The stage instance or channel could not be found.

  • HTTPException – Getting the stage instance failed.

await fetch_invite(url, *, with_counts=True, with_expiration=True, event_id=None)[kaynak]

This function is a coroutine.

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

Not

If the invite is for a guild you have not joined, the guild and channel attributes of the returned Invite will be PartialInviteGuild and PartialInviteChannel respectively.

Parametreler:
Dönüşler:

The invite from the URL/ID.

Dönüş türü:

Invite

Harekete geçirir:
await delete_invite(invite)[kaynak]

This function is a coroutine.

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

You must have the manage_channels permission in the associated guild to do this.

Parametreler:

invite (Invite | str) – The invite to revoke.

Harekete geçirir:
  • Forbidden – You do not have permissions to revoke invites.

  • NotFound – The invite is invalid or expired.

  • HTTPException – Revoking the invite failed.

Dönüş türü:

None

await fetch_widget(guild_id, /)[kaynak]

This function is a coroutine.

Gets a Widget from a guild ID.

Not

The guild must have the widget enabled to get this information.

Parametreler:

guild_id (int) – The ID of the guild.

Dönüşler:

The guild’s widget.

Dönüş türü:

Widget

Harekete geçirir:
await application_info()[kaynak]

This function is a coroutine.

Retrieves the bot’s application information.

Dönüşler:

The bot’s application information.

Dönüş türü:

AppInfo

Harekete geçirir:

HTTPException – Retrieving the information failed somehow.

await fetch_user(user_id, /)[kaynak]

This function is a coroutine.

Retrieves a User based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Not

This method is an API call. If you have discord.Intents.members and member cache enabled, consider get_user() instead.

Parametreler:

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

Dönüşler:

The user you requested.

Dönüş türü:

User

Harekete geçirir:
await fetch_channel(channel_id, /)[kaynak]

This function is a coroutine.

Retrieves a abc.GuildChannel, abc.PrivateChannel, or Thread with the specified ID.

Not

This method is an API call. For general usage, consider get_channel() instead.

Added in version 1.2.

Dönüşler:

The channel from the ID.

Dönüş türü:

GuildChannel | PrivateChannel | Thread

Harekete geçirir:
  • InvalidData – An unknown channel type was received from Discord.

  • HTTPException – Retrieving the channel failed.

  • NotFound – Invalid Channel ID.

  • Forbidden – You do not have permission to fetch this channel.

Parametreler:

channel_id (int)

await fetch_webhook(webhook_id, /)[kaynak]

This function is a coroutine.

Retrieves a Webhook with the specified ID.

Dönüşler:

The webhook you requested.

Dönüş türü:

Webhook

Harekete geçirir:
Parametreler:

webhook_id (int)

await fetch_sticker(sticker_id, /)[kaynak]

This function is a coroutine.

Retrieves a Sticker with the specified ID.

Added in version 2.0.

Dönüşler:

The sticker you requested.

Dönüş türü:

StandardSticker | GuildSticker

Harekete geçirir:
Parametreler:

sticker_id (int)

await fetch_premium_sticker_packs()[kaynak]

This function is a coroutine.

Retrieves all available premium sticker packs.

Added in version 2.0.

Dönüşler:

All available premium sticker packs.

Dönüş türü:

list[StickerPack]

Harekete geçirir:

HTTPException – Retrieving the sticker packs failed.

await create_dm(user)[kaynak]

This function is a coroutine.

Creates a DMChannel with this user.

This should be rarely called, as this is done transparently for most people.

Added in version 2.0.

Parametreler:

user (Snowflake) – The user to create a DM with.

Dönüşler:

The channel that was created.

Dönüş türü:

DMChannel

add_view(view, *, message_id=None)[kaynak]

Registers a BaseView for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

Added in version 2.0.

Parametreler:
  • view (BaseView) – The view to register for dispatching.

  • message_id (int | None) – The message ID that the view is attached to. This is currently used to refresh the view’s state during message update events. If not given then message update events are not propagated for the view.

Harekete geçirir:
  • TypeError – A view was not passed.

  • ValueError – The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided custom_id.

Dönüş türü:

None

property persistent_views: Sequence[BaseView]

A sequence of persistent views added to the client.

Added in version 2.0.

await fetch_role_connection_metadata_records()[kaynak]

This function is a coroutine.

Fetches the bot’s role connection metadata records.

Added in version 2.4.

Dönüşler:

The bot’s role connection metadata records.

Dönüş türü:

list[ApplicationRoleConnectionMetadata]

await update_role_connection_metadata_records(*role_connection_metadata)[kaynak]

This function is a coroutine.

Updates the bot’s role connection metadata records.

Added in version 2.4.

Parametreler:

*role_connection_metadata (ApplicationRoleConnectionMetadata) – The new metadata records to send to Discord.

Dönüşler:

The updated role connection metadata records.

Dönüş türü:

list[ApplicationRoleConnectionMetadata]

await fetch_skus()[kaynak]

This function is a coroutine.

Fetches the bot’s SKUs.

Added in version 2.5.

Dönüşler:

The bot’s SKUs.

Dönüş türü:

list[SKU]

entitlements(user=None, skus=None, before=None, after=None, limit=100, guild=None, exclude_ended=False)[kaynak]

Returns an AsyncIterator that enables fetching the application’s entitlements.

Added in version 2.6.

Parametreler:
  • user (Snowflake | None) – Limit the fetched entitlements to entitlements owned by this user.

  • skus (list[Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.

  • before (Snowflake | datetime | None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • limit (int | None) – The number of entitlements to retrieve. If None, retrieves every entitlement, which may be slow. Defaults to 100.

  • guild (Snowflake | None) – Limit the fetched entitlements to entitlements owned by this guild.

  • exclude_ended (bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults to False.

Getiriler:

Entitlement – The application’s entitlements.

Harekete geçirir:

HTTPException – Retrieving the entitlements failed.

Dönüş türü:

EntitlementIterator

Örnekler

Usage

async for entitlement in client.entitlements():
    print(entitlement.user_id)

Flattening into a list

entitlements = await user.entitlements().flatten()

All parameters are optional.

property store_url: str

The URL that leads to the application’s store page for monetization.

Added in version 2.6.

Type:

str

await fetch_emojis()[kaynak]

This function is a coroutine.

Retrieves all custom AppEmojis from the application.

Harekete geçirir:

HTTPException – An error occurred fetching the emojis.

Dönüşler:

The retrieved emojis.

Dönüş türü:

list[AppEmoji]

await fetch_emoji(emoji_id, /)[kaynak]

This function is a coroutine.

Retrieves a custom AppEmoji from the application.

Parametreler:

emoji_id (int) – The emoji’s ID.

Dönüşler:

The retrieved emoji.

Dönüş türü:

AppEmoji

Harekete geçirir:
  • NotFound – The emoji requested could not be found.

  • HTTPException – An error occurred fetching the emoji.

await create_emoji(*, name, image)[kaynak]

This function is a coroutine.

Creates a custom AppEmoji for the application.

There is currently a limit of 2000 emojis per application.

Parametreler:
  • 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, PNG and GIF images are supported.

Harekete geçirir:

HTTPException – An error occurred creating an emoji.

Dönüşler:

The created emoji.

Dönüş türü:

AppEmoji

await delete_emoji(emoji)[kaynak]

This function is a coroutine.

Deletes the custom AppEmoji from the application.

Parametreler:

emoji (Snowflake) – The emoji you are deleting.

Harekete geçirir:

HTTPException – An error occurred deleting the emoji.

Dönüş türü:

None

get_sound(sound_id)[kaynak]

Gets a Sound from the bot’s sound cache.

Added in version 2.7.

Parametreler:

sound_id (int) – The ID of the sound to get.

Dönüşler:

The sound with the given ID.

Dönüş türü:

SoundboardSound | None

property sounds: list[SoundboardSound]

A list of all the sounds the bot can see.

Added in version 2.7.

await fetch_default_sounds()[kaynak]

This function is a coroutine.

Fetches the bot’s default sounds.

Added in version 2.7.

Dönüşler:

The bot’s default sounds.

Dönüş türü:

list[SoundboardSound]

class discord.AutoShardedClient(*args, loop=None, **kwargs)[kaynak]

A client similar to Client except it handles the complications of sharding for the user into a more manageable and transparent single process bot.

When using this client, you will be able to use it as-if it was a regular Client with a single shard when implementation wise internally it is split up into multiple shards. This allows you to not have to deal with IPC or other complicated infrastructure.

It is recommended to use this client only if you have surpassed at least 1000 guilds.

If no shard_count is provided, then the library will use the Bot Gateway endpoint call to figure out how many shards to use.

If a shard_ids parameter is given, then those shard IDs will be used to launch the internal shards. Note that shard_count must be provided if this is used. By default, when omitted, the client will launch shards from 0 to shard_count - 1.

shard_ids

An optional list of shard_ids to launch the shards with.

Type:

Optional[List[int]]

Parametreler:
property latency: float

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This operates similarly to Client.latency() except it uses the average latency of every shard’s latency. To get a list of shard latency, check the latencies property. Returns nan if there are no shards ready.

property latencies: list[tuple[int, float]]

A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This returns a list of tuples with elements (shard_id, latency).

get_shard(shard_id)[kaynak]

Gets the shard information at a given shard ID or None if not found.

Parametreler:

shard_id (int)

Dönüş türü:

ShardInfo | None

property shards: dict[int, ShardInfo]

Returns a mapping of shard IDs to their respective info object.

await connect(*, reconnect=True)[kaynak]

This function is a coroutine.

Creates a WebSocket connection and lets the WebSocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.

Parametreler:

reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).

Harekete geçirir:
  • GatewayNotFound – The gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.

  • ConnectionClosed – The WebSocket connection has been terminated.

Dönüş türü:

None

await close()[kaynak]

This function is a coroutine.

Closes the connection to Discord.

Dönüş türü:

None

await change_presence(*, activity=None, status=None, shard_id=None)[kaynak]

This function is a coroutine.

Changes the client’s presence.

Example:

game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)

2.0 sürümünde değişti: Removed the afk keyword-only parameter.

Parametreler:
  • activity (BaseActivity | None) – The activity being done. None if no currently active activity is done.

  • status (Status | None) – Indicates what status to change to. If None, then Status.online is used.

  • shard_id (int) – The shard_id to change the presence to. If not specified or None, then it will change the presence of every shard the bot can see.

Harekete geçirir:

InvalidArgument – If the activity parameter is not of proper type.

Dönüş türü:

None

is_ws_ratelimited()[kaynak]

Whether the websocket is currently rate limited.

This can be useful to know when deciding whether you should query members using HTTP or via the gateway.

This implementation checks if any of the shards are rate limited. For more granular control, consider ShardInfo.is_ws_ratelimited().

Added in version 1.6.

Dönüş türü:

bool