APIリファレンス

The following section outlines the API of ndiscord.py.

注釈

This module uses the Python logging module to log diagnostic and errors in an output independent way. If the logging module is not configured, these logs will not be output anywhere. See ログの設定 for more information on how to set up and use the logging module with ndiscord.py.

Clients

クライアント

class discord.Client(*args, **kwargs)

Discordに接続するクライアント接続を表します。このクラスは、DiscordのWebSocket、及びAPIとの対話に使用されます。

多くのオプションを Client に渡すことが可能です。

パラメータ
  • 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 で変更: Allow disabling the message cache and change the default size to 1000.

  • loop (Optional[asyncio.AbstractEventLoop]) -- 非同期操作に使用する asyncio.AbstractEventLoop 。デフォルトは None です。この場合、デフォルトのイベントループは asyncio.get_event_loop() を介して使用されます。

  • connector (Optional[aiohttp.BaseConnector]) -- コネクションプーリングに使用するコネクタ。

  • proxy (Optional[str]) -- プロキシのURL。

  • proxy_auth (Optional[aiohttp.BasicAuth]) -- プロキシのHTTP Basic認証を表すオブジェクト。

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

  • shard_count (Optional[int]) -- Shardの総数。

  • 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.

    バージョン 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.

    バージョン 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.

    バージョン 1.5 で追加.

  • status (Optional[Status]) -- Discordにログインした際の、開始時ステータス。

  • activity (Optional[BaseActivity]) -- Discordにログインした際の、開始時アクティビティ。

  • allowed_mentions (Optional[AllowedMentions]) --

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

    バージョン 1.4 で追加.

  • heartbeat_timeout (float) -- HEARTBEAT_ACKを受信できない際に、WebSocketをタイムアウトさせて再起動するまでの最大秒数。最初のパケットの処理に時間がかかり、接続を切断できないというような状況時に便利です。デフォルトでは60秒に設定されています。

  • 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.

    バージョン 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.

    バージョン 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.

    バージョン 2.0 で追加.

ws

クライアントが現在接続しているWebSocketゲートウェイ。 None でもかまいません。

loop

The event loop that the client uses for asynchronous operations.

Type

asyncio.AbstractEventLoop

@event

リッスンするイベントを登録するデコレータ。

イベントの詳細については 以下のドキュメント を参照してください。

イベントは コルーチン でなければいけません。違う場合は TypeError が発生します。

サンプル

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

TypeError -- The coroutine passed is not actually a coroutine.

async for ... in fetch_guilds(*, limit=100, before=None, after=None)

Botが所属するGuildを取得できる、 AsyncIterator を取得します。

注釈

これを使った場合、各 GuildGuild.ownerGuild.iconGuild.idGuild.name のみ取得できます。

注釈

これはAPIを呼び出します。通常は guilds を代わりに使用してください。

サンプル

使い方

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

リストへフラット化

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

すべてのパラメータがオプションです。

パラメータ
  • limit (Optional[int]) -- 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 (Union[abc.Snowflake, datetime.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 (Union[abc.Snowflake, datetime.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.

例外

HTTPException -- Getting the guilds failed.

列挙

Guild -- データを解析したGuild。

@application_command(*args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_application().

バージョン 2.0 で追加.

戻り値

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

戻り値の型

Callable[..., ApplicationCommand]

@slash_command(*args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_application(). This shortcut is made specifically for SlashCommand.

バージョン 2.0 で追加.

パラメータ
  • name (Optional[str]) -- The name of the command. Defaults to the name of the method.

  • description (Optional[str]) -- A short description of the command.

  • guild_ids (Optional[List[int]]) -- Guild IDs where the command can be run on. Setting this will make the command only usable from this guild.

  • checks (Optional[List[Callable[[ApplicationContext], bool]]]) -- A list of predicates that must be true for the command to be invoked.

戻り値

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

戻り値の型

Callable[..., SlashCommand]

@user_command(*args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_application(). This shortcut is made specifically for UserCommand.

バージョン 2.0 で追加.

パラメータ
  • name (Optional[str]) -- The name of the command. Defaults to the name of the method.

  • guild_ids (Optional[List[int]]) -- Guild IDs where the command can be run on. Setting this will make the command only usable from this guild.

  • checks (Optional[List[Callable[[ApplicationContext], bool]]]) -- A list of predicates that must be true for the command to be invoked.

戻り値

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

戻り値の型

Callable[..., UserCommand]

@message_command(*args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_application(). This shortcut is made specifically for MessageCommand.

バージョン 2.0 で追加.

パラメータ
  • name (Optional[str]) -- The name of the command. Defaults to the name of the method.

  • guild_ids (Optional[List[int]]) -- Guild IDs where the command can be run on. Setting this will make the command only usable from this guild.

  • checks (Optional[List[Callable[[ApplicationContext], bool]]]) -- A list of predicates that must be true for the command to be invoked.

戻り値

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

戻り値の型

Callable[..., MessageCommand]

property latency: float

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

これはDiscord WebSocketプロトコルの待ち時間とも言えます。

Type

float

is_ws_ratelimited()

bool: 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.

バージョン 1.6 で追加.

property user: Optional[discord.user.ClientUser]

Represents the connected client. None if not logged in.

Type

Optional[ClientUser]

property guilds: List[discord.guild.Guild]

The guilds that the connected client is a member of.

Type

List[Guild]

property emojis: List[discord.emoji.Emoji]

The emojis that the connected client has.

Type

List[Emoji]

property stickers: List[discord.sticker.GuildSticker]

The stickers that the connected client has.

バージョン 2.0 で追加.

Type

List[GuildSticker]

property cached_messages: Sequence[Message]

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

バージョン 1.1 で追加.

Type

Sequence[Message]

property private_channels: List[PrivateChannel]

The private channels that the connected client is participating on.

注釈

Discordでのプライベートチャンネルの取扱いは内部的に処理されているため、これは最新のプライベートチャンネルから最大128個までしか取得できません。

Type

List[abc.PrivateChannel]

property voice_clients: List[VoiceProtocol]

Represents a list of voice connections.

These are usually VoiceClient instances.

Type

List[VoiceProtocol]

property application_id: Optional[int]

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.

バージョン 2.0 で追加.

Type

Optional[int]

property application_flags: discord.flags.ApplicationFlags

The client's application flags.

バージョン 2.0 で追加.

Type

ApplicationFlags

is_ready()

bool: Specifies if the client's internal cache is ready for use.

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

This function is a coroutine.

クライアントによって提供されるデフォルトのエラーハンドラ。

デフォルトでは、これは sys.stderr に出力されますが、異なる実装によって上書きされる可能性があります。詳細については on_error() を確認してください。

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.

バージョン 1.4 で追加.

パラメータ
  • shard_id (int) -- The shard ID that requested being IDENTIFY'd

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

await login(token)

This function is a coroutine.

指定された資格情報を使用してクライアントにログインします。

パラメータ

token (str) -- 認証用のトークン。このライブラリが処理するため、トークンの頭に何も付けないでください。

例外
  • 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.

await connect(*, reconnect=True)

This function is a coroutine.

WebSocket接続を作成し、Discordからのメッセージをリッスンできるようにします。これはイベントシステム全体とライブラリの様々な機能を実行するループです。WebSocket接続が終了するまで、制御は再開されません。

パラメータ

reconnect (bool) -- インターネットの障害やDiscord側の特定の障害が発生した際に再接続を試みるかどうかを表します。不正な状態へつながることによる特定の切断(無効なシャーディングペイロードや不正なトークンなど)は処理されません。

例外
  • GatewayNotFound -- If 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.

await close()

This function is a coroutine.

Discordとの接続を閉じます。

clear()

Botの内部状態をクリアします。

これが実行されると、Botは「再オープン」されたとみなされます。そのため、 is_closed()is_ready()False を返し、内部のキャッシュもクリアされます。

await start(token, *, reconnect=True)

This function is a coroutine.

login() + connect() を簡略化したコルーチン。

例外

TypeError -- An unexpected keyword argument was received.

run(*args, **kwargs)

イベントループの初期化を抽象化するブロッキングコール。

イベントループをより詳細に制御するには、この関数を使用しないでください。 start() または connect() + login() を使用してください。

おおよそ次のものに相当:

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

警告

この関数はブロッキングを行うため、必ず最後に呼び出してください。この関数を呼び出した後に呼び出されるイベントや関数は、Botが停止するまで実行されません。

await on_connect()

This function is a coroutine.

Initialize application registration. If you decide to override this, you need to make sure that you call register_application_commands() at some point to make sure application commands works.

Or you can do super().on_connect() too.

await register_application_commands()

This function is a coroutine.

Method to start registering and unregistering commands.

is_closed()

bool: Indicates if the websocket connection is closed.

property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]

The activity being used upon logging in.

Type

Optional[BaseActivity]

property status

Status: The status being used upon logging on to Discord.

property allowed_mentions: Optional[discord.mentions.AllowedMentions]

The allowed mention configuration.

バージョン 1.4 で追加.

Type

Optional[AllowedMentions]

property intents: discord.flags.Intents

The intents configured for this connection.

バージョン 1.5 で追加.

Type

Intents

property users: List[discord.user.User]

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

Type

List[User]

get_channel(id, /)

Returns a channel or thread with the given ID.

パラメータ

id (int) -- The ID to search for.

戻り値

The returned channel or None if not found.

戻り値の型

Optional[Union[abc.GuildChannel, Thread, abc.PrivateChannel]]

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.

バージョン 2.0 で追加.

パラメータ
  • id (int) -- The channel ID to create a partial messageable for.

  • type (Optional[ChannelType]) -- The underlying channel type for the partial messageable.

戻り値

The partial messageable

戻り値の型

PartialMessageable

get_stage_instance(id, /)

Returns a stage instance with the given stage channel ID.

バージョン 2.0 で追加.

パラメータ

id (int) -- The ID to search for.

戻り値

The returns stage instance of None if not found.

戻り値の型

Optional[StageInstance]

get_guild(id, /)

Returns a guild with the given ID.

パラメータ

id (int) -- The ID to search for.

戻り値

The guild or None if not found.

戻り値の型

Optional[Guild]

get_guild_event(id, /)

Returns a scheduled event with the given ID.

バージョン 2.0 で追加.

パラメータ

id (int) -- The ID to search for.

戻り値

The event or None if not found.

戻り値の型

Optional[GuildScheduledEvent]

get_user(id, /)

Returns a user with the given ID.

パラメータ

id (int) -- The ID to search for.

戻り値

The user or None if not found.

戻り値の型

Optional[User]

get_emoji(id, /)

Returns an emoji with the given ID.

パラメータ

id (int) -- The ID to search for.

戻り値

The custom emoji or None if not found.

戻り値の型

Optional[Emoji]

get_sticker(id, /)

Returns a guild sticker with the given ID.

バージョン 2.0 で追加.

注釈

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

戻り値

The sticker or None if not found.

戻り値の型

Optional[GuildSticker]

for ... in get_all_channels()

クライアントが「アクセス」できるすべての abc.GuildChannel のジェネレータを取得します。

使用例:

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

注釈

abc.GuildChannel を受け取ったからと言って、そのチャンネルで発言ができるという意味ではありません。発言可能なチャンネルのみを取得したいのなら、 abc.GuildChannel.permissions_for() を使いましょう。

列挙

abc.GuildChannel -- A channel the client can 'access'.

for ... in get_all_members()

クライアントが参照可能なすべての Member のジェネレータを返します。

使用例:

for guild in client.guilds:
    for member in guild.members:
        yield member
列挙

Member -- A member the client can see.

await wait_until_ready()

This function is a coroutine.

クライアントの内部キャッシュの準備が完了するまで待機します。

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

This function is a coroutine.

WebSocketイベントがディスパッチされるまで待機します。

メッセージの送信者が、メッセージに返信したり、リアクションをつけたり、編集したりする、自己完結型の処理に利用できます。

timeout パラメータは asyncio.wait_for() に渡されます。デフォルトではタイムアウトしません。タイムアウトした際に asyncio.TimeoutError が発生するのは、使いやすさを考慮したためです。

イベントが複数の引数を返す場合は、それらを含む tuple が代わりに返ります。イベントとそのパラメーターについては ドキュメント を参照してください。

この関数は 条件を満たす最初のイベント を返します。

サンプル

ユーザーからの返信を待つ場合:

@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}!')

メッセージ送信者がサムズアップリアクションを付けるのを待つ場合:

@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('👍')
パラメータ
  • event (str) -- イベント名は イベントリファレンス に似ていますが接頭詞の on_ が必要ありません。

  • check (Optional[Callable[..., bool]]) -- 待っているものに該当するかを確認する関数。引数は待機しているイベントのパラメータを満たしている必要があります。

  • timeout (Optional[float]) -- タイムアウトして asyncio.TimeoutError が発生するまでの秒数。

例外

asyncio.TimeoutError -- If a timeout is provided and it was reached.

戻り値

単一の引数、あるいは イベントリファレンス のパラメータを反映した複数の引数の値を含む tuple が返ります。返る引数がない場合もあります。

戻り値の型

Any

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

This function is a coroutine.

クライアントのプレゼンスを変更します。

サンプル

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

バージョン 2.0 で変更: Removed the afk keyword-only parameter.

パラメータ
  • activity (Optional[BaseActivity]) -- 実行中のアクティビティ。何も実行していない場合は None です。

  • status (Optional[Status]) -- 変更するステータスを示します。 None の場合、:attr:`.Status.online`となります。

例外

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

await fetch_template(code)

This function is a coroutine.

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

パラメータ

code (Union[Template, str]) -- The Discord Template Code or URL (must be a discord.new URL).

例外
戻り値

The template from the URL/code.

戻り値の型

Template

await fetch_guild(guild_id, /)

This function is a coroutine.

IDから Guild を取得します。

注釈

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

注釈

このメソッドはAPIを呼び出します。通常は get_guild() を代わりとして使用してください。

パラメータ

guild_id (int) -- 取得したいギルドのID。

例外
戻り値

IDから取得したギルド。

戻り値の型

Guild

await create_guild(*, name, region=<VoiceRegion.us_west: 'us-west'>, icon=..., code=...)

This function is a coroutine.

Guild を作成します。

10以上のギルドに参加しているBotアカウントはギルドの作成ができません。

パラメータ
  • name (str) -- ギルドの名前。

  • region (VoiceRegion) -- ボイスチャンネルの通信サーバーのリージョンです。デフォルトは VoiceRegion.us_west です。

  • icon (Optional[bytes]) -- アイコンを表す bytes-like object です。 ClientUser.edit() で、予期されるデータの詳細を確認してください。

  • code (str) --

    The code for a template to create the guild with.

    バージョン 1.4 で追加.

例外
戻り値

作成されたギルド。キャッシュに追加されるギルドとは別物です。

戻り値の型

Guild

await fetch_stage_instance(channel_id, /)

This function is a coroutine.

Gets a StageInstance for a stage channel id.

バージョン 2.0 で追加.

パラメータ

channel_id (int) -- The stage channel ID.

例外
  • NotFound -- The stage instance or channel could not be found.

  • HTTPException -- Getting the stage instance failed.

戻り値

The stage instance from the stage channel ID.

戻り値の型

StageInstance

await fetch_guild_event(guild_id, event_id, /)

This function is a coroutine.

Gets a GuildScheduledEvent for a guild event id.

バージョン 2.0 で追加.

パラメータ

event_id (int) -- The event ID.

例外
戻り値

The event from the event ID.

戻り値の型

GuildScheduledEvent

await fetch_guild_events(guild_id, /)

This function is a coroutine.

Gets a list of GuildScheduledEvent for a guild.

バージョン 2.0 で追加.

パラメータ

guild_id (int) -- The guild ID to get the events for.

例外

HTTPException -- Getting the guild events failed.

戻り値

The list of scheduled events for the guild.

戻り値の型

List[GuildScheduledEvent]

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

This function is a coroutine.

Invite をdiscord.gg URLやIDから取得します。

注釈

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.

パラメータ
  • url (Union[Invite, str]) -- Discordの招待ID、またはURL(discord.gg URLである必要があります)。

  • with_counts (bool) -- 招待にカウントの情報を含めるかどうか。これにより Invite.approximate_member_countInvite.approximate_presence_count が追加されます。

  • with_expiration (bool) --

    Whether to include the expiration date of the invite. This fills the Invite.expires_at field.

    バージョン 2.0 で追加.

  • guild_scheduled_event_id (Optional[int]) --

    The ID of the guild scheduled event to which the invite belongs. If provided and valid, it might return a GuildScheduledEvent data.

    バージョン 2.0 で追加.

例外
戻り値

URL/IDから取得した招待。

戻り値の型

Invite

await delete_invite(invite)

This function is a coroutine.

Invite や、招待のURL、IDを削除します。

これを行うには、関連付けられたGuildにて、 manage_channels 権限が必要です。

パラメータ

invite (Union[Invite, str]) -- 取り消す招待。

例外
  • Forbidden -- You do not have permissions to revoke invites.

  • NotFound -- The invite is invalid or expired.

  • HTTPException -- Revoking the invite failed.

await fetch_widget(guild_id, /)

This function is a coroutine.

ギルドIDから Widget を取得します。

注釈

この情報を取得するためには、ギルドのウィジェットを有効化しておく必要があります。

パラメータ

guild_id (int) -- ギルドのID。

例外
戻り値

ギルドのウィジェット。

戻り値の型

Widget

await application_info()

This function is a coroutine.

Botのアプリケーション情報を取得します。

例外

HTTPException -- Retrieving the information failed somehow.

戻り値

Botのアプリケーション情報。

戻り値の型

AppInfo

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.

注釈

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

パラメータ

user_id (int) -- 取得したいユーザーのID。

例外
戻り値

あなたがリクエストしたユーザー。

戻り値の型

User

await fetch_channel(channel_id, /)

This function is a coroutine.

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

注釈

このメソッドはAPIを呼び出します。通常は get_channel() を代わりとして使用してください。

バージョン 1.2 で追加.

例外
  • 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.

戻り値

IDから取得したチャンネル。

戻り値の型

Union[abc.GuildChannel, abc.PrivateChannel, Thread]

await fetch_webhook(webhook_id, /)

This function is a coroutine.

特定のIDの Webhook を取得します。

例外
戻り値

要求したWebhook。

戻り値の型

Webhook

await fetch_sticker(sticker_id, /)

This function is a coroutine.

Retrieves a Sticker with the specified ID.

バージョン 2.0 で追加.

例外
戻り値

The sticker you requested.

戻り値の型

Union[StandardSticker, GuildSticker]

await fetch_premium_sticker_packs()

This function is a coroutine.

Retrieves all available premium sticker packs.

バージョン 2.0 で追加.

例外

HTTPException -- Retrieving the sticker packs failed.

戻り値

All available premium sticker packs.

戻り値の型

List[StickerPack]

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.

バージョン 2.0 で追加.

パラメータ

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

戻り値

The channel that was created.

戻り値の型

DMChannel

add_view(view, *, message_id=None)

Registers a View 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.

バージョン 2.0 で追加.

パラメータ
  • view (discord.ui.View) -- The view to register for dispatching.

  • message_id (Optional[int]) -- 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.

例外
  • 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.

property persistent_views: Sequence[discord.ui.view.View]

A sequence of persistent views added to the client.

バージョン 2.0 で追加.

Type

Sequence[View]

get_applications()

A list of application that are registered.

バージョン 2.0 で追加.

戻り値

List of registered global applications.

戻り値の型

List[ApplicationCommand]

add_application(command)

Register a new application command.

パラメータ

command (ApplicationCommand) -- The command to register.

get_application(id)

Get an application by its ID.

バージョン 2.0 で追加.

パラメータ

id (int) -- The application ID.

戻り値

The application command or None if not found.

戻り値の型

Optional[ApplicationCommand]

await get_application_context(interaction, cls=None)

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.

パラメータ
  • interaction (discord.Interaction) -- The interaction to get the invocation context from.

  • cls -- 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.

戻り値

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

戻り値の型

ApplicationContext

await on_application_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.

await on_interaction(interaction)

This function is a coroutine.

This event handle should handle all interaction coming from Discord. This would pass the information into process_application_commands()

If you're overriding this, please dont forget to call the process_application_commands() or the application wont work.

パラメータ

interaction (discord.Interaction) -- The interaction to process

await process_application_commands(interaction)

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 ApplicationCommandMixin.application_command() and runs ApplicationCommand.invoke() on it. If no matching command was found, it replies to the interaction with a default message.

バージョン 2.0 で追加.

パラメータ

interaction (discord.Interaction) -- The interaction to process

register_application(command, *, force=False)

Register the command to the factories and remove from pending section. Please make sure the app already been registered to Discord.

パラメータ
  • command (ApplicationCommand) -- The command to register.

  • force (bool) -- If True, the command will be registered even if it's not registered to Discord.

remove_application(command)

Remove command from the list of registered commands.

パラメータ

command (ApplicationCommand) -- The command to register.

get_guild_applications(guild_id)

A list of application that are registered for a guild.

バージョン 2.0 で追加.

パラメータ

guild_id (int) -- The guild ID.

戻り値

List of registered applications for a guild.

戻り値の型

List[ApplicationCommand]

get_guild_application(id, app_id)

A list of application that are registered for a guild.

バージョン 2.0 で追加.

パラメータ
  • id (int) -- The guild ID.

  • app_id (int) -- The application ID.

戻り値

The application command or None if not found.

戻り値の型

Optional[ApplicationCommand]

await fetch_global_applications()

This function is a coroutine.

Get all registered global commands on Discord.

バージョン 2.0 で追加.

注釈

This method is an API call. For general usage use get_applications().

例外

HTTPException -- Retrieving the global application commands failed.

戻り値

The collection of global command that registred on Discord.

戻り値の型

List[Union[ApplicationCommand, RawApplicationCommand]]

await fetch_guild_applications(guild_id)

This function is a coroutine.

Get all registered guild commands on Discord.

バージョン 2.0 で追加.

注釈

This method is an API call. For general usage use get_guild_applications().

パラメータ

guild_id (int) -- The guild ID to be fetched.

例外

HTTPException -- Retrieving the guild application commands failed.

戻り値

The collection of guild command that registred on Discord.

戻り値の型

List[Union[ApplicationCommand, RawApplicationCommand]]

await is_owner(user)

This function is a coroutine.

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

パラメータ

user (abc.User) -- The user to check for.

戻り値

Whether the user is the owner.

戻り値の型

bool

AutoShardedClient

class discord.AutoShardedClient(*args, **kwargs)

このクライアントは Client に似ていますが、管理しやすく、かつ透過的なシングルプロセスのBotに分割するという複雑な処理を行います。

このクライアントは、実装に関して内部的に複数のシャードに分割されていても、単一のシャードの通常の Client のように使用することができます。これにより、IPCやその他の複雑なインフラストラクチャへの対処を行う必要がなくなります。

少なくとも1000を超えるギルドで使用される場合にのみ、このクライアントを使用することをおすすめします。

shard_count が指定されていない場合、ライブラリはBot Gatewayのエンドポイント呼び出しを使用して使用するシャードの数を見つけ出します。

shard_ids パラメータが指定されている場合、それらのシャードIDが内部シャードの起動時に使用されます。これを使用する場合 shard_count の指定が必須です。このパラメータを省略した場合は、クライアントは0から shard_count - 1 までのシャードを起動します。

shard_ids

An optional list of shard_ids to launch the shards with.

Type

Optional[List[int]]

property latency: float

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

これは Client.latency() と同様に機能しますが、すべてのシャードの平均待ち時間を使用する点が異なります。シャードの待ち時間のリストを取得するには latencies プロパティを参照してください。準備ができていない場合は nan を返します。

Type

float

property latencies: List[Tuple[int, float]]

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

これは、 (shard_id, latency) の要素を持つタプルのリストを返します。

Type

List[Tuple[int, float]]

get_shard(shard_id)

Optional[ShardInfo]: Gets the shard information at a given shard ID or None if not found.

property shards: Dict[int, discord.shard.ShardInfo]

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

Type

Mapping[int, ShardInfo]

await connect(*, reconnect=True)

This function is a coroutine.

WebSocket接続を作成し、Discordからのメッセージをリッスンできるようにします。これはイベントシステム全体とライブラリの様々な機能を実行するループです。WebSocket接続が終了するまで、制御は再開されません。

パラメータ

reconnect (bool) -- インターネットの障害やDiscord側の特定の障害が発生した際に再接続を試みるかどうかを表します。不正な状態へつながることによる特定の切断(無効なシャーディングペイロードや不正なトークンなど)は処理されません。

例外
  • GatewayNotFound -- If 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.

await close()

This function is a coroutine.

Discordとの接続を閉じます。

await on_shard_connect(shard_id)

This function is a coroutine.

Initialize application registration to first shard.

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

This function is a coroutine.

クライアントのプレゼンスを変更します。

例:

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

バージョン 2.0 で変更: Removed the afk keyword-only parameter.

パラメータ
  • activity (Optional[BaseActivity]) -- 実行中のアクティビティ。何も実行していない場合は None です。

  • status (Optional[Status]) -- 変更するステータスを示します。 None の場合、 Status.online となります。

  • shard_id (Optional[int]) -- プレゼンスを変更したいシャードのshard_id。指定されていない、または None が渡された場合はBotがアクセスできるすべてのシャードのプレゼンスが変更されます。

例外

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

is_ws_ratelimited()

bool: 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().

バージョン 1.6 で追加.

Application Info

AppInfo

class discord.AppInfo

Discordが提供するBotのアプリケーション情報を表します。

id

The application ID.

Type

int

name

The application name.

Type

str

owner

The application owner.

Type

User

team

The application's team.

バージョン 1.3 で追加.

Type

Optional[Team]

description

The application description.

Type

str

bot_public

Whether the bot can be invited by anyone or if it is locked to the application owner.

Type

bool

bot_require_code_grant

Whether the bot requires the completion of the full oauth2 code grant flow to join.

Type

bool

rpc_origins

A list of RPC origin URLs, if RPC is enabled.

Type

Optional[List[str]]

summary

If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU.

バージョン 1.3 で追加.

Type

str

verify_key

The hex encoded key for verification in interactions and the GameSDK's GetTicket.

バージョン 1.3 で追加.

Type

str

guild_id

If this application is a game sold on Discord, this field will be the guild to which it has been linked to.

バージョン 1.3 で追加.

Type

Optional[int]

primary_sku_id

If this application is a game sold on Discord, this field will be the id of the "Game SKU" that is created, if it exists.

バージョン 1.3 で追加.

Type

Optional[int]

slug

If this application is a game sold on Discord, this field will be the URL slug that links to the store page.

バージョン 1.3 で追加.

Type

Optional[str]

terms_of_service_url

The application's terms of service URL, if set.

バージョン 2.0 で追加.

Type

Optional[str]

privacy_policy_url

The application's privacy policy URL, if set.

バージョン 2.0 で追加.

Type

Optional[str]

property icon: Optional[discord.asset.Asset]

Retrieves the application's icon asset, if any.

Type

Optional[Asset]

property cover_image: Optional[discord.asset.Asset]

Retrieves the cover image on a store embed, if any.

This is only available if the application is a game sold on Discord.

Type

Optional[Asset]

property guild: Optional[Guild]

If this application is a game sold on Discord, this field will be the guild to which it has been linked

バージョン 1.3 で追加.

Type

Optional[Guild]

PartialAppInfo

class discord.PartialAppInfo

Represents a partial AppInfo given by create_invite()

バージョン 2.0 で追加.

id

The application ID.

Type

int

name

The application name.

Type

str

description

The application description.

Type

str

rpc_origins

A list of RPC origin URLs, if RPC is enabled.

Type

Optional[List[str]]

summary

If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU.

Type

str

verify_key

The hex encoded key for verification in interactions and the GameSDK's GetTicket.

Type

str

terms_of_service_url

The application's terms of service URL, if set.

Type

Optional[str]

privacy_policy_url

The application's privacy policy URL, if set.

Type

Optional[str]

property icon: Optional[discord.asset.Asset]

Retrieves the application's icon asset, if any.

Type

Optional[Asset]

Team

class discord.Team

Represents an application team for a bot provided by Discord.

id

The team ID.

Type

int

name

The team name

Type

str

owner_id

The team's owner ID.

Type

int

members

A list of the members in the team

バージョン 1.3 で追加.

Type

List[TeamMember]

property icon: Optional[discord.asset.Asset]

Retrieves the team's icon asset, if any.

Type

Optional[Asset]

property owner: Optional[discord.team.TeamMember]

The team's owner.

Type

Optional[TeamMember]

TeamMember

class discord.TeamMember

Represents a team member in a team.

x == y

Checks if two team members are equal.

x != y

Checks if two team members are not equal.

hash(x)

Return the team member's hash.

str(x)

Returns the team member's name with discriminator.

バージョン 1.3 で追加.

name

The team member's username.

Type

str

id

The team member's unique ID.

Type

int

discriminator

The team member's discriminator. This is given when the username has conflicts.

Type

str

avatar

The avatar hash the team member has. Could be None.

Type

Optional[str]

bot

Specifies if the user is a bot account.

Type

bool

team

The team that the member is from.

Type

Team

membership_state

The membership state of the member (e.g. invited or accepted)

Type

TeamMembershipState

イベントリファレンス

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

イベントを登録する方法は二通りあります。一つ目は Client.event() を使用する方法です。二つ目は Client を継承してサブクラスを作り、イベントをオーバーライドする方法です。この方法を用いた場合は以下のようになります:

import discord

class MyClient(discord.Client):
    async def on_message(self, message):
        if message.author == self.user:
            return

        if message.content.startswith('$hello'):
            await message.channel.send('Hello World!')

イベントハンドラが例外を発生させると、それを処理するために on_error() が呼び出されます。 デフォルトではトレースバックが出力され、例外は無視されます。

警告

すべてのイベントは coroutine である必要があります。 coroutine でない場合、予期せぬエラーが発生する可能性があります。関数をコルーチンにするには、関数定義の際に async def を使用してください。

discord.on_connect()

クライアントがDiscordに正常に接続できたときに呼び出されます。クライアントの準備が完了していることと同義ではありません。 on_ready() を参照してください。

on_ready() での警告も適用されます。

discord.on_shard_connect(shard_id)

Similar to on_connect() except used by AutoShardedClient to denote when a particular shard ID has connected to Discord.

バージョン 1.4 で追加.

パラメータ

shard_id (int) -- The shard ID that has connected.

discord.on_disconnect()

Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.

This function can be called many times without a corresponding on_connect() call.

discord.on_shard_disconnect(shard_id)

Similar to on_disconnect() except used by AutoShardedClient to denote when a particular shard ID has disconnected from Discord.

バージョン 1.4 で追加.

パラメータ

shard_id (int) -- The shard ID that has disconnected.

discord.on_ready()

クライアントがDiscordから受信したデータの準備を完了した際に呼び出されます。通常はログインが成功したあと、 Client.guilds とそれに関連するものの準備が完了したときです。

警告

このイベントは、最初に呼び出されるイベントとは限りません。同時に、このイベントは 一度だけ呼ばれるという保証もできません 。このライブラリは、再接続ロジックを実装しているためリジューム要求が失敗するたびにこのイベントが呼び出されることになります。

discord.on_shard_ready(shard_id)

特定の Shard IDが準備完了になったかを確認するために AutoShardedClient で使用される以外は on_ready() とほとんど同じです。

パラメータ

shard_id (int) -- 準備が完了したShard ID。

discord.on_resumed()

クライアントがセッションを再開したときに呼び出されます。

discord.on_shard_resumed(shard_id)

Similar to on_resumed() except used by AutoShardedClient to denote when a particular shard ID has resumed a session.

バージョン 1.4 で追加.

パラメータ

shard_id (int) -- The shard ID that has resumed.

discord.on_error(event, *args, **kwargs)

イベントがキャッチされない例外を発生させた場合、通常はトレースバックがstderrに出力され、その例外は無視されます。何らかの理由でこの動作を変更して、自分自身で例外処理を行いたい場合は、このイベントをオーバーライドすることができます。これを行った場合、トレースバックを出力するというデフォルトの動作は行われません。

発生した例外の情報と、例外事態は sys.exc_info() への標準呼び出しで取得できます。

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

注釈

on_error will only be dispatched to Client.event().

It will not be received by Client.wait_for(), or, if used, Bots listeners such as listen() or listener().

パラメータ
  • event (str) -- 例外を発生させたイベントの名前。

  • args -- 例外を発生させたイベントの位置引数。

  • kwargs -- 例外を発生させたイベントのキーワード引数。

discord.on_socket_event_type(event_type)

Called whenever a websocket event is received from the WebSocket.

This is mainly useful for logging how many events you are receiving from the Discord gateway.

バージョン 2.0 で追加.

パラメータ

event_type (str) -- The event type from Discord that is received, e.g. 'READY'.

discord.on_socket_raw_receive(msg)

Called whenever a message is completely received from the WebSocket, before it's processed and parsed. This event is always dispatched when a complete message is received and the passed data is not parsed in any way.

これはWebSocketストリームを取得してデバッグする時のみに役に立ちます。

This requires setting the enable_debug_events setting in the Client.

注釈

これは、クライアントWebSocketから受信したメッセージ専用です。音声WebSocketではこのイベントは実行されません。

パラメータ

msg (str) -- The message passed in from the WebSocket library.

discord.on_socket_raw_send(payload)

メッセージが送信される前にWebSocketで送信操作が行われるたびに呼び出されます。渡されるパラメータはWebSocketに送信されているメッセージです。

これはWebSocketストリームを取得してデバッグする時のみに役に立ちます。

This requires setting the enable_debug_events setting in the Client.

注釈

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

パラメータ

payload -- WebSocketライブラリから渡されるメッセージ。バイナリメッセージの場合は bytes 、通常のメッセージの場合は str です。

discord.on_typing(channel, user, when)

誰かがメッセージを入力し始めたときに呼び出されます。

channelパラメータは abc.Messageable インスタンスにすることができます。 TextChannelGroupChannel 、または DMChannel のいずれかです。

channelTextChannel である場合、 user パラメータは Member 、それ以外の場合は User です。

This requires Intents.typing to be enabled.

パラメータ
  • channel (abc.Messageable) -- 入力が行われたチャンネル。

  • user (Union[User, Member]) -- 入力を始めたユーザー。

  • when (datetime.datetime) -- When the typing started as an aware datetime in UTC.

discord.on_message(message)

Message が作成され送信されたときに呼び出されます。

This requires Intents.messages to be enabled.

警告

Botのメッセージとプライベートメッセージはこのイベントを通して送信されます。Botのプログラムによっては「再帰呼び出し」を続けることになります。Botが自分自身に返信しないようにするためにはユーザーIDを確認する方法が考えられます。この問題はBotが抱えるものではありません。

パラメータ

message (Message) -- 現在のメッセージ。

discord.on_message_delete(message)

メッセージが削除された際に呼び出されます。メッセージが内部のメッセージキャッシュに見つからない場合、このイベントは呼び出されません。これはメッセージが古すぎるか、クライアントが通信の多いギルドに参加している場合に発生します。

If this occurs increase the max_messages parameter or use the on_raw_message_delete() event instead.

This requires Intents.messages to be enabled.

パラメータ

message (Message) -- 削除されたメッセージ。

discord.on_bulk_message_delete(messages)

メッセージが一括削除されたときに呼び出されます。メッセージが内部のメッセージキャッシュに見つからない場合、このイベントは呼び出されません。個々のメッセージが見つからない場合でも、このイベントは呼び出されますが、見つからなかったメッセージはメッセージのリストに含まれません。これはメッセージが古すぎるか、クライアントが通信の多いギルドに参加している場合に発生します。

If this occurs increase the max_messages parameter or use the on_raw_bulk_message_delete() event instead.

This requires Intents.messages to be enabled.

パラメータ

messages (List[Message]) -- 削除されたメッセージのリスト。

discord.on_raw_message_delete(payload)

メッセージが削除されたときに呼び出されます。 on_message_delete() とは異なり、削除されたメッセージが内部キャッシュに存在するか否かにかかわらず呼び出されます。

メッセージがメッセージキャッシュ内に見つかった場合、 RawMessageDeleteEvent.cached_message を介してアクセスすることができます。

This requires Intents.messages to be enabled.

パラメータ

payload (RawMessageDeleteEvent) -- 生のイベントペイロードデータ。

discord.on_raw_bulk_message_delete(payload)

メッセージが一括削除されたときに呼び出されます。 on_bulk_message_delete() とは異なり、削除されたメッセージが内部キャッシュに存在するか否かにかかわらず呼び出されます。

メッセージがメッセージキャッシュ内に見つかった場合、 RawBulkMessageDeleteEvent.cached_messages を介してアクセスすることができます。

This requires Intents.messages to be enabled.

パラメータ

payload (RawBulkMessageDeleteEvent) -- 生のイベントペイロードデータ。

discord.on_message_edit(before, after)

Message が更新イベントを受け取ったときに呼び出されます。メッセージが内部のメッセージキャッシュに見つからない場合、このイベントは呼び出されません。これはメッセージが古すぎるか、クライアントが通信の多いギルドに参加している場合に発生します。

If this occurs increase the max_messages parameter or use the on_raw_message_edit() event instead.

以下の非網羅的ケースがこのイベントを発生させます:

  • メッセージをピン留め、または解除した。

  • メッセージの内容を変更した。

  • メッセージが埋め込みを受け取った。

    • パフォーマンス上の理由から、埋め込みのサーバーはこれを「一貫した」方法では行いません。

  • The message's embeds were suppressed or unsuppressed.

  • 通話呼び出しメッセージの参加者や終了時刻が変わった。

This requires Intents.messages to be enabled.

パラメータ
  • before (Message) -- 更新前のメッセージ。

  • after (Message) -- 更新後のメッセージ。

discord.on_raw_message_edit(payload)

メッセージが編集されたときに呼び出されます。 on_message_edit() とは異なり、これは内部のメッセージキャッシュの状態に関係なく呼び出されます。

If the message is found in the message cache, it can be accessed via RawMessageUpdateEvent.cached_message. The cached message represents the message before it has been edited. For example, if the content of a message is modified and triggers the on_raw_message_edit() coroutine, the RawMessageUpdateEvent.cached_message will return a Message object that represents the message before the content was modified.

Due to the inherently raw nature of this event, the data parameter coincides with the raw data given by the gateway.

データのペイロードが部分的であるため、データにアクセスするときは気をつけてください。部分的なデータの主な場合のひとつは、``'content'``にアクセスできない場合です。Discordの埋め込みサーバーによって、埋め込みが更新される、"埋め込み"しか変わっていない編集がそうです。

This requires Intents.messages to be enabled.

パラメータ

payload (RawMessageUpdateEvent) -- 生のイベントペイロードデータ。

discord.on_reaction_add(reaction, user)

Called when a message has a reaction added to it. Similar to on_message_edit(), if the message is not found in the internal message cache, then this event will not be called. Consider using on_raw_reaction_add() instead.

注釈

リアクションの付いた:class:`Message`を取得するには、:attr:`Reaction.message`を使ってください。

This requires Intents.reactions to be enabled.

注釈

This doesn't require Intents.members within a guild context, but due to Discord not providing updated user information in a direct message it's required for direct messages to receive this event. Consider using on_raw_reaction_add() if you need this and do not otherwise want to enable the members intent.

パラメータ
  • reaction (Reaction) -- リアクションの現在の状態。

  • user (Union[Member, User]) -- リアクションを追加したユーザー。

discord.on_raw_reaction_add(payload)

メッセージにリアクションが追加されたときに呼び出されます。 on_reaction_add() とは異なり、これは内部のメッセージキャッシュの状態に関係なく呼び出されます。

This requires Intents.reactions to be enabled.

パラメータ

payload (RawReactionActionEvent) -- 生のイベントペイロードデータ。

discord.on_reaction_remove(reaction, user)

メッセージのリアクションが取り除かれたときに呼び出されます。on_message_editのように、内部のメッセージキャッシュにメッセージがないときには、このイベントは呼び出されません。

注釈

リアクションの付いたメッセージを取得するには、:attr:`Reaction.message`を使ってください。

This requires both Intents.reactions and Intents.members to be enabled.

注釈

Consider using on_raw_reaction_remove() if you need this and do not want to enable the members intent.

パラメータ
  • reaction (Reaction) -- リアクションの現在の状態。

  • user (Union[Member, User]) -- リアクションを追加したユーザー。

discord.on_raw_reaction_remove(payload)

メッセージからリアクションが削除されたときに呼び出されます。 on_reaction_remove() とは異なり、これは内部メッセージキャッシュの状態に関係なく呼び出されます。

This requires Intents.reactions to be enabled.

パラメータ

payload (RawReactionActionEvent) -- 生のイベントペイロードデータ。

discord.on_reaction_clear(message, reactions)

Called when a message has all its reactions removed from it. Similar to on_message_edit(), if the message is not found in the internal message cache, then this event will not be called. Consider using on_raw_reaction_clear() instead.

This requires Intents.reactions to be enabled.

パラメータ
  • message (Message) -- リアクションが削除されたメッセージ。

  • reactions (List[Reaction]) -- 除去されたリアクション。

discord.on_raw_reaction_clear(payload)

メッセージからリアクションがすべて削除されたときに呼び出されます。 on_reaction_clear() とは異なり、これは内部メッセージキャッシュの状態に関係なく呼び出されます。

This requires Intents.reactions to be enabled.

パラメータ

payload (RawReactionClearEvent) -- 生のイベントペイロードデータ。

discord.on_reaction_clear_emoji(reaction)

Called when a message has a specific reaction removed from it. Similar to on_message_edit(), if the message is not found in the internal message cache, then this event will not be called. Consider using on_raw_reaction_clear_emoji() instead.

This requires Intents.reactions to be enabled.

バージョン 1.3 で追加.

パラメータ

reaction (Reaction) -- The reaction that got cleared.

discord.on_raw_reaction_clear_emoji(payload)

Called when a message has a specific reaction removed from it. Unlike on_reaction_clear_emoji() this is called regardless of the state of the internal message cache.

This requires Intents.reactions to be enabled.

バージョン 1.3 で追加.

パラメータ

payload (RawReactionClearEmojiEvent) -- 生のイベントペイロードデータ。

discord.on_interaction(interaction)

Called when an interaction happened.

This currently happens due to slash command invocations or components being used.

警告

This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the View instead as it provides a nicer user experience.

バージョン 2.0 で追加.

パラメータ

interaction (Interaction) -- The interaction data.

discord.on_application_registered()

Called after the bot has registered every application commands with Discord.

バージョン 2.0 で追加.

discord.on_private_channel_update(before, after)

プライベートグループDMが更新されたとき呼び出されます。 例: 名前やトピックの変更。

This requires Intents.messages to be enabled.

パラメータ
  • before (GroupChannel) -- 更新されたグループチャンネルの更新前情報。

  • after (GroupChannel) -- 更新されたグループチャンネルの更新後情報。

discord.on_private_channel_pins_update(channel, last_pin)

プライベートチャンネルのメッセージがピン留めされたりはずされたりしたときに呼ばれます。

パラメータ
  • channel (abc.PrivateChannel) -- ピン留めが更新されたプライベートチャンネル。

  • last_pin (Optional[datetime.datetime]) -- The latest message that was pinned as an aware datetime in UTC. Could be None.

discord.on_guild_channel_delete(channel)
discord.on_guild_channel_create(channel)

ギルドのチャンネルが削除・作成されたとき呼び出されます。

ギルドは guild で取得できます。

This requires Intents.guilds to be enabled.

パラメータ

channel (abc.GuildChannel) -- 作成、または削除されたギルドチャンネル。

discord.on_guild_channel_update(before, after)

ギルドチャンネルが更新されるたびに呼び出されます。例えば名前、トピック、権限の変更などです。

This requires Intents.guilds to be enabled.

パラメータ
discord.on_guild_channel_pins_update(channel, last_pin)

ギルドチャンネルのメッセージがピン留めされたり、解除されたりしたときに呼び出されます。

This requires Intents.guilds to be enabled.

パラメータ
  • channel (Union[abc.GuildChannel, Thread]) -- ピン留めが更新されたギルドチャンネル。

  • last_pin (Optional[datetime.datetime]) -- The latest message that was pinned as an aware datetime in UTC. Could be None.

discord.on_guild_scheduled_event_create(event)

Called whenever a scheduled event is created from a guild.

This requires Intents.guild_scheduled_events to be enabled.

バージョン 2.0 で追加.

パラメータ

event (GuildScheduledEvent) -- The scheduled event that got created.

discord.on_guild_scheduled_event_remove(event)

Called whenever a scheduled event is removed from a guild.

This requires Intents.guild_scheduled_events to be enabled.

バージョン 2.0 で追加.

パラメータ

event (GuildScheduledEvent) -- The scheduled event that got removed.

discord.on_guild_scheduled_event_update(before, after)

Called whenever a scheduled event is updated from a guild.

This requires Intents.guild_scheduled_events to be enabled.

バージョン 2.0 で追加.

パラメータ
discord.on_guild_scheduled_event_member_join(event, member)
discord.on_guild_scheduled_event_member_remove(event, member)

Called whenever a Member or an User leaves or joins a GuildScheduledEvent

You can later access the member via GuildScheduledEvent.get_member() or GuildScheduledEvent.members.

This requires Intents.guild_scheduled_events to be enabled.

バージョン 2.0 で追加.

パラメータ
discord.on_thread_join(thread)

Called whenever a thread is joined or created. Note that from the API's perspective there is no way to differentiate between a thread being created or the bot joining a thread.

Note that you can get the guild from Thread.guild.

This requires Intents.guilds to be enabled.

バージョン 2.0 で追加.

パラメータ

thread (Thread) -- The thread that got joined.

discord.on_thread_remove(thread)

Called whenever a thread is removed. This is different from a thread being deleted.

Note that you can get the guild from Thread.guild.

This requires Intents.guilds to be enabled.

警告

Due to technical limitations, this event might not be called as soon as one expects. Since the library tracks thread membership locally, the API only sends updated thread membership status upon being synced by joining a thread.

バージョン 2.0 で追加.

パラメータ

thread (Thread) -- The thread that got removed.

discord.on_thread_delete(thread)

Called whenever a thread is deleted.

Note that you can get the guild from Thread.guild.

This requires Intents.guilds to be enabled.

バージョン 2.0 で追加.

パラメータ

thread (Thread) -- The thread that got deleted.

discord.on_thread_member_join(member)
discord.on_thread_member_remove(member)

Called when a ThreadMember leaves or joins a Thread.

You can get the thread a member belongs in by accessing ThreadMember.thread.

This requires Intents.members to be enabled.

バージョン 2.0 で追加.

パラメータ

member (ThreadMember) -- 参加、または脱退したメンバー。

discord.on_thread_update(before, after)

Called whenever a thread is updated.

This requires Intents.guilds to be enabled.

バージョン 2.0 で追加.

パラメータ
  • before (Thread) -- The updated thread's old info.

  • after (Thread) -- The updated thread's new info.

discord.on_guild_integrations_update(guild)

ギルドの連携サービスが作成、更新、削除されるたびに呼び出されます。

This requires Intents.integrations to be enabled.

バージョン 1.4 で追加.

パラメータ

guild (Guild) -- 連携サービスが更新されたギルド。

discord.on_integration_create(integration)

Called when an integration is created.

This requires Intents.integrations to be enabled.

バージョン 2.0 で追加.

パラメータ

integration (Integration) -- The integration that was created.

discord.on_integration_update(integration)

Called when an integration is updated.

This requires Intents.integrations to be enabled.

バージョン 2.0 で追加.

パラメータ

integration (Integration) -- The integration that was created.

discord.on_raw_integration_delete(payload)

Called when an integration is deleted.

This requires Intents.integrations to be enabled.

バージョン 2.0 で追加.

パラメータ

payload (RawIntegrationDeleteEvent) -- 生のイベントペイロードデータ。

discord.on_raw_thread_delete(payload)

Called whenever a thread is deleted. Unlike on_thread_delete() this is called regardless of the thread being in the internal thread cache or not.

This requires Intents.guilds to be enabled.

バージョン 2.0 で追加.

パラメータ

payload (RawThreadDeleteEvent) -- 生のイベントペイロードデータ。

discord.on_webhooks_update(channel)

ギルドチャンネルのWebhookが作成、更新、削除されたときに呼び出されます。

This requires Intents.webhooks to be enabled.

パラメータ

channel (abc.GuildChannel) -- Webhookが更新されたチャンネル。

discord.on_member_join(member)
discord.on_member_remove(member)

MemberGuild に参加したり退出したりしたときに呼び出されます。

This requires Intents.members to be enabled.

パラメータ

member (Member) -- 参加、または脱退したメンバー。

discord.on_member_update(before, after)

Member がプロフィールを編集したとき呼び出されます。

これらのうちひとつ以上が変更されたとき呼び出されます:

  • ニックネーム

  • roles

  • pending

This requires Intents.members to be enabled.

パラメータ
  • before (Member) -- 更新されたメンバーの更新前情報。

  • after (Member) -- 更新されたメンバーの更新後情報。

discord.on_presence_update(before, after)

Called when a Member updates their presence.

これらのうちひとつ以上が変更されたとき呼び出されます:

  • ステータス

  • activity

This requires Intents.presences and Intents.members to be enabled.

バージョン 2.0 で追加.

パラメータ
  • before (Member) -- 更新されたメンバーの更新前情報。

  • after (Member) -- 更新されたメンバーの更新後情報。

discord.on_user_update(before, after)

User がプロフィールを編集したとき呼び出されます。

これらのうちひとつ以上が変更されたとき呼び出されます:

  • アバター

  • ユーザー名

  • 識別子

This requires Intents.members to be enabled.

パラメータ
  • before (User) -- 更新されたユーザーの更新前情報。

  • after (User) -- 更新されたユーザーの更新後情報。

discord.on_guild_join(guild)

Client によって Guild が作成された。または Client がギルドに参加したときに呼び出されます。

This requires Intents.guilds to be enabled.

パラメータ

guild (Guild) -- 参加したギルド。

discord.on_guild_remove(guild)

ClientGuild から削除されたときに呼び出されます。

これは以下の状況時に呼び出されますが、これに限ったものではありません:

  • クライアントがBANされた。

  • クライアントがキックされた。

  • クライアントがギルドから退出した。

  • クライアント、またはギルドオーナーがギルドを削除した。

このイベントが呼び出されるためには、 Client がギルドに参加している必要があります。(つまり、 Client.guilds にギルドが存在しなければならない)

This requires Intents.guilds to be enabled.

パラメータ

guild (Guild) -- 削除されたギルド。

discord.on_guild_update(before, after)

Guild が更新されたときに呼び出されます。例えば:

  • 名前が変更された

  • AFKチャンネルが変更された

  • AFKのタイムアウト時間が変更された

  • その他

This requires Intents.guilds to be enabled.

パラメータ
  • before (Guild) -- 更新される前のギルド。

  • after (Guild) -- 更新された後のギルド。

discord.on_guild_role_create(role)
discord.on_guild_role_delete(role)

GuildRole が新しく作成されたか、削除されたときに呼び出されます。

ギルドを取得するには Role.guild を使用してください。

This requires Intents.guilds to be enabled.

パラメータ

role (Role) -- 作成、または削除された役職。

discord.on_guild_role_update(before, after)

Role がギルド全体で変更されたときに呼び出されます。

This requires Intents.guilds to be enabled.

パラメータ
  • before (Role) -- 更新された役職の更新前情報。

  • after (Role) -- 更新された役職の更新後情報。

discord.on_guild_emojis_update(guild, before, after)

GuildEmoji が追加、または削除されたときに呼び出されます。

This requires Intents.emojis_and_stickers to be enabled.

パラメータ
  • guild (Guild) -- 絵文字が更新されたギルド。

  • before (Sequence[Emoji]) -- 更新前の絵文字のリスト。

  • after (Sequence[Emoji]) -- 更新後の絵文字のリスト。

discord.on_guild_stickers_update(guild, before, after)

Called when a Guild updates its stickers.

This requires Intents.emojis_and_stickers to be enabled.

バージョン 2.0 で追加.

パラメータ
  • guild (Guild) -- The guild who got their stickers updated.

  • before (Sequence[GuildSticker]) -- A list of stickers before the update.

  • after (Sequence[GuildSticker]) -- A list of stickers after the update.

discord.on_guild_available(guild)
discord.on_guild_unavailable(guild)

ギルドが利用可能・不可能になったときに呼び出されます。ギルドは Client.guilds キャッシュに存在していないといけません。

This requires Intents.guilds to be enabled.

パラメータ

guild -- 利用状況が変わった:class:Guild

discord.on_voice_state_update(member, before, after)

MemberVoiceState を変更したとき呼び出されます。

これらの場合に限りませんが、例を挙げると、以下の場合に呼び出されます:

  • A member joins a voice or stage channel.

  • A member leaves a voice or stage channel.

  • メンバーが自身でマイクやスピーカーをミュートしたとき。

  • メンバーがギルドの管理者によってマイクやスピーカーをミュートされたとき。

This requires Intents.voice_states to be enabled.

パラメータ
  • member (Member) -- ボイスの状態が変わった Member

  • before (VoiceState) -- 更新前のボイス状態。

  • after (VoiceState) -- The voice state after the changes.

discord.on_stage_instance_create(stage_instance)
discord.on_stage_instance_delete(stage_instance)

Called when a StageInstance is created or deleted for a StageChannel.

バージョン 2.0 で追加.

パラメータ

stage_instance (StageInstance) -- The stage instance that was created or deleted.

discord.on_stage_instance_update(before, after)

Called when a StageInstance is updated.

これらの場合に限りませんが、例を挙げると、以下の場合に呼び出されます:

  • The topic is changed.

  • The privacy level is changed.

バージョン 2.0 で追加.

パラメータ
discord.on_member_ban(guild, user)

ユーザーが Guild からBANされたとき呼び出されます。

This requires Intents.bans to be enabled.

パラメータ
  • guild (Guild) -- ユーザーがBANされたギルド。

  • user (Union[User, Member]) -- BANされたユーザー。BAN時にユーザーがギルドにいたかによって、 UserMember になります。

discord.on_member_unban(guild, user)

UserGuild のBANを解除されたとき呼び出されます。

This requires Intents.bans to be enabled.

パラメータ
  • guild (Guild) -- ユーザーのBANが解除されたギルド。

  • user (User) -- Banが解除されたユーザー。

discord.on_invite_create(invite)

Called when an Invite is created. You must have the manage_channels permission to receive this.

バージョン 1.3 で追加.

注釈

There is a rare possibility that the Invite.guild and Invite.channel attributes will be of Object rather than the respective models.

This requires Intents.invites to be enabled.

パラメータ

invite (Invite) -- The invite that was created.

discord.on_invite_delete(invite)

Called when an Invite is deleted. You must have the manage_channels permission to receive this.

バージョン 1.3 で追加.

注釈

There is a rare possibility that the Invite.guild and Invite.channel attributes will be of Object rather than the respective models.

Outside of those two attributes, the only other attribute guaranteed to be filled by the Discord gateway for this event is Invite.code.

This requires Intents.invites to be enabled.

パラメータ

invite (Invite) -- The invite that was deleted.

discord.on_group_join(channel, user)
discord.on_group_remove(channel, user)

誰かが GroupChannel に参加、または脱退したときに呼び出されます。

パラメータ
  • channel (GroupChannel) -- ユーザーが参加または脱退したグループ。

  • user (User) -- 参加または脱退したユーザー。

ユーティリティ関数

discord.utils.find(predicate, seq)

与えられた関数を満たす最初の要素を返すヘルパー。例:

member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)

は、名前が'Mighty'である最初に見つかった Member を返します。見つからない場合は None を返します。

これは、適切な値を見つけると止まる点で、 filter() と異なります。

パラメータ
discord.utils.get(iterable, **attrs)

attrs に渡されたすべての条件を満たす最初の要素を返すヘルパー。 find() の代替案です。

複数の条件が指定されている場合、またはではなくかつでチェックされます。つまり、どれかではなく、すべての条件を満たさないといけません。

ネストされている属性で検索するとき (例: x.y で検索) は、キーワード引数に x__y を渡してください。

与えられた属性にマッチする項目がない場合、 None を返します。

サンプル

基本的な使用法:

member = discord.utils.get(message.guild.members, name='Foo')

複数の属性のマッチ:

channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)

ネストされた属性のマッチ:

channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
パラメータ
  • iterable -- 検索するイテラブル。

  • **attrs -- 検索用の属性を表すキーワード引数。

discord.utils.snowflake_time(id)
パラメータ

id (int) -- The snowflake ID.

戻り値

An aware datetime in UTC representing the creation time of the snowflake.

戻り値の型

datetime.datetime

discord.utils.oauth_url(client_id, *, permissions=..., guild=..., redirect_uri=..., scopes=..., disable_guild_select=False)

ボットをギルドに招待するOAuth2 URLを返すヘルパー関数。

パラメータ
  • client_id (Union[int, str]) -- ボットのクライアントID。

  • permissions (Permissions) -- 要求する権限。もし与えられていない場合、権限を要求しません。

  • guild (Snowflake) -- 利用できる場合は、認証画面であらかじめ選択されるギルド。

  • redirect_uri (str) -- 任意の有効なリダイレクトURI。

  • scopes (Iterable[str]) --

    An optional valid list of scopes. Defaults to ('bot',).

    バージョン 1.7 で追加.

  • disable_guild_select (bool) --

    Whether to disallow the user from changing the guild dropdown.

    バージョン 2.0 で追加.

戻り値

The OAuth2 URL for inviting the bot into guilds.

戻り値の型

str

discord.utils.remove_markdown(text, *, ignore_links=True)

A helper function that removes markdown characters.

バージョン 1.7 で追加.

注釈

This function is not markdown aware and may remove meaning from the original text. For example, if the input contains 10 * 5 then it will be converted into 10  5.

パラメータ
  • text (str) -- The text to remove markdown from.

  • ignore_links (bool) -- Whether to leave links alone when removing markdown. For example, if a URL in the text contains characters such as _ then it will be left alone. Defaults to True.

戻り値

The text with the markdown special characters removed.

戻り値の型

str

discord.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)

Discordのマークダウンをエスケープするヘルパー関数。

パラメータ
  • text (str) -- マークダウンをエスケープするテキスト。

  • as_needed (bool) -- 必要に応じてマークダウンをエスケープするかどうか。必要でなければ無関係な文字をエスケープしません。 **hello**\*\*hello\*\* ではなく \*\*hello** にエスケープされます。ただし、これによって巧妙な構文の乱用が発生する可能性があります。デフォルトは False です。

  • ignore_links (bool) -- マークダウンをエスケープするときにリンクを残すかどうか。たとえば、テキスト中のURLが _ のような文字を含む場合、これは残されます。これは as_needed と併用できません。デフォルトは True です。

戻り値

マークダウンの特殊文字をスラッシュでエスケープしたテキスト。

戻り値の型

str

discord.utils.escape_mentions(text)

everyone、here、役職とユーザーのメンションをエスケープするヘルパー関数。

注釈

チャンネルのメンションはエスケープしません。

注釈

For more granular control over what mentions should be escaped within messages, refer to the AllowedMentions class.

パラメータ

text (str) -- メンションをエスケープするテキスト。

戻り値

メンションが削除されたテキスト。

戻り値の型

str

discord.utils.resolve_invite(invite)

Resolves an invite from a Invite, URL or code.

パラメータ

invite (Union[Invite, str]) -- 招待。

戻り値

招待コード。

戻り値の型

str

discord.utils.resolve_template(code)

Resolves a template code from a Template, URL or code.

バージョン 1.4 で追加.

パラメータ

code (Union[Template, str]) -- The code.

戻り値

The template code.

戻り値の型

str

await discord.utils.sleep_until(when, result=None)

This function is a coroutine.

Sleep until a specified time.

If the time supplied is in the past this function will yield instantly.

バージョン 1.3 で追加.

パラメータ
  • when (datetime.datetime) -- The timestamp in which to sleep until. If the datetime is naive then it is assumed to be local time.

  • result (Any) -- If provided is returned to the caller when the coroutine completes.

discord.utils.utcnow()

A helper function to return an aware UTC datetime representing the current time.

This should be preferred to datetime.datetime.utcnow() since it is an aware datetime, compared to the naive datetime in the standard library.

バージョン 2.0 で追加.

戻り値

The current aware datetime in UTC.

戻り値の型

datetime.datetime

discord.utils.format_dt(dt, /, style=None)

A helper function to format a datetime.datetime for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown.

Style

Example Output

Description

t

22:57

Short Time

T

22:57:58

Long Time

d

17/05/2016

Short Date

D

17 May 2016

Long Date

f (default)

17 May 2016 22:57

Short Date Time

F

Tuesday, 17 May 2016 22:57

Long Date Time

R

5 years ago

Relative Time

Note that the exact output depends on the user's locale setting in the client. The example output presented is using the en-GB locale.

バージョン 2.0 で追加.

パラメータ
  • dt (datetime.datetime) -- The datetime to format.

  • style (str) -- The style to format the datetime with.

戻り値

The formatted string.

戻り値の型

str

discord.utils.as_chunks(iterator, max_size)

A helper function that collects an iterator into chunks of a given size.

バージョン 2.0 で追加.

パラメータ

警告

The last chunk collected may not be as large as max_size.

戻り値

A new iterator which yields chunks of a given size.

戻り値の型

Union[Iterator, AsyncIterator]

列挙型

APIは、文字列が将来変わることに備え、文字列を直書きするのを防ぐために、いくらかの文字列の列挙型を提供します。

列挙型はすべて enum.Enum の動作を模倣した内部クラスのサブクラスです。

class discord.ChannelType

特定チャンネルのチャンネルタイプ。

text

テキストチャンネル。

voice

ボイスチャンネル。

private

プライベートのテキストチャンネル。ダイレクトメッセージとも呼ばれています。

group

プライベートのグループDM。

category

A category channel.

news

ギルドのニュースチャンネル。

store

ギルドのストアチャンネル。

stage_voice

A guild stage voice channel.

バージョン 1.7 で追加.

news_thread

A news thread

バージョン 2.0 で追加.

public_thread

A public thread

バージョン 2.0 で追加.

private_thread

A private thread

バージョン 2.0 で追加.

class discord.MessageType

Message のタイプを指定します。これは、メッセージが通常のものかシステムメッセージかを判断するのに使用できます。

x == y

Checks if two messages are equal.

x != y

Checks if two messages are not equal.

default

デフォルトのメッセージ。これは通常のメッセージと同じです。

recipient_add

The system message when a user is added to a group private message or a thread.

recipient_remove

The system message when a user is removed from a group private message or a thread.

call

通話の状態を示すシステムメッセージ。例: 不在着信、通話の開始、その他。

channel_name_change

チャンネル名の変更を示すシステムメッセージ。

channel_icon_change

チャンネルのアイコンの変更を示すシステムメッセージ。

pins_add

ピン留めの追加を示すシステムメッセージ。

new_member

ギルドの新規メンバーの参加を示すシステムメッセージ。

premium_guild_subscription

メンバーがギルドを「ニトロブースト」したことを表すシステムメッセージ。

premium_guild_tier_1

メンバーがギルドを「ニトロブースト」し、それによってギルドがレベル1に到達したことを表すシステムメッセージ。

premium_guild_tier_2

メンバーがギルドを「ニトロブースト」し、それによってギルドがレベル2に到達したことを表すシステムメッセージ。

premium_guild_tier_3

メンバーがギルドを「ニトロブースト」し、それによってギルドがレベル3に到達したことを表すシステムメッセージ。

channel_follow_add

The system message denoting that an announcement channel has been followed.

バージョン 1.3 で追加.

guild_stream

The system message denoting that a member is streaming in the guild.

バージョン 1.7 で追加.

guild_discovery_disqualified

The system message denoting that the guild is no longer eligible for Server Discovery.

バージョン 1.7 で追加.

guild_discovery_requalified

The system message denoting that the guild has become eligible again for Server Discovery.

バージョン 1.7 で追加.

guild_discovery_grace_period_initial_warning

The system message denoting that the guild has failed to meet the Server Discovery requirements for one week.

バージョン 1.7 で追加.

guild_discovery_grace_period_final_warning

The system message denoting that the guild has failed to meet the Server Discovery requirements for 3 weeks in a row.

バージョン 1.7 で追加.

thread_created

The system message denoting that a thread has been created. This is only sent if the thread has been created from an older message. The period of time required for a message to be considered old cannot be relied upon and is up to Discord.

バージョン 2.0 で追加.

reply

The system message denoting that the author is replying to a message.

バージョン 2.0 で追加.

chat_input_command

The system message denoting that an application (or "slash") command was executed.

バージョン 2.0 で追加.

注釈

Originally this was application_command, but changed following Discord changes.

guild_invite_reminder

The system message sent as a reminder to invite people to the guild.

バージョン 2.0 で追加.

thread_starter_message

The system message denoting the message in the thread that is the one that started the thread's conversation topic.

バージョン 2.0 で追加.

context_menu_command

The system message denoting that an context menu ("user" or "message") command was executed.

バージョン 2.0 で追加.

class discord.UserFlags

Represents Discord User flags.

staff

The user is a Discord Employee.

partner

The user is a Discord Partner.

hypesquad

The user is a HypeSquad Events member.

bug_hunter

The user is a Bug Hunter.

mfa_sms

The user has SMS recovery for Multi Factor Authentication enabled.

premium_promo_dismissed

The user has dismissed the Discord Nitro promotion.

hypesquad_bravery

The user is a HypeSquad Bravery member.

hypesquad_brilliance

The user is a HypeSquad Brilliance member.

hypesquad_balance

The user is a HypeSquad Balance member.

early_supporter

The user is an Early Supporter.

team_user

The user is a Team User.

system

The user is a system user (i.e. represents Discord officially).

has_unread_urgent_messages

The user has an unread system message.

bug_hunter_level_2

The user is a Bug Hunter Level 2.

verified_bot

The user is a Verified Bot.

verified_bot_developer

The user is an Early Verified Bot Developer.

discord_certified_moderator

The user is a Discord Certified Moderator.

class discord.ActivityType

Activity のタイプを指定します。これはアクティビティをどう解釈するか確認するために使われます。

unknown

不明なアクティビティタイプ。これは通常起こらないはずです。

playing

プレイ中のアクティビティタイプ。

streaming

放送中のアクティビティタイプ。

listening

再生中のアクティビティタイプ。

watching

視聴中のアクティビティタイプ。

custom

A custom activity type.

competing

A competing activity type.

バージョン 1.5 で追加.

class discord.InteractionType

Specifies the type of Interaction.

バージョン 2.0 で追加.

ping

Represents Discord pinging to see if the interaction response server is alive.

application_command

Represents a slash command interaction.

component

Represents a component based interaction, i.e. using the Discord Bot UI Kit.

class discord.InteractionResponseType

Specifies the response type for the interaction.

バージョン 2.0 で追加.

pong

Pongs the interaction when given a ping.

See also InteractionResponse.pong()

channel_message

Respond to the interaction with a message.

See also InteractionResponse.send_message()

deferred_channel_message

Responds to the interaction with a message at a later time.

See also InteractionResponse.defer()

deferred_message_update

Acknowledges the component interaction with a promise that the message will update later (though there is no need to actually update the message).

See also InteractionResponse.defer()

message_update

Responds to the interaction by editing the message.

See also InteractionResponse.edit_message()

class discord.ApplicationCommandType

Represents the application type that Discord have.

バージョン 2.0 で追加.

slash

Represents a slash command.

user

Represents a user context command.

message

Represents a message context command.

class discord.SlashCommandOptionType

Represents the slash command option type.

バージョン 2.0 で追加.

sub_command

Represents a slash subcommand.

sub_command_group

Represents a slash subcommand group.

string

Represents that the option is a string.

integer

Represents that the option is a integer.

boolean

Represents that the option is a boolean (true/false).

user

Represents that the option is a User or Member.

channel

Represents that the option is a GuildChannel.

role

Represents that the option is a Role.

mentionable

Represents that the option is a mentionable type.

Should be one of:

number

Represents that the option is a number.

It support both float and int.

custom

Represents a custom type.

You should provide a way to parse this custom format later.

class discord.ComponentType

Represents the component type of a component.

バージョン 2.0 で追加.

action_row

Represents the group component which holds different components in a row.

button

Represents a button component.

select

Represents a select component.

class discord.ButtonStyle

Represents the style of the button component.

バージョン 2.0 で追加.

primary

Represents a blurple button for the primary action.

secondary

Represents a grey button for the secondary action.

success

Represents a green button for a successful action.

danger

Represents a red button for a dangerous action.

Represents a link button.

blurple

An alias for primary.

grey

An alias for secondary.

gray

An alias for secondary.

green

An alias for success.

red

An alias for danger.

url

An alias for link.

class discord.VoiceRegion

ボイスサーバーのリージョンを指定します。

amsterdam

アムステルダムリージョン。

brazil

ブラジルリージョン。

dubai

The Dubai region.

バージョン 1.3 で追加.

eu_central

中央ヨーロッパのリージョン。

eu_west

東ヨーロッパのリージョン。

europe

The Europe region.

バージョン 1.3 で追加.

frankfurt

フランクフルトリージョン。

hongkong

香港リージョン。

india

インドリージョン。

バージョン 1.2 で追加.

japan

日本リージョン。

london

ロンドンリージョン。

russia

ロシアリージョン。

singapore

シンガポールリージョン。

southafrica

南アフリカリージョン。

south_korea

The South Korea region.

sydney

シドニーリージョン。

us_central

中央アメリカのリージョン。

us_east

アメリカ西部のリージョン。

us_south

アメリカ南部のリージョン。

us_west

アメリカ東部のリージョン。

vip_amsterdam

VIPギルド用のアムステルダムリージョン。

vip_us_east

VIPギルド用のアメリカ東部リージョン。

vip_us_west

VIPギルド用のアメリカ西部リージョン。

class discord.VerificationLevel

Guild の認証レベルを指定します。これは、メンバーがギルドにメッセージを送信できるようになるまでの条件です。

バージョン 2.0 で追加.

x == y

認証レベルが等しいか確認します。

x != y

認証レベルが等しくないか確認します。

x > y

認証レベルがあるレベルより厳しいか確認します。

x < y

認証レベルがあるレベルより緩いか確認します。

x >= y

認証レベルがあるレベルと同じ、又は厳しいか確認します。

x <= y

認証レベルがあるレベルと同じ、又は緩いか確認します。

none

無制限。

low

メンバーはDiscordアカウントのメール認証を済ませないといけません。

medium

メンバーはメール認証をし、かつアカウント登録から5分経過しないといけません。

high

メンバーはメール認証をし、Discordのアカウント登録から5分経過し、かつ10分以上ギルドに所属していないといけません。

highest

メンバーはDiscordアカウントの電話番号認証を済ませないといけません。

class discord.NotificationLevel

Guild の通知対象のデフォルト設定をすべてのメッセージ、またはメンションのみに指定します。

バージョン 2.0 で追加.

x == y

Checks if two notification levels are equal.

x != y

Checks if two notification levels are not equal.

x > y

Checks if a notification level is higher than another.

x < y

Checks if a notification level is lower than another.

x >= y

Checks if a notification level is higher or equal to another.

x <= y

Checks if a notification level is lower or equal to another.

all_messages

メンバーは、メンションされているかどうかに関わらず、すべてのメッセージの通知を受け取ります。

only_mentions

メンバーは自分がメンションされているメッセージの通知のみ受け取ります。

class discord.ContentFilter

Guild の不適切な表現のフィルターを指定します。これはDiscordがポルノ画像や不適切な表現を検出するために使用している機械学習アルゴリズムです。

バージョン 2.0 で追加.

x == y

表現のフィルターのレベルが等しいか確認します。

x != y

表現のフィルターのレベルが等しくないか確認します。

x > y

表現のフィルターのレベルが他のレベルより大きいか確認します。

x < y

表現のフィルターのレベルが他のレベルより小さいか確認します。

x >= y

表現のフィルターのレベルが他のレベルより大きい、または等しいか確認します。

x <= y

表現のフィルターのレベルが他のレベルより小さい、または等しいか確認します。

disabled

ギルドで表現のフィルターが有効ではない。

no_role

ギルドで役職を持たないメンバーに対して表現のフィルターが有効化されている。

all_members

ギルドで、すべてのメンバーに対して表現のフィルターが有効化されている。

class discord.Status

Member のステータスを指定します。

online

メンバーがオンライン。

offline

メンバーがオフライン。

idle

メンバーが退席中。

dnd

メンバーが取り込み中。

do_not_disturb

dnd のエイリアス。

invisible

メンバーがオンライン状態を隠す。実際には、これは Client.change_presence() でプレゼンスを送信する時のみ使用します。ユーザーのプレゼンスを受け取った場合、これは offline に置き換えられます。

class discord.AuditLogAction

AuditLogEntry で行われた動作の種類を取得します。AuditLogEntryは Guild.audit_logs() で取得可能です。

guild_update

ギルドが更新された。このトリガーとなるものは以下のとおりです。

  • ギルドのvanity URLの変更

  • ギルドの招待時のスプラッシュ画像の変更

  • ギルドのAFKチャンネル、またはタイムアウトの変更

  • ギルドの音声通話のサーバーリージョンの変更

  • Changing the guild icon, banner, or discovery splash

  • ギルドの管理設定の変更

  • ギルドのウィジェットに関連するものの変更

これが上記のactionならば、target のtypeは :class:`Guild`になります。

AuditLogDiff から、以下の属性を参照できます:

channel_create

チャンネルが作成されました。

これが上記のactionならば、 target のtypeは、IDが設定されている abc.GuildChannel か、 Object のいずれかになります。

Object の場合、 after を使用して、より詳細な情報を持つオブジェクトを見つけることができます。

AuditLogDiff から、以下の属性を参照できます:

channel_update

チャンネルが更新されました。これのトリガーとなるものは以下の通りです。

  • チャンネルのチャンネルトピックの変更、または名前の変更。

  • チャンネルのビットレートの変更。

これが上記のactionならば、 target のtypeは、IDが設定されている abc.GuildChannel か、 Object のいずれかになります。

Object の場合、 after または before を使用して、より詳細な情報を持つオブジェクトを見つけることができます。

AuditLogDiff から、以下の属性を参照できます:

channel_delete

チャンネルの削除。

これが上記のactionならば、 target のtypeは、IDが設定されている Object になります。

A more filled out object can be found by using the before object.

AuditLogDiff から、以下の属性を参照できます:

overwrite_create

チャンネルにおける権限の上書き設定の作成。

これが上記のactionならば、 target のtypeは、IDが設定されている abc.GuildChannel か、 Object のいずれかになります。

この場合には、 extraRoleMember です。もしオブジェクトが見つからない場合はid、name、 'role''member' である``type`` 属性がある Object です。

AuditLogDiff から、以下の属性を参照できます:

overwrite_update

チャンネルの権限の上書きが変更されました。典型的な例は、権限が変更された場合です。

overwrite_create に、 targetextra についての説明があります。

AuditLogDiff から、以下の属性を参照できます:

overwrite_delete

チャンネルにおける権限の上書き設定の削除。

overwrite_create に、 targetextra についての説明があります。

AuditLogDiff から、以下の属性を参照できます:

kick

メンバーのキック。

これが上記のactionならば、target のtypeはキックされたユーザーに該当する User になります。

これが上記のactionなら、changes は空になります。

member_prune

非アクティブメンバーの一括キック。

これが上記のactionならば、target のtypeは None に設定されます。

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • delete_members_days: An integer specifying how far the prune was.

  • members_removed: An integer specifying how many members were removed.

これが上記のactionなら、changes は空になります。

ban

メンバーのBAN。

これが上記のactionならば、target のtypeはBANされたユーザーに該当する User になります。

これが上記のactionなら、changes は空になります。

unban

メンバーのBANの解除。

これが上記のactionならば、target のtypeはBANが解除されたユーザーに該当する User になります。

これが上記のactionなら、changes は空になります。

member_update

メンバーの何らかの更新。これのトリガーとなるのは以下の場合です:

  • メンバーのニックネームの変更。

  • They were server muted or deafened (or it was undo'd)

これが上記のactionならば、 target のtypeは、更新の行われた Member あるいは User になります。

AuditLogDiff から、以下の属性を参照できます:

member_role_update

A member's role has been updated. This triggers when a member either gains a role or loses a role.

これが上記のactionならば、 target のtypeは、役職の更新が行われた Member あるいは User になります。

AuditLogDiff から、以下の属性を参照できます:

member_move

A member's voice channel has been updated. This triggers when a member is moved to a different voice channel.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • channel: A TextChannel or Object with the channel ID where the members were moved.

  • count: An integer specifying how many members were moved.

バージョン 1.3 で追加.

member_disconnect

A member's voice state has changed. This triggers when a member is force disconnected from voice.

When this is the action, the type of extra is set to an unspecified proxy object with one attribute:

  • count: An integer specifying how many members were disconnected.

バージョン 1.3 で追加.

bot_add

A bot was added to the guild.

When this is the action, the type of target is the Member or User which was added to the guild.

バージョン 1.3 で追加.

role_create

新しい役職の作成。

これが上記のactionならば、 target のtypeは、IDが設定されている Role か、 Object のいずれかになります。

バージョン 2.0 で変更: Added icon and unicode_emoji.

AuditLogDiff から、以下の属性を参照できます:

role_update

役職の何らかの更新。これのトリガーとなるのは以下の場合です:

  • 名前の更新。

  • The permissions have changed

  • The colour has changed

  • Its hoist/mentionable state has changed

これが上記のactionならば、 target のtypeは、IDが設定されている Role か、 Object のいずれかになります。

バージョン 2.0 で変更: Added icon and unicode_emoji.

AuditLogDiff から、以下の属性を参照できます:

role_delete

役職の削除。

これが上記のactionならば、 target のtypeは、IDが設定されている Role か、 Object のいずれかになります。

バージョン 2.0 で変更: Added icon and unicode_emoji.

AuditLogDiff から、以下の属性を参照できます:

invite_create

招待の作成。

これが上記のactionならば、target のtypeは作成された招待に該当する Invite になります。

AuditLogDiff から、以下の属性を参照できます:

invite_update

招待の更新。

When this is the action, the type of target is the Invite that was updated.

invite_delete

An invite was deleted.

When this is the action, the type of target is the Invite that was deleted.

AuditLogDiff から、以下の属性を参照できます:

webhook_create

A webhook was created.

When this is the action, the type of target is the Object with the webhook ID.

AuditLogDiff から、以下の属性を参照できます:

webhook_update

A webhook was updated. This trigger in the following situations:

  • The webhook name changed

  • The webhook channel changed

When this is the action, the type of target is the Object with the webhook ID.

AuditLogDiff から、以下の属性を参照できます:

webhook_delete

A webhook was deleted.

When this is the action, the type of target is the Object with the webhook ID.

AuditLogDiff から、以下の属性を参照できます:

emoji_create

An emoji was created.

When this is the action, the type of target is the Emoji or Object with the emoji ID.

AuditLogDiff から、以下の属性を参照できます:

emoji_update

An emoji was updated. This triggers when the name has changed.

When this is the action, the type of target is the Emoji or Object with the emoji ID.

AuditLogDiff から、以下の属性を参照できます:

emoji_delete

An emoji was deleted.

When this is the action, the type of target is the Object with the emoji ID.

AuditLogDiff から、以下の属性を参照できます:

message_delete

A message was deleted by a moderator. Note that this only triggers if the message was deleted by someone other than the author.

When this is the action, the type of target is the Member or User who had their message deleted.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • count: An integer specifying how many messages were deleted.

  • channel: A TextChannel or Object with the channel ID where the message got deleted.

message_bulk_delete

Messages were bulk deleted by a moderator.

When this is the action, the type of target is the TextChannel or Object with the ID of the channel that was purged.

When this is the action, the type of extra is set to an unspecified proxy object with one attribute:

  • count: An integer specifying how many messages were deleted.

バージョン 1.3 で追加.

message_pin

A message was pinned in a channel.

When this is the action, the type of target is the Member or User who had their message pinned.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • channel: A TextChannel or Object with the channel ID where the message was pinned.

  • message_id: the ID of the message which was pinned.

バージョン 1.3 で追加.

message_unpin

A message was unpinned in a channel.

When this is the action, the type of target is the Member or User who had their message unpinned.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • channel: A TextChannel or Object with the channel ID where the message was unpinned.

  • message_id: the ID of the message which was unpinned.

バージョン 1.3 で追加.

integration_create

A guild integration was created.

When this is the action, the type of target is the Object with the integration ID of the integration which was created.

バージョン 1.3 で追加.

integration_update

A guild integration was updated.

When this is the action, the type of target is the Object with the integration ID of the integration which was updated.

バージョン 1.3 で追加.

integration_delete

A guild integration was deleted.

When this is the action, the type of target is the Object with the integration ID of the integration which was deleted.

バージョン 1.3 で追加.

stage_instance_create

A stage instance was started.

When this is the action, the type of target is the StageInstance or Object with the ID of the stage instance which was created.

AuditLogDiff から、以下の属性を参照できます:

バージョン 2.0 で追加.

stage_instance_update

A stage instance was updated.

When this is the action, the type of target is the StageInstance or Object with the ID of the stage instance which was updated.

AuditLogDiff から、以下の属性を参照できます:

バージョン 2.0 で追加.

stage_instance_delete

A stage instance was ended.

バージョン 2.0 で追加.

sticker_create

A sticker was created.

When this is the action, the type of target is the GuildSticker or Object with the ID of the sticker which was updated.

AuditLogDiff から、以下の属性を参照できます:

バージョン 2.0 で追加.

sticker_update

A sticker was updated.

When this is the action, the type of target is the GuildSticker or Object with the ID of the sticker which was updated.

AuditLogDiff から、以下の属性を参照できます:

バージョン 2.0 で追加.

sticker_delete

A sticker was deleted.

When this is the action, the type of target is the GuildSticker or Object with the ID of the sticker which was updated.

AuditLogDiff から、以下の属性を参照できます:

バージョン 2.0 で追加.

guild_scheduled_event_create

A guild scheduled event was created.

When this is the action, the type of target is the GuildScheduledEvent or Object with the ID of the scheduled guild event which was created.

Possible attribute for AuditLogDiff:

バージョン 2.0 で追加.

guild_scheduled_event_update

A guild scheduled event was updated.

When this is the action, the type of target is the GuildScheduledEvent or Object with the ID of the scheduled guild event which was updated.

Possible attribute for AuditLogDiff:

バージョン 2.0 で追加.

guild_scheduled_event_delete

A guild scheduled event was deleted.

When this is the action, the type of target is the GuildScheduledEvent or Object with the ID of the scheduled guild event which was deleted.

Possible attribute for AuditLogDiff:

バージョン 2.0 で追加.

thread_create

A thread was created.

When this is the action, the type of target is the Thread or Object with the ID of the thread which was created.

AuditLogDiff から、以下の属性を参照できます:

バージョン 2.0 で追加.

thread_update

A thread was updated.

When this is the action, the type of target is the Thread or Object with the ID of the thread which was updated.

AuditLogDiff から、以下の属性を参照できます:

バージョン 2.0 で追加.

thread_delete

A thread was deleted.

When this is the action, the type of target is the Thread or Object with the ID of the thread which was deleted.

AuditLogDiff から、以下の属性を参照できます:

バージョン 2.0 で追加.

class discord.AuditLogActionCategory

Represents the category that the AuditLogAction belongs to.

This can be retrieved via AuditLogEntry.category.

create

The action is the creation of something.

delete

The action is the deletion of something.

update

The action is the update of something.

class discord.TeamMembershipState

Represents the membership state of a team member retrieved through Client.application_info().

バージョン 1.3 で追加.

invited

Represents an invited member.

accepted

Represents a member currently in the team.

class discord.WebhookType

Represents the type of webhook that can be received.

バージョン 1.3 で追加.

incoming

Represents a webhook that can post messages to channels with a token.

channel_follower

Represents a webhook that is internally managed by Discord, used for following channels.

application

Represents a webhook that is used for interactions or applications.

バージョン 2.0 で追加.

class discord.ExpireBehaviour

Represents the behaviour the Integration should perform when a user's subscription has finished.

There is an alias for this called ExpireBehavior.

バージョン 1.4 で追加.

remove_role

This will remove the StreamIntegration.role from the user when their subscription is finished.

kick

This will kick the user when their subscription is finished.

class discord.DefaultAvatar

Represents the default avatar of a Discord User

blurple

Represents the default avatar with the color blurple. See also Colour.blurple

grey

Represents the default avatar with the color grey. See also Colour.greyple

gray

An alias for grey.

green

Represents the default avatar with the color green. See also Colour.green

orange

Represents the default avatar with the color orange. See also Colour.orange

red

Represents the default avatar with the color red. See also Colour.red

class discord.StickerType

Represents the type of sticker.

バージョン 2.0 で追加.

standard

Represents a standard sticker that all Nitro users can use.

guild

Represents a custom sticker created in a guild.

class discord.StickerFormatType

Represents the type of sticker images.

バージョン 1.6 で追加.

png

Represents a sticker with a png image.

apng

Represents a sticker with an apng image.

lottie

Represents a sticker with a lottie image.

class discord.InviteTarget

Represents the invite type for voice channel invites.

バージョン 2.0 で追加.

unknown

The invite doesn't target anyone or anything.

stream

A stream invite that targets a user.

embedded_application

A stream invite that targets an embedded application.

class discord.VideoQualityMode

Represents the camera video quality mode for voice channel participants.

バージョン 2.0 で追加.

auto

Represents auto camera video quality.

full

Represents full camera video quality.

class discord.StagePrivacyLevel

Represents a stage instance's privacy level.

バージョン 2.0 で追加.

public

The stage instance can be joined by external users.

closed

The stage instance can only be joined by members of the guild.

guild_only

Alias for closed

class discord.NSFWLevel

Represents the NSFW level of a guild.

バージョン 2.0 で追加.

x == y

Checks if two NSFW levels are equal.

x != y

Checks if two NSFW levels are not equal.

x > y

Checks if a NSFW level is higher than another.

x < y

Checks if a NSFW level is lower than another.

x >= y

Checks if a NSFW level is higher or equal to another.

x <= y

Checks if a NSFW level is lower or equal to another.

default

The guild has not been categorised yet.

explicit

The guild contains NSFW content.

safe

The guild does not contain any NSFW content.

age_restricted

The guild may contain NSFW content.

class discord.GuildScheduledEventType

Represents the type of a guild scheduled event.

バージョン 2.0 で追加.

none

The guild event has not been categorised yet.

stage_instance

The guild event is a stage instance.

voice

The guild event is a voice event.

location

The guild event is a location based event.

class discord.GuildScheduledEventStatus

Represents the status of a guild scheduled event.

バージョン 2.0 で追加.

scheduled

The guild event is scheduled/upcoming.

active

The guild event is currently ongoing.

completed

The guild event is already finished.

canceled

The guild event is canceled.

class discord.GuildScheduledEventPrivacyLevel

Represents the privacy level of a guild scheduled event. Almost the same as StagePrivacyLevel.

バージョン 2.0 で追加.

public

The guild event is public and can be seen from discovery.

members_only

The guild event is only visible and can only be joined by the members of the guild

非同期イテレータ

一部のAPI関数では「非同期イテレータ」を返します。非同期イテレータは async for 構文 で使用できるものです。

これら非同期イテレータは以下のようにして使用可能です:

async for elem in channel.history():
    # do stuff with elem here

Certain utilities make working with async iterators easier, detailed below.

class discord.AsyncIterator

Represents the "AsyncIterator" concept. Note that no such class exists, it is purely abstract.

async for x in y

Iterates over the contents of the async iterator.

await next()

This function is a coroutine.

Advances the iterator by one, if possible. If no more items are found then this raises NoMoreItems.

await get(**attrs)

This function is a coroutine.

Similar to utils.get() except run over the async iterator.

Getting the last message by a user named 'Dave' or None:

msg = await channel.history().get(author__name='Dave')
await find(predicate)

This function is a coroutine.

Similar to utils.find() except run over the async iterator.

Unlike utils.find(), the predicate provided can be a coroutine.

Getting the last audit log with a reason or None:

def predicate(event):
    return event.reason is not None

event = await guild.audit_logs().find(predicate)
パラメータ

predicate -- The predicate to use. Could be a coroutine.

戻り値

The first element that returns True for the predicate or None.

await flatten()

This function is a coroutine.

Flattens the async iterator into a list with all the elements.

戻り値

A list of every element in the async iterator.

戻り値の型

list

chunk(max_size)

Collects items into chunks of up to a given maximum size. Another AsyncIterator is returned which collects items into lists of a given size. The maximum chunk size must be a positive integer.

バージョン 1.6 で追加.

Collecting groups of users:

async for leader, *users in reaction.users().chunk(3):
    ...

警告

The last chunk collected may not be as large as max_size.

パラメータ

max_size -- The size of individual chunks.

戻り値の型

AsyncIterator

map(func)

This is similar to the built-in map function. Another AsyncIterator is returned that executes the function on every element it is iterating over. This function can either be a regular function or a coroutine.

Creating a content iterator:

def transform(message):
    return message.content

async for content in channel.history().map(transform):
    message_length = len(content)
パラメータ

func -- The function to call on every element. Could be a coroutine.

戻り値の型

AsyncIterator

filter(predicate)

This is similar to the built-in filter function. Another AsyncIterator is returned that filters over the original async iterator. This predicate can be a regular function or a coroutine.

Getting messages by non-bot accounts:

def predicate(message):
    return not message.author.bot

async for elem in channel.history().filter(predicate):
    ...
パラメータ

predicate -- The predicate to call on every element. Could be a coroutine.

戻り値の型

AsyncIterator

監査ログデータ

Working with Guild.audit_logs() is a complicated process with a lot of machinery involved. The library attempts to make it easy to use and friendly. In order to accomplish this goal, it must make use of a couple of data classes that aid in this goal.

AuditLogEntry

class discord.AuditLogEntry(*, users, data, guild)

Represents an Audit Log entry.

You retrieve these via Guild.audit_logs().

x == y

Checks if two entries are equal.

x != y

Checks if two entries are not equal.

hash(x)

Returns the entry's hash.

バージョン 1.7 で変更: Audit log entries are now comparable and hashable.

action

The action that was done.

Type

AuditLogAction

user

The user who initiated this action. Usually a Member, unless gone then it's a User.

Type

abc.User

id

The entry ID.

Type

int

target

The target that got changed. The exact type of this depends on the action being done.

Type

Any

reason

The reason this action was done.

Type

Optional[str]

extra

Extra information that this entry has that might be useful. For most actions, this is None. However in some cases it contains extra information. See AuditLogAction for which actions have this field filled out.

Type

Any

created_at

Returns the entry's creation time in UTC.

Type

datetime.datetime

category

The category of the action, if applicable.

Type

Optional[AuditLogActionCategory]

changes

The list of changes this entry has.

Type

AuditLogChanges

before

The target's prior state.

Type

AuditLogDiff

after

The target's subsequent state.

Type

AuditLogDiff

AuditLogChanges

Attributes
class discord.AuditLogChanges

An audit log change set.

before

The old value. The attribute has the type of AuditLogDiff.

Depending on the AuditLogActionCategory retrieved by category, the data retrieved by this attribute differs:

Category

Description

create

All attributes are set to None.

delete

All attributes are set the value before deletion.

update

All attributes are set the value before updating.

None

No attributes are set.

after

The new value. The attribute has the type of AuditLogDiff.

Depending on the AuditLogActionCategory retrieved by category, the data retrieved by this attribute differs:

Category

Description

create

All attributes are set to the created value

delete

All attributes are set to None

update

All attributes are set the value after updating.

None

No attributes are set.

AuditLogDiff

class discord.AuditLogDiff

Represents an audit log "change" object. A change object has dynamic attributes that depend on the type of action being done. Certain actions map to certain attributes being set.

Note that accessing an attribute that does not match the specified action will lead to an attribute error.

To get a list of attributes that have been set, you can iterate over them. To see a list of all possible attributes that could be set based on the action being done, check the documentation for AuditLogAction, otherwise check the documentation below for all attributes that are possible.

iter(diff)

Returns an iterator over (attribute, value) tuple of this diff.

name

A name of something.

Type

str

icon

Depending on the action type, this may be a guild's icon or a role's icon.

See also Guild.icon or Role.icon.

Type

Asset

splash

The guild's invite splash. See also Guild.splash.

Type

Asset

discovery_splash

The guild's discovery splash. See also Guild.discovery_splash.

Type

Asset

banner

The guild's banner. See also Guild.banner.

Type

Asset

owner

The guild's owner. See also Guild.owner

Type

Union[Member, User]

region

The guild's voice region. See also Guild.region.

Type

VoiceRegion

afk_channel

The guild's AFK channel.

If this could not be found, then it falls back to a Object with the ID being set.

See Guild.afk_channel.

Type

Union[VoiceChannel, Object]

system_channel

The guild's system channel.

If this could not be found, then it falls back to a Object with the ID being set.

See Guild.system_channel.

Type

Union[TextChannel, Object]

rules_channel

The guild's rules channel.

If this could not be found then it falls back to a Object with the ID being set.

See Guild.rules_channel.

Type

Union[TextChannel, Object]

public_updates_channel

The guild's public updates channel.

If this could not be found then it falls back to a Object with the ID being set.

See Guild.public_updates_channel.

Type

Union[TextChannel, Object]

afk_timeout

The guild's AFK timeout. See Guild.afk_timeout.

Type

int

mfa_level

The guild's MFA level. See Guild.mfa_level.

Type

int

widget_enabled

The guild's widget has been enabled or disabled.

Type

bool

widget_channel

The widget's channel.

If this could not be found then it falls back to a Object with the ID being set.

Type

Union[TextChannel, Object]

verification_level

The guild's verification level.

See also Guild.verification_level.

Type

VerificationLevel

default_notifications

The guild's default notification level.

See also Guild.default_notifications.

Type

NotificationLevel

explicit_content_filter

The guild's content filter.

See also Guild.explicit_content_filter.

Type

ContentFilter

default_message_notifications

The guild's default message notification setting.

Type

int

vanity_url_code

The guild's vanity URL.

See also Guild.vanity_invite() and Guild.edit().

Type

str

position

The position of a Role or abc.GuildChannel.

Type

int

type

The type of channel or sticker.

Type

Union[ChannelType, StickerType]

topic

The topic of a TextChannel or StageChannel.

See also TextChannel.topic or StageChannel.topic.

Type

str

bitrate

The bitrate of a VoiceChannel.

See also VoiceChannel.bitrate.

Type

int

overwrites

A list of permission overwrite tuples that represents a target and a PermissionOverwrite for said target.

The first element is the object being targeted, which can either be a Member or User or Role. If this object is not found then it is a Object with an ID being filled and a type attribute set to either 'role' or 'member' to help decide what type of ID it is.

Type

List[Tuple[target, PermissionOverwrite]]

privacy_level

The privacy level of the stage instance or guild events.

Type

Union[StagePrivacyLevel, GuildScheduledEventStatus]

roles

A list of roles being added or removed from a member.

If a role is not found then it is a Object with the ID and name being filled in.

Type

List[Union[Role, Object]]

nick

The nickname of a member.

See also Member.nick

Type

Optional[str]

deaf

Whether the member is being server deafened.

See also VoiceState.deaf.

Type

bool

mute

Whether the member is being server muted.

See also VoiceState.mute.

Type

bool

permissions

The permissions of a role.

See also Role.permissions.

Type

Permissions

colour
color

The colour of a role.

See also Role.colour

Type

Colour

hoist

Whether the role is being hoisted or not.

See also Role.hoist

Type

bool

mentionable

Whether the role is mentionable or not.

See also Role.mentionable

Type

bool

code

The invite's code.

See also Invite.code

Type

str

channel

A guild channel.

If the channel is not found then it is a Object with the ID being set. In some cases the channel name is also set.

Type

Union[abc.GuildChannel, Object]

inviter

The user who created the invite.

See also Invite.inviter.

Type

Optional[User]

max_uses

The invite's max uses.

See also Invite.max_uses.

Type

int

uses

The invite's current uses.

See also Invite.uses.

Type

int

max_age

The invite's max age in seconds.

See also Invite.max_age.

Type

int

temporary

If the invite is a temporary invite.

See also Invite.temporary.

Type

bool

allow
deny

The permissions being allowed or denied.

Type

Permissions

id

The ID of the object being changed.

Type

int

avatar

The avatar of a member.

See also User.avatar.

Type

Asset

slowmode_delay

The number of seconds members have to wait before sending another message in the channel.

See also TextChannel.slowmode_delay.

Type

int

rtc_region

The region for the voice channel’s voice communication. A value of None indicates automatic voice region detection.

See also VoiceChannel.rtc_region.

Type

VoiceRegion

video_quality_mode

The camera video quality for the voice channel's participants.

See also VoiceChannel.video_quality_mode.

Type

VideoQualityMode

format_type

The format type of a sticker being changed.

See also GuildSticker.format

Type

StickerFormatType

emoji

The name of the emoji that represents a sticker being changed.

See also GuildSticker.emoji

Type

str

description

The description of a sticker or guild events being changed.

See also GuildSticker.description and GuildScheduledEvent.description.

Type

str

available

The availability of a sticker being changed.

See also GuildSticker.available

Type

bool

archived

The thread is now archived.

Type

bool

locked

The thread is being locked or unlocked.

Type

bool

auto_archive_duration

The thread's auto archive duration being changed.

See also Thread.auto_archive_duration

Type

int

default_auto_archive_duration

The default auto archive duration for newly created threads being changed.

Type

int

entity_type

The type for scheduled guild event being changed.

Type

GuildScheduledEventType

status

The status for scheduled guild event being changed.

Type

GuildScheduledEventStatus

location

The location for scheduled guild event being changed.

Type

str

unicode_emoji

The unicode emoji that represents when role got changed.

Type

str

Webhookサポート

ndiscord.py offers support for creating, editing, and executing webhooks through the Webhook class.

Webhook

class discord.Webhook

Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as Guild.webhooks() and TextChannel.webhooks(). The ones received by the library will automatically be bound using the library's internal HTTP session.

The second form involves creating a webhook object manually using the from_url() or partial() classmethods.

For example, creating a webhook from a URL and using aiohttp:

from discord import Webhook
import aiohttp

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url-here', session=session)
        await webhook.send('Hello World', username='Foo')

For a synchronous counterpart, see SyncWebhook.

x == y

Checks if two webhooks are equal.

x != y

Checks if two webhooks are not equal.

hash(x)

Returns the webhooks's hash.

バージョン 1.4 で変更: Webhooks are now comparable and hashable.

id

The webhook's ID

Type

int

type

The type of the webhook.

バージョン 1.3 で追加.

Type

WebhookType

token

The authentication token of the webhook. If this is None then the webhook cannot be used to make requests.

Type

Optional[str]

guild_id

The guild ID this webhook is for.

Type

Optional[int]

channel_id

The channel ID this webhook is for.

Type

Optional[int]

user

The user this webhook was created by. If the webhook was received without authentication then this will be None.

Type

Optional[abc.User]

name

The default name of the webhook.

Type

Optional[str]

source_guild

The guild of the channel that this webhook is following. Only given if type is WebhookType.channel_follower.

バージョン 2.0 で追加.

Type

Optional[PartialWebhookGuild]

source_channel

The channel that this webhook is following. Only given if type is WebhookType.channel_follower.

バージョン 2.0 で追加.

Type

Optional[PartialWebhookChannel]

property url: str

Returns the webhook's url.

Type

str

classmethod partial(id, token, *, session, bot_token=None)

Creates a partial Webhook.

パラメータ
  • id (int) -- The ID of the webhook.

  • token (str) -- The authentication token of the webhook.

  • session (aiohttp.ClientSession) --

    The session to use to send requests with. Note that the library does not manage the session and will not close it.

    バージョン 2.0 で追加.

  • bot_token (Optional[str]) --

    The bot authentication token for authenticated requests involving the webhook.

    バージョン 2.0 で追加.

戻り値

A partial Webhook. A partial webhook is just a webhook object with an ID and a token.

戻り値の型

Webhook

classmethod from_url(url, *, session, bot_token=None)

Creates a partial Webhook from a webhook URL.

パラメータ
  • url (str) -- The URL of the webhook.

  • session (aiohttp.ClientSession) --

    The session to use to send requests with. Note that the library does not manage the session and will not close it.

    バージョン 2.0 で追加.

  • bot_token (Optional[str]) --

    The bot authentication token for authenticated requests involving the webhook.

    バージョン 2.0 で追加.

例外

InvalidArgument -- The URL is invalid.

戻り値

A partial Webhook. A partial webhook is just a webhook object with an ID and a token.

戻り値の型

Webhook

await fetch(*, prefer_auth=True)

This function is a coroutine.

Fetches the current webhook.

This could be used to get a full webhook from a partial webhook.

バージョン 2.0 で追加.

注釈

When fetching with an unauthenticated webhook, i.e. is_authenticated() returns False, then the returned webhook does not contain any user information.

パラメータ

prefer_auth (bool) -- Whether to use the bot token over the webhook token if available. Defaults to True.

例外
戻り値

The fetched webhook.

戻り値の型

Webhook

await delete(*, reason=None, prefer_auth=True)

This function is a coroutine.

Deletes this Webhook.

パラメータ
  • reason (Optional[str]) --

    The reason for deleting this webhook. Shows up on the audit log.

    バージョン 1.4 で追加.

  • prefer_auth (bool) --

    Whether to use the bot token over the webhook token if available. Defaults to True.

    バージョン 2.0 で追加.

例外
  • HTTPException -- Deleting the webhook failed.

  • NotFound -- This webhook does not exist.

  • Forbidden -- You do not have permissions to delete this webhook.

  • InvalidArgument -- This webhook does not have a token associated with it.

await edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)

This function is a coroutine.

Edits this Webhook.

パラメータ
  • name (Optional[str]) -- The webhook's new default name.

  • avatar (Optional[bytes]) -- A bytes-like object representing the webhook's new default avatar.

  • channel (Optional[abc.Snowflake]) --

    The webhook's new channel. This requires an authenticated webhook.

    バージョン 2.0 で追加.

  • reason (Optional[str]) --

    The reason for editing this webhook. Shows up on the audit log.

    バージョン 1.4 で追加.

  • prefer_auth (bool) --

    Whether to use the bot token over the webhook token if available. Defaults to True.

    バージョン 2.0 で追加.

例外
  • HTTPException -- Editing the webhook failed.

  • NotFound -- This webhook does not exist.

  • InvalidArgument -- This webhook does not have a token associated with it or it tried editing a channel without authentication.

property avatar: discord.asset.Asset

Returns an Asset for the avatar the webhook has.

If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead.

Type

Asset

property channel: Optional[TextChannel]

The text channel this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type

Optional[TextChannel]

property created_at: datetime.datetime

Returns the webhook's creation time in UTC.

Type

datetime.datetime

property guild: Optional[Guild]

The guild this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type

Optional[Guild]

is_authenticated()

bool: Whether the webhook is authenticated with a bot token.

バージョン 2.0 で追加.

is_partial()

bool: Whether the webhook is a "partial" webhook.

バージョン 2.0 で追加.

await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., wait=False)

This function is a coroutine.

Sends a message using the webhook.

The content must be a type that can convert to a string through str(content).

To upload a single file, the file parameter should be used with a single File object.

If the embed parameter is provided, it must be of type Embed and it must be a rich embed type. You cannot mix the embed parameter with the embeds parameter, which must be a list of Embed objects to send.

パラメータ
  • content (str) -- The content of the message to send.

  • wait (bool) -- Whether the server should wait before sending a response. This essentially means that the return type of this function changes from None to a WebhookMessage if set to True. If the type of webhook is WebhookType.application then this is always set to True.

  • username (str) -- The username to send with this message. If no username is provided then the default username for the webhook is used.

  • avatar_url (str) -- The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used. If this is not a string then it is explicitly cast using str.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • ephemeral (bool) --

    Indicates if the message should only be visible to the user. This is only available to WebhookType.application webhooks. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.

    バージョン 2.0 で追加.

  • file (File) -- The file to upload. This cannot be mixed with files parameter.

  • files (List[File]) -- A list of files to send with the content. This cannot be mixed with the file parameter.

  • embed (Embed) -- The rich embed for the content to send. This cannot be mixed with embeds parameter.

  • embeds (List[Embed]) -- A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed parameter.

  • allowed_mentions (AllowedMentions) --

    Controls the mentions being processed in this message.

    バージョン 1.4 で追加.

  • view (discord.ui.View) --

    The view to send with the message. You can only send a view if this webhook is not partial and has state attached. A webhook has state attached if the webhook is managed by the library.

    バージョン 2.0 で追加.

  • thread (Snowflake) --

    The thread to send this webhook to.

    バージョン 2.0 で追加.

例外
  • HTTPException -- Sending the message failed.

  • NotFound -- This webhook was not found.

  • Forbidden -- The authorization token for the webhook is incorrect.

  • TypeError -- You specified both embed and embeds or file and files.

  • ValueError -- The length of embeds was invalid.

  • InvalidArgument -- There was no token associated with this webhook or ephemeral was passed with the improper webhook type or there was no state attached with this webhook when giving it a view.

戻り値

If wait is True then the message that was sent, otherwise None.

戻り値の型

Optional[WebhookMessage]

await fetch_message(id)

This function is a coroutine.

Retrieves a single WebhookMessage owned by this webhook.

バージョン 2.0 で追加.

パラメータ

id (int) -- The message ID to look for.

例外
  • NotFound -- The specified message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

  • InvalidArgument -- There was no token associated with this webhook.

戻り値

The message asked for.

戻り値の型

WebhookMessage

await edit_message(message_id, *, content=..., embeds=..., embed=..., file=..., files=..., view=..., allowed_mentions=None)

This function is a coroutine.

Edits a message owned by this webhook.

This is a lower level interface to WebhookMessage.edit() in case you only have an ID.

バージョン 1.6 で追加.

バージョン 2.0 で変更: The edit is no longer in-place, instead the newly edited message is returned.

パラメータ
  • message_id (int) -- The message ID to edit.

  • content (Optional[str]) -- The content to edit the message with or None to clear it.

  • embeds (List[Embed]) -- A list of embeds to edit the message with.

  • embed (Optional[Embed]) -- The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • file (File) --

    The file to upload. This cannot be mixed with files parameter.

    バージョン 2.0 で追加.

  • files (List[File]) --

    A list of files to send with the content. This cannot be mixed with the file parameter.

    バージョン 2.0 で追加.

  • allowed_mentions (AllowedMentions) -- Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

  • view (Optional[View]) --

    The updated view to update this message with. If None is passed then the view is removed. The webhook must have state attached, similar to send().

    バージョン 2.0 で追加.

例外
  • HTTPException -- Editing the message failed.

  • Forbidden -- Edited a message that is not yours.

  • TypeError -- You specified both embed and embeds or file and files

  • ValueError -- The length of embeds was invalid

  • InvalidArgument -- There was no token associated with this webhook or the webhook had no state.

戻り値

The newly edited webhook message.

戻り値の型

WebhookMessage

await delete_message(message_id, /)

This function is a coroutine.

Deletes a message owned by this webhook.

This is a lower level interface to WebhookMessage.delete() in case you only have an ID.

バージョン 1.6 で追加.

パラメータ

message_id (int) -- The message ID to delete.

例外

WebhookMessage

Methods
class discord.WebhookMessage

Represents a message sent from your webhook.

This allows you to edit or delete a message sent by your webhook.

This inherits from discord.Message with changes to edit() and delete() to work.

バージョン 1.6 で追加.

await edit(content=..., embeds=..., embed=..., file=..., files=..., view=..., allowed_mentions=None)

This function is a coroutine.

Edits the message.

バージョン 1.6 で追加.

バージョン 2.0 で変更: The edit is no longer in-place, instead the newly edited message is returned.

パラメータ
  • content (Optional[str]) -- The content to edit the message with or None to clear it.

  • embeds (List[Embed]) -- A list of embeds to edit the message with.

  • embed (Optional[Embed]) -- The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • file (File) --

    The file to upload. This cannot be mixed with files parameter.

    バージョン 2.0 で追加.

  • files (List[File]) --

    A list of files to send with the content. This cannot be mixed with the file parameter.

    バージョン 2.0 で追加.

  • allowed_mentions (AllowedMentions) -- Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

  • view (Optional[View]) --

    The updated view to update this message with. If None is passed then the view is removed.

    バージョン 2.0 で追加.

例外
戻り値

The newly edited message.

戻り値の型

WebhookMessage

await delete(*, delay=None)

This function is a coroutine.

Deletes the message.

パラメータ

delay (Optional[float]) -- If provided, the number of seconds to wait before deleting the message. The waiting is done in the background and deletion failures are ignored.

例外
  • Forbidden -- You do not have proper permissions to delete the message.

  • NotFound -- The message was deleted already.

  • HTTPException -- Deleting the message failed.

SyncWebhook

class discord.SyncWebhook

Represents a synchronous Discord webhook.

For an asynchronous counterpart, see Webhook.

x == y

Checks if two webhooks are equal.

x != y

Checks if two webhooks are not equal.

hash(x)

Returns the webhooks's hash.

バージョン 1.4 で変更: Webhooks are now comparable and hashable.

id

The webhook's ID

Type

int

type

The type of the webhook.

バージョン 1.3 で追加.

Type

WebhookType

token

The authentication token of the webhook. If this is None then the webhook cannot be used to make requests.

Type

Optional[str]

guild_id

The guild ID this webhook is for.

Type

Optional[int]

channel_id

The channel ID this webhook is for.

Type

Optional[int]

user

The user this webhook was created by. If the webhook was received without authentication then this will be None.

Type

Optional[abc.User]

name

The default name of the webhook.

Type

Optional[str]

source_guild

The guild of the channel that this webhook is following. Only given if type is WebhookType.channel_follower.

バージョン 2.0 で追加.

Type

Optional[PartialWebhookGuild]

source_channel

The channel that this webhook is following. Only given if type is WebhookType.channel_follower.

バージョン 2.0 で追加.

Type

Optional[PartialWebhookChannel]

property url: str

Returns the webhook's url.

Type

str

classmethod partial(id, token, *, session=..., bot_token=None)

Creates a partial Webhook.

パラメータ
  • id (int) -- The ID of the webhook.

  • token (str) -- The authentication token of the webhook.

  • session (requests.Session) -- The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, the requests auto session creation functions are used instead.

  • bot_token (Optional[str]) -- The bot authentication token for authenticated requests involving the webhook.

戻り値

A partial Webhook. A partial webhook is just a webhook object with an ID and a token.

戻り値の型

Webhook

classmethod from_url(url, *, session=..., bot_token=None)

Creates a partial Webhook from a webhook URL.

パラメータ
  • url (str) -- The URL of the webhook.

  • session (requests.Session) -- The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, the requests auto session creation functions are used instead.

  • bot_token (Optional[str]) -- The bot authentication token for authenticated requests involving the webhook.

例外

InvalidArgument -- The URL is invalid.

戻り値

A partial Webhook. A partial webhook is just a webhook object with an ID and a token.

戻り値の型

Webhook

fetch(*, prefer_auth=True)

Fetches the current webhook.

This could be used to get a full webhook from a partial webhook.

注釈

When fetching with an unauthenticated webhook, i.e. is_authenticated() returns False, then the returned webhook does not contain any user information.

パラメータ

prefer_auth (bool) -- Whether to use the bot token over the webhook token if available. Defaults to True.

例外
戻り値

The fetched webhook.

戻り値の型

SyncWebhook

delete(*, reason=None, prefer_auth=True)

Deletes this Webhook.

パラメータ
  • reason (Optional[str]) --

    The reason for deleting this webhook. Shows up on the audit log.

    バージョン 1.4 で追加.

  • prefer_auth (bool) -- Whether to use the bot token over the webhook token if available. Defaults to True.

例外
  • HTTPException -- Deleting the webhook failed.

  • NotFound -- This webhook does not exist.

  • Forbidden -- You do not have permissions to delete this webhook.

  • InvalidArgument -- This webhook does not have a token associated with it.

edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)

Edits this Webhook.

パラメータ
  • name (Optional[str]) -- The webhook's new default name.

  • avatar (Optional[bytes]) -- A bytes-like object representing the webhook's new default avatar.

  • channel (Optional[abc.Snowflake]) -- The webhook's new channel. This requires an authenticated webhook.

  • reason (Optional[str]) --

    The reason for editing this webhook. Shows up on the audit log.

    バージョン 1.4 で追加.

  • prefer_auth (bool) -- Whether to use the bot token over the webhook token if available. Defaults to True.

例外
  • HTTPException -- Editing the webhook failed.

  • NotFound -- This webhook does not exist.

  • InvalidArgument -- This webhook does not have a token associated with it or it tried editing a channel without authentication.

戻り値

The newly edited webhook.

戻り値の型

SyncWebhook

send(content=..., *, username=..., avatar_url=..., tts=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., thread=..., wait=False)

Sends a message using the webhook.

The content must be a type that can convert to a string through str(content).

To upload a single file, the file parameter should be used with a single File object.

If the embed parameter is provided, it must be of type Embed and it must be a rich embed type. You cannot mix the embed parameter with the embeds parameter, which must be a list of Embed objects to send.

パラメータ
  • content (str) -- The content of the message to send.

  • wait (bool) -- Whether the server should wait before sending a response. This essentially means that the return type of this function changes from None to a WebhookMessage if set to True.

  • username (str) -- The username to send with this message. If no username is provided then the default username for the webhook is used.

  • avatar_url (str) -- The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used. If this is not a string then it is explicitly cast using str.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • file (File) -- The file to upload. This cannot be mixed with files parameter.

  • files (List[File]) -- A list of files to send with the content. This cannot be mixed with the file parameter.

  • embed (Embed) -- The rich embed for the content to send. This cannot be mixed with embeds parameter.

  • embeds (List[Embed]) -- A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed parameter.

  • allowed_mentions (AllowedMentions) --

    Controls the mentions being processed in this message.

    バージョン 1.4 で追加.

  • thread (Snowflake) --

    The thread to send this message to.

    バージョン 2.0 で追加.

例外
  • HTTPException -- Sending the message failed.

  • NotFound -- This webhook was not found.

  • Forbidden -- The authorization token for the webhook is incorrect.

  • TypeError -- You specified both embed and embeds or file and files

  • ValueError -- The length of embeds was invalid

  • InvalidArgument -- There was no token associated with this webhook.

戻り値

If wait is True then the message that was sent, otherwise None.

戻り値の型

Optional[SyncWebhookMessage]

fetch_message(id, /)

Retrieves a single SyncWebhookMessage owned by this webhook.

バージョン 2.0 で追加.

パラメータ

id (int) -- The message ID to look for.

例外
  • NotFound -- The specified message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

  • InvalidArgument -- There was no token associated with this webhook.

戻り値

The message asked for.

戻り値の型

SyncWebhookMessage

property avatar: discord.asset.Asset

Returns an Asset for the avatar the webhook has.

If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead.

Type

Asset

property channel: Optional[TextChannel]

The text channel this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type

Optional[TextChannel]

property created_at: datetime.datetime

Returns the webhook's creation time in UTC.

Type

datetime.datetime

edit_message(message_id, *, content=..., embeds=..., embed=..., file=..., files=..., allowed_mentions=None)

Edits a message owned by this webhook.

This is a lower level interface to WebhookMessage.edit() in case you only have an ID.

バージョン 1.6 で追加.

パラメータ
  • message_id (int) -- The message ID to edit.

  • content (Optional[str]) -- The content to edit the message with or None to clear it.

  • embeds (List[Embed]) -- A list of embeds to edit the message with.

  • embed (Optional[Embed]) -- The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • file (File) -- The file to upload. This cannot be mixed with files parameter.

  • files (List[File]) -- A list of files to send with the content. This cannot be mixed with the file parameter.

  • allowed_mentions (AllowedMentions) -- Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

例外
property guild: Optional[Guild]

The guild this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type

Optional[Guild]

is_authenticated()

bool: Whether the webhook is authenticated with a bot token.

バージョン 2.0 で追加.

is_partial()

bool: Whether the webhook is a "partial" webhook.

バージョン 2.0 で追加.

delete_message(message_id, /)

Deletes a message owned by this webhook.

This is a lower level interface to WebhookMessage.delete() in case you only have an ID.

バージョン 1.6 で追加.

パラメータ

message_id (int) -- The message ID to delete.

例外

SyncWebhookMessage

Methods
class discord.SyncWebhookMessage

Represents a message sent from your webhook.

This allows you to edit or delete a message sent by your webhook.

This inherits from discord.Message with changes to edit() and delete() to work.

バージョン 2.0 で追加.

edit(content=..., embeds=..., embed=..., file=..., files=..., allowed_mentions=None)

Edits the message.

パラメータ
  • content (Optional[str]) -- The content to edit the message with or None to clear it.

  • embeds (List[Embed]) -- A list of embeds to edit the message with.

  • embed (Optional[Embed]) -- The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • file (File) -- The file to upload. This cannot be mixed with files parameter.

  • files (List[File]) -- A list of files to send with the content. This cannot be mixed with the file parameter.

  • allowed_mentions (AllowedMentions) -- Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

例外
戻り値

The newly edited message.

戻り値の型

SyncWebhookMessage

delete(*, delay=None)

Deletes the message.

パラメータ

delay (Optional[float]) -- If provided, the number of seconds to wait before deleting the message. This blocks the thread.

例外
  • Forbidden -- You do not have proper permissions to delete the message.

  • NotFound -- The message was deleted already.

  • HTTPException -- Deleting the message failed.

抽象基底クラス

An abstract base class (also known as an abc) is a class that models can inherit to get their behaviour. Abstract base classes should not be instantiated. They are mainly there for usage with isinstance() and issubclass().

This library has a module related to abstract base classes, in which all the ABCs are subclasses of typing.Protocol.

Snowflake

Attributes
class discord.abc.Snowflake

An ABC that details the common operations on a Discord model.

Almost all Discord models meet this abstract base class.

If you want to create a snowflake on your own, consider using Object.

id

The model's unique ID.

Type

int

User

class discord.abc.User

An ABC that details the common operations on a Discord user.

The following implement this ABC:

This ABC must also implement Snowflake.

name

The user's username.

Type

str

discriminator

The user's discriminator.

Type

str

avatar

The avatar asset the user has.

Type

Asset

bot

If the user is a bot account.

Type

bool

property display_name: str

Returns the user's display name.

Type

str

property mention: str

Returns a string that allows you to mention the given user.

Type

str

PrivateChannel

Attributes
class discord.abc.PrivateChannel

An ABC that details the common operations on a private Discord channel.

The following implement this ABC:

This ABC must also implement Snowflake.

me

The user presenting yourself.

Type

ClientUser

GuildChannel

class discord.abc.GuildChannel

An ABC that details the common operations on a Discord guild channel.

The following implement this ABC:

This ABC must also implement Snowflake.

name

The channel name.

Type

str

guild

The guild the channel belongs to.

Type

Guild

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type

int

property changed_roles: List[discord.role.Role]

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

property mention: str

The string that allows you to mention the channel.

Type

str

property created_at: datetime.datetime

Returns the channel's creation time in UTC.

Type

datetime.datetime

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

パラメータ

obj (Union[Role, User]) -- The role or user denoting whose overwrite to get.

戻り値

The permission overwrites for this object.

戻り値の型

PermissionOverwrite

property overwrites: Dict[Union[Role, Member], PermissionOverwrite]

Returns all of the channel's overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

戻り値

The channel's permission overwrites.

戻り値の型

Dict[Union[Role, Member], PermissionOverwrite]

property category: Optional[CategoryChannel]

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property permissions_synced: bool

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

バージョン 1.3 で追加.

Type

bool

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

バージョン 2.0 で変更: The object passed in can now be a role object.

パラメータ

obj (Union[Member, Role]) -- The object to resolve permissions for. This could be either a member or a role. If it's a role then member overwrites are not computed.

戻り値

The resolved permissions for the member or role.

戻り値の型

Permissions

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

パラメータ

reason (Optional[str]) -- The reason for deleting this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have proper permissions to delete the channel.

  • NotFound -- The channel was not found or was already deleted.

  • HTTPException -- Deleting the channel failed.

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)

This function is a coroutine.

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

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have the manage_roles permission to use this.

注釈

This method replaces the old overwrites with the ones given.

サンプル

Setting allow and deny:

await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
パラメータ
  • target (Union[Member, Role]) -- The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) -- The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions -- A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

  • reason (Optional[str]) -- The reason for doing this action. Shows up on the audit log.

例外
  • Forbidden -- You do not have permissions to edit channel specific permissions.

  • HTTPException -- Editing channel specific permissions failed.

  • NotFound -- The role or member being edited is not part of the guild.

  • InvalidArgument -- The overwrite parameter invalid or the target type was not Role or Member.

await clone(*, name=None, reason=None)

This function is a coroutine.

Clones this channel. This creates a channel with the same properties as this channel.

You must have the manage_channels permission to do this.

バージョン 1.1 で追加.

パラメータ
  • name (Optional[str]) -- The name of the new channel. If not provided, defaults to this channel name.

  • reason (Optional[str]) -- The reason for cloning this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

戻り値

The channel that was created.

戻り値の型

abc.GuildChannel

await move(**kwargs)

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have the manage_channels permission to do this.

注釈

Voice channels will always be sorted below text channels. This is a Discord limitation.

バージョン 1.7 で追加.

パラメータ
  • beginning (bool) -- Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) -- Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (Snowflake) -- The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (Snowflake) -- The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) -- The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[Snowflake]) -- The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) -- Whether to sync the permissions with the category (if given).

  • reason (str) -- The reason for the move.

例外
  • InvalidArgument -- An invalid position was given or a bad mix of arguments were passed.

  • Forbidden -- You do not have permissions to move the channel.

  • HTTPException -- Moving the channel failed.

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

パラメータ
  • max_age (int) -- How long the invite should last in seconds. If it's 0 then the invite doesn't expire. Defaults to 0.

  • max_uses (int) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to 0.

  • temporary (bool) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (bool) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • reason (Optional[str]) -- The reason for creating this invite. Shows up on the audit log.

  • target_type (Optional[InviteTarget]) --

    The type of target for the voice channel invite, if any.

    バージョン 2.0 で追加.

  • target_user (Optional[User]) --

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    バージョン 2.0 で追加.

  • target_application_id: --

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    バージョン 2.0 で追加.

例外
  • HTTPException -- Invite creation failed.

  • NotFound -- The channel that was passed is a category or an invalid channel.

戻り値

The invite that was created.

戻り値の型

Invite

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this channel.

You must have manage_channels to get this information.

例外
  • Forbidden -- You do not have proper permissions to get the information.

  • HTTPException -- An error occurred while fetching the information.

戻り値

The list of invites that are currently active.

戻り値の型

List[Invite]

await create_event(name, scheduled_start_time, *, description=..., privacy_level=..., entity_type=...)

This function is a coroutine.

Create a new guild event with this channel.

You must have the manage_events permission to create a guild event.

注釈

Another extra permissions is required for different type of entity_type.

If your entity type is GuildScheduledEventType.stage_instance, you must have the following extra permissions:

  • manage_channels

  • mute_members

  • move_members

If your entity type is GuildScheduledEventType.voice, you must have the following extra permissions:

  • view_channel for channel associated with the event.

  • connect for channel associated with the event.

If your entity type is GuildScheduledEventType.external, you dont need any extra permissions.

バージョン 2.0 で追加.

パラメータ
  • name (str) -- The name of the event.

  • description (Optional[str]) -- The description of the event. Could be None for no description.

  • privacy_level (Optional[GuildScheduledEventPrivacyLevel]) -- The event privacy level, same thing as StageInstance PrivacyLevel

  • scheduled_start_time (datetime.datetime) -- The scheduled start time, timezone must be UTC. If not it will be converted automatically.

  • entity_type (Optional[GuildScheduledEventType]) -- The entity_type or type for the event. If you don't provide this, it will automatically check from the channel type.

例外
  • Forbidden -- You do not have permissions to create the guild event.

  • HTTPException -- Creating the guild event failed.

  • ValueError -- Validation error occurred.

戻り値

The newly updated guild event.

戻り値の型

GuildScheduledEvent

Messageable

Methods
class discord.abc.Messageable

An ABC that details the common operations on a model that can send messages.

The following implement this ABC:

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Returns an AsyncIterator that enables receiving the destination's message history.

You must have read_message_history permissions to use this.

サンプル

使い方

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

すべてのパラメータがオプションです。

パラメータ
  • limit (Optional[int]) -- The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages before this date or message. 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 (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. 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.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

  • oldest_first (Optional[bool]) -- If set to True, return messages in oldest->newest order. Defaults to True if after is specified, otherwise False.

例外
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

列挙

Message -- The message with the message data parsed.

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

注釈

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

パラメータ
  • content (Optional[str]) -- The content of the message to send.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • embed (Embed) -- The rich embed for the content.

  • file (File) -- The file to upload.

  • files (List[File]) -- A list of files to upload. Must be a maximum of 10.

  • nonce (int) -- The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) -- If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) --

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    バージョン 1.4 で追加.

  • reference (Union[Message, MessageReference, PartialMessage]) --

    A reference to the Message to which you are replying, this can be created using to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    バージョン 1.6 で追加.

  • mention_author (Optional[bool]) --

    If set, overrides the replied_user attribute of allowed_mentions.

    バージョン 1.6 で追加.

  • view (discord.ui.View) -- A Discord UI View to add to the message.

  • embeds (List[Embed]) --

    A list of embeds to upload. Must be a maximum of 10.

    バージョン 2.0 で追加.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) --

    A list of stickers to upload. Must be a maximum of 3.

    バージョン 2.0 で追加.

例外
戻り値

The message that was sent.

戻り値の型

Message

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

パラメータ

id (int) -- The message ID to look for.

例外
  • NotFound -- The specified message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

戻り値

The message asked for.

戻り値の型

Message

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

注釈

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

例外

HTTPException -- Retrieving the pinned messages failed.

戻り値

The messages that are currently pinned.

戻り値の型

List[Message]

Connectable

class discord.abc.Connectable

An ABC that details the common operations on a channel that can connect to a voice server.

The following implement this ABC:

注釈

This ABC is not decorated with typing.runtime_checkable(), so will fail isinstance()/issubclass() checks.

Discordモデル

モデルはDiscordから受け取るクラスであり、ユーザーによって作成されることを想定していません。

危険

下記のクラスは、 ユーザーによって作成されることを想定しておらず 、中には 読み取り専用 のものもあります。

つまり、独自の User を作成は行うべきではなく、また、 User インスタンスの値の変更もするべきではありません。

このようなモデルクラスのインスタンスを取得したい場合は、 キャッシュを経由して取得する必要があります。一般的な方法としては utils.find() 関数を用いるか、 イベントリファレンス の特定のイベントから受け取る方法が挙げられます。

注釈

ほぼすべてのクラスに __slots__ が定義されています。つまり、データクラスに動的に変数を追加することは不可能です。

ClientUser

class discord.ClientUser

あなたのDiscordユーザーを表します。

x == y

二つのユーザーが等しいかを比較します。

x != y

二つのユーザーが等しいものではないか比較します。

hash(x)

ユーザーのハッシュ値を返します。

str(x)

ユーザー名とディスクリミネータを返します。

name

The user's username.

Type

str

id

The user's unique ID.

Type

int

discriminator

The user's discriminator. This is given when the username has conflicts.

Type

str

bot

Specifies if the user is a bot account.

Type

bool

system

Specifies if the user is a system user (i.e. represents Discord officially).

バージョン 1.3 で追加.

Type

bool

verified

Specifies if the user's email is verified.

Type

bool

locale

The IETF language tag used to identify the language the user is using.

Type

Optional[str]

mfa_enabled

Specifies if the user has MFA turned on and working.

Type

bool

await edit(*, username=..., avatar=...)

This function is a coroutine.

現在のクライアントのプロフィールを編集します。

注釈

アバターをアップロードする際には、アップロードする画像を表す bytes-like object を渡す必要があります。これをファイルを介して行う場合、ファイルを open('some_filename', 'rb') で開き、 bytes-like objectfp.read() で取得できます。

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

バージョン 2.0 で変更: The edit is no longer in-place, instead the newly edited client user is returned.

パラメータ
  • username (str) -- 変更する際の新しいユーザー名。

  • avatar (bytes) -- アップロードする画像を表す bytes-like object 。アバターをなしにしたい場合は None を設定することが出来ます。

例外
戻り値

The newly edited client user.

戻り値の型

ClientUser

property accent_color: Optional[discord.colour.Colour]

Returns the user's accent color, if applicable.

There is an alias for this named accent_colour.

バージョン 2.0 で追加.

注釈

This information is only available via Client.fetch_user().

Type

Optional[Colour]

property accent_colour: Optional[discord.colour.Colour]

Returns the user's accent colour, if applicable.

There is an alias for this named accent_color.

バージョン 2.0 で追加.

注釈

This information is only available via Client.fetch_user().

Type

Optional[Colour]

property avatar: Optional[discord.asset.Asset]

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, None is returned. If you want the avatar that a user has displayed, consider display_avatar.

Type

Optional[Asset]

property banner: Optional[discord.asset.Asset]

Returns the user's banner asset, if available.

バージョン 2.0 で追加.

注釈

This information is only available via Client.fetch_user().

Type

Optional[Asset]

property color: discord.colour.Colour

A property that returns a color denoting the rendered color for the user. This always returns Colour.default().

There is an alias for this named colour.

Type

Colour

property colour: discord.colour.Colour

A property that returns a colour denoting the rendered colour for the user. This always returns Colour.default().

There is an alias for this named color.

Type

Colour

property created_at: datetime

Returns the user's creation time in UTC.

This is when the user's Discord account was created.

Type

datetime.datetime

property default_avatar: discord.asset.Asset

Returns the default avatar for a given user. This is calculated by the user's discriminator.

Type

Asset

property display_avatar: discord.asset.Asset

Returns the user's display avatar.

For regular users this is just their default avatar or uploaded avatar.

バージョン 2.0 で追加.

Type

Asset

property display_name: str

Returns the user's display name.

通常であれば、これはユーザー名がそのまま返りますが、ギルドにてニックネームを設定している場合は、代替としてニックネームが返ります。

Type

str

property mention: str

Returns a string that allows you to mention the given user.

Type

str

mentioned_in(message)

指定のメッセージにユーザーに対するメンションが含まれているかを確認します。

パラメータ

message (Message) -- メンションが含まれているかを確認するメッセージ。

戻り値

Indicates if the user is mentioned in the message.

戻り値の型

bool

property public_flags: discord.flags.PublicUserFlags

The publicly available flags the user has.

Type

PublicUserFlags

User

class discord.User

Represents a Discord user.

x == y

二つのユーザーが等しいかを比較します。

x != y

二つのユーザーが等しいものではないか比較します。

hash(x)

ユーザーのハッシュ値を返します。

str(x)

ユーザー名とディスクリミネータを返します。

name

The user's username.

Type

str

id

The user's unique ID.

Type

int

discriminator

The user's discriminator. This is given when the username has conflicts.

Type

str

bot

Specifies if the user is a bot account.

Type

bool

system

Specifies if the user is a system user (i.e. represents Discord officially).

Type

bool

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Returns an AsyncIterator that enables receiving the destination's message history.

You must have read_message_history permissions to use this.

サンプル

使い方

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

すべてのパラメータがオプションです。

パラメータ
  • limit (Optional[int]) -- The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages before this date or message. 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 (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. 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.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

  • oldest_first (Optional[bool]) -- If set to True, return messages in oldest->newest order. Defaults to True if after is specified, otherwise False.

例外
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

列挙

Message -- The message with the message data parsed.

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

注釈

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property dm_channel: Optional[DMChannel]

Returns the channel associated with this user if it exists.

これが ``None``を返すなら、あなたは create_dm() コルーチン関数を使って、DMチャンネルを作ることができます。

Type

Optional[DMChannel]

property mutual_guilds: List[Guild]

The guilds that the user shares with the client.

注釈

This will only return mutual guilds within the client's internal cache.

バージョン 1.7 で追加.

Type

List[Guild]

property accent_color: Optional[discord.colour.Colour]

Returns the user's accent color, if applicable.

There is an alias for this named accent_colour.

バージョン 2.0 で追加.

注釈

This information is only available via Client.fetch_user().

Type

Optional[Colour]

property accent_colour: Optional[discord.colour.Colour]

Returns the user's accent colour, if applicable.

There is an alias for this named accent_color.

バージョン 2.0 で追加.

注釈

This information is only available via Client.fetch_user().

Type

Optional[Colour]

property avatar: Optional[discord.asset.Asset]

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, None is returned. If you want the avatar that a user has displayed, consider display_avatar.

Type

Optional[Asset]

property banner: Optional[discord.asset.Asset]

Returns the user's banner asset, if available.

バージョン 2.0 で追加.

注釈

This information is only available via Client.fetch_user().

Type

Optional[Asset]

property color: discord.colour.Colour

A property that returns a color denoting the rendered color for the user. This always returns Colour.default().

There is an alias for this named colour.

Type

Colour

property colour: discord.colour.Colour

A property that returns a colour denoting the rendered colour for the user. This always returns Colour.default().

There is an alias for this named color.

Type

Colour

await create_dm()

This function is a coroutine.

このユーザーと DMChannel を作ります。

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

戻り値

The channel that was created.

戻り値の型

DMChannel

property created_at: datetime

Returns the user's creation time in UTC.

This is when the user's Discord account was created.

Type

datetime.datetime

property default_avatar: discord.asset.Asset

Returns the default avatar for a given user. This is calculated by the user's discriminator.

Type

Asset

property display_avatar: discord.asset.Asset

Returns the user's display avatar.

For regular users this is just their default avatar or uploaded avatar.

バージョン 2.0 で追加.

Type

Asset

property display_name: str

Returns the user's display name.

通常であれば、これはユーザー名がそのまま返りますが、ギルドにてニックネームを設定している場合は、代替としてニックネームが返ります。

Type

str

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

パラメータ

id (int) -- The message ID to look for.

例外
  • NotFound -- The specified message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

戻り値

The message asked for.

戻り値の型

Message

property mention: str

Returns a string that allows you to mention the given user.

Type

str

mentioned_in(message)

指定のメッセージにユーザーに対するメンションが含まれているかを確認します。

パラメータ

message (Message) -- メンションが含まれているかを確認するメッセージ。

戻り値

Indicates if the user is mentioned in the message.

戻り値の型

bool

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

注釈

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

例外

HTTPException -- Retrieving the pinned messages failed.

戻り値

The messages that are currently pinned.

戻り値の型

List[Message]

property public_flags: discord.flags.PublicUserFlags

The publicly available flags the user has.

Type

PublicUserFlags

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

パラメータ
  • content (Optional[str]) -- The content of the message to send.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • embed (Embed) -- The rich embed for the content.

  • file (File) -- The file to upload.

  • files (List[File]) -- A list of files to upload. Must be a maximum of 10.

  • nonce (int) -- The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) -- If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) --

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    バージョン 1.4 で追加.

  • reference (Union[Message, MessageReference, PartialMessage]) --

    A reference to the Message to which you are replying, this can be created using to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    バージョン 1.6 で追加.

  • mention_author (Optional[bool]) --

    If set, overrides the replied_user attribute of allowed_mentions.

    バージョン 1.6 で追加.

  • view (discord.ui.View) -- A Discord UI View to add to the message.

  • embeds (List[Embed]) --

    A list of embeds to upload. Must be a maximum of 10.

    バージョン 2.0 で追加.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) --

    A list of stickers to upload. Must be a maximum of 3.

    バージョン 2.0 で追加.

例外
戻り値

The message that was sent.

戻り値の型

Message

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

Attachment

class discord.Attachment

Represents an attachment from Discord.

str(x)

Returns the URL of the attachment.

x == y

Checks if the attachment is equal to another attachment.

x != y

Checks if the attachment is not equal to another attachment.

hash(x)

Returns the hash of the attachment.

バージョン 1.7 で変更: Attachment can now be casted to str and is hashable.

id

The attachment ID.

Type

int

description

The attachment description.

バージョン 2.0 で追加.

Type

Optional[str]

size

The attachment size in bytes.

Type

int

height

The attachment's height, in pixels. Only applicable to images and videos.

Type

Optional[int]

width

The attachment's width, in pixels. Only applicable to images and videos.

Type

Optional[int]

filename

The attachment's filename.

Type

str

url

The attachment URL. If the message this attachment was attached to is deleted, then this will 404.

Type

str

proxy_url

The proxy URL. This is a cached version of the url in the case of images. When the message is deleted, this URL might be valid for a few minutes or not valid at all.

Type

str

content_type

The attachment's media type

バージョン 1.7 で追加.

Type

Optional[str]

ephermal

Whether this attachment is ephermal. Ephemeral attachments will automatically be removed after a set period of time. Ephemeral attachments on messages are guaranteed to be available as long as the message itself exists.

バージョン 2.0 で追加.

Type

bool

is_spoiler()

bool: Whether this attachment contains a spoiler.

await save(fp, *, seek_begin=True, use_cached=False)

This function is a coroutine.

Saves this attachment into a file-like object.

パラメータ
  • fp (Union[io.BufferedIOBase, os.PathLike]) -- The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) -- Whether to seek to the beginning of the file after saving is successfully done.

  • use_cached (bool) -- Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

例外
戻り値

The number of bytes written.

戻り値の型

int

await read(*, use_cached=False)

This function is a coroutine.

Retrieves the content of this attachment as a bytes object.

バージョン 1.1 で追加.

パラメータ

use_cached (bool) -- Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

例外
  • HTTPException -- Downloading the attachment failed.

  • Forbidden -- You do not have permissions to access this attachment

  • NotFound -- The attachment was deleted.

戻り値

The contents of the attachment.

戻り値の型

bytes

await to_file(*, use_cached=False, spoiler=False)

This function is a coroutine.

Converts the attachment into a File suitable for sending via abc.Messageable.send().

バージョン 1.3 で追加.

パラメータ
  • use_cached (bool) --

    Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

    バージョン 1.4 で追加.

  • spoiler (bool) --

    Whether the file is a spoiler.

    バージョン 1.4 で追加.

例外
  • HTTPException -- Downloading the attachment failed.

  • Forbidden -- You do not have permissions to access this attachment

  • NotFound -- The attachment was deleted.

戻り値

The attachment as a file suitable for sending.

戻り値の型

File

Asset

Attributes
class discord.Asset

Represents a CDN asset on Discord.

str(x)

Returns the URL of the CDN asset.

len(x)

Returns the length of the CDN asset's URL.

x == y

Checks if the asset is equal to another asset.

x != y

Checks if the asset is not equal to another asset.

hash(x)

Returns the hash of the asset.

property url: str

Returns the underlying URL of the asset.

Type

str

property key: str

Returns the identifying key of the asset.

Type

str

is_animated()

bool: Returns whether the asset is animated.

replace(*, size=..., format=..., static_format=...)

Returns a new asset with the passed components replaced.

パラメータ
  • size (int) -- The new size of the asset.

  • format (str) -- The new format to change it to. Must be either 'webp', 'jpeg', 'jpg', 'png', or 'gif' if it's animated.

  • static_format (str) -- The new format to change it to if the asset isn't animated. Must be either 'webp', 'jpeg', 'jpg', or 'png'.

例外

InvalidArgument -- An invalid size or format was passed.

戻り値

The newly updated asset.

戻り値の型

Asset

with_size(size, /)

Returns a new asset with the specified size.

パラメータ

size (int) -- The new size of the asset.

例外

InvalidArgument -- The asset had an invalid size.

戻り値

The new updated asset.

戻り値の型

Asset

with_format(format, /)

Returns a new asset with the specified format.

パラメータ

format (str) -- The new format of the asset.

例外

InvalidArgument -- The asset had an invalid format.

戻り値

The new updated asset.

戻り値の型

Asset

with_static_format(format, /)

Returns a new asset with the specified static format.

This only changes the format if the underlying asset is not animated. Otherwise, the asset is not changed.

パラメータ

format (str) -- The new static format of the asset.

例外

InvalidArgument -- The asset had an invalid format.

戻り値

The new updated asset.

戻り値の型

Asset

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

例外
戻り値

The content of the asset.

戻り値の型

bytes

await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

パラメータ
  • fp (Union[io.BufferedIOBase, os.PathLike]) -- The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) -- Whether to seek to the beginning of the file after saving is successfully done.

例外
戻り値

The number of bytes written.

戻り値の型

int

Message

class discord.Message

Represents a message from Discord.

x == y

Checks if two messages are equal.

x != y

Checks if two messages are not equal.

hash(x)

Returns the message's hash.

tts

Specifies if the message was done with text-to-speech. This can only be accurately received in on_message() due to a discord limitation.

Type

bool

type

The type of message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for system_content.

Type

MessageType

author

A Member that sent the message. If channel is a private channel or the user has the left the guild, then it is a User instead.

Type

Union[Member, abc.User]

content

The actual contents of the message.

Type

str

nonce

The value used by the discord guild and the client to verify that the message is successfully sent. This is not stored long term within Discord's servers and is only used ephemerally.

Type

Optional[Union[str, int]]

embeds

A list of embeds the message has.

Type

List[Embed]

channel

The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if it's a private message.

Type

Union[TextChannel, Thread, DMChannel, GroupChannel, PartialMessageable]

reference

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

バージョン 1.5 で追加.

Type

Optional[MessageReference]

mention_everyone

Specifies if the message mentions everyone.

注釈

This does not check if the @everyone or the @here text is in the message itself. Rather this boolean indicates if either the @everyone or the @here text is in the message and it did end up mentioning.

Type

bool

mentions

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

警告

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

Type

List[abc.User]

channel_mentions

A list of abc.GuildChannel that were mentioned. If the message is in a private message then the list is always empty.

Type

List[abc.GuildChannel]

role_mentions

A list of Role that were mentioned. If the message is in a private message then the list is always empty.

Type

List[Role]

id

The message ID.

Type

int

webhook_id

If this message was sent by a webhook, then this is the webhook ID's that sent this message.

Type

Optional[int]

attachments

A list of attachments given to a message.

Type

List[Attachment]

pinned

Specifies if the message is currently pinned.

Type

bool

flags

Extra features of the message.

バージョン 1.3 で追加.

Type

MessageFlags

reactions

Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.

Type

List[Reaction]

activity

The activity associated with this message. Sent with Rich-Presence related messages that for example, request joining, spectating, or listening to or with another member.

It is a dictionary with the following optional keys:

  • type: An integer denoting the type of message activity being requested.

  • party_id: The party ID associated with the party.

Type

Optional[dict]

application

The rich presence enabled application associated with this message.

It is a dictionary with the following keys:

  • id: A string representing the application's ID.

  • name: A string representing the application's name.

  • description: A string representing the application's description.

  • icon: A string representing the icon ID of the application.

  • cover_image: A string representing the embed's image asset ID.

Type

Optional[dict]

stickers

A list of sticker items given to the message.

バージョン 1.6 で追加.

Type

List[StickerItem]

components

A list of components in the message.

バージョン 2.0 で追加.

Type

List[Component]

guild

The guild that the message belongs to, if applicable.

Type

Optional[Guild]

raw_mentions

A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content.

This allows you to receive the user IDs of mentioned users even in a private message context.

Type

List[int]

raw_channel_mentions

A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content.

Type

List[int]

raw_role_mentions

A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content.

Type

List[int]

clean_content

A property that returns the content in a "cleaned up" manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.

This will also transform @everyone and @here mentions into non-mentions.

注釈

This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() or utils.remove_markdown() respectively, along with this function.

Type

str

property created_at: datetime.datetime

The message's creation time in UTC.

Type

datetime.datetime

property edited_at: Optional[datetime.datetime]

An aware UTC datetime object containing the edited time of the message.

Type

Optional[datetime.datetime]

property jump_url: str

Returns a URL that allows the client to jump to this message.

Type

str

is_system()

bool: Whether the message is a system message.

A system message is a message that is constructed entirely by the Discord API in response to something.

バージョン 1.3 で追加.

system_content

A property that returns the content that is rendered regardless of the Message.type.

In the case of MessageType.default and MessageType.reply, this just returns the regular Message.content. Otherwise this returns an English message denoting the contents of the system message.

Type

str

await delete(*, delay=None)

This function is a coroutine.

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people's messages, you need the manage_messages permission.

バージョン 1.1 で変更: Added the new delay keyword-only parameter.

パラメータ

delay (Optional[float]) -- If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.

例外
  • Forbidden -- You do not have proper permissions to delete the message.

  • NotFound -- The message was deleted already

  • HTTPException -- Deleting the message failed.

await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)

This function is a coroutine.

Edits the message.

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

バージョン 1.3 で変更: The suppress keyword-only parameter was added.

パラメータ
  • content (Optional[str]) -- The new content to replace the message with. Could be None to remove the content.

  • embed (Optional[Embed]) -- The new embed to replace the original with. Could be None to remove the embed.

  • embeds (List[Embed]) --

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

    バージョン 2.0 で追加.

  • attachments (List[Attachment]) -- A list of attachments to keep in the message. If [] is passed then all attachments are removed.

  • suppress (bool) -- Whether to suppress embeds for the message. This removes all the embeds if set to True. If set to False this brings the embeds back if they were suppressed. Using this parameter requires manage_messages.

  • delete_after (Optional[float]) -- If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.

  • allowed_mentions (Optional[AllowedMentions]) --

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    バージョン 1.4 で追加.

  • view (Optional[View]) -- The updated view to update this message with. If None is passed then the view is removed.

例外
  • HTTPException -- Editing the message failed.

  • Forbidden -- Tried to suppress a message without permissions or edited a message's content or embed that isn't yours.

  • InvalidArgument -- You specified both embed and embeds

await publish()

This function is a coroutine.

Publishes this message to your announcement channel.

You must have the send_messages permission to do this.

If the message is not your own then the manage_messages permission is also needed.

例外
  • Forbidden -- You do not have the proper permissions to publish this message.

  • HTTPException -- Publishing the message failed.

await pin(*, reason=None)

This function is a coroutine.

Pins the message.

You must have the manage_messages permission to do this in a non-private channel context.

パラメータ

reason (Optional[str]) --

The reason for pinning the message. Shows up on the audit log.

バージョン 1.4 で追加.

例外
  • Forbidden -- You do not have permissions to pin the message.

  • NotFound -- The message or channel was not found or deleted.

  • HTTPException -- Pinning the message failed, probably due to the channel having more than 50 pinned messages.

await unpin(*, reason=None)

This function is a coroutine.

Unpins the message.

You must have the manage_messages permission to do this in a non-private channel context.

パラメータ

reason (Optional[str]) --

The reason for unpinning the message. Shows up on the audit log.

バージョン 1.4 で追加.

例外
  • Forbidden -- You do not have permissions to unpin the message.

  • NotFound -- The message or channel was not found or deleted.

  • HTTPException -- Unpinning the message failed.

await add_reaction(emoji)

This function is a coroutine.

Add a reaction to the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You must have the read_message_history permission to use this. If nobody else has reacted to the message using this emoji, the add_reactions permission is required.

パラメータ

emoji (Union[Emoji, Reaction, PartialEmoji, str]) -- The emoji to react with.

例外
  • HTTPException -- Adding the reaction failed.

  • Forbidden -- You do not have the proper permissions to react to the message.

  • NotFound -- The emoji you specified was not found.

  • InvalidArgument -- The emoji parameter is invalid.

await remove_reaction(emoji, member)

This function is a coroutine.

Remove a reaction by the member from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

If the reaction is not your own (i.e. member parameter is not you) then the manage_messages permission is needed.

The member parameter must represent a member and meet the abc.Snowflake abc.

パラメータ
例外
  • HTTPException -- Removing the reaction failed.

  • Forbidden -- You do not have the proper permissions to remove the reaction.

  • NotFound -- The member or emoji you specified was not found.

  • InvalidArgument -- The emoji parameter is invalid.

await clear_reaction(emoji)

This function is a coroutine.

Clears a specific reaction from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You need the manage_messages permission to use this.

バージョン 1.3 で追加.

パラメータ

emoji (Union[Emoji, Reaction, PartialEmoji, str]) -- The emoji to clear.

例外
  • HTTPException -- Clearing the reaction failed.

  • Forbidden -- You do not have the proper permissions to clear the reaction.

  • NotFound -- The emoji you specified was not found.

  • InvalidArgument -- The emoji parameter is invalid.

await clear_reactions()

This function is a coroutine.

Removes all the reactions from the message.

You need the manage_messages permission to use this.

例外
  • HTTPException -- Removing the reactions failed.

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

await create_thread(*, name, auto_archive_duration=...)

This function is a coroutine.

Creates a public thread from this message.

You must have create_public_threads in order to create a public thread from a message.

The channel this message belongs in must be a TextChannel.

バージョン 2.0 で追加.

パラメータ
  • name (str) -- The name of the thread.

  • auto_archive_duration (int) -- The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel's default auto archive duration is used.

例外
戻り値

The created thread.

戻り値の型

Thread

await reply(content=None, **kwargs)

This function is a coroutine.

A shortcut method to abc.Messageable.send() to reply to the Message.

バージョン 1.6 で追加.

例外
  • HTTPException -- Sending the message failed.

  • Forbidden -- You do not have the proper permissions to send the message.

  • InvalidArgument -- The files list is not of the appropriate size or you specified both file and files.

戻り値

The message that was sent.

戻り値の型

Message

to_reference(*, fail_if_not_exists=True)

Creates a MessageReference from the current message.

バージョン 1.6 で追加.

パラメータ

fail_if_not_exists (bool) --

Whether replying using the message reference should raise HTTPException if the message no longer exists or Discord could not fetch the message.

バージョン 1.7 で追加.

戻り値

The reference to this message.

戻り値の型

MessageReference

Component

Attributes
class discord.Component

Represents a Discord Bot UI Kit Component.

Currently, the only components supported by Discord are:

This class is abstract and cannot be instantiated.

バージョン 2.0 で追加.

type

The type of component.

Type

ComponentType

ActionRow

Attributes
class discord.ActionRow

Represents a Discord Bot UI Kit Action Row.

This is a component that holds up to 5 children components in a row.

This inherits from Component.

バージョン 2.0 で追加.

type

The type of component.

Type

ComponentType

children

The children components that this holds, if any.

Type

List[Component]

Button

class discord.Button

Represents a button from the Discord Bot UI Kit.

This inherits from Component.

注釈

The user constructible and usable type to create a button is discord.ui.Button not this one.

バージョン 2.0 で追加.

style

The style of the button.

Type

ButtonStyle

custom_id

The ID of the button that gets received during an interaction. If this button is for a URL, it does not have a custom ID.

Type

Optional[str]

url

The URL this button sends you to.

Type

Optional[str]

disabled

Whether the button is disabled or not.

Type

bool

label

The label of the button, if any.

Type

Optional[str]

emoji

The emoji of the button, if available.

Type

Optional[PartialEmoji]

SelectMenu

class discord.SelectMenu

Represents a select menu from the Discord Bot UI Kit.

A select menu is functionally the same as a dropdown, however on mobile it renders a bit differently.

注釈

The user constructible and usable type to create a select menu is discord.ui.Select not this one.

バージョン 2.0 で追加.

custom_id

The ID of the select menu that gets received during an interaction.

Type

Optional[str]

placeholder

The placeholder text that is shown if nothing is selected, if any.

Type

Optional[str]

min_values

The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

Type

int

max_values

The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

Type

int

options

A list of options that can be selected in this menu.

Type

List[SelectOption]

disabled

Whether the select is disabled or not.

Type

bool

DeletedReferencedMessage

Attributes
class discord.DeletedReferencedMessage

A special sentinel type that denotes whether the resolved message referenced message had since been deleted.

The purpose of this class is to separate referenced messages that could not be fetched and those that were previously fetched but have since been deleted.

バージョン 1.6 で追加.

property id: int

The message ID of the deleted referenced message.

Type

int

property channel_id: int

The channel ID of the deleted referenced message.

Type

int

property guild_id: Optional[int]

The guild ID of the deleted referenced message.

Type

Optional[int]

Reaction

Attributes
Methods
class discord.Reaction

Represents a reaction to a message.

Depending on the way this object was created, some of the attributes can have a value of None.

x == y

Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered "equal".

x != y

Checks if two reactions are not equal.

hash(x)

Returns the reaction's hash.

str(x)

Returns the string form of the reaction's emoji.

emoji

The reaction emoji. May be a custom emoji, or a unicode emoji.

Type

Union[Emoji, PartialEmoji, str]

count

Number of times this reaction was made

Type

int

me

If the user sent this reaction.

Type

bool

message

Message this reaction is for.

Type

Message

async for ... in users(*, limit=None, after=None)

Returns an AsyncIterator representing the users that have reacted to the message.

The after parameter must represent a member and meet the abc.Snowflake abc.

サンプル

使い方

# I do not actually recommend doing this.
async for user in reaction.users():
    await channel.send(f'{user} has reacted with {reaction.emoji}!')

Flattening into a list:

users = await reaction.users().flatten()
# users is now a list of User...
winner = random.choice(users)
await channel.send(f'{winner} has won the raffle.')
パラメータ
  • limit (Optional[int]) -- The maximum number of results to return. If not provided, returns all the users who reacted to the message.

  • after (Optional[abc.Snowflake]) -- For pagination, reactions are sorted by member.

例外

HTTPException -- Getting the users for the reaction failed.

列挙

Union[User, Member] -- The member (if retrievable) or the user that has reacted to this message. The case where it can be a Member is in a guild message context. Sometimes it can be a User if the member has left the guild.

is_custom_emoji()

bool: If this is a custom emoji.

await remove(user)

This function is a coroutine.

Remove the reaction by the provided User from the message.

If the reaction is not your own (i.e. user parameter is not you) then the manage_messages permission is needed.

The user parameter must represent a user or member and meet the abc.Snowflake abc.

パラメータ

user (abc.Snowflake) -- The user or member from which to remove the reaction.

例外
  • HTTPException -- Removing the reaction failed.

  • Forbidden -- You do not have the proper permissions to remove the reaction.

  • NotFound -- The user you specified, or the reaction's message was not found.

await clear()

This function is a coroutine.

Clears this reaction from the message.

You need the manage_messages permission to use this.

バージョン 1.3 で追加.

例外
  • HTTPException -- Clearing the reaction failed.

  • Forbidden -- You do not have the proper permissions to clear the reaction.

  • NotFound -- The emoji you specified was not found.

  • InvalidArgument -- The emoji parameter is invalid.

Guild

class discord.Guild

Represents a Discord guild.

This is referred to as a "server" in the official Discord UI.

x == y

Checks if two guilds are equal.

x != y

Checks if two guilds are not equal.

hash(x)

Returns the guild's hash.

str(x)

Returns the guild's name.

name

The guild name.

Type

str

emojis

All emojis that the guild owns.

Type

Tuple[Emoji, ...]

stickers

All stickers that the guild owns.

バージョン 2.0 で追加.

Type

Tuple[GuildSticker, ...]

region

The region the guild belongs on. There is a chance that the region will be a str if the value is not recognised by the enumerator.

Type

VoiceRegion

afk_timeout

The timeout to get sent to the AFK channel.

Type

int

afk_channel

The channel that denotes the AFK channel. None if it doesn't exist.

Type

Optional[VoiceChannel]

id

The guild's ID.

Type

int

owner_id

The guild owner's ID. Use Guild.owner instead.

Type

int

unavailable

Indicates if the guild is unavailable. If this is True then the reliability of other attributes outside of Guild.id is slim and they might all be None. It is best to not do anything with the guild if it is unavailable.

Check the on_guild_unavailable() and on_guild_available() events.

Type

bool

max_presences

The maximum amount of presences for the guild.

Type

Optional[int]

max_members

The maximum amount of members for the guild.

注釈

This attribute is only available via Client.fetch_guild().

Type

Optional[int]

max_video_channel_users

The maximum amount of users in a video channel.

バージョン 1.4 で追加.

Type

Optional[int]

description

The guild's description.

Type

Optional[str]

mfa_level

Indicates the guild's two factor authorisation level. If this value is 0 then the guild does not require 2FA for their administrative members. If the value is 1 then they do.

Type

int

verification_level

The guild's verification level.

Type

VerificationLevel

explicit_content_filter

The guild's explicit content filter.

Type

ContentFilter

default_notifications

The guild's notification settings.

Type

NotificationLevel

features

A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord.

They are currently as follows:

  • ANIMATED_BANNER: Guild can upload an animated banner.

  • ANIMATED_ICON: Guild can upload an animated icon.

  • BANNER: Guild can upload and use a banner. (i.e. banner)

  • COMMERCE: Guild can sell things using store channels.

  • COMMUNITY: Guild is a community server.

  • DISCOVERABLE: Guild shows up in Server Discovery.

  • FEATURABLE: Guild is able to be featured in Server Discovery.

  • INVITE_SPLASH: Guild's invite page can have a special splash.

  • MEMBER_VERIFICATION_GATE_ENABLED: Guild has Membership Screening enabled.

  • MONETIZATION_ENABLED: Guild has enabled monetization.

  • MORE_EMOJI: Guild has increased custom emoji slots.

  • MORE_STICKERS: Guild has increased custom sticker slots.

  • NEWS: Guild can create news channels.

  • PARTNERED: Guild is a partnered server.

  • PREVIEW_ENABLED: Guild can be viewed before being accepted via Membership Screening.

  • PRIVATE_THREADS: Guild has access to create private threads.

  • ROLE_ICONS: Guild has access to set icon for roles.

  • SEVEN_DAY_THREAD_ARCHIVE: Guild has access to the seven day archive time for threads.

  • THREE_DAY_THREAD_ARCHIVE: Guild has access to the three day archive time for threads.

  • TICKETED_EVENTS_ENABLED: Guild has enabled ticketed events.

  • VANITY_URL: Guild can have a vanity invite URL (e.g. discord.gg/discord-api).

  • VERIFIED: Guild is a verified server.

  • VIP_REGIONS: Guild has VIP voice regions.

  • WELCOME_SCREEN_ENABLED: Guild has enabled the welcome screen.

Type

List[str]

premium_tier

The premium tier for this guild. Corresponds to "Nitro Server" in the official UI. The number goes from 0 to 3 inclusive.

Type

int

premium_subscription_count

The number of "boosts" this guild currently has.

Type

int

preferred_locale

The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.

Type

Optional[str]

nsfw_level

The guild's NSFW level.

バージョン 2.0 で追加.

Type

NSFWLevel

async for ... in fetch_members(*, limit=1000, after=None)

Retrieves an AsyncIterator that enables receiving the guild's members. In order to use this, Intents.members() must be enabled.

注釈

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

バージョン 1.3 で追加.

すべてのパラメータがオプションです。

パラメータ
  • limit (Optional[int]) -- The number of members to retrieve. Defaults to 1000. Pass None to fetch all members. Note that this is potentially slow.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) -- Retrieve members 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.

例外
列挙

Member -- The member with the member data parsed.

サンプル

使い方

async for member in guild.fetch_members(limit=150):
    print(member.name)

リストへフラット化

members = await guild.fetch_members(limit=150).flatten()
# members is now a list of Member...
async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)

Returns an AsyncIterator that enables receiving the guild's audit logs.

You must have the view_audit_log permission to use this.

サンプル

Getting the first 100 entries:

async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')

Getting entries for a specific action:

async for entry in guild.audit_logs(action=discord.AuditLogAction.ban):
    print(f'{entry.user} banned {entry.target}')

Getting entries made by a specific user:

entries = await guild.audit_logs(limit=None, user=guild.me).flatten()
await channel.send(f'I made {len(entries)} moderation actions.')
パラメータ
  • limit (Optional[int]) -- The number of entries to retrieve. If None retrieve all entries.

  • before (Union[abc.Snowflake, datetime.datetime]) -- Retrieve entries before this date or entry. 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 (Union[abc.Snowflake, datetime.datetime]) -- Retrieve entries after this date or entry. 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.

  • oldest_first (bool) -- If set to True, return entries in oldest->newest order. Defaults to True if after is specified, otherwise False.

  • user (abc.Snowflake) -- The moderator to filter entries from.

  • action (AuditLogAction) -- The action to filter with.

例外
  • Forbidden -- You are not allowed to fetch audit logs

  • HTTPException -- An error occurred while fetching the audit logs.

列挙

AuditLogEntry -- The audit log entry.

property channels: List[GuildChannel]

A list of channels that belongs to this guild.

Type

List[abc.GuildChannel]

property events: List[discord.guild_events.GuildScheduledEvent]

A list of guild events that belong to this guild.

Type

List[GuildScheduledEvent]

property threads: List[discord.threads.Thread]

A list of threads that you have permission to view.

バージョン 2.0 で追加.

Type

List[Thread]

property large: bool

Indicates if the guild is a 'large' guild.

A large guild is defined as having more than large_threshold count members, which for this library is set to the maximum of 250.

Type

bool

property voice_channels: List[discord.channel.VoiceChannel]

A list of voice channels that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.

Type

List[VoiceChannel]

property stage_channels: List[discord.channel.StageChannel]

A list of stage channels that belongs to this guild.

バージョン 1.7 で追加.

This is sorted by the position and are in UI order from top to bottom.

Type

List[StageChannel]

property me: discord.member.Member

Similar to Client.user except an instance of Member. This is essentially used to get the member version of yourself.

Type

Member

property voice_client: Optional[VoiceProtocol]

Returns the VoiceProtocol associated with this guild, if any.

Type

Optional[VoiceProtocol]

property text_channels: List[discord.channel.TextChannel]

A list of text channels that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.

Type

List[TextChannel]

property categories: List[discord.channel.CategoryChannel]

A list of categories that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.

Type

List[CategoryChannel]

by_category()

Returns every CategoryChannel and their associated channels.

These channels and categories are sorted in the official Discord UI order.

If the channels do not have a category, then the first element of the tuple is None.

戻り値

The categories and their associated channels.

戻り値の型

List[Tuple[Optional[CategoryChannel], List[abc.GuildChannel]]]

get_channel_or_thread(channel_id, /)

Returns a channel or thread with the given ID.

バージョン 2.0 で追加.

パラメータ

channel_id (int) -- The ID to search for.

戻り値

The returned channel or thread or None if not found.

戻り値の型

Optional[Union[Thread, abc.GuildChannel]]

get_channel(channel_id, /)

Returns a channel with the given ID.

注釈

This does not search for threads.

パラメータ

channel_id (int) -- The ID to search for.

戻り値

The returned channel or None if not found.

戻り値の型

Optional[abc.GuildChannel]

get_event(event_id, /)

Returns a event with the given ID.

バージョン 2.0 で追加.

パラメータ

event_id (int) -- The ID to search for.

戻り値

The returned event or None if not found.

戻り値の型

Optional[GuildScheduledEvent]

get_thread(thread_id, /)

Returns a thread with the given ID.

バージョン 2.0 で追加.

パラメータ

thread_id (int) -- The ID to search for.

戻り値

The returned thread or None if not found.

戻り値の型

Optional[Thread]

await fetch_event(event_id, /)

This function is a coroutine.

Returns a event with the given ID.

This function will request to the API directly, you might want to use get_event() instead.

バージョン 2.0 で追加.

パラメータ

event_id (int) -- The ID to search for.

戻り値

The requested scheduled event.

戻り値の型

GuildScheduledEvent

例外
  • Forbidden -- You do not have the proper permissions to get the event.

  • HTTPException -- An error occurred while fetching the event.

property system_channel: Optional[discord.channel.TextChannel]

Returns the guild's channel used for system messages.

If no channel is set, then this returns None.

Type

Optional[TextChannel]

property system_channel_flags: discord.flags.SystemChannelFlags

Returns the guild's system channel settings.

Type

SystemChannelFlags

property rules_channel: Optional[discord.channel.TextChannel]

Return's the guild's channel used for the rules. The guild must be a Community guild.

If no channel is set, then this returns None.

バージョン 1.3 で追加.

Type

Optional[TextChannel]

property public_updates_channel: Optional[discord.channel.TextChannel]

Return's the guild's channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.

If no channel is set, then this returns None.

バージョン 1.4 で追加.

Type

Optional[TextChannel]

property emoji_limit: int

The maximum number of emoji slots this guild has.

Type

int

property sticker_limit: int

The maximum number of sticker slots this guild has.

バージョン 2.0 で追加.

Type

int

property bitrate_limit: float

The maximum bitrate for voice channels this guild can have.

Type

float

property filesize_limit: int

The maximum number of bytes files can have when uploaded to this guild.

Type

int

property members: List[discord.member.Member]

A list of members that belong to this guild.

Type

List[Member]

get_member(user_id, /)

Returns a member with the given ID.

パラメータ

user_id (int) -- The ID to search for.

戻り値

The member or None if not found.

戻り値の型

Optional[Member]

property premium_subscribers: List[discord.member.Member]

A list of members who have "boosted" this guild.

Type

List[Member]

property roles: List[discord.role.Role]

Returns a list of the guild's roles in hierarchy order.

The first element of this list will be the lowest role in the hierarchy.

Type

List[Role]

get_role(role_id, /)

Returns a role with the given ID.

パラメータ

role_id (int) -- The ID to search for.

戻り値

The role or None if not found.

戻り値の型

Optional[Role]

property default_role: discord.role.Role

Gets the @everyone role that all members have by default.

Type

Role

property premium_subscriber_role: Optional[discord.role.Role]

Gets the premium subscriber role, AKA "boost" role, in this guild.

バージョン 1.6 で追加.

Type

Optional[Role]

property self_role: Optional[discord.role.Role]

Gets the role associated with this client's user, if any.

バージョン 1.6 で追加.

Type

Optional[Role]

property stage_instances: List[discord.stage_instance.StageInstance]

Returns a list of the guild's stage instances that are currently running.

バージョン 2.0 で追加.

Type

List[StageInstance]

get_stage_instance(stage_instance_id, /)

Returns a stage instance with the given ID.

バージョン 2.0 で追加.

パラメータ

stage_instance_id (int) -- The ID to search for.

戻り値

The stage instance or None if not found.

戻り値の型

Optional[StageInstance]

property owner: Optional[discord.member.Member]

The member that owns the guild.

Type

Optional[Member]

property icon: Optional[discord.asset.Asset]

Returns the guild's icon asset, if available.

Type

Optional[Asset]

property banner: Optional[discord.asset.Asset]

Returns the guild's banner asset, if available.

Type

Optional[Asset]

property splash: Optional[discord.asset.Asset]

Returns the guild's banner asset, if available.

バージョン 2.0 で変更: Can be animated if the guild have ANIMATED_BANNER feature.

Type

Optional[Asset]

property discovery_splash: Optional[discord.asset.Asset]

Returns the guild's discovery splash asset, if available.

Type

Optional[Asset]

property member_count: int

Returns the true member count regardless of it being loaded fully or not.

警告

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires Intents.members to be specified.

Type

int

property chunked: bool

Returns a boolean indicating if the guild is "chunked".

A chunked guild means that member_count is equal to the number of members stored in the internal members cache.

If this value returns False, then you should request for offline members.

Type

bool

property shard_id: int

Returns the shard ID for this guild if applicable.

Type

int

property created_at: datetime.datetime

Returns the guild's creation time in UTC.

Type

datetime.datetime

get_member_named(name, /)

Returns the first member found that matches the name provided.

The name can have an optional discriminator argument, e.g. "Jake#0001" or "Jake" will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.

If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.

If no member is found, None is returned.

パラメータ

name (str) -- The name of the member to lookup with an optional discriminator.

戻り値

The member in this guild with the associated name. If not found then None is returned.

戻り値の型

Optional[Member]

await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)

This function is a coroutine.

Creates a TextChannel for the guild.

Note that you need the manage_channels permission to create the channel.

The overwrites parameter can be used to create a 'secret' channel upon creation. This parameter expects a dict of overwrites with the target (either a Member or a Role) as the key and a PermissionOverwrite as the value.

注釈

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to edit() will be required to update the position of the channel in the channel list.

サンプル

Creating a basic channel:

channel = await guild.create_text_channel('cool-channel')

Creating a "secret" channel:

overwrites = {
    guild.default_role: discord.PermissionOverwrite(read_messages=False),
    guild.me: discord.PermissionOverwrite(read_messages=True)
}

channel = await guild.create_text_channel('secret', overwrites=overwrites)
パラメータ
  • name (str) -- The channel's name.

  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) -- A dict of target (either a role or a member) to PermissionOverwrite to apply upon creation of a channel. Useful for creating secret channels.

  • category (Optional[CategoryChannel]) -- The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.

  • position (int) -- The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

  • topic (str) -- The new channel's topic.

  • slowmode_delay (int) -- Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is 21600.

  • nsfw (bool) -- To mark the channel as NSFW or not.

  • reason (Optional[str]) -- The reason for creating this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

  • InvalidArgument -- The permission overwrite information is not in proper form.

戻り値

The channel that was just created.

戻り値の型

TextChannel

await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)

This function is a coroutine.

This is similar to create_text_channel() except makes a VoiceChannel instead.

パラメータ
  • name (str) -- The channel's name.

  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) -- A dict of target (either a role or a member) to PermissionOverwrite to apply upon creation of a channel. Useful for creating secret channels.

  • category (Optional[CategoryChannel]) -- The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.

  • position (int) -- The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

  • bitrate (int) -- The channel's preferred audio bitrate in bits per second.

  • user_limit (int) -- The channel's limit for number of members that can be in a voice channel.

  • rtc_region (Optional[VoiceRegion]) --

    The region for the voice channel's voice communication. A value of None indicates automatic voice region detection.

    バージョン 1.7 で追加.

  • video_quality_mode (VideoQualityMode) --

    The camera video quality for the voice channel's participants.

    バージョン 2.0 で追加.

  • reason (Optional[str]) -- The reason for creating this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

  • InvalidArgument -- The permission overwrite information is not in proper form.

戻り値

The channel that was just created.

戻り値の型

VoiceChannel

await create_stage_channel(name, *, topic, position=..., overwrites=..., category=None, reason=None)

This function is a coroutine.

This is similar to create_text_channel() except makes a StageChannel instead.

バージョン 1.7 で追加.

パラメータ
  • name (str) -- The channel's name.

  • topic (str) -- The new channel's topic.

  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) -- A dict of target (either a role or a member) to PermissionOverwrite to apply upon creation of a channel. Useful for creating secret channels.

  • category (Optional[CategoryChannel]) -- The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.

  • position (int) -- The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

  • reason (Optional[str]) -- The reason for creating this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

  • InvalidArgument -- The permission overwrite information is not in proper form.

戻り値

The channel that was just created.

戻り値の型

StageChannel

await create_category(name, *, overwrites=..., reason=None, position=...)

This function is a coroutine.

Same as create_text_channel() except makes a CategoryChannel instead.

注釈

The category parameter is not supported in this function since categories cannot have categories.

例外
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

  • InvalidArgument -- The permission overwrite information is not in proper form.

戻り値

The channel that was just created.

戻り値の型

CategoryChannel

await create_category_channel(name, *, overwrites=..., reason=None, position=...)

This function is a coroutine.

Same as create_text_channel() except makes a CategoryChannel instead.

注釈

The category parameter is not supported in this function since categories cannot have categories.

例外
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

  • InvalidArgument -- The permission overwrite information is not in proper form.

戻り値

The channel that was just created.

戻り値の型

CategoryChannel

await create_event(name, scheduled_start_time, *, description=..., scheduled_end_time=..., privacy_level=..., channel=..., entity_type=..., location=...)

This function is a coroutine.

Create a new guild event.

You must have the manage_events permission to create a guild event.

注釈

Another extra permissions is required for different type of entity_type.

If your entity type is GuildScheduledEventType.stage_instance, you must have the following extra permissions:

If your entity type is GuildScheduledEventType.voice, you must have the following extra permissions:

  • view_channel for channel associated with the event.

  • connect for channel associated with the event.

If your entity type is GuildScheduledEventType.external, you dont need any extra permissions.

バージョン 2.0 で追加.

パラメータ
  • name (str) -- The name of the event.

  • description (Optional[str]) -- The description of the event. Could be None for no description.

  • channel (Optional[abc.GuildChannel]) -- The channel where the event will be conducted.

  • privacy_level (Optional[GuildScheduledEventPrivacyLevel]) -- The event privacy level, same thing as StageInstance PrivacyLevel

  • scheduled_start_time (datetime.datetime) -- The scheduled start time, timezone must be UTC. If not it will be converted automatically.

  • scheduled_end_time (Optional[datetime.datetime]) -- The scheduled end time, timezone must be UTC. If not it will be converted automatically. It would be used if the event is a GuildScheduledEventType.location event.

  • entity_type (Optional[GuildScheduledEventType]) -- The entity_type or type for the event.

  • location (Optional[str]) -- The location for the event. It would be used if the event is a GuildScheduledEventType.location event.

例外
  • Forbidden -- You do not have permissions to create the guild event.

  • HTTPException -- Creating the guild event failed.

  • ValueError -- Validation error occurred.

戻り値

The newly updated guild event.

戻り値の型

GuildScheduledEvent

await create_scheduled_event(name, scheduled_start_time, *, description=..., scheduled_end_time=..., privacy_level=..., channel=..., entity_type=..., location=...)

This function is a coroutine.

Create a new guild event.

You must have the manage_events permission to create a guild event.

注釈

Another extra permissions is required for different type of entity_type.

If your entity type is GuildScheduledEventType.stage_instance, you must have the following extra permissions:

If your entity type is GuildScheduledEventType.voice, you must have the following extra permissions:

  • view_channel for channel associated with the event.

  • connect for channel associated with the event.

If your entity type is GuildScheduledEventType.external, you dont need any extra permissions.

バージョン 2.0 で追加.

パラメータ
  • name (str) -- The name of the event.

  • description (Optional[str]) -- The description of the event. Could be None for no description.

  • channel (Optional[abc.GuildChannel]) -- The channel where the event will be conducted.

  • privacy_level (Optional[GuildScheduledEventPrivacyLevel]) -- The event privacy level, same thing as StageInstance PrivacyLevel

  • scheduled_start_time (datetime.datetime) -- The scheduled start time, timezone must be UTC. If not it will be converted automatically.

  • scheduled_end_time (Optional[datetime.datetime]) -- The scheduled end time, timezone must be UTC. If not it will be converted automatically. It would be used if the event is a GuildScheduledEventType.location event.

  • entity_type (Optional[GuildScheduledEventType]) -- The entity_type or type for the event.

  • location (Optional[str]) -- The location for the event. It would be used if the event is a GuildScheduledEventType.location event.

例外
  • Forbidden -- You do not have permissions to create the guild event.

  • HTTPException -- Creating the guild event failed.

  • ValueError -- Validation error occurred.

戻り値

The newly updated guild event.

戻り値の型

GuildScheduledEvent

await leave()

This function is a coroutine.

Leaves the guild.

注釈

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

例外

HTTPException -- Leaving the guild failed.

await delete()

This function is a coroutine.

Deletes the guild. You must be the guild owner to delete the guild.

例外
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., region=..., afk_channel=..., owner=..., afk_timeout=..., default_notifications=..., verification_level=..., explicit_content_filter=..., vanity_code=..., system_channel=..., system_channel_flags=..., preferred_locale=..., rules_channel=..., public_updates_channel=...)

This function is a coroutine.

Edits the guild.

You must have the manage_guild permission to edit the guild.

バージョン 1.4 で変更: The rules_channel and public_updates_channel keyword-only parameters were added.

バージョン 2.0 で変更: The discovery_splash and community keyword-only parameters were added.

バージョン 2.0 で変更: The newly updated guild is returned.

パラメータ
  • name (str) -- The new name of the guild.

  • description (Optional[str]) -- The new description of the guild. Could be None for no description. This is only available to guilds that contain PUBLIC in Guild.features.

  • icon (bytes) -- A bytes-like object representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that contain ANIMATED_ICON in Guild.features. Could be None to denote removal of the icon.

  • banner (bytes) -- A bytes-like object representing the banner. Could be None to denote removal of the banner. This is only available to guilds that contain BANNER in Guild.features.

  • splash (bytes) -- A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could be None to denote removing the splash. This is only available to guilds that contain INVITE_SPLASH in Guild.features.

  • discovery_splash (bytes) -- A bytes-like object representing the discovery splash. Only PNG/JPEG supported. Could be None to denote removing the splash. This is only available to guilds that contain DISCOVERABLE in Guild.features.

  • community (bool) -- Whether the guild should be a Community guild. If set to True, both rules_channel and public_updates_channel parameters are required.

  • region (Union[str, VoiceRegion]) -- The new region for the guild's voice communication.

  • afk_channel (Optional[VoiceChannel]) -- The new channel that is the AFK channel. Could be None for no AFK channel.

  • afk_timeout (int) -- The number of seconds until someone is moved to the AFK channel.

  • owner (Member) -- The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this.

  • verification_level (VerificationLevel) -- The new verification level for the guild.

  • default_notifications (NotificationLevel) -- The new default notification level for the guild.

  • explicit_content_filter (ContentFilter) -- The new explicit content filter for the guild.

  • vanity_code (str) -- The new vanity code for the guild.

  • system_channel (Optional[TextChannel]) -- The new channel that is used for the system channel. Could be None for no system channel.

  • system_channel_flags (SystemChannelFlags) -- The new system channel settings to use with the new system channel.

  • preferred_locale (str) -- The new preferred locale for the guild. Used as the primary language in the guild. If set, this must be an ISO 639 code, e.g. en-US or ja or zh-CN.

  • rules_channel (Optional[TextChannel]) -- The new channel that is used for rules. This is only available to guilds that contain PUBLIC in Guild.features. Could be None for no rules channel.

  • public_updates_channel (Optional[TextChannel]) -- The new channel that is used for public updates from Discord. This is only available to guilds that contain PUBLIC in Guild.features. Could be None for no public updates channel.

  • reason (Optional[str]) -- The reason for editing this guild. Shows up on the audit log.

例外
  • Forbidden -- You do not have permissions to edit the guild.

  • HTTPException -- Editing the guild failed.

  • InvalidArgument -- The image format passed in to icon is invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.

戻り値

The newly updated guild. Note that this has the same limitations as mentioned in Client.fetch_guild() and may not have full data.

戻り値の型

Guild

await fetch_channels()

This function is a coroutine.

Retrieves all abc.GuildChannel that the guild has.

注釈

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

バージョン 1.2 で追加.

例外
戻り値

All channels in the guild.

戻り値の型

Sequence[abc.GuildChannel]

await active_threads()

This function is a coroutine.

Returns a list of active Thread that the client can access.

This includes both private and public threads.

バージョン 2.0 で追加.

例外

HTTPException -- The request to get the active threads failed.

戻り値

The active threads

戻り値の型

List[Thread]

await fetch_member(member_id, /)

This function is a coroutine.

Retrieves a Member from a guild ID, and a member ID.

注釈

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

パラメータ

member_id (int) -- The member's ID to fetch from.

例外
戻り値

The member from the member ID.

戻り値の型

Member

await fetch_ban(user)

This function is a coroutine.

Retrieves the BanEntry for a user.

You must have the ban_members permission to get this information.

パラメータ

user (abc.Snowflake) -- The user to get ban information from.

例外
  • Forbidden -- You do not have proper permissions to get the information.

  • NotFound -- This user is not banned.

  • HTTPException -- An error occurred while fetching the information.

戻り値

The BanEntry object for the specified user.

戻り値の型

BanEntry

await fetch_channel(channel_id, /)

This function is a coroutine.

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

注釈

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

バージョン 2.0 で追加.

例外
  • InvalidData -- An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.

  • HTTPException -- Retrieving the channel failed.

  • NotFound -- Invalid Channel ID.

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

戻り値

IDから取得したチャンネル。

戻り値の型

Union[abc.GuildChannel, Thread]

await fetch_events()

This function is a coroutine.

Retrieves all the events that are scheduled or ongoing from the guild as a list of GuildScheduledEvent.

バージョン 2.0 で追加.

例外

HTTPException -- Retrieving the events failed.

戻り値

A list of GuildScheduledEvent objects.

戻り値の型

List[GuildScheduledEvent]

await bans()

This function is a coroutine.

Retrieves all the users that are banned from the guild as a list of BanEntry.

You must have the ban_members permission to get this information.

例外
  • Forbidden -- You do not have proper permissions to get the information.

  • HTTPException -- An error occurred while fetching the information.

戻り値

A list of BanEntry objects.

戻り値の型

List[BanEntry]

await prune_members(*, days, compute_prune_count=True, roles=..., reason=None)

This function is a coroutine.

Prunes the guild from its inactive members.

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

You must have the kick_members permission to use this.

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

To prune members that have specific roles see the roles parameter.

バージョン 1.4 で変更: The roles keyword-only parameter was added.

パラメータ
  • days (int) -- The number of days before counting as inactive.

  • reason (Optional[str]) -- The reason for doing this action. Shows up on the audit log.

  • compute_prune_count (bool) -- Whether to compute the prune count. This defaults to True which makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this to False. If this is set to False, then this function will always return None.

  • roles (List[abc.Snowflake]) -- A list of abc.Snowflake that represent roles to include in the pruning process. If a member has a role that is not specified, they'll be excluded.

例外
戻り値

The number of members pruned. If compute_prune_count is False then this returns None.

戻り値の型

Optional[int]

await templates()

This function is a coroutine.

Gets the list of templates from this guild.

Requires manage_guild permissions.

バージョン 1.7 で追加.

例外

Forbidden -- You don't have permissions to get the templates.

戻り値

The templates for this guild.

戻り値の型

List[Template]

await webhooks()

This function is a coroutine.

Gets the list of webhooks from this guild.

Requires manage_webhooks permissions.

例外

Forbidden -- You don't have permissions to get the webhooks.

戻り値

The webhooks for this guild.

戻り値の型

List[Webhook]

await estimate_pruned_members(*, days, roles=...)

This function is a coroutine.

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

パラメータ
  • days (int) -- The number of days before counting as inactive.

  • roles (List[abc.Snowflake]) --

    A list of abc.Snowflake that represent roles to include in the estimate. If a member has a role that is not specified, they'll be excluded.

    バージョン 1.7 で追加.

例外
  • Forbidden -- You do not have permissions to prune members.

  • HTTPException -- An error occurred while fetching the prune members estimate.

  • InvalidArgument -- An integer was not passed for days.

戻り値

The number of members estimated to be pruned.

戻り値の型

int

await invites()

This function is a coroutine.

Returns a list of all active instant invites from the guild.

You must have the manage_guild permission to get this information.

例外
  • Forbidden -- You do not have proper permissions to get the information.

  • HTTPException -- An error occurred while fetching the information.

戻り値

The list of invites that are currently active.

戻り値の型

List[Invite]

await create_template(*, name, description=...)

This function is a coroutine.

Creates a template for the guild.

You must have the manage_guild permission to do this.

バージョン 1.7 で追加.

パラメータ
  • name (str) -- The name of the template.

  • description (str) -- The description of the template.

await create_integration(*, type, id)

This function is a coroutine.

Attaches an integration to the guild.

You must have the manage_guild permission to do this.

バージョン 1.4 で追加.

パラメータ
  • type (str) -- The integration type (e.g. Twitch).

  • id (int) -- The integration ID.

例外
  • Forbidden -- You do not have permission to create the integration.

  • HTTPException -- The account could not be found.

await integrations()

This function is a coroutine.

Returns a list of all integrations attached to the guild.

You must have the manage_guild permission to do this.

バージョン 1.4 で追加.

例外
  • Forbidden -- You do not have permission to create the integration.

  • HTTPException -- Fetching the integrations failed.

戻り値

The list of integrations that are attached to the guild.

戻り値の型

List[Integration]

await fetch_stickers()

This function is a coroutine.

Retrieves a list of all Stickers for the guild.

バージョン 2.0 で追加.

注釈

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

例外

HTTPException -- An error occurred fetching the stickers.

戻り値

The retrieved stickers.

戻り値の型

List[GuildSticker]

await fetch_sticker(sticker_id, /)

This function is a coroutine.

Retrieves a custom Sticker from the guild.

バージョン 2.0 で追加.

注釈

This method is an API call. For general usage, consider iterating over stickers instead.

パラメータ

sticker_id (int) -- The sticker's ID.

例外
  • NotFound -- The sticker requested could not be found.

  • HTTPException -- An error occurred fetching the sticker.

戻り値

The retrieved sticker.

戻り値の型

GuildSticker

await create_sticker(*, name, description=None, emoji, file, reason=None)

This function is a coroutine.

Creates a Sticker for the guild.

You must have manage_emojis_and_stickers permission to do this.

バージョン 2.0 で追加.

パラメータ
  • name (str) -- The sticker name. Must be at least 2 characters.

  • description (Optional[str]) -- The sticker's description. Can be None.

  • emoji (str) -- The name of a unicode emoji that represents the sticker's expression.

  • file (File) -- The file of the sticker to upload.

  • reason (str) -- The reason for creating this sticker. Shows up on the audit log.

例外
戻り値

The created sticker.

戻り値の型

GuildSticker

await delete_sticker(sticker, *, reason=None)

This function is a coroutine.

Deletes the custom Sticker from the guild.

You must have manage_emojis_and_stickers permission to do this.

バージョン 2.0 で追加.

パラメータ
  • sticker (abc.Snowflake) -- The sticker you are deleting.

  • reason (Optional[str]) -- The reason for deleting this sticker. Shows up on the audit log.

例外
  • Forbidden -- You are not allowed to delete stickers.

  • HTTPException -- An error occurred deleting the sticker.

await fetch_emojis()

This function is a coroutine.

Retrieves all custom Emojis from the guild.

注釈

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

例外

HTTPException -- An error occurred fetching the emojis.

戻り値

The retrieved emojis.

戻り値の型

List[Emoji]

await fetch_emoji(emoji_id, /)

This function is a coroutine.

Retrieves a custom Emoji from the guild.

注釈

This method is an API call. For general usage, consider iterating over emojis instead.

パラメータ

emoji_id (int) -- The emoji's ID.

例外
  • NotFound -- The emoji requested could not be found.

  • HTTPException -- An error occurred fetching the emoji.

戻り値

The retrieved emoji.

戻り値の型

Emoji

await create_custom_emoji(*, name, image, roles=..., reason=None)

This function is a coroutine.

Creates a custom Emoji for the guild.

There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the MORE_EMOJI feature which extends the limit to 200.

You must have the manage_emojis permission to do this.

パラメータ
  • 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.

  • roles (List[Role]) -- A list of Roles that can use this emoji. Leave empty to make it available to everyone.

  • reason (Optional[str]) -- The reason for creating this emoji. Shows up on the audit log.

例外
戻り値

The created emoji.

戻り値の型

Emoji

await delete_emoji(emoji, *, reason=None)

This function is a coroutine.

Deletes the custom Emoji from the guild.

You must have manage_emojis permission to do this.

パラメータ
  • emoji (abc.Snowflake) -- The emoji you are deleting.

  • reason (Optional[str]) -- The reason for deleting this emoji. Shows up on the audit log.

例外
await fetch_roles()

This function is a coroutine.

Retrieves all Role that the guild has.

注釈

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

バージョン 1.3 で追加.

例外

HTTPException -- Retrieving the roles failed.

戻り値

All roles in the guild.

戻り値の型

List[Role]

await create_role(*, name=..., permissions=..., color=..., colour=..., icon=..., emoji_unicode=..., hoist=..., mentionable=..., reason=None)

This function is a coroutine.

Creates a Role for the guild.

All fields are optional.

You must have the manage_roles permission to do this.

バージョン 1.6 で変更: Can now pass int to colour keyword-only parameter.

バージョン 2.0 で変更: Added icon and emoji_unicode parameter.

パラメータ
  • name (str) -- The role name. Defaults to 'new role'.

  • permissions (Permissions) -- The permissions to have. Defaults to no permissions.

  • colour (Union[Colour, int]) -- The colour for the role. Defaults to Colour.default(). This is aliased to color as well.

  • icon (Optional[bytes]) --

    A bytes object representing the role icon.

    バージョン 2.0 で追加.

  • emoji_unicode (Optional[str]) --

    The unicode value of the new role to change to.

    バージョン 2.0 で追加.

  • hoist (bool) -- Indicates if the role should be shown separately in the member list. Defaults to False.

  • mentionable (bool) -- Indicates if the role should be mentionable by others. Defaults to False.

  • reason (Optional[str]) -- The reason for creating this role. Shows up on the audit log.

例外
戻り値

The newly created role.

戻り値の型

Role

await edit_role_positions(positions, *, reason=None)

This function is a coroutine.

Bulk edits a list of Role in the guild.

You must have the manage_roles permission to do this.

バージョン 1.4 で追加.

Example:

positions = {
    bots_role: 1, # penultimate role
    tester_role: 2,
    admin_role: 6
}

await guild.edit_role_positions(positions=positions)
パラメータ
  • positions -- A dict of Role to int to change the positions of each given role.

  • reason (Optional[str]) -- The reason for editing the role positions. Shows up on the audit log.

例外
戻り値

A list of all the roles in the guild.

戻り値の型

List[Role]

await kick(user, *, reason=None)

This function is a coroutine.

Kicks a user from the guild.

The user must meet the abc.Snowflake abc.

You must have the kick_members permission to do this.

パラメータ
  • user (abc.Snowflake) -- The user to kick from their guild.

  • reason (Optional[str]) -- The reason the user got kicked.

例外
await ban(user, *, reason=None, delete_message_days=1)

This function is a coroutine.

Bans a user from the guild.

The user must meet the abc.Snowflake abc.

You must have the ban_members permission to do this.

パラメータ
  • user (abc.Snowflake) -- The user to ban from their guild.

  • delete_message_days (int) -- The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 7.

  • reason (Optional[str]) -- The reason the user got banned.

例外
await unban(user, *, reason=None)

This function is a coroutine.

Unbans a user from the guild.

The user must meet the abc.Snowflake abc.

You must have the ban_members permission to do this.

パラメータ
  • user (abc.Snowflake) -- The user to unban.

  • reason (Optional[str]) -- The reason for doing this action. Shows up on the audit log.

例外
await vanity_invite()

This function is a coroutine.

Returns the guild's special vanity invite.

The guild must have VANITY_URL in features.

You must have the manage_guild permission to use this as well.

例外
  • Forbidden -- You do not have the proper permissions to get this.

  • HTTPException -- Retrieving the vanity invite failed.

戻り値

The special vanity invite. If None then the guild does not have a vanity invite set.

戻り値の型

Optional[Invite]

await welcome_screen()

This function is a coroutine.

Returns the guild's welcome screen.

The guild must have COMMUNITY in features.

You must have the manage_guild permission to use this as well.

バージョン 2.0 で追加.

例外
  • Forbidden -- You do not have the proper permissions to get this.

  • HTTPException -- Retrieving the vanity invite failed.

戻り値

The welcome screen.

戻り値の型

WelcomeScreen

await edit_welcome_screen(**kwargs)

This function is a coroutine.

A shorthand method of WelcomeScreen.edit without needing to fetch the welcome screen beforehand.

You must have the manage_guild permission in the guild to do this.

注釈

Welcome channels can only accept custom emojis if premium_tier is level 2 or above.

パラメータ
  • enabled (bool) -- Should we enable the welcome screen of not.

  • channels (List[WelcomeChannel]) -- The channels to use for the welcome screen.

  • description (str) -- The description of the welcome screen.

  • reason (Optional[str]) -- The reason for editing the welcome screen. Shows up on the audit log.

例外
await widget()

This function is a coroutine.

Returns the widget of the guild.

注釈

この情報を取得するためには、ギルドのウィジェットを有効化しておく必要があります。

例外
戻り値

ギルドのウィジェット。

戻り値の型

Widget

await edit_widget(*, enabled=..., channel=...)

This function is a coroutine.

Edits the widget of the guild.

You must have the manage_guild permission to use this

バージョン 2.0 で追加.

パラメータ
  • enabled (bool) -- Whether to enable the widget for the guild.

  • channel (Optional[Snowflake]) -- The new widget channel. None removes the widget channel.

例外
await chunk(*, cache=True)

This function is a coroutine.

Requests all members that belong to this guild. In order to use this, Intents.members() must be enabled.

This is a websocket operation and can be slow.

バージョン 1.5 で追加.

パラメータ

cache (bool) -- Whether to cache the members as well.

例外

ClientException -- The members intent is not enabled.

await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)

This function is a coroutine.

Request members that belong to this guild whose username starts with the query given.

This is a websocket operation and can be slow.

バージョン 1.3 で追加.

パラメータ
  • query (Optional[str]) -- The string that the username's start with.

  • limit (int) -- The maximum number of members to send back. This must be a number between 5 and 100.

  • presences (bool) --

    Whether to request for presences to be provided. This defaults to False.

    バージョン 1.6 で追加.

  • cache (bool) -- Whether to cache the members internally. This makes operations such as get_member() work for those that matched.

  • user_ids (Optional[List[int]]) --

    List of user IDs to search for. If the user ID is not in the guild then it won't be returned.

    バージョン 1.4 で追加.

例外
戻り値

The list of members that have matched the query.

戻り値の型

List[Member]

await change_voice_state(*, channel, self_mute=False, self_deaf=False)

This function is a coroutine.

Changes client's voice state in the guild.

バージョン 1.4 で追加.

パラメータ
  • channel (Optional[VoiceChannel]) -- Channel the client wants to join. Use None to disconnect.

  • self_mute (bool) -- Indicates if the client should be self-muted.

  • self_deaf (bool) -- Indicates if the client should be self-deafened.

class discord.BanEntry

A namedtuple which represents a ban returned from bans().

reason

The reason this user was banned.

Type

Optional[str]

user

The User that was banned.

Type

User

GuildScheduledEvent

警告

Event is not fetched on startup, you need to fetch it manually for your guild via Client.fetch_guild_events().

class discord.GuildScheduledEvent

Represents a Discord guild event.

バージョン 2.0 で追加.

x == y

Checks if two events are equal.

x != y

Checks if two events are not equal.

hash(x)

Returns the event's hash.

str(x)

Returns the event's name.

id

The event's ID.

Type

int

name

The event's name.

Type

str

description

The event's description.

Type

Optional[str]

type

The guild event type.

Type

GuildScheduledEventType

start_time

The event's scheduled start time.

Type

datetime.datetime

end_time

The event's scheduled end time.

Type

Optional[datetime.datetime]

status

The event's current status.

Type

GuildScheduledEventStatus

privacy_level

The event's privacy level.

Type

GuildScheduledEventPrivacyLevel

guild

The guild the event belongs to.

Type

Guild

async for ... in fetch_members(*, limit=100, before=None, after=None)

Retrieves an AsyncIterator that enables receiving your guild event members.

注釈

If the member joining the event is not in the guild, it will return User instead of Member.

注釈

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

サンプル

使い方

async for member in event.fetch_members(limit=100):
    print(member.name)

リストへフラット化

members = await event.fetch_members(limit=100).flatten()
# members is now a list of User or Member...

すべてのパラメータがオプションです。

パラメータ
  • limit (Optional[int]) -- The number of members to retrieve. If None, it retrieves every members you have access to. Note, however, that this would make it a slow operation. Defaults to 100, maximum is ``100`.

  • before (Union[abc.Snowflake, datetime.datetime]) -- Retrieves members before this date or object (user id). 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 (Union[abc.Snowflake, datetime.datetime]) -- Retrieve members after this date or object (user id). 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.

例外
  • Forbidden -- You do not have permissions to fetch the members.

  • HTTPException -- Fetching the members failed.

列挙

Union[Member, User] -- The member or user that are attending the event.

property channel: Optional[GuildChannel]

The channel associated with this event, can be None.

Type

Optional[abc.GuildChannel]

property image: Optional[discord.asset.Asset]

The image associated with the event, can be None.

Type

Optional[Asset]

property members: List[Union[Member, User]]

List of user that subscribed to the event.

Type

List[Union[Member, User]]

get_member(user_id, /)

Returns a member with the given ID.

パラメータ

user_id (int) -- The ID to search for.

戻り値

The member or None if not found.

戻り値の型

Optional[Union[Member, User]]

property member_count: Optional[int]

Total member that are subscribed to the event

Type

Optional[int]

property location: Optional[str]

Location of the event

Type

Optional[str]

property metadata: discord.guild_events.GuildEventEntityMetadata

Get the entity metadata of the event.

This attribute or class will contains:

Not all of the fields will be filled, it will depends on what the event type is.

Type

GuildEventEntityMetadata

property creator: Optional[Union[Member, User]]

The user that created the event

Type

Optional[Union[Member, User]]

await edit(*, name=..., description=..., channel=..., privacy_level=..., scheduled_start_time=..., scheduled_end_time=..., entity_type=..., location=...)

This function is a coroutine.

Edits the guild event.

You must have the manage_events permission to edit the guild event.

パラメータ
  • name (str) -- The new name of the event.

  • description (Optional[str]) -- The new description of the event. Could be None for no description.

  • channel (Optional[abc.GuildChannel]) -- The channel where the event will be conducted.

  • privacy_level (Optional[GuildScheduledEventPrivacyLevel]) -- The event privacy level.

  • scheduled_start_time (Optional[datetime.datetime]) -- The new scheduled start time, timezone must be UTC. If not it will be converted automatically.

  • scheduled_end_time (Optional[datetime.datetime]) -- The new scheduled end time, timezone must be UTC. If not it will be converted automatically. It would be used if the event is a GuildScheduledEventType.location event.

  • entity_type (Optional[GuildScheduledEventType]) -- The new entity type or type for the event.

  • location (Optional[str]) -- The new location for the event. It would be used if the event is a GuildScheduledEventType.location event.

例外
  • Forbidden -- You do not have permissions to edit the guild event.

  • HTTPException -- Editing the guild event failed.

戻り値

The newly updated guild event.

戻り値の型

GuildScheduledEvent

await delete()

This function is a coroutine.

Deletes the guild event.

You must have the manage_events permission to be able to delete the guild event.

例外
  • Forbidden -- You do not have permissions to delete the guild event.

  • HTTPException -- Deleting the guild event failed.

Attributes
class discord.GuildEventEntityMetadata

Represents metadata about a guild event.

location

The location of the event, this will be filled if the event type is GuildScheduledEventType.location event.

Type

Optional[str]

Integration

class discord.Integration

Represents a guild integration.

バージョン 1.4 で追加.

id

The integration ID.

Type

int

name

The integration name.

Type

str

guild

The guild of the integration.

Type

Guild

type

The integration type (i.e. Twitch).

Type

str

enabled

Whether the integration is currently enabled.

Type

bool

account

The account linked to this integration.

Type

IntegrationAccount

user

The user that added this integration.

Type

User

await delete(*, reason=None)

This function is a coroutine.

Deletes the integration.

You must have the manage_guild permission to do this.

パラメータ

reason (str) --

The reason the integration was deleted. Shows up on the audit log.

バージョン 2.0 で追加.

例外
  • Forbidden -- You do not have permission to delete the integration.

  • HTTPException -- Deleting the integration failed.

class discord.IntegrationAccount

Represents an integration account.

バージョン 1.4 で追加.

id

The account ID.

Type

str

name

The account name.

Type

str

class discord.BotIntegration

Represents a bot integration on discord.

バージョン 2.0 で追加.

id

The integration ID.

Type

int

name

The integration name.

Type

str

guild

The guild of the integration.

Type

Guild

type

The integration type (i.e. Twitch).

Type

str

enabled

Whether the integration is currently enabled.

Type

bool

user

The user that added this integration.

Type

User

account

The integration account information.

Type

IntegrationAccount

application

The application tied to this integration.

Type

IntegrationApplication

class discord.IntegrationApplication

Represents an application for a bot integration.

バージョン 2.0 で追加.

id

The ID for this application.

Type

int

name

The application's name.

Type

str

icon

The application's icon hash.

Type

Optional[str]

description

The application's description. Can be an empty string.

Type

str

summary

The summary of the application. Can be an empty string.

Type

str

user

The bot user on this application.

Type

Optional[User]

class discord.StreamIntegration

Represents a stream integration for Twitch or YouTube.

バージョン 2.0 で追加.

id

The integration ID.

Type

int

name

The integration name.

Type

str

guild

The guild of the integration.

Type

Guild

type

The integration type (i.e. Twitch).

Type

str

enabled

Whether the integration is currently enabled.

Type

bool

syncing

Where the integration is currently syncing.

Type

bool

enable_emoticons

Whether emoticons should be synced for this integration (currently twitch only).

Type

Optional[bool]

expire_behaviour

The behaviour of expiring subscribers. Aliased to expire_behavior as well.

Type

ExpireBehaviour

expire_grace_period

The grace period (in days) for expiring subscribers.

Type

int

user

The user for the integration.

Type

User

account

The integration account information.

Type

IntegrationAccount

synced_at

An aware UTC datetime representing when the integration was last synced.

Type

datetime.datetime

property expire_behavior: discord.enums.ExpireBehaviour

An alias for expire_behaviour.

Type

ExpireBehaviour

property role: Optional[Role]

Optional[Role] The role which the integration uses for subscribers.

await edit(*, expire_behaviour=..., expire_grace_period=..., enable_emoticons=...)

This function is a coroutine.

Edits the integration.

You must have the manage_guild permission to do this.

パラメータ
  • expire_behaviour (ExpireBehaviour) -- The behaviour when an integration subscription lapses. Aliased to expire_behavior as well.

  • expire_grace_period (int) -- The period (in days) where the integration will ignore lapsed subscriptions.

  • enable_emoticons (bool) -- Where emoticons should be synced for this integration (currently twitch only).

例外
await sync()

This function is a coroutine.

Syncs the integration.

You must have the manage_guild permission to do this.

例外
  • Forbidden -- You do not have permission to sync the integration.

  • HTTPException -- Syncing the integration failed.

Interaction

class discord.Interaction

Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

バージョン 2.0 で追加.

id

The interaction's ID.

Type

int

type

The interaction type.

Type

InteractionType

guild_id

The guild ID the interaction was sent from.

Type

Optional[int]

channel_id

The channel ID the interaction was sent from.

Type

Optional[int]

application_id

The application ID that the interaction was for.

Type

int

user

The user or member that sent the interaction.

Type

Optional[Union[User, Member]]

message

The message that sent this interaction.

Type

Optional[Message]

token

The token to continue the interaction. These are valid for 15 minutes.

Type

str

data

The raw interaction data.

Type

dict

property guild: Optional[Guild]

The guild the interaction was sent from.

Type

Optional[Guild]

channel

The channel the interaction was sent from.

Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.

Type

Optional[Union[abc.GuildChannel, PartialMessageable, Thread]]

property permissions: discord.permissions.Permissions

The resolved permissions of the member in the channel, including overwrites.

In a non-guild context where this doesn't apply, an empty permissions object is returned.

Type

Permissions

response

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

Type

InteractionResponse

followup

Returns the follow up webhook for follow up interactions.

Type

Webhook

await original_message()

This function is a coroutine.

Fetches the original interaction response message associated with the interaction.

If the interaction response was InteractionResponse.send_message() then this would return the message that was sent using that response. Otherwise, this would return the message that triggered the interaction.

Repeated calls to this will return a cached value.

例外
戻り値

The original interaction response message.

戻り値の型

InteractionMessage

await edit_original_message(*, content=..., embeds=..., embed=..., file=..., files=..., view=..., allowed_mentions=None)

This function is a coroutine.

Edits the original interaction response message.

This is a lower level interface to InteractionMessage.edit() in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.

パラメータ
  • content (Optional[str]) -- The content to edit the message with or None to clear it.

  • embeds (List[Embed]) -- A list of embeds to edit the message with.

  • embed (Optional[Embed]) -- The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • file (File) -- The file to upload. This cannot be mixed with files parameter.

  • files (List[File]) -- A list of files to send with the content. This cannot be mixed with the file parameter.

  • allowed_mentions (AllowedMentions) -- Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

  • view (Optional[View]) -- The updated view to update this message with. If None is passed then the view is removed.

例外
  • HTTPException -- Editing the message failed.

  • Forbidden -- Edited a message that is not yours.

  • TypeError -- You specified both embed and embeds or file and files

  • ValueError -- The length of embeds was invalid.

戻り値

The newly edited message.

戻り値の型

InteractionMessage

await delete_original_message()

This function is a coroutine.

Deletes the original interaction response message.

This is a lower level interface to InteractionMessage.delete() in case you do not want to fetch the message and save an HTTP request.

例外

InteractionResponse

Methods
class discord.InteractionResponse

Represents a Discord interaction response.

This type can be accessed through Interaction.response.

バージョン 2.0 で追加.

is_done()

bool: Indicates whether an interaction response has been done before.

An interaction can only be responded to once.

await defer(*, ephemeral=False)

This function is a coroutine.

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

パラメータ

ephemeral (bool) -- Indicates whether the deferred message will eventually be ephemeral. This only applies for interactions of type InteractionType.application_command.

例外
await pong()

This function is a coroutine.

Pongs the ping interaction.

This should rarely be used.

例外
await send_message(content=None, *, embed=..., embeds=..., view=..., tts=False, ephemeral=False)

This function is a coroutine.

Responds to this interaction by sending a message.

パラメータ
  • content (Optional[str]) -- The content of the message to send.

  • embeds (List[Embed]) -- A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed parameter.

  • embed (Embed) -- The rich embed for the content to send. This cannot be mixed with embeds parameter.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • view (discord.ui.View) -- The view to send with the message.

  • ephemeral (bool) -- Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.

例外
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=...)

This function is a coroutine.

Responds to this interaction by editing the original message of a component interaction.

パラメータ
  • content (Optional[str]) -- The new content to replace the message with. None removes the content.

  • embeds (List[Embed]) -- A list of embeds to edit the message with.

  • embed (Optional[Embed]) -- The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • attachments (List[Attachment]) -- A list of attachments to keep in the message. If [] is passed then all attachments are removed.

  • view (Optional[View]) -- The updated view to update this message with. If None is passed then the view is removed.

例外

InteractionMessage

Methods
class discord.InteractionMessage

Represents the original interaction response message.

This allows you to edit or delete the message associated with the interaction response. To retrieve this object see Interaction.original_message().

This inherits from discord.Message with changes to edit() and delete() to work.

バージョン 2.0 で追加.

await edit(content=..., embeds=..., embed=..., file=..., files=..., view=..., allowed_mentions=None)

This function is a coroutine.

Edits the message.

パラメータ
  • content (Optional[str]) -- The content to edit the message with or None to clear it.

  • embeds (List[Embed]) -- A list of embeds to edit the message with.

  • embed (Optional[Embed]) -- The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • file (File) -- The file to upload. This cannot be mixed with files parameter.

  • files (List[File]) -- A list of files to send with the content. This cannot be mixed with the file parameter.

  • allowed_mentions (AllowedMentions) -- Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

  • view (Optional[View]) -- The updated view to update this message with. If None is passed then the view is removed.

例外
  • HTTPException -- Editing the message failed.

  • Forbidden -- Edited a message that is not yours.

  • TypeError -- You specified both embed and embeds or file and files

  • ValueError -- The length of embeds was invalid.

戻り値

The newly edited message.

戻り値の型

InteractionMessage

await delete(*, delay=None)

This function is a coroutine.

Deletes the message.

パラメータ

delay (Optional[float]) -- If provided, the number of seconds to wait before deleting the message. The waiting is done in the background and deletion failures are ignored.

例外
  • Forbidden -- You do not have proper permissions to delete the message.

  • NotFound -- The message was deleted already.

  • HTTPException -- Deleting the message failed.

Member

class discord.Member

Represents a Discord member to a Guild.

This implements a lot of the functionality of User.

x == y

Checks if two members are equal. Note that this works with User instances too.

x != y

Checks if two members are not equal. Note that this works with User instances too.

hash(x)

Returns the member's hash.

str(x)

Returns the member's name with the discriminator.

joined_at

An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.

Type

Optional[datetime.datetime]

activities

The activities that the user is currently doing.

注釈

Due to a Discord API limitation, a user's Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

Type

Tuple[Union[BaseActivity, Spotify]]

guild

The guild that the member belongs to.

Type

Guild

nick

The guild specific nickname of the user.

Type

Optional[str]

pending

Whether the member is pending member verification.

バージョン 1.6 で追加.

Type

bool

premium_since

An aware datetime object that specifies the date and time in UTC when the member used their "Nitro boost" on the guild, if available. This could be None.

Type

Optional[datetime.datetime]

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Returns an AsyncIterator that enables receiving the destination's message history.

You must have read_message_history permissions to use this.

サンプル

使い方

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

すべてのパラメータがオプションです。

パラメータ
  • limit (Optional[int]) -- The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages before this date or message. 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 (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. 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.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

  • oldest_first (Optional[bool]) -- If set to True, return messages in oldest->newest order. Defaults to True if after is specified, otherwise False.

例外
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

列挙

Message -- The message with the message data parsed.

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

注釈

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property name

Equivalent to User.name

property id

Equivalent to User.id

property discriminator

Equivalent to User.discriminator

property bot

Equivalent to User.bot

property system

Equivalent to User.system

property created_at

Equivalent to User.created_at

property default_avatar

Equivalent to User.default_avatar

property avatar

Equivalent to User.avatar

property dm_channel

Equivalent to User.dm_channel

await create_dm()

This function is a coroutine.

このユーザーと DMChannel を作ります。

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

戻り値

The channel that was created.

戻り値の型

DMChannel

property mutual_guilds

Equivalent to User.mutual_guilds

property public_flags

Equivalent to User.public_flags

property banner

Equivalent to User.banner

property accent_color

Equivalent to User.accent_color

property accent_colour

Equivalent to User.accent_colour

property raw_status: str

The member's overall status as a string value.

バージョン 1.5 で追加.

Type

str

property status: discord.enums.Status

The member's overall status. If the value is unknown, then it will be a str instead.

Type

Status

property mobile_status: discord.enums.Status

The member's status on a mobile device, if applicable.

Type

Status

property desktop_status: discord.enums.Status

The member's status on the desktop client, if applicable.

Type

Status

property web_status: discord.enums.Status

The member's status on the web client, if applicable.

Type

Status

is_on_mobile()

bool: A helper function that determines if a member is active on a mobile device.

property colour: discord.colour.Colour

A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of Colour.default() is returned.

There is an alias for this named color.

Type

Colour

property color: discord.colour.Colour

A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of Colour.default() is returned.

There is an alias for this named colour.

Type

Colour

property roles: List[Role]

A list of Role that the member belongs to. Note that the first element of this list is always the default '@everyone' role.

These roles are sorted by their position in the role hierarchy.

Type

List[Role]

property mention: str

Returns a string that allows you to mention the member.

Type

str

property display_name: str

Returns the user's display name.

通常であれば、これはユーザー名がそのまま返りますが、ギルドにてニックネームを設定している場合は、代替としてニックネームが返ります。

Type

str

property display_avatar: discord.asset.Asset

Returns the member's display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

バージョン 2.0 で追加.

Type

Asset

property guild_avatar: Optional[discord.asset.Asset]

Returns an Asset for the guild avatar the member has. If unavailable, None is returned.

バージョン 2.0 で追加.

Type

Optional[Asset]

property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]

Returns the primary activity the user is currently doing. Could be None if no activity is being done.

注釈

Due to a Discord API limitation, this may be None if the user is listening to a song on Spotify with a title longer than 128 characters. See GH-1738 for more information.

注釈

A user may have multiple activities, these can be accessed under activities.

Type

Optional[Union[BaseActivity, Spotify]]

mentioned_in(message)

Checks if the member is mentioned in the specified message.

パラメータ

message (Message) -- メンションが含まれているかを確認するメッセージ。

戻り値

Indicates if the member is mentioned in the message.

戻り値の型

bool

property top_role: Role

Returns the member's highest role.

This is useful for figuring where a member stands in the role hierarchy chain.

Type

Role

property guild_permissions: discord.permissions.Permissions

Returns the member's guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use abc.GuildChannel.permissions_for().

This does take into consideration guild ownership and the administrator implication.

Type

Permissions

property voice: Optional[discord.member.VoiceState]

Returns the member's current voice state.

Type

Optional[VoiceState]

await ban(*, delete_message_days=1, reason=None)

This function is a coroutine.

Bans this member. Equivalent to Guild.ban().

await unban(*, reason=None)

This function is a coroutine.

Unbans this member. Equivalent to Guild.unban().

await kick(*, reason=None)

This function is a coroutine.

Kicks this member. Equivalent to Guild.kick().

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., reason=None)

This function is a coroutine.

Edits the member's data.

Depending on the parameter passed, this requires different permissions listed below:

すべてのパラメータがオプションです。

バージョン 1.1 で変更: Can now pass None to voice_channel to kick a member from voice.

バージョン 2.0 で変更: The newly member is now optionally returned, if applicable.

パラメータ
  • nick (Optional[str]) -- The member's new nickname. Use None to remove the nickname.

  • mute (bool) -- Indicates if the member should be guild muted or un-muted.

  • deafen (bool) -- Indicates if the member should be guild deafened or un-deafened.

  • suppress (bool) --

    Indicates if the member should be suppressed in stage channels.

    バージョン 1.7 で追加.

  • roles (List[Role]) -- The member's new list of roles. This replaces the roles.

  • voice_channel (Optional[VoiceChannel]) -- The voice channel to move the member to. Pass None to kick them from voice.

  • reason (Optional[str]) -- The reason for editing this member. Shows up on the audit log.

例外
  • Forbidden -- You do not have the proper permissions to the action requested.

  • HTTPException -- The operation failed.

戻り値

The newly updated member, if applicable. This is only returned when certain fields are updated.

戻り値の型

Optional[Member]

await request_to_speak()

This function is a coroutine.

Request to speak in the connected channel.

Only applies to stage channels.

注釈

Requesting members that are not the client is equivalent to edit providing suppress as False.

バージョン 1.7 で追加.

例外
  • Forbidden -- You do not have the proper permissions to the action requested.

  • HTTPException -- The operation failed.

await move_to(channel, *, reason=None)

This function is a coroutine.

Moves a member to a new voice channel (they must be connected first).

You must have the move_members permission to use this.

This raises the same exceptions as edit().

バージョン 1.1 で変更: Can now pass None to kick a member from voice.

パラメータ
  • channel (Optional[VoiceChannel]) -- The new voice channel to move the member to. Pass None to kick them from voice.

  • reason (Optional[str]) -- The reason for doing this action. Shows up on the audit log.

await add_roles(*roles, reason=None, atomic=True)

This function is a coroutine.

Gives the member a number of Roles.

You must have the manage_roles permission to use this, and the added Roles must appear lower in the list of roles than the highest role of the member.

パラメータ
  • *roles (abc.Snowflake) -- An argument list of abc.Snowflake representing a Role to give to the member.

  • reason (Optional[str]) -- The reason for adding these roles. Shows up on the audit log.

  • atomic (bool) -- Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.

例外
await remove_roles(*roles, reason=None, atomic=True)

This function is a coroutine.

Removes Roles from this member.

You must have the manage_roles permission to use this, and the removed Roles must appear lower in the list of roles than the highest role of the member.

パラメータ
  • *roles (abc.Snowflake) -- An argument list of abc.Snowflake representing a Role to remove from the member.

  • reason (Optional[str]) -- The reason for removing these roles. Shows up on the audit log.

  • atomic (bool) -- Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.

例外
await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

パラメータ

id (int) -- The message ID to look for.

例外
  • NotFound -- The specified message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

戻り値

The message asked for.

戻り値の型

Message

get_role(role_id, /)

Returns a role with the given ID from roles which the member has.

バージョン 2.0 で追加.

パラメータ

role_id (int) -- The ID to search for.

戻り値

The role or None if not found in the member's roles.

戻り値の型

Optional[Role]

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

注釈

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

例外

HTTPException -- Retrieving the pinned messages failed.

戻り値

The messages that are currently pinned.

戻り値の型

List[Message]

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

パラメータ
  • content (Optional[str]) -- The content of the message to send.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • embed (Embed) -- The rich embed for the content.

  • file (File) -- The file to upload.

  • files (List[File]) -- A list of files to upload. Must be a maximum of 10.

  • nonce (int) -- The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) -- If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) --

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    バージョン 1.4 で追加.

  • reference (Union[Message, MessageReference, PartialMessage]) --

    A reference to the Message to which you are replying, this can be created using to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    バージョン 1.6 で追加.

  • mention_author (Optional[bool]) --

    If set, overrides the replied_user attribute of allowed_mentions.

    バージョン 1.6 で追加.

  • view (discord.ui.View) -- A Discord UI View to add to the message.

  • embeds (List[Embed]) --

    A list of embeds to upload. Must be a maximum of 10.

    バージョン 2.0 で追加.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) --

    A list of stickers to upload. Must be a maximum of 3.

    バージョン 2.0 で追加.

例外
戻り値

The message that was sent.

戻り値の型

Message

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

Spotify

class discord.Spotify

Represents a Spotify listening activity from Discord. This is a special case of Activity that makes it easier to work with the Spotify integration.

x == y

Checks if two activities are equal.

x != y

Checks if two activities are not equal.

hash(x)

Returns the activity's hash.

str(x)

Returns the string 'Spotify'.

property type: discord.enums.ActivityType

Returns the activity's type. This is for compatibility with Activity.

It always returns ActivityType.listening.

Type

ActivityType

property created_at: Optional[datetime.datetime]

When the user started listening in UTC.

バージョン 1.3 で追加.

Type

Optional[datetime.datetime]

property colour: discord.colour.Colour

Returns the Spotify integration colour, as a Colour.

There is an alias for this named color

Type

Colour

property color: discord.colour.Colour

Returns the Spotify integration colour, as a Colour.

There is an alias for this named colour

Type

Colour

property name: str

The activity's name. This will always return "Spotify".

Type

str

property title: str

The title of the song being played.

Type

str

property artists: List[str]

The artists of the song being played.

Type

List[str]

property artist: str

The artist of the song being played.

This does not attempt to split the artist information into multiple artists. Useful if there's only a single artist.

Type

str

property album: str

The album that the song being played belongs to.

Type

str

property album_cover_url: str

The album cover image URL from Spotify's CDN.

Type

str

property track_id: str

The track ID used by Spotify to identify this song.

Type

str

property track_url: str

The track URL to listen on Spotify.

バージョン 2.0 で追加.

Type

str

property start: datetime.datetime

When the user started playing this song in UTC.

Type

datetime.datetime

property end: datetime.datetime

When the user will stop playing this song in UTC.

Type

datetime.datetime

property duration: datetime.timedelta

The duration of the song being played.

Type

datetime.timedelta

property party_id: str

The party ID of the listening party.

Type

str

VoiceState

class discord.VoiceState

Represents a Discord user's voice state.

deaf

Indicates if the user is currently deafened by the guild.

Type

bool

mute

Indicates if the user is currently muted by the guild.

Type

bool

self_mute

Indicates if the user is currently muted by their own accord.

Type

bool

self_deaf

Indicates if the user is currently deafened by their own accord.

Type

bool

self_stream

Indicates if the user is currently streaming via 'Go Live' feature.

バージョン 1.3 で追加.

Type

bool

self_video

Indicates if the user is currently broadcasting video.

Type

bool

suppress

Indicates if the user is suppressed from speaking.

Only applies to stage channels.

バージョン 1.7 で追加.

Type

bool

requested_to_speak_at

An aware datetime object that specifies the date and time in UTC that the member requested to speak. It will be None if they are not requesting to speak anymore or have been accepted to speak.

Only applicable to stage channels.

バージョン 1.7 で追加.

Type

Optional[datetime.datetime]

afk

Indicates if the user is currently in the AFK channel in the guild.

Type

bool

channel

The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.

Type

Optional[Union[VoiceChannel, StageChannel]]

Emoji

class discord.Emoji

Represents a custom emoji.

Depending on the way this object was created, some of the attributes can have a value of None.

x == y

Checks if two emoji are the same.

x != y

Checks if two emoji are not the same.

hash(x)

Return the emoji's hash.

iter(x)

Returns an iterator of (field, value) pairs. This allows this class to be used as an iterable in list/dict/etc constructions.

str(x)

Returns the emoji rendered for discord.

name

The name of the emoji.

Type

str

id

The emoji's ID.

Type

int

require_colons

If colons are required to use this emoji in the client (:PJSalt: vs PJSalt).

Type

bool

animated

Whether an emoji is animated or not.

Type

bool

managed

If this emoji is managed by a Twitch integration.

Type

bool

guild_id

The guild ID the emoji belongs to.

Type

int

available

Whether the emoji is available for use.

Type

bool

user

The user that created the emoji. This can only be retrieved using Guild.fetch_emoji() and having the manage_emojis permission.

Type

Optional[User]

property created_at: datetime

Returns the emoji's creation time in UTC.

Type

datetime.datetime

property url: str

Returns the URL of the emoji.

Type

str

property roles: List[Role]

A list of roles that is allowed to use this emoji.

If roles is empty, the emoji is unrestricted.

Type

List[Role]

property guild: Guild

The guild this emoji belongs to.

Type

Guild

is_usable()

bool: Whether the bot can use this emoji.

バージョン 1.3 で追加.

await delete(*, reason=None)

This function is a coroutine.

Deletes the custom emoji.

You must have manage_emojis permission to do this.

パラメータ

reason (Optional[str]) -- The reason for deleting this emoji. Shows up on the audit log.

例外
await edit(*, name=..., roles=..., reason=None)

This function is a coroutine.

Edits the custom emoji.

You must have manage_emojis permission to do this.

バージョン 2.0 で変更: The newly updated emoji is returned.

パラメータ
  • name (str) -- The new emoji name.

  • roles (Optional[List[Snowflake]]) -- A list of roles that can use this emoji. An empty list can be passed to make it available to everyone.

  • reason (Optional[str]) -- The reason for editing this emoji. Shows up on the audit log.

例外
戻り値

The newly updated emoji.

戻り値の型

Emoji

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

例外
戻り値

The content of the asset.

戻り値の型

bytes

await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

パラメータ
  • fp (Union[io.BufferedIOBase, os.PathLike]) -- The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) -- Whether to seek to the beginning of the file after saving is successfully done.

例外
戻り値

The number of bytes written.

戻り値の型

int

PartialEmoji

class discord.PartialEmoji

Represents a "partial" emoji.

This model will be given in two scenarios:

x == y

Checks if two emoji are the same.

x != y

Checks if two emoji are not the same.

hash(x)

Return the emoji's hash.

str(x)

Returns the emoji rendered for discord.

name

The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji. This can be None if the emoji got deleted (e.g. removing a reaction with a deleted emoji).

Type

Optional[str]

animated

Whether the emoji is animated or not.

Type

bool

id

The ID of the custom emoji, if applicable.

Type

Optional[int]

classmethod from_str(value)

Converts a Discord string representation of an emoji to a PartialEmoji.

The formats accepted are:

  • a:name:id

  • <a:name:id>

  • name:id

  • <:name:id>

If the format does not match then it is assumed to be a unicode emoji.

バージョン 2.0 で追加.

パラメータ

value (str) -- The string representation of an emoji.

戻り値

The partial emoji from this string.

戻り値の型

PartialEmoji

is_custom_emoji()

bool: Checks if this is a custom non-Unicode emoji.

is_unicode_emoji()

bool: Checks if this is a Unicode emoji.

property created_at: Optional[datetime]

Returns the emoji's creation time in UTC, or None if Unicode emoji.

バージョン 1.6 で追加.

Type

Optional[datetime.datetime]

property url: str

Returns the URL of the emoji, if it is custom.

If this isn't a custom emoji then an empty string is returned

Type

str

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

例外
戻り値

The content of the asset.

戻り値の型

bytes

await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

パラメータ
  • fp (Union[io.BufferedIOBase, os.PathLike]) -- The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) -- Whether to seek to the beginning of the file after saving is successfully done.

例外
戻り値

The number of bytes written.

戻り値の型

int

Role

class discord.Role

Represents a Discord role in a Guild.

x == y

Checks if two roles are equal.

x != y

Checks if two roles are not equal.

x > y

Checks if a role is higher than another in the hierarchy.

x < y

Checks if a role is lower than another in the hierarchy.

x >= y

Checks if a role is higher or equal to another in the hierarchy.

x <= y

Checks if a role is lower or equal to another in the hierarchy.

hash(x)

役職のハッシュを返します。

str(x)

役職の名前を返します。

id

The ID for the role.

Type

int

name

The name of the role.

Type

str

guild

The guild the role belongs to.

Type

Guild

hoist

Indicates if the role will be displayed separately from other members.

Type

bool

position

The position of the role. This number is usually positive. The bottom role has a position of 0.

警告

Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.

Type

int

managed

Indicates if the role is managed by the guild through some form of integrations such as Twitch.

Type

bool

mentionable

Indicates if the role can be mentioned by users.

Type

bool

tags

The role tags associated with this role.

Type

Optional[RoleTags]

is_default()

bool: Checks if the role is the default role.

is_bot_managed()

bool: Whether the role is associated with a bot.

バージョン 1.6 で追加.

is_premium_subscriber()

bool: Whether the role is the premium subscriber, AKA "boost", role for the guild.

バージョン 1.6 で追加.

is_integration()

bool: Whether the role is managed by an integration.

バージョン 1.6 で追加.

is_assignable()

bool: Whether the role is able to be assigned or removed by the bot.

バージョン 2.0 で追加.

property permissions: discord.permissions.Permissions

Returns the role's permissions.

Type

Permissions

property colour: discord.colour.Colour

Returns the role colour. An alias exists under color.

Type

Colour

property color: discord.colour.Colour

Returns the role color. An alias exists under colour.

Type

Colour

property created_at: datetime.datetime

Returns the role's creation time in UTC.

Type

datetime.datetime

property mention: str

Returns a string that allows you to mention a role.

Type

str

property members: List[Member]

Returns all the members with this role.

Type

List[Member]

property icon: Optional[discord.asset.Asset]

Returns the icon asset associated with this role, can be None.

バージョン 2.0 で追加.

注釈

The guild needs to have the ROLE_ICONS features to have this enabled.

Type

Optional[Asset]

property emoji: Optional[discord.partial_emoji.PartialEmoji]

Returns the emoji that associated with this role, can be None.

バージョン 2.0 で追加.

注釈

The guild needs to have the ROLE_ICONS features to have this enabled.

Type

Optional[PartialEmoji]

await edit(*, name=..., permissions=..., colour=..., color=..., icon=..., emoji_unicode=..., hoist=..., mentionable=..., position=..., reason=...)

This function is a coroutine.

Edits the role.

You must have the manage_roles permission to use this.

All fields are optional.

バージョン 1.4 で変更: Can now pass int to colour keyword-only parameter.

バージョン 2.0 で変更: Edits are no longer in-place, the newly edited role is returned instead. Also added a new icon and emoji_unicode parameter to change role icons.

パラメータ
  • name (str) -- The new role name to change to.

  • permissions (Permissions) -- The new permissions to change to.

  • colour (Union[Colour, int]) -- The new colour to change to. (aliased to color as well)

  • icon (bytes) --

    A bytes object representing the role icon.

    バージョン 2.0 で追加.

  • emoji_unicode (str) --

    The unicode value of the new role to change to.

    バージョン 2.0 で追加.

  • hoist (bool) -- Indicates if the role should be shown separately in the member list.

  • mentionable (bool) -- Indicates if the role should be mentionable by others.

  • position (int) -- The new role's position. This must be below your top role's position or it will fail.

  • reason (Optional[str]) -- The reason for editing this role. Shows up on the audit log.

例外
  • Forbidden -- You do not have permissions to change the role.

  • HTTPException -- Editing the role failed.

  • InvalidArgument -- An invalid position was given or the default role was asked to be moved.

戻り値

The newly edited role.

戻り値の型

Role

await delete(*, reason=None)

This function is a coroutine.

Deletes the role.

You must have the manage_roles permission to use this.

パラメータ

reason (Optional[str]) -- The reason for deleting this role. Shows up on the audit log.

例外

RoleTags

class discord.RoleTags

Represents tags on a role.

A role tag is a piece of extra information attached to a managed role that gives it context for the reason the role is managed.

While this can be accessed, a useful interface is also provided in the Role and Guild classes as well.

バージョン 1.6 で追加.

bot_id

The bot's user ID that manages this role.

Type

Optional[int]

integration_id

The integration ID that manages the role.

Type

Optional[int]

is_bot_managed()

bool: Whether the role is associated with a bot.

is_premium_subscriber()

bool: Whether the role is the premium subscriber, AKA "boost", role for the guild.

is_integration()

bool: Whether the role is managed by an integration.

PartialMessageable

Attributes
Methods
class discord.PartialMessageable

Represents a partial messageable to aid with working messageable channels when only a channel ID are present.

The only way to construct this class is through Client.get_partial_messageable().

Note that this class is trimmed down and has no rich attributes.

バージョン 2.0 で追加.

x == y

Checks if two partial messageables are equal.

x != y

Checks if two partial messageables are not equal.

hash(x)

Returns the partial messageable's hash.

id

The channel ID associated with this partial messageable.

Type

int

type

The channel type associated with this partial messageable, if given.

Type

Optional[ChannelType]

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

パラメータ

id (int) -- The message ID to look for.

例外
  • NotFound -- The specified message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

戻り値

The message asked for.

戻り値の型

Message

history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Returns an AsyncIterator that enables receiving the destination's message history.

You must have read_message_history permissions to use this.

サンプル

使い方

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

すべてのパラメータがオプションです。

パラメータ
  • limit (Optional[int]) -- The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages before this date or message. 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 (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. 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.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

  • oldest_first (Optional[bool]) -- If set to True, return messages in oldest->newest order. Defaults to True if after is specified, otherwise False.

例外
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

列挙

Message -- The message with the message data parsed.

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

注釈

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

例外

HTTPException -- Retrieving the pinned messages failed.

戻り値

The messages that are currently pinned.

戻り値の型

List[Message]

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

パラメータ
  • content (Optional[str]) -- The content of the message to send.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • embed (Embed) -- The rich embed for the content.

  • file (File) -- The file to upload.

  • files (List[File]) -- A list of files to upload. Must be a maximum of 10.

  • nonce (int) -- The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) -- If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) --

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    バージョン 1.4 で追加.

  • reference (Union[Message, MessageReference, PartialMessage]) --

    A reference to the Message to which you are replying, this can be created using to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    バージョン 1.6 で追加.

  • mention_author (Optional[bool]) --

    If set, overrides the replied_user attribute of allowed_mentions.

    バージョン 1.6 で追加.

  • view (discord.ui.View) -- A Discord UI View to add to the message.

  • embeds (List[Embed]) --

    A list of embeds to upload. Must be a maximum of 10.

    バージョン 2.0 で追加.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) --

    A list of stickers to upload. Must be a maximum of 3.

    バージョン 2.0 で追加.

例外
戻り値

The message that was sent.

戻り値の型

Message

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

注釈

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
get_partial_message(message_id, /)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

パラメータ

message_id (int) -- The message ID to create a partial message for.

戻り値

The partial message.

戻り値の型

PartialMessage

TextChannel

class discord.TextChannel

Represents a Discord guild text channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel's hash.

str(x)

Returns the channel's name.

name

The channel name.

Type

str

guild

The guild the channel belongs to.

Type

Guild

id

The channel ID.

Type

int

category_id

The category channel ID this channel belongs to, if applicable.

Type

Optional[int]

topic

The channel's topic. None if it doesn't exist.

Type

Optional[str]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type

int

last_message_id

The last message ID of the message sent to this channel. It may not point to an existing or valid message.

Type

Optional[int]

slowmode_delay

The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.

Type

int

nsfw

If the channel is marked as "not safe for work".

注釈

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

Type

bool

default_auto_archive_duration

The default auto archive duration in minutes for threads created in this channel.

バージョン 2.0 で追加.

Type

int

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Returns an AsyncIterator that enables receiving the destination's message history.

You must have read_message_history permissions to use this.

サンプル

使い方

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

すべてのパラメータがオプションです。

パラメータ
  • limit (Optional[int]) -- The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages before this date or message. 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 (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. 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.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

  • oldest_first (Optional[bool]) -- If set to True, return messages in oldest->newest order. Defaults to True if after is specified, otherwise False.

例外
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

列挙

Message -- The message with the message data parsed.

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

注釈

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property type: discord.enums.ChannelType

The channel's Discord type.

Type

ChannelType

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

バージョン 2.0 で変更: The object passed in can now be a role object.

パラメータ

obj (Union[Member, Role]) -- The object to resolve permissions for. This could be either a member or a role. If it's a role then member overwrites are not computed.

戻り値

The resolved permissions for the member or role.

戻り値の型

Permissions

property members: List[Member]

Returns all members that can see this channel.

Type

List[Member]

property threads: List[discord.threads.Thread]

Returns all the threads that you can see.

バージョン 2.0 で追加.

Type

List[Thread]

is_nsfw()

bool: Checks if the channel is NSFW.

is_news()

bool: Checks if the channel is a news channel.

property last_message: Optional[Message]

Fetches the last message from this channel in cache.

The message might not be valid or point to an existing message.

Reliable Fetching

For a slightly more reliable method of fetching the last message, consider using either history() or fetch_message() with the last_message_id attribute.

戻り値

The last message in this channel or None if not found.

戻り値の型

Optional[Message]

await edit(*, reason=None, **options)

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

バージョン 1.3 で変更: The overwrites keyword-only parameter was added.

バージョン 1.4 で変更: The type keyword-only parameter was added.

バージョン 2.0 で変更: Edits are no longer in-place, the newly edited channel is returned instead.

パラメータ
  • name (str) -- The new channel name.

  • topic (str) -- The new channel's topic.

  • position (int) -- The new channel's position.

  • nsfw (bool) -- To mark the channel as NSFW or not.

  • sync_permissions (bool) -- Whether to sync permissions with the channel's new or pre-existing category. Defaults to False.

  • category (Optional[CategoryChannel]) -- The new category for this channel. Can be None to remove the category.

  • slowmode_delay (int) -- Specifies the slowmode rate limit for user in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.

  • type (ChannelType) -- Change the type of this text channel. Currently, only conversion between ChannelType.text and ChannelType.news is supported. This is only available to guilds that contain NEWS in Guild.features.

  • reason (Optional[str]) -- The reason for editing this channel. Shows up on the audit log.

  • overwrites (Mapping) -- A Mapping of target (either a role or a member) to PermissionOverwrite to apply to the channel.

  • default_auto_archive_duration (int) -- The new default auto archive duration in minutes for threads created in this channel. Must be one of 60, 1440, 4320, or 10080.

例外
  • InvalidArgument -- If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form.

  • Forbidden -- You do not have permissions to edit the channel.

  • HTTPException -- Editing the channel failed.

戻り値

The newly edited text channel. If the edit was only positional then None is returned instead.

戻り値の型

Optional[TextChannel]

await clone(*, name=None, reason=None)

This function is a coroutine.

Clones this channel. This creates a channel with the same properties as this channel.

You must have the manage_channels permission to do this.

バージョン 1.1 で追加.

パラメータ
  • name (Optional[str]) -- The name of the new channel. If not provided, defaults to this channel name.

  • reason (Optional[str]) -- The reason for cloning this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

戻り値

The channel that was created.

戻り値の型

abc.GuildChannel

await delete_messages(messages)

This function is a coroutine.

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

As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it's more than two, then bulk delete is used.

You cannot bulk delete more than 100 messages or messages that are older than 14 days old.

You must have the manage_messages permission to use this.

パラメータ

messages (Iterable[abc.Snowflake]) -- An iterable of messages denoting which ones to bulk delete.

例外
  • ClientException -- The number of messages to delete was more than 100.

  • Forbidden -- You do not have proper permissions to delete the messages.

  • NotFound -- If single delete, then the message was already deleted.

  • HTTPException -- Deleting the messages failed.

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)

This function is a coroutine.

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

You must have the manage_messages permission to delete messages even if they are your own. The read_message_history permission is also needed to retrieve message history.

サンプル

Deleting bot's messages

def is_me(m):
    return m.author == client.user

deleted = await channel.purge(limit=100, check=is_me)
await channel.send(f'Deleted {len(deleted)} message(s)')
パラメータ
例外
  • Forbidden -- You do not have proper permissions to do the actions required.

  • HTTPException -- Purging the messages failed.

戻り値

The list of messages that were deleted.

戻り値の型

List[Message]

await webhooks()

This function is a coroutine.

Gets the list of webhooks from this channel.

Requires manage_webhooks permissions.

例外

Forbidden -- You don't have permissions to get the webhooks.

戻り値

The webhooks for this channel.

戻り値の型

List[Webhook]

await create_webhook(*, name, avatar=None, reason=None)

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

バージョン 1.1 で変更: Added the reason keyword-only parameter.

パラメータ
  • name (str) -- The webhook's name.

  • avatar (Optional[bytes]) -- A bytes-like object representing the webhook's default avatar. This operates similarly to edit().

  • reason (Optional[str]) -- The reason for creating this webhook. Shows up in the audit logs.

例外
戻り値

The created webhook.

戻り値の型

Webhook

await follow(*, destination, reason=None)

Follows a channel using a webhook.

Only news channels can be followed.

注釈

The webhook returned will not provide a token to do webhook actions, as Discord does not provide it.

バージョン 1.3 で追加.

パラメータ
  • destination (TextChannel) -- The channel you would like to follow from.

  • reason (Optional[str]) --

    The reason for following the channel. Shows up on the destination guild's audit log.

    バージョン 1.4 で追加.

例外
  • HTTPException -- Following the channel failed.

  • Forbidden -- You do not have the permissions to create a webhook.

戻り値

The created webhook.

戻り値の型

Webhook

get_partial_message(message_id, /)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

バージョン 1.6 で追加.

パラメータ

message_id (int) -- The message ID to create a partial message for.

戻り値

The partial message.

戻り値の型

PartialMessage

get_thread(thread_id, /)

Returns a thread with the given ID.

バージョン 2.0 で追加.

パラメータ

thread_id (int) -- The ID to search for.

戻り値

The returned thread or None if not found.

戻り値の型

Optional[Thread]

await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None)

This function is a coroutine.

Creates a thread in this text channel.

To create a public thread, you must have create_public_threads. For a private thread, create_private_threads is needed instead.

バージョン 2.0 で追加.

パラメータ
  • name (str) -- The name of the thread.

  • message (Optional[abc.Snowflake]) -- A snowflake representing the message to create the thread with. If None is passed then a private thread is created. Defaults to None.

  • auto_archive_duration (int) -- The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel's default auto archive duration is used.

  • type (Optional[ChannelType]) -- The type of thread to create. If a message is passed then this parameter is ignored, as a thread created with a message is always a public thread. By default this creates a private thread if this is None.

  • reason (str) -- The reason for creating a new thread. Shows up on the audit log.

例外
戻り値

The created thread

戻り値の型

Thread

archived_threads(*, private=False, joined=False, limit=50, before=None)

Returns an AsyncIterator that iterates over all archived threads in the guild.

You must have read_message_history to use this. If iterating over private threads then manage_threads is also required.

バージョン 2.0 で追加.

パラメータ
  • limit (Optional[bool]) -- The number of threads to retrieve. If None, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) -- Retrieve archived channels before the given date or ID.

  • private (bool) -- Whether to retrieve private archived threads.

  • joined (bool) -- Whether to retrieve private archived threads that you've joined. You cannot set joined to True and private to False.

例外
  • Forbidden -- You do not have permissions to get archived threads.

  • HTTPException -- The request to get the archived threads failed.

列挙

Thread -- The archived threads.

property category: Optional[CategoryChannel]

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property changed_roles: List[discord.role.Role]

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

await create_event(name, scheduled_start_time, *, description=..., privacy_level=..., entity_type=...)

This function is a coroutine.

Create a new guild event with this channel.

You must have the manage_events permission to create a guild event.

注釈

Another extra permissions is required for different type of entity_type.

If your entity type is GuildScheduledEventType.stage_instance, you must have the following extra permissions:

If your entity type is GuildScheduledEventType.voice, you must have the following extra permissions:

  • view_channel for channel associated with the event.

  • connect for channel associated with the event.

If your entity type is GuildScheduledEventType.external, you dont need any extra permissions.

バージョン 2.0 で追加.

パラメータ
  • name (str) -- The name of the event.

  • description (Optional[str]) -- The description of the event. Could be None for no description.

  • privacy_level (Optional[GuildScheduledEventPrivacyLevel]) -- The event privacy level, same thing as StageInstance PrivacyLevel

  • scheduled_start_time (datetime.datetime) -- The scheduled start time, timezone must be UTC. If not it will be converted automatically.

  • entity_type (Optional[GuildScheduledEventType]) -- The entity_type or type for the event. If you don't provide this, it will automatically check from the channel type.

例外
  • Forbidden -- You do not have permissions to create the guild event.

  • HTTPException -- Creating the guild event failed.

  • ValueError -- Validation error occurred.

戻り値

The newly updated guild event.

戻り値の型

GuildScheduledEvent

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

パラメータ
  • max_age (int) -- How long the invite should last in seconds. If it's 0 then the invite doesn't expire. Defaults to 0.

  • max_uses (int) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to 0.

  • temporary (bool) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (bool) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • reason (Optional[str]) -- The reason for creating this invite. Shows up on the audit log.

  • target_type (Optional[InviteTarget]) --

    The type of target for the voice channel invite, if any.

    バージョン 2.0 で追加.

  • target_user (Optional[User]) --

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    バージョン 2.0 で追加.

  • target_application_id: --

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    バージョン 2.0 で追加.

例外
  • HTTPException -- Invite creation failed.

  • NotFound -- The channel that was passed is a category or an invalid channel.

戻り値

The invite that was created.

戻り値の型

Invite

property created_at: datetime.datetime

Returns the channel's creation time in UTC.

Type

datetime.datetime

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

パラメータ

reason (Optional[str]) -- The reason for deleting this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have proper permissions to delete the channel.

  • NotFound -- The channel was not found or was already deleted.

  • HTTPException -- Deleting the channel failed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

パラメータ

id (int) -- The message ID to look for.

例外
  • NotFound -- The specified message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

戻り値

The message asked for.

戻り値の型

Message

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this channel.

You must have manage_channels to get this information.

例外
  • Forbidden -- You do not have proper permissions to get the information.

  • HTTPException -- An error occurred while fetching the information.

戻り値

The list of invites that are currently active.

戻り値の型

List[Invite]

property mention: str

The string that allows you to mention the channel.

Type

str

await move(**kwargs)

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have the manage_channels permission to do this.

注釈

Voice channels will always be sorted below text channels. This is a Discord limitation.

バージョン 1.7 で追加.

パラメータ
  • beginning (bool) -- Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) -- Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (Snowflake) -- The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (Snowflake) -- The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) -- The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[Snowflake]) -- The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) -- Whether to sync the permissions with the category (if given).

  • reason (str) -- The reason for the move.

例外
  • InvalidArgument -- An invalid position was given or a bad mix of arguments were passed.

  • Forbidden -- You do not have permissions to move the channel.

  • HTTPException -- Moving the channel failed.

property overwrites: Dict[Union[Role, Member], PermissionOverwrite]

Returns all of the channel's overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

戻り値

The channel's permission overwrites.

戻り値の型

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

パラメータ

obj (Union[Role, User]) -- The role or user denoting whose overwrite to get.

戻り値

The permission overwrites for this object.

戻り値の型

PermissionOverwrite

property permissions_synced: bool

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

バージョン 1.3 で追加.

Type

bool

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

注釈

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

例外

HTTPException -- Retrieving the pinned messages failed.

戻り値

The messages that are currently pinned.

戻り値の型

List[Message]

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

パラメータ
  • content (Optional[str]) -- The content of the message to send.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • embed (Embed) -- The rich embed for the content.

  • file (File) -- The file to upload.

  • files (List[File]) -- A list of files to upload. Must be a maximum of 10.

  • nonce (int) -- The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) -- If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) --

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    バージョン 1.4 で追加.

  • reference (Union[Message, MessageReference, PartialMessage]) --

    A reference to the Message to which you are replying, this can be created using to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    バージョン 1.6 で追加.

  • mention_author (Optional[bool]) --

    If set, overrides the replied_user attribute of allowed_mentions.

    バージョン 1.6 で追加.

  • view (discord.ui.View) -- A Discord UI View to add to the message.

  • embeds (List[Embed]) --

    A list of embeds to upload. Must be a maximum of 10.

    バージョン 2.0 で追加.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) --

    A list of stickers to upload. Must be a maximum of 3.

    バージョン 2.0 で追加.

例外
戻り値

The message that was sent.

戻り値の型

Message

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)

This function is a coroutine.

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

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have the manage_roles permission to use this.

注釈

This method replaces the old overwrites with the ones given.

サンプル

Setting allow and deny:

await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
パラメータ
  • target (Union[Member, Role]) -- The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) -- The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions -- A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

  • reason (Optional[str]) -- The reason for doing this action. Shows up on the audit log.

例外
  • Forbidden -- You do not have permissions to edit channel specific permissions.

  • HTTPException -- Editing channel specific permissions failed.

  • NotFound -- The role or member being edited is not part of the guild.

  • InvalidArgument -- The overwrite parameter invalid or the target type was not Role or Member.

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

Thread

class discord.Thread

Represents a Discord thread.

x == y

Checks if two threads are equal.

x != y

Checks if two threads are not equal.

hash(x)

Returns the thread's hash.

str(x)

Returns the thread's name.

バージョン 2.0 で追加.

name

The thread name.

Type

str

guild

The guild the thread belongs to.

Type

Guild

id

The thread ID.

Type

int

parent_id

The parent TextChannel ID this thread belongs to.

Type

int

owner_id

The user's ID that created this thread.

Type

int

last_message_id

The last message ID of the message sent to this thread. It may not point to an existing or valid message.

Type

Optional[int]

slowmode_delay

The number of seconds a member must wait between sending messages in this thread. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.

Type

int

message_count

An approximate number of messages in this thread. This caps at 50.

Type

int

member_count

An approximate number of members in this thread. This caps at 50.

Type

int

me

A thread member representing yourself, if you've joined the thread. This could not be available.

Type

Optional[ThreadMember]

archived

Whether the thread is archived.

Type

bool

locked

Whether the thread is locked.

Type

bool

invitable

Whether non-moderators can add other non-moderators to this thread. This is always True for public threads.

Type

bool

archiver_id

The user's ID that archived this thread.

Type

Optional[int]

auto_archive_duration

The duration in minutes until the thread is automatically archived due to inactivity. Usually a value of 60, 1440, 4320 and 10080.

Type

int

archive_timestamp

An aware timestamp of when the thread's archived status was last updated in UTC.

Type

datetime.datetime

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Returns an AsyncIterator that enables receiving the destination's message history.

You must have read_message_history permissions to use this.

サンプル

使い方

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

すべてのパラメータがオプションです。

パラメータ
  • limit (Optional[int]) -- The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages before this date or message. 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 (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. 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.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

  • oldest_first (Optional[bool]) -- If set to True, return messages in oldest->newest order. Defaults to True if after is specified, otherwise False.

例外
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

列挙

Message -- The message with the message data parsed.

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

注釈

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property type: discord.enums.ChannelType

The channel's Discord type.

Type

ChannelType

property parent: Optional[TextChannel]

The parent channel this thread belongs to.

Type

Optional[TextChannel]

property owner: Optional[Member]

The member this thread belongs to.

Type

Optional[Member]

property mention: str

The string that allows you to mention the thread.

Type

str

property members: List[discord.threads.ThreadMember]

A list of thread members in this thread.

This requires Intents.members to be properly filled. Most of the time however, this data is not provided by the gateway and a call to fetch_members() is needed.

Type

List[ThreadMember]

property last_message: Optional[Message]

Fetches the last message from this channel in cache.

The message might not be valid or point to an existing message.

Reliable Fetching

For a slightly more reliable method of fetching the last message, consider using either history() or fetch_message() with the last_message_id attribute.

戻り値

The last message in this channel or None if not found.

戻り値の型

Optional[Message]

property category: Optional[CategoryChannel]

The category channel the parent channel belongs to, if applicable.

例外

ClientException -- The parent channel was not cached and returned None.

戻り値

The parent channel's category.

戻り値の型

Optional[CategoryChannel]

property category_id: Optional[int]

The category channel ID the parent channel belongs to, if applicable.

例外

ClientException -- The parent channel was not cached and returned None.

戻り値

The parent channel's category ID.

戻り値の型

Optional[int]

is_private()

bool: Whether the thread is a private thread.

A private thread is only viewable by those that have been explicitly invited or have manage_threads.

is_news()

bool: Whether the thread is a news thread.

A news thread is a thread that has a parent that is a news channel, i.e. TextChannel.is_news() is True.

is_nsfw()

bool: Whether the thread is NSFW or not.

An NSFW thread is a thread that has a parent that is an NSFW channel, i.e. TextChannel.is_nsfw() is True.

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

Since threads do not have their own permissions, they inherit them from the parent channel. This is a convenience method for calling permissions_for() on the parent channel.

パラメータ

obj (Union[Member, Role]) -- The object to resolve permissions for. This could be either a member or a role. If it's a role then member overwrites are not computed.

例外

ClientException -- The parent channel was not cached and returned None

戻り値

The resolved permissions for the member or role.

戻り値の型

Permissions

await delete_messages(messages)

This function is a coroutine.

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

As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it's more than two, then bulk delete is used.

You cannot bulk delete more than 100 messages or messages that are older than 14 days old.

You must have the manage_messages permission to use this.

Usable only by bot accounts.

パラメータ

messages (Iterable[abc.Snowflake]) -- An iterable of messages denoting which ones to bulk delete.

例外
  • ClientException -- The number of messages to delete was more than 100.

  • Forbidden -- You do not have proper permissions to delete the messages or you're not using a bot account.

  • NotFound -- If single delete, then the message was already deleted.

  • HTTPException -- Deleting the messages failed.

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)

This function is a coroutine.

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

You must have the manage_messages permission to delete messages even if they are your own (unless you are a user account). The read_message_history permission is also needed to retrieve message history.

サンプル

Deleting bot's messages

def is_me(m):
    return m.author == client.user

deleted = await thread.purge(limit=100, check=is_me)
await thread.send(f'Deleted {len(deleted)} message(s)')
パラメータ
例外
  • Forbidden -- You do not have proper permissions to do the actions required.

  • HTTPException -- Purging the messages failed.

戻り値

The list of messages that were deleted.

戻り値の型

List[Message]

await edit(*, name=..., archived=..., locked=..., invitable=..., slowmode_delay=..., auto_archive_duration=...)

This function is a coroutine.

Edits the thread.

Editing the thread requires Permissions.manage_threads. The thread creator can also edit name, archived or auto_archive_duration. Note that if the thread is locked then only those with Permissions.manage_threads can unarchive a thread.

The thread must be unarchived to be edited.

パラメータ
  • name (str) -- The new name of the thread.

  • archived (bool) -- Whether to archive the thread or not.

  • locked (bool) -- Whether to lock the thread or not.

  • invitable (bool) -- Whether non-moderators can add other non-moderators to this thread. Only available for private threads.

  • auto_archive_duration (int) -- The new duration in minutes before a thread is automatically archived for inactivity. Must be one of 60, 1440, 4320, or 10080.

  • slowmode_delay (int) -- Specifies the slowmode rate limit for user in this thread, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.

例外
戻り値

The newly edited thread.

戻り値の型

Thread

await join()

This function is a coroutine.

Joins this thread.

You must have send_messages_in_threads to join a thread. If the thread is private, manage_threads is also needed.

例外
await leave()

This function is a coroutine.

Leaves this thread.

例外

HTTPException -- Leaving the thread failed.

await add_user(user)

This function is a coroutine.

Adds a user to this thread.

You must have send_messages and use_threads to add a user to a public thread. If the thread is private then send_messages and either use_private_threads or manage_messages is required to add a user to the thread.

パラメータ

user (abc.Snowflake) -- The user to add to the thread.

例外
  • Forbidden -- You do not have permissions to add the user to the thread.

  • HTTPException -- Adding the user to the thread failed.

await remove_user(user)

This function is a coroutine.

Removes a user from this thread.

You must have manage_threads or be the creator of the thread to remove a user.

パラメータ

user (abc.Snowflake) -- The user to add to the thread.

例外
  • Forbidden -- You do not have permissions to remove the user from the thread.

  • HTTPException -- Removing the user from the thread failed.

await fetch_members()

This function is a coroutine.

Retrieves all ThreadMember that are in this thread.

This requires Intents.members to get information about members other than yourself.

例外

HTTPException -- Retrieving the members failed.

戻り値

All thread members in the thread.

戻り値の型

List[ThreadMember]

await delete()

This function is a coroutine.

Deletes this thread.

You must have manage_threads to delete threads.

例外
  • Forbidden -- You do not have permissions to delete this thread.

  • HTTPException -- Deleting the thread failed.

get_partial_message(message_id, /)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

バージョン 2.0 で追加.

パラメータ

message_id (int) -- The message ID to create a partial message for.

戻り値

The partial message.

戻り値の型

PartialMessage

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

パラメータ

id (int) -- The message ID to look for.

例外
  • NotFound -- The specified message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

戻り値

The message asked for.

戻り値の型

Message

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

注釈

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

例外

HTTPException -- Retrieving the pinned messages failed.

戻り値

The messages that are currently pinned.

戻り値の型

List[Message]

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

パラメータ
  • content (Optional[str]) -- The content of the message to send.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • embed (Embed) -- The rich embed for the content.

  • file (File) -- The file to upload.

  • files (List[File]) -- A list of files to upload. Must be a maximum of 10.

  • nonce (int) -- The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) -- If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) --

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    バージョン 1.4 で追加.

  • reference (Union[Message, MessageReference, PartialMessage]) --

    A reference to the Message to which you are replying, this can be created using to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    バージョン 1.6 で追加.

  • mention_author (Optional[bool]) --

    If set, overrides the replied_user attribute of allowed_mentions.

    バージョン 1.6 で追加.

  • view (discord.ui.View) -- A Discord UI View to add to the message.

  • embeds (List[Embed]) --

    A list of embeds to upload. Must be a maximum of 10.

    バージョン 2.0 で追加.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) --

    A list of stickers to upload. Must be a maximum of 3.

    バージョン 2.0 で追加.

例外
戻り値

The message that was sent.

戻り値の型

Message

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

ThreadMember

class discord.ThreadMember

Represents a Discord thread member.

x == y

Checks if two thread members are equal.

x != y

Checks if two thread members are not equal.

hash(x)

Returns the thread member's hash.

str(x)

Returns the thread member's name.

バージョン 2.0 で追加.

id

The thread member's ID.

Type

int

thread_id

The thread's ID.

Type

int

joined_at

The time the member joined the thread in UTC.

Type

datetime.datetime

property thread: discord.threads.Thread

The thread this member belongs to.

Type

Thread

StoreChannel

class discord.StoreChannel

Represents a Discord guild store channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel's hash.

str(x)

Returns the channel's name.

name

The channel name.

Type

str

guild

The guild the channel belongs to.

Type

Guild

id

The channel ID.

Type

int

category_id

The category channel ID this channel belongs to.

Type

int

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type

int

nsfw

If the channel is marked as "not safe for work".

注釈

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

Type

bool

property type: discord.enums.ChannelType

The channel's Discord type.

Type

ChannelType

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

バージョン 2.0 で変更: The object passed in can now be a role object.

パラメータ

obj (Union[Member, Role]) -- The object to resolve permissions for. This could be either a member or a role. If it's a role then member overwrites are not computed.

戻り値

The resolved permissions for the member or role.

戻り値の型

Permissions

is_nsfw()

bool: Checks if the channel is NSFW.

await clone(*, name=None, reason=None)

This function is a coroutine.

Clones this channel. This creates a channel with the same properties as this channel.

You must have the manage_channels permission to do this.

バージョン 1.1 で追加.

パラメータ
  • name (Optional[str]) -- The name of the new channel. If not provided, defaults to this channel name.

  • reason (Optional[str]) -- The reason for cloning this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

戻り値

The channel that was created.

戻り値の型

abc.GuildChannel

await edit(*, reason=None, **options)

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

バージョン 2.0 で変更: Edits are no longer in-place, the newly edited channel is returned instead.

パラメータ
  • name (str) -- The new channel name.

  • position (int) -- The new channel's position.

  • nsfw (bool) -- To mark the channel as NSFW or not.

  • sync_permissions (bool) -- Whether to sync permissions with the channel's new or pre-existing category. Defaults to False.

  • category (Optional[CategoryChannel]) -- The new category for this channel. Can be None to remove the category.

  • reason (Optional[str]) -- The reason for editing this channel. Shows up on the audit log.

  • overwrites (Mapping) --

    A Mapping of target (either a role or a member) to PermissionOverwrite to apply to the channel.

    バージョン 1.3 で追加.

例外
  • InvalidArgument -- If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form.

  • Forbidden -- You do not have permissions to edit the channel.

  • HTTPException -- Editing the channel failed.

戻り値

The newly edited store channel. If the edit was only positional then None is returned instead.

戻り値の型

Optional[StoreChannel]

property category: Optional[CategoryChannel]

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property changed_roles: List[discord.role.Role]

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

await create_event(name, scheduled_start_time, *, description=..., privacy_level=..., entity_type=...)

This function is a coroutine.

Create a new guild event with this channel.

You must have the manage_events permission to create a guild event.

注釈

Another extra permissions is required for different type of entity_type.

If your entity type is GuildScheduledEventType.stage_instance, you must have the following extra permissions:

If your entity type is GuildScheduledEventType.voice, you must have the following extra permissions:

  • view_channel for channel associated with the event.

  • connect for channel associated with the event.

If your entity type is GuildScheduledEventType.external, you dont need any extra permissions.

バージョン 2.0 で追加.

パラメータ
  • name (str) -- The name of the event.

  • description (Optional[str]) -- The description of the event. Could be None for no description.

  • privacy_level (Optional[GuildScheduledEventPrivacyLevel]) -- The event privacy level, same thing as StageInstance PrivacyLevel

  • scheduled_start_time (datetime.datetime) -- The scheduled start time, timezone must be UTC. If not it will be converted automatically.

  • entity_type (Optional[GuildScheduledEventType]) -- The entity_type or type for the event. If you don't provide this, it will automatically check from the channel type.

例外
  • Forbidden -- You do not have permissions to create the guild event.

  • HTTPException -- Creating the guild event failed.

  • ValueError -- Validation error occurred.

戻り値

The newly updated guild event.

戻り値の型

GuildScheduledEvent

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

パラメータ
  • max_age (int) -- How long the invite should last in seconds. If it's 0 then the invite doesn't expire. Defaults to 0.

  • max_uses (int) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to 0.

  • temporary (bool) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (bool) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • reason (Optional[str]) -- The reason for creating this invite. Shows up on the audit log.

  • target_type (Optional[InviteTarget]) --

    The type of target for the voice channel invite, if any.

    バージョン 2.0 で追加.

  • target_user (Optional[User]) --

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    バージョン 2.0 で追加.

  • target_application_id: --

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    バージョン 2.0 で追加.

例外
  • HTTPException -- Invite creation failed.

  • NotFound -- The channel that was passed is a category or an invalid channel.

戻り値

The invite that was created.

戻り値の型

Invite

property created_at: datetime.datetime

Returns the channel's creation time in UTC.

Type

datetime.datetime

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

パラメータ

reason (Optional[str]) -- The reason for deleting this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have proper permissions to delete the channel.

  • NotFound -- The channel was not found or was already deleted.

  • HTTPException -- Deleting the channel failed.

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this channel.

You must have manage_channels to get this information.

例外
  • Forbidden -- You do not have proper permissions to get the information.

  • HTTPException -- An error occurred while fetching the information.

戻り値

The list of invites that are currently active.

戻り値の型

List[Invite]

property mention: str

The string that allows you to mention the channel.

Type

str

await move(**kwargs)

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have the manage_channels permission to do this.

注釈

Voice channels will always be sorted below text channels. This is a Discord limitation.

バージョン 1.7 で追加.

パラメータ
  • beginning (bool) -- Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) -- Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (Snowflake) -- The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (Snowflake) -- The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) -- The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[Snowflake]) -- The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) -- Whether to sync the permissions with the category (if given).

  • reason (str) -- The reason for the move.

例外
  • InvalidArgument -- An invalid position was given or a bad mix of arguments were passed.

  • Forbidden -- You do not have permissions to move the channel.

  • HTTPException -- Moving the channel failed.

property overwrites: Dict[Union[Role, Member], PermissionOverwrite]

Returns all of the channel's overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

戻り値

The channel's permission overwrites.

戻り値の型

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

パラメータ

obj (Union[Role, User]) -- The role or user denoting whose overwrite to get.

戻り値

The permission overwrites for this object.

戻り値の型

PermissionOverwrite

property permissions_synced: bool

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

バージョン 1.3 で追加.

Type

bool

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)

This function is a coroutine.

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

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have the manage_roles permission to use this.

注釈

This method replaces the old overwrites with the ones given.

サンプル

Setting allow and deny:

await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
パラメータ
  • target (Union[Member, Role]) -- The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) -- The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions -- A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

  • reason (Optional[str]) -- The reason for doing this action. Shows up on the audit log.

例外
  • Forbidden -- You do not have permissions to edit channel specific permissions.

  • HTTPException -- Editing channel specific permissions failed.

  • NotFound -- The role or member being edited is not part of the guild.

  • InvalidArgument -- The overwrite parameter invalid or the target type was not Role or Member.

VoiceChannel

class discord.VoiceChannel

Discordサーバーのボイスチャンネルを表します。

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel's hash.

str(x)

Returns the channel's name.

name

The channel name.

Type

str

guild

The guild the channel belongs to.

Type

Guild

id

The channel ID.

Type

int

category_id

The category channel ID this channel belongs to, if applicable.

Type

Optional[int]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type

int

bitrate

The channel's preferred audio bitrate in bits per second.

Type

int

user_limit

The channel's limit for number of members that can be in a voice channel.

Type

int

rtc_region

The region for the voice channel's voice communication. A value of None indicates automatic voice region detection.

バージョン 1.7 で追加.

Type

Optional[VoiceRegion]

video_quality_mode

The camera video quality for the voice channel's participants.

バージョン 2.0 で追加.

Type

VideoQualityMode

property type: discord.enums.ChannelType

The channel's Discord type.

Type

ChannelType

await clone(*, name=None, reason=None)

This function is a coroutine.

Clones this channel. This creates a channel with the same properties as this channel.

You must have the manage_channels permission to do this.

バージョン 1.1 で追加.

パラメータ
  • name (Optional[str]) -- The name of the new channel. If not provided, defaults to this channel name.

  • reason (Optional[str]) -- The reason for cloning this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

戻り値

The channel that was created.

戻り値の型

abc.GuildChannel

await edit(*, reason=None, **options)

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

バージョン 1.3 で変更: The overwrites keyword-only parameter was added.

バージョン 2.0 で変更: Edits are no longer in-place, the newly edited channel is returned instead.

パラメータ
  • name (str) -- The new channel's name.

  • bitrate (int) -- The new channel's bitrate.

  • user_limit (int) -- The new channel's user limit.

  • position (int) -- The new channel's position.

  • sync_permissions (bool) -- Whether to sync permissions with the channel's new or pre-existing category. Defaults to False.

  • category (Optional[CategoryChannel]) -- The new category for this channel. Can be None to remove the category.

  • reason (Optional[str]) -- The reason for editing this channel. Shows up on the audit log.

  • overwrites (Mapping) -- A Mapping of target (either a role or a member) to PermissionOverwrite to apply to the channel.

  • rtc_region (Optional[VoiceRegion]) --

    The new region for the voice channel's voice communication. A value of None indicates automatic voice region detection.

    バージョン 1.7 で追加.

  • video_quality_mode (VideoQualityMode) --

    The camera video quality for the voice channel's participants.

    バージョン 2.0 で追加.

例外
  • InvalidArgument -- If the permission overwrite information is not in proper form.

  • Forbidden -- You do not have permissions to edit the channel.

  • HTTPException -- Editing the channel failed.

戻り値

The newly edited voice channel. If the edit was only positional then None is returned instead.

戻り値の型

Optional[VoiceChannel]

property category: Optional[CategoryChannel]

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property changed_roles: List[discord.role.Role]

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)

This function is a coroutine.

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

This requires Intents.voice_states.

パラメータ
  • timeout (float) -- The timeout in seconds to wait for the voice endpoint.

  • reconnect (bool) -- Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) -- A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

例外
戻り値

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

戻り値の型

VoiceProtocol

await create_event(name, scheduled_start_time, *, description=..., privacy_level=..., entity_type=...)

This function is a coroutine.

Create a new guild event with this channel.

You must have the manage_events permission to create a guild event.

注釈

Another extra permissions is required for different type of entity_type.

If your entity type is GuildScheduledEventType.stage_instance, you must have the following extra permissions:

If your entity type is GuildScheduledEventType.voice, you must have the following extra permissions:

  • view_channel for channel associated with the event.

  • connect for channel associated with the event.

If your entity type is GuildScheduledEventType.external, you dont need any extra permissions.

バージョン 2.0 で追加.

パラメータ
  • name (str) -- The name of the event.

  • description (Optional[str]) -- The description of the event. Could be None for no description.

  • privacy_level (Optional[GuildScheduledEventPrivacyLevel]) -- The event privacy level, same thing as StageInstance PrivacyLevel

  • scheduled_start_time (datetime.datetime) -- The scheduled start time, timezone must be UTC. If not it will be converted automatically.

  • entity_type (Optional[GuildScheduledEventType]) -- The entity_type or type for the event. If you don't provide this, it will automatically check from the channel type.

例外
  • Forbidden -- You do not have permissions to create the guild event.

  • HTTPException -- Creating the guild event failed.

  • ValueError -- Validation error occurred.

戻り値

The newly updated guild event.

戻り値の型

GuildScheduledEvent

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

パラメータ
  • max_age (int) -- How long the invite should last in seconds. If it's 0 then the invite doesn't expire. Defaults to 0.

  • max_uses (int) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to 0.

  • temporary (bool) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (bool) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • reason (Optional[str]) -- The reason for creating this invite. Shows up on the audit log.

  • target_type (Optional[InviteTarget]) --

    The type of target for the voice channel invite, if any.

    バージョン 2.0 で追加.

  • target_user (Optional[User]) --

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    バージョン 2.0 で追加.

  • target_application_id: --

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    バージョン 2.0 で追加.

例外
  • HTTPException -- Invite creation failed.

  • NotFound -- The channel that was passed is a category or an invalid channel.

戻り値

The invite that was created.

戻り値の型

Invite

property created_at: datetime.datetime

Returns the channel's creation time in UTC.

Type

datetime.datetime

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

パラメータ

reason (Optional[str]) -- The reason for deleting this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have proper permissions to delete the channel.

  • NotFound -- The channel was not found or was already deleted.

  • HTTPException -- Deleting the channel failed.

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this channel.

You must have manage_channels to get this information.

例外
  • Forbidden -- You do not have proper permissions to get the information.

  • HTTPException -- An error occurred while fetching the information.

戻り値

The list of invites that are currently active.

戻り値の型

List[Invite]

property members: List[Member]

Returns all members that are currently inside this voice channel.

Type

List[Member]

property mention: str

The string that allows you to mention the channel.

Type

str

await move(**kwargs)

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have the manage_channels permission to do this.

注釈

Voice channels will always be sorted below text channels. This is a Discord limitation.

バージョン 1.7 で追加.

パラメータ
  • beginning (bool) -- Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) -- Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (Snowflake) -- The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (Snowflake) -- The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) -- The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[Snowflake]) -- The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) -- Whether to sync the permissions with the category (if given).

  • reason (str) -- The reason for the move.

例外
  • InvalidArgument -- An invalid position was given or a bad mix of arguments were passed.

  • Forbidden -- You do not have permissions to move the channel.

  • HTTPException -- Moving the channel failed.

property overwrites: Dict[Union[Role, Member], PermissionOverwrite]

Returns all of the channel's overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

戻り値

The channel's permission overwrites.

戻り値の型

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

パラメータ

obj (Union[Role, User]) -- The role or user denoting whose overwrite to get.

戻り値

The permission overwrites for this object.

戻り値の型

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

バージョン 2.0 で変更: The object passed in can now be a role object.

パラメータ

obj (Union[Member, Role]) -- The object to resolve permissions for. This could be either a member or a role. If it's a role then member overwrites are not computed.

戻り値

The resolved permissions for the member or role.

戻り値の型

Permissions

property permissions_synced: bool

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

バージョン 1.3 で追加.

Type

bool

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)

This function is a coroutine.

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

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have the manage_roles permission to use this.

注釈

This method replaces the old overwrites with the ones given.

サンプル

Setting allow and deny:

await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
パラメータ
  • target (Union[Member, Role]) -- The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) -- The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions -- A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

  • reason (Optional[str]) -- The reason for doing this action. Shows up on the audit log.

例外
  • Forbidden -- You do not have permissions to edit channel specific permissions.

  • HTTPException -- Editing channel specific permissions failed.

  • NotFound -- The role or member being edited is not part of the guild.

  • InvalidArgument -- The overwrite parameter invalid or the target type was not Role or Member.

property voice_states: Dict[int, VoiceState]

Returns a mapping of member IDs who have voice states in this channel.

バージョン 1.3 で追加.

注釈

This function is intentionally low level to replace members when the member cache is unavailable.

戻り値

The mapping of member ID to a voice state.

戻り値の型

Mapping[int, VoiceState]

StageChannel

class discord.StageChannel

Represents a Discord guild stage channel.

バージョン 1.7 で追加.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel's hash.

str(x)

Returns the channel's name.

name

The channel name.

Type

str

guild

The guild the channel belongs to.

Type

Guild

id

The channel ID.

Type

int

topic

The channel's topic. None if it isn't set.

Type

Optional[str]

category_id

The category channel ID this channel belongs to, if applicable.

Type

Optional[int]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type

int

bitrate

The channel's preferred audio bitrate in bits per second.

Type

int

user_limit

The channel's limit for number of members that can be in a stage channel.

Type

int

rtc_region

The region for the stage channel's voice communication. A value of None indicates automatic voice region detection.

Type

Optional[VoiceRegion]

video_quality_mode

The camera video quality for the stage channel's participants.

バージョン 2.0 で追加.

Type

VideoQualityMode

property requesting_to_speak: List[Member]

A list of members who are requesting to speak in the stage channel.

Type

List[Member]

property speakers: List[Member]

A list of members who have been permitted to speak in the stage channel.

バージョン 2.0 で追加.

Type

List[Member]

property listeners: List[Member]

A list of members who are listening in the stage channel.

バージョン 2.0 で追加.

Type

List[Member]

property moderators: List[Member]

A list of members who are moderating the stage channel.

バージョン 2.0 で追加.

Type

List[Member]

property type: discord.enums.ChannelType

The channel's Discord type.

Type

ChannelType

await clone(*, name=None, reason=None)

This function is a coroutine.

Clones this channel. This creates a channel with the same properties as this channel.

You must have the manage_channels permission to do this.

バージョン 1.1 で追加.

パラメータ
  • name (Optional[str]) -- The name of the new channel. If not provided, defaults to this channel name.

  • reason (Optional[str]) -- The reason for cloning this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

戻り値

The channel that was created.

戻り値の型

abc.GuildChannel

property instance: Optional[discord.stage_instance.StageInstance]

The running stage instance of the stage channel.

バージョン 2.0 で追加.

Type

Optional[StageInstance]

await create_instance(*, topic, privacy_level=..., reason=None)

This function is a coroutine.

Create a stage instance.

You must have the manage_channels permission to use this.

バージョン 2.0 で追加.

パラメータ
例外
  • InvalidArgument -- If the privacy_level parameter is not the proper type.

  • Forbidden -- You do not have permissions to create a stage instance.

  • HTTPException -- Creating a stage instance failed.

戻り値

The newly created stage instance.

戻り値の型

StageInstance

await fetch_instance()

This function is a coroutine.

Gets the running StageInstance.

バージョン 2.0 で追加.

例外
  • NotFound -- The stage instance or channel could not be found.

  • HTTPException -- Getting the stage instance failed.

戻り値

The stage instance.

戻り値の型

StageInstance

await edit(*, reason=None, **options)

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

バージョン 2.0 で変更: The topic parameter must now be set via create_instance.

バージョン 2.0 で変更: Edits are no longer in-place, the newly edited channel is returned instead.

パラメータ
  • name (str) -- The new channel's name.

  • position (int) -- The new channel's position.

  • sync_permissions (bool) -- Whether to sync permissions with the channel's new or pre-existing category. Defaults to False.

  • category (Optional[CategoryChannel]) -- The new category for this channel. Can be None to remove the category.

  • reason (Optional[str]) -- The reason for editing this channel. Shows up on the audit log.

  • overwrites (Mapping) -- A Mapping of target (either a role or a member) to PermissionOverwrite to apply to the channel.

  • rtc_region (Optional[VoiceRegion]) -- The new region for the stage channel's voice communication. A value of None indicates automatic voice region detection.

  • video_quality_mode (VideoQualityMode) --

    The camera video quality for the stage channel's participants.

    バージョン 2.0 で追加.

例外
  • InvalidArgument -- If the permission overwrite information is not in proper form.

  • Forbidden -- You do not have permissions to edit the channel.

  • HTTPException -- Editing the channel failed.

戻り値

The newly edited stage channel. If the edit was only positional then None is returned instead.

戻り値の型

Optional[StageChannel]

property category: Optional[CategoryChannel]

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property changed_roles: List[discord.role.Role]

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)

This function is a coroutine.

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

This requires Intents.voice_states.

パラメータ
  • timeout (float) -- The timeout in seconds to wait for the voice endpoint.

  • reconnect (bool) -- Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) -- A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

例外
戻り値

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

戻り値の型

VoiceProtocol

await create_event(name, scheduled_start_time, *, description=..., privacy_level=..., entity_type=...)

This function is a coroutine.

Create a new guild event with this channel.

You must have the manage_events permission to create a guild event.

注釈

Another extra permissions is required for different type of entity_type.

If your entity type is GuildScheduledEventType.stage_instance, you must have the following extra permissions:

If your entity type is GuildScheduledEventType.voice, you must have the following extra permissions:

  • view_channel for channel associated with the event.

  • connect for channel associated with the event.

If your entity type is GuildScheduledEventType.external, you dont need any extra permissions.

バージョン 2.0 で追加.

パラメータ
  • name (str) -- The name of the event.

  • description (Optional[str]) -- The description of the event. Could be None for no description.

  • privacy_level (Optional[GuildScheduledEventPrivacyLevel]) -- The event privacy level, same thing as StageInstance PrivacyLevel

  • scheduled_start_time (datetime.datetime) -- The scheduled start time, timezone must be UTC. If not it will be converted automatically.

  • entity_type (Optional[GuildScheduledEventType]) -- The entity_type or type for the event. If you don't provide this, it will automatically check from the channel type.

例外
  • Forbidden -- You do not have permissions to create the guild event.

  • HTTPException -- Creating the guild event failed.

  • ValueError -- Validation error occurred.

戻り値

The newly updated guild event.

戻り値の型

GuildScheduledEvent

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

パラメータ
  • max_age (int) -- How long the invite should last in seconds. If it's 0 then the invite doesn't expire. Defaults to 0.

  • max_uses (int) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to 0.

  • temporary (bool) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (bool) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • reason (Optional[str]) -- The reason for creating this invite. Shows up on the audit log.

  • target_type (Optional[InviteTarget]) --

    The type of target for the voice channel invite, if any.

    バージョン 2.0 で追加.

  • target_user (Optional[User]) --

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    バージョン 2.0 で追加.

  • target_application_id: --

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    バージョン 2.0 で追加.

例外
  • HTTPException -- Invite creation failed.

  • NotFound -- The channel that was passed is a category or an invalid channel.

戻り値

The invite that was created.

戻り値の型

Invite

property created_at: datetime.datetime

Returns the channel's creation time in UTC.

Type

datetime.datetime

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

パラメータ

reason (Optional[str]) -- The reason for deleting this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have proper permissions to delete the channel.

  • NotFound -- The channel was not found or was already deleted.

  • HTTPException -- Deleting the channel failed.

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this channel.

You must have manage_channels to get this information.

例外
  • Forbidden -- You do not have proper permissions to get the information.

  • HTTPException -- An error occurred while fetching the information.

戻り値

The list of invites that are currently active.

戻り値の型

List[Invite]

property members: List[Member]

Returns all members that are currently inside this voice channel.

Type

List[Member]

property mention: str

The string that allows you to mention the channel.

Type

str

await move(**kwargs)

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have the manage_channels permission to do this.

注釈

Voice channels will always be sorted below text channels. This is a Discord limitation.

バージョン 1.7 で追加.

パラメータ
  • beginning (bool) -- Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) -- Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (Snowflake) -- The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (Snowflake) -- The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) -- The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[Snowflake]) -- The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) -- Whether to sync the permissions with the category (if given).

  • reason (str) -- The reason for the move.

例外
  • InvalidArgument -- An invalid position was given or a bad mix of arguments were passed.

  • Forbidden -- You do not have permissions to move the channel.

  • HTTPException -- Moving the channel failed.

property overwrites: Dict[Union[Role, Member], PermissionOverwrite]

Returns all of the channel's overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

戻り値

The channel's permission overwrites.

戻り値の型

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

パラメータ

obj (Union[Role, User]) -- The role or user denoting whose overwrite to get.

戻り値

The permission overwrites for this object.

戻り値の型

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

バージョン 2.0 で変更: The object passed in can now be a role object.

パラメータ

obj (Union[Member, Role]) -- The object to resolve permissions for. This could be either a member or a role. If it's a role then member overwrites are not computed.

戻り値

The resolved permissions for the member or role.

戻り値の型

Permissions

property permissions_synced: bool

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

バージョン 1.3 で追加.

Type

bool

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)

This function is a coroutine.

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

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have the manage_roles permission to use this.

注釈

This method replaces the old overwrites with the ones given.

サンプル

Setting allow and deny:

await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
パラメータ
  • target (Union[Member, Role]) -- The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) -- The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions -- A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

  • reason (Optional[str]) -- The reason for doing this action. Shows up on the audit log.

例外
  • Forbidden -- You do not have permissions to edit channel specific permissions.

  • HTTPException -- Editing channel specific permissions failed.

  • NotFound -- The role or member being edited is not part of the guild.

  • InvalidArgument -- The overwrite parameter invalid or the target type was not Role or Member.

property voice_states: Dict[int, VoiceState]

Returns a mapping of member IDs who have voice states in this channel.

バージョン 1.3 で追加.

注釈

This function is intentionally low level to replace members when the member cache is unavailable.

戻り値

The mapping of member ID to a voice state.

戻り値の型

Mapping[int, VoiceState]

StageInstance

class discord.StageInstance

Represents a stage instance of a stage channel in a guild.

バージョン 2.0 で追加.

x == y

Checks if two stage instances are equal.

x != y

Checks if two stage instances are not equal.

hash(x)

Returns the stage instance's hash.

id

The stage instance's ID.

Type

int

guild

The guild that the stage instance is running in.

Type

Guild

channel_id

The ID of the channel that the stage instance is running in.

Type

int

topic

The topic of the stage instance.

Type

str

privacy_level

The privacy level of the stage instance.

Type

StagePrivacyLevel

discoverable_disabled

Whether discoverability for the stage instance is disabled.

Type

bool

channel

The channel that stage instance is running in.

Type

Optional[StageChannel]

await edit(*, topic=..., privacy_level=..., reason=None)

This function is a coroutine.

Edits the stage instance.

You must have the manage_channels permission to use this.

パラメータ
  • topic (str) -- The stage instance's new topic.

  • privacy_level (StagePrivacyLevel) -- The stage instance's new privacy level.

  • reason (str) -- The reason the stage instance was edited. Shows up on the audit log.

例外
  • InvalidArgument -- If the privacy_level parameter is not the proper type.

  • Forbidden -- You do not have permissions to edit the stage instance.

  • HTTPException -- Editing a stage instance failed.

await delete(*, reason=None)

This function is a coroutine.

Deletes the stage instance.

You must have the manage_channels permission to use this.

パラメータ

reason (str) -- The reason the stage instance was deleted. Shows up on the audit log.

例外
  • Forbidden -- You do not have permissions to delete the stage instance.

  • HTTPException -- Deleting the stage instance failed.

CategoryChannel

class discord.CategoryChannel

Discordのチャンネルカテゴリを表します。

These are useful to group channels to logical compartments.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

カテゴリのハッシュを返します。

str(x)

カテゴリの名前を返します。

name

The category name.

Type

str

guild

The guild the category belongs to.

Type

Guild

id

The category channel ID.

Type

int

position

The position in the category list. This is a number that starts at 0. e.g. the top category is position 0.

Type

int

nsfw

If the channel is marked as "not safe for work".

注釈

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

Type

bool

property type: discord.enums.ChannelType

The channel's Discord type.

Type

ChannelType

is_nsfw()

bool: Checks if the category is NSFW.

await clone(*, name=None, reason=None)

This function is a coroutine.

Clones this channel. This creates a channel with the same properties as this channel.

You must have the manage_channels permission to do this.

バージョン 1.1 で追加.

パラメータ
  • name (Optional[str]) -- The name of the new channel. If not provided, defaults to this channel name.

  • reason (Optional[str]) -- The reason for cloning this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

戻り値

The channel that was created.

戻り値の型

abc.GuildChannel

await edit(*, reason=None, **options)

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

バージョン 1.3 で変更: The overwrites keyword-only parameter was added.

バージョン 2.0 で変更: Edits are no longer in-place, the newly edited channel is returned instead.

パラメータ
  • name (str) -- The new category's name.

  • position (int) -- The new category's position.

  • nsfw (bool) -- To mark the category as NSFW or not.

  • reason (Optional[str]) -- The reason for editing this category. Shows up on the audit log.

  • overwrites (Mapping) -- A Mapping of target (either a role or a member) to PermissionOverwrite to apply to the channel.

例外
  • InvalidArgument -- If position is less than 0 or greater than the number of categories.

  • Forbidden -- You do not have permissions to edit the category.

  • HTTPException -- Editing the category failed.

戻り値

The newly edited category channel. If the edit was only positional then None is returned instead.

戻り値の型

Optional[CategoryChannel]

await move(**kwargs)

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have the manage_channels permission to do this.

注釈

Voice channels will always be sorted below text channels. This is a Discord limitation.

バージョン 1.7 で追加.

パラメータ
  • beginning (bool) -- Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) -- Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (Snowflake) -- The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (Snowflake) -- The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) -- The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[Snowflake]) -- The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) -- Whether to sync the permissions with the category (if given).

  • reason (str) -- The reason for the move.

例外
  • InvalidArgument -- An invalid position was given or a bad mix of arguments were passed.

  • Forbidden -- You do not have permissions to move the channel.

  • HTTPException -- Moving the channel failed.

property channels: List[GuildChannelType]

Returns the channels that are under this category.

These are sorted by the official Discord UI, which places voice channels below the text channels.

Type

List[abc.GuildChannel]

property text_channels: List[discord.channel.TextChannel]

Returns the text channels that are under this category.

Type

List[TextChannel]

property voice_channels: List[discord.channel.VoiceChannel]

Returns the voice channels that are under this category.

Type

List[VoiceChannel]

property stage_channels: List[discord.channel.StageChannel]

Returns the stage channels that are under this category.

バージョン 1.7 で追加.

Type

List[StageChannel]

await create_text_channel(name, **options)

This function is a coroutine.

A shortcut method to Guild.create_text_channel() to create a TextChannel in the category.

戻り値

The channel that was just created.

戻り値の型

TextChannel

await create_voice_channel(name, **options)

This function is a coroutine.

A shortcut method to Guild.create_voice_channel() to create a VoiceChannel in the category.

戻り値

The channel that was just created.

戻り値の型

VoiceChannel

await create_stage_channel(name, **options)

This function is a coroutine.

A shortcut method to Guild.create_stage_channel() to create a StageChannel in the category.

バージョン 1.7 で追加.

戻り値

The channel that was just created.

戻り値の型

StageChannel

property category: Optional[CategoryChannel]

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property changed_roles: List[discord.role.Role]

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

await create_event(name, scheduled_start_time, *, description=..., privacy_level=..., entity_type=...)

This function is a coroutine.

Create a new guild event with this channel.

You must have the manage_events permission to create a guild event.

注釈

Another extra permissions is required for different type of entity_type.

If your entity type is GuildScheduledEventType.stage_instance, you must have the following extra permissions:

If your entity type is GuildScheduledEventType.voice, you must have the following extra permissions:

  • view_channel for channel associated with the event.

  • connect for channel associated with the event.

If your entity type is GuildScheduledEventType.external, you dont need any extra permissions.

バージョン 2.0 で追加.

パラメータ
  • name (str) -- The name of the event.

  • description (Optional[str]) -- The description of the event. Could be None for no description.

  • privacy_level (Optional[GuildScheduledEventPrivacyLevel]) -- The event privacy level, same thing as StageInstance PrivacyLevel

  • scheduled_start_time (datetime.datetime) -- The scheduled start time, timezone must be UTC. If not it will be converted automatically.

  • entity_type (Optional[GuildScheduledEventType]) -- The entity_type or type for the event. If you don't provide this, it will automatically check from the channel type.

例外
  • Forbidden -- You do not have permissions to create the guild event.

  • HTTPException -- Creating the guild event failed.

  • ValueError -- Validation error occurred.

戻り値

The newly updated guild event.

戻り値の型

GuildScheduledEvent

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

パラメータ
  • max_age (int) -- How long the invite should last in seconds. If it's 0 then the invite doesn't expire. Defaults to 0.

  • max_uses (int) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to 0.

  • temporary (bool) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (bool) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • reason (Optional[str]) -- The reason for creating this invite. Shows up on the audit log.

  • target_type (Optional[InviteTarget]) --

    The type of target for the voice channel invite, if any.

    バージョン 2.0 で追加.

  • target_user (Optional[User]) --

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    バージョン 2.0 で追加.

  • target_application_id: --

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    バージョン 2.0 で追加.

例外
  • HTTPException -- Invite creation failed.

  • NotFound -- The channel that was passed is a category or an invalid channel.

戻り値

The invite that was created.

戻り値の型

Invite

property created_at: datetime.datetime

Returns the channel's creation time in UTC.

Type

datetime.datetime

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

パラメータ

reason (Optional[str]) -- The reason for deleting this channel. Shows up on the audit log.

例外
  • Forbidden -- You do not have proper permissions to delete the channel.

  • NotFound -- The channel was not found or was already deleted.

  • HTTPException -- Deleting the channel failed.

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this channel.

You must have manage_channels to get this information.

例外
  • Forbidden -- You do not have proper permissions to get the information.

  • HTTPException -- An error occurred while fetching the information.

戻り値

The list of invites that are currently active.

戻り値の型

List[Invite]

property mention: str

The string that allows you to mention the channel.

Type

str

property overwrites: Dict[Union[Role, Member], PermissionOverwrite]

Returns all of the channel's overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

戻り値

The channel's permission overwrites.

戻り値の型

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

パラメータ

obj (Union[Role, User]) -- The role or user denoting whose overwrite to get.

戻り値

The permission overwrites for this object.

戻り値の型

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

バージョン 2.0 で変更: The object passed in can now be a role object.

パラメータ

obj (Union[Member, Role]) -- The object to resolve permissions for. This could be either a member or a role. If it's a role then member overwrites are not computed.

戻り値

The resolved permissions for the member or role.

戻り値の型

Permissions

property permissions_synced: bool

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

バージョン 1.3 で追加.

Type

bool

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)

This function is a coroutine.

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

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have the manage_roles permission to use this.

注釈

This method replaces the old overwrites with the ones given.

サンプル

Setting allow and deny:

await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
パラメータ
  • target (Union[Member, Role]) -- The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) -- The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions -- A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

  • reason (Optional[str]) -- The reason for doing this action. Shows up on the audit log.

例外
  • Forbidden -- You do not have permissions to edit channel specific permissions.

  • HTTPException -- Editing channel specific permissions failed.

  • NotFound -- The role or member being edited is not part of the guild.

  • InvalidArgument -- The overwrite parameter invalid or the target type was not Role or Member.

DMChannel

class discord.DMChannel

Represents a Discord direct message channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel's hash.

str(x)

Returns a string representation of the channel

recipient

The user you are participating with in the direct message channel. If this channel is received through the gateway, the recipient information may not be always available.

Type

Optional[User]

me

The user presenting yourself.

Type

ClientUser

id

The direct message channel ID.

Type

int

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Returns an AsyncIterator that enables receiving the destination's message history.

You must have read_message_history permissions to use this.

サンプル

使い方

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

すべてのパラメータがオプションです。

パラメータ
  • limit (Optional[int]) -- The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages before this date or message. 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 (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. 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.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

  • oldest_first (Optional[bool]) -- If set to True, return messages in oldest->newest order. Defaults to True if after is specified, otherwise False.

例外
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

列挙

Message -- The message with the message data parsed.

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

注釈

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property type: discord.enums.ChannelType

The channel's Discord type.

Type

ChannelType

property created_at: datetime.datetime

Returns the direct message channel's creation time in UTC.

Type

datetime.datetime

permissions_for(obj=None, /)

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

Actual direct messages do not really have the concept of permissions.

This returns all the Text related permissions set to True except:

パラメータ

obj (User) -- The user to check permissions for. This parameter is ignored but kept for compatibility with other permissions_for methods.

戻り値

The resolved permissions.

戻り値の型

Permissions

get_partial_message(message_id, /)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

バージョン 1.6 で追加.

パラメータ

message_id (int) -- The message ID to create a partial message for.

戻り値

The partial message.

戻り値の型

PartialMessage

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

パラメータ

id (int) -- The message ID to look for.

例外
  • NotFound -- The specified message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

戻り値

The message asked for.

戻り値の型

Message

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

注釈

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

例外

HTTPException -- Retrieving the pinned messages failed.

戻り値

The messages that are currently pinned.

戻り値の型

List[Message]

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

パラメータ
  • content (Optional[str]) -- The content of the message to send.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • embed (Embed) -- The rich embed for the content.

  • file (File) -- The file to upload.

  • files (List[File]) -- A list of files to upload. Must be a maximum of 10.

  • nonce (int) -- The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) -- If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) --

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    バージョン 1.4 で追加.

  • reference (Union[Message, MessageReference, PartialMessage]) --

    A reference to the Message to which you are replying, this can be created using to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    バージョン 1.6 で追加.

  • mention_author (Optional[bool]) --

    If set, overrides the replied_user attribute of allowed_mentions.

    バージョン 1.6 で追加.

  • view (discord.ui.View) -- A Discord UI View to add to the message.

  • embeds (List[Embed]) --

    A list of embeds to upload. Must be a maximum of 10.

    バージョン 2.0 で追加.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) --

    A list of stickers to upload. Must be a maximum of 3.

    バージョン 2.0 で追加.

例外
戻り値

The message that was sent.

戻り値の型

Message

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

GroupChannel

class discord.GroupChannel

Represents a Discord group channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel's hash.

str(x)

Returns a string representation of the channel

recipients

The users you are participating with in the group channel.

Type

List[User]

me

The user presenting yourself.

Type

ClientUser

id

The group channel ID.

Type

int

owner

The user that owns the group channel.

Type

Optional[User]

owner_id

The owner ID that owns the group channel.

バージョン 2.0 で追加.

Type

int

name

The group channel's name if provided.

Type

Optional[str]

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Returns an AsyncIterator that enables receiving the destination's message history.

You must have read_message_history permissions to use this.

サンプル

使い方

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

すべてのパラメータがオプションです。

パラメータ
  • limit (Optional[int]) -- The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages before this date or message. 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 (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. 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.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

  • oldest_first (Optional[bool]) -- If set to True, return messages in oldest->newest order. Defaults to True if after is specified, otherwise False.

例外
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

列挙

Message -- The message with the message data parsed.

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

注釈

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property type: discord.enums.ChannelType

The channel's Discord type.

Type

ChannelType

property icon: Optional[discord.asset.Asset]

Returns the channel's icon asset if available.

Type

Optional[Asset]

property created_at: datetime.datetime

Returns the channel's creation time in UTC.

Type

datetime.datetime

permissions_for(obj, /)

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

Actual direct messages do not really have the concept of permissions.

This returns all the Text related permissions set to True except:

This also checks the kick_members permission if the user is the owner.

パラメータ

obj (Snowflake) -- The user to check permissions for.

戻り値

The resolved permissions for the user.

戻り値の型

Permissions

await leave()

This function is a coroutine.

Leave the group.

If you are the only one in the group, this deletes it as well.

例外

HTTPException -- Leaving the group failed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

パラメータ

id (int) -- The message ID to look for.

例外
  • NotFound -- The specified message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

戻り値

The message asked for.

戻り値の型

Message

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

注釈

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

例外

HTTPException -- Retrieving the pinned messages failed.

戻り値

The messages that are currently pinned.

戻り値の型

List[Message]

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

パラメータ
  • content (Optional[str]) -- The content of the message to send.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • embed (Embed) -- The rich embed for the content.

  • file (File) -- The file to upload.

  • files (List[File]) -- A list of files to upload. Must be a maximum of 10.

  • nonce (int) -- The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) -- If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) --

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    バージョン 1.4 で追加.

  • reference (Union[Message, MessageReference, PartialMessage]) --

    A reference to the Message to which you are replying, this can be created using to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    バージョン 1.6 で追加.

  • mention_author (Optional[bool]) --

    If set, overrides the replied_user attribute of allowed_mentions.

    バージョン 1.6 で追加.

  • view (discord.ui.View) -- A Discord UI View to add to the message.

  • embeds (List[Embed]) --

    A list of embeds to upload. Must be a maximum of 10.

    バージョン 2.0 で追加.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) --

    A list of stickers to upload. Must be a maximum of 3.

    バージョン 2.0 で追加.

例外
戻り値

The message that was sent.

戻り値の型

Message

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

PartialInviteGuild

class discord.PartialInviteGuild

Represents a "partial" invite guild.

This model will be given when the user is not part of the guild the Invite resolves to.

x == y

Checks if two partial guilds are the same.

x != y

Checks if two partial guilds are not the same.

hash(x)

Return the partial guild's hash.

str(x)

Returns the partial guild's name.

name

The partial guild's name.

Type

str

id

The partial guild's ID.

Type

int

verification_level

The partial guild's verification level.

Type

VerificationLevel

features

A list of features the guild has. See Guild.features for more information.

Type

List[str]

description

The partial guild's description.

Type

Optional[str]

property created_at: datetime.datetime

Returns the guild's creation time in UTC.

Type

datetime.datetime

property icon: Optional[discord.asset.Asset]

Returns the guild's icon asset, if available.

Type

Optional[Asset]

property banner: Optional[discord.asset.Asset]

Returns the guild's banner asset, if available.

Type

Optional[Asset]

property splash: Optional[discord.asset.Asset]

Returns the guild's invite splash asset, if available.

Type

Optional[Asset]

PartialInviteChannel

class discord.PartialInviteChannel

Represents a "partial" invite channel.

This model will be given when the user is not part of the guild the Invite resolves to.

x == y

Checks if two partial channels are the same.

x != y

Checks if two partial channels are not the same.

hash(x)

Return the partial channel's hash.

str(x)

Returns the partial channel's name.

name

The partial channel's name.

Type

str

id

The partial channel's ID.

Type

int

type

The partial channel's type.

Type

ChannelType

property mention: str

The string that allows you to mention the channel.

Type

str

property created_at: datetime.datetime

Returns the channel's creation time in UTC.

Type

datetime.datetime

Invite

class discord.Invite

Represents a Discord Guild or abc.GuildChannel invite or a User invite.

Depending on the way this object was created, some of the attributes can have a value of None.

x == y

Checks if two invites are equal.

x != y

Checks if two invites are not equal.

hash(x)

Returns the invite hash.

str(x)

Returns the invite URL.

The following table illustrates what methods will obtain the attributes:

If it's not in the table above then it is available by all methods.

max_age

How long before the invite expires in seconds. A value of 0 indicates that it doesn't expire.

Type

int

code

The URL fragment used for the invite.

Type

str

guild

The guild the invite is for. Can be None if it's from a group direct message.

Type

Optional[Union[Guild, Object, PartialInviteGuild]]

revoked

Indicates if the invite has been revoked.

Type

bool

created_at

An aware UTC datetime object denoting the time the invite was created.

Type

datetime.datetime

temporary

Indicates that the invite grants temporary membership. If True, members who joined via this invite will be kicked upon disconnect.

Type

bool

uses

How many times the invite has been used.

Type

int

max_uses

How many times the invite can be used. A value of 0 indicates that it has unlimited uses.

Type

int

inviter

The user who created the invite.

Type

Optional[User]

approximate_member_count

The approximate number of members in the guild.

Type

Optional[int]

approximate_presence_count

The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded.

Type

Optional[int]

expires_at

The expiration date of the invite. If the value is None when received through Client.fetch_invite with with_expiration enabled, the invite will never expire.

バージョン 2.0 で追加.

Type

Optional[datetime.datetime]

channel

The channel the invite is for.

バージョン 2.0 で変更: The channel is now an optional attribute. If the invite is for a guild channel it will be filled in, but if it's a friend invite it will be empty.

Type

Optional[Union[abc.GuildChannel, Object, PartialInviteChannel]]

target_type

The type of target for the voice channel invite.

バージョン 2.0 で追加.

Type

InviteTarget

target_user

The user whose stream to display for this invite, if any.

バージョン 2.0 で追加.

Type

Optional[User]

target_application

The embedded application the invite targets, if any.

バージョン 2.0 で追加.

Type

Optional[PartialAppInfo]

guild_scheduled_event

The guild scheduled event the invite targets, if any.

バージョン 2.0 で追加.

Type

Optional[GuildScheduledEvent]

property id: str

Returns the proper code portion of the invite.

Type

str

property url: str

A property that retrieves the invite URL.

Type

str

property friend_invite

Check if the Invite is friend invite.

バージョン 2.0 で追加.

Type

bool

await delete(*, reason=None)

This function is a coroutine.

Revokes the instant invite.

You must have the manage_channels permission to do this.

パラメータ

reason (Optional[str]) -- The reason for deleting this invite. Shows up on the audit log.

例外
  • Forbidden -- You do not have permissions to revoke invites.

  • NotFound -- The invite is invalid or expired.

  • HTTPException -- Revoking the invite failed.

Template

class discord.Template

Represents a Discord template.

バージョン 1.4 で追加.

code

The template code.

Type

str

uses

How many times the template has been used.

Type

int

name

The name of the template.

Type

str

description

The description of the template.

Type

str

creator

The creator of the template.

Type

User

created_at

An aware datetime in UTC representing when the template was created.

Type

datetime.datetime

updated_at

An aware datetime in UTC representing when the template was last updated. This is referred to as "last synced" in the official Discord client.

Type

datetime.datetime

source_guild

The source guild.

Type

Guild

is_dirty

Whether the template has unsynced changes.

バージョン 2.0 で追加.

Type

Optional[bool]

await create_guild(name, region=None, icon=None)

This function is a coroutine.

Creates a Guild using the template.

10以上のギルドに参加しているBotアカウントはギルドの作成ができません。

パラメータ
例外
戻り値

作成されたギルド。キャッシュに追加されるギルドとは別物です。

戻り値の型

Guild

await sync()

This function is a coroutine.

Sync the template to the guild's current state.

You must have the manage_guild permission in the source guild to do this.

バージョン 1.7 で追加.

バージョン 2.0 で変更: The template is no longer edited in-place, instead it is returned.

例外
  • HTTPException -- Editing the template failed.

  • Forbidden -- You don't have permissions to edit the template.

  • NotFound -- This template does not exist.

戻り値

The newly edited template.

戻り値の型

Template

await edit(*, name=..., description=...)

This function is a coroutine.

Edit the template metadata.

You must have the manage_guild permission in the source guild to do this.

バージョン 1.7 で追加.

バージョン 2.0 で変更: The template is no longer edited in-place, instead it is returned.

パラメータ
  • name (str) -- The template's new name.

  • description (Optional[str]) -- The template's new description.

例外
  • HTTPException -- Editing the template failed.

  • Forbidden -- You don't have permissions to edit the template.

  • NotFound -- This template does not exist.

戻り値

The newly edited template.

戻り値の型

Template

await delete()

This function is a coroutine.

Delete the template.

You must have the manage_guild permission in the source guild to do this.

バージョン 1.7 で追加.

例外
  • HTTPException -- Editing the template failed.

  • Forbidden -- You don't have permissions to edit the template.

  • NotFound -- This template does not exist.

property url: str

The template url.

バージョン 2.0 で追加.

Type

str

WelcomeChannel

class discord.WelcomeChannel

Represents a WelcomeScreen welcome channel.

バージョン 2.0 で追加.

channel

The snowflake of the channel, this can be any channel.

Type

abc.Snowflake

description

The description of the welcome channel.

Type

str

emoji

The emoji of the welcome channel if exists.

Type

Optional[Union[Emoji, PartialEmoji, str]]

WelcomeScreen

Methods
class discord.WelcomeScreen

Represents a welcome screen for a Guild.

バージョン 2.0 で追加.

guild

The guild the welcome screen belongs to.

Type

Guild

description

The description of the welcome screen.

Type

Optional[str]

channels

The list of welcome channels.

Type

List[WelcomeChannel]

property enabled: bool

Returns if the welcome screen is enabled.

Type

bool

await edit(*, enabled=..., channels=..., description=..., reason=None)

This function is a coroutine.

Edit the welcome screen of a guild.

You must have the manage_guild permission in the guild to do this.

注釈

Welcome channels can only accept custom emojis if premium_tier is level 2 or above.

パラメータ
  • enabled (bool) -- Should we enable the welcome screen of not.

  • channels (List[WelcomeChannel]) -- The channels to use for the welcome screen.

  • description (str) -- The description of the welcome screen.

  • reason (Optional[str]) -- The reason for editing the welcome screen. Shows up on the audit log.

例外

WidgetChannel

class discord.WidgetChannel

Represents a "partial" widget channel.

x == y

Checks if two partial channels are the same.

x != y

Checks if two partial channels are not the same.

hash(x)

Return the partial channel's hash.

str(x)

Returns the partial channel's name.

id

The channel's ID.

Type

int

name

The channel's name.

Type

str

position

The channel's position

Type

int

property mention: str

The string that allows you to mention the channel.

Type

str

property created_at: datetime.datetime

Returns the channel's creation time in UTC.

Type

datetime.datetime

WidgetMember

class discord.WidgetMember

Represents a "partial" member of the widget's guild.

x == y

Checks if two widget members are the same.

x != y

Checks if two widget members are not the same.

hash(x)

Return the widget member's hash.

str(x)

Returns the widget member's name#discriminator.

id

The member's ID.

Type

int

name

The member's username.

Type

str

discriminator

The member's discriminator.

Type

str

bot

Whether the member is a bot.

Type

bool

status

The member's status.

Type

Status

nick

The member's nickname.

Type

Optional[str]

avatar

The member's avatar hash.

Type

Optional[str]

activity

The member's activity.

Type

Optional[Union[BaseActivity, Spotify]]

deafened

Whether the member is currently deafened.

Type

Optional[bool]

muted

Whether the member is currently muted.

Type

Optional[bool]

suppress

Whether the member is currently being suppressed.

Type

Optional[bool]

connected_channel

Which channel the member is connected to.

Type

Optional[WidgetChannel]

property display_name: str

Returns the member's display name.

Type

str

property accent_color: Optional[discord.colour.Colour]

Returns the user's accent color, if applicable.

There is an alias for this named accent_colour.

バージョン 2.0 で追加.

注釈

This information is only available via Client.fetch_user().

Type

Optional[Colour]

property accent_colour: Optional[discord.colour.Colour]

Returns the user's accent colour, if applicable.

There is an alias for this named accent_color.

バージョン 2.0 で追加.

注釈

This information is only available via Client.fetch_user().

Type

Optional[Colour]

property banner: Optional[discord.asset.Asset]

Returns the user's banner asset, if available.

バージョン 2.0 で追加.

注釈

This information is only available via Client.fetch_user().

Type

Optional[Asset]

property color: discord.colour.Colour

A property that returns a color denoting the rendered color for the user. This always returns Colour.default().

There is an alias for this named colour.

Type

Colour

property colour: discord.colour.Colour

A property that returns a colour denoting the rendered colour for the user. This always returns Colour.default().

There is an alias for this named color.

Type

Colour

property created_at: datetime

Returns the user's creation time in UTC.

This is when the user's Discord account was created.

Type

datetime.datetime

property default_avatar: discord.asset.Asset

Returns the default avatar for a given user. This is calculated by the user's discriminator.

Type

Asset

property display_avatar: discord.asset.Asset

Returns the user's display avatar.

For regular users this is just their default avatar or uploaded avatar.

バージョン 2.0 で追加.

Type

Asset

property mention: str

Returns a string that allows you to mention the given user.

Type

str

mentioned_in(message)

指定のメッセージにユーザーに対するメンションが含まれているかを確認します。

パラメータ

message (Message) -- メンションが含まれているかを確認するメッセージ。

戻り値

Indicates if the user is mentioned in the message.

戻り値の型

bool

property public_flags: discord.flags.PublicUserFlags

The publicly available flags the user has.

Type

PublicUserFlags

Widget

class discord.Widget

Represents a Guild widget.

x == y

Checks if two widgets are the same.

x != y

Checks if two widgets are not the same.

str(x)

Returns the widget's JSON URL.

id

The guild's ID.

Type

int

name

The guild's name.

Type

str

channels

The accessible voice channels in the guild.

Type

List[WidgetChannel]

members

The online members in the server. Offline members do not appear in the widget.

注釈

Due to a Discord limitation, if this data is available the users will be "anonymized" with linear IDs and discriminator information being incorrect. Likewise, the number of members retrieved is capped.

Type

List[Member]

property created_at: datetime.datetime

Returns the member's creation time in UTC.

Type

datetime.datetime

property json_url: str

The JSON URL of the widget.

Type

str

property invite_url: str

The invite URL for the guild, if available.

Type

Optional[str]

await fetch_invite(*, with_counts=True)

This function is a coroutine.

Retrieves an Invite from the widget's invite URL. This is the same as Client.fetch_invite(); the invite code is abstracted away.

パラメータ

with_counts (bool) -- Whether to include count information in the invite. This fills the Invite.approximate_member_count and Invite.approximate_presence_count fields.

戻り値

The invite from the widget's invite URL.

戻り値の型

Invite

StickerPack

class discord.StickerPack

Represents a sticker pack.

バージョン 2.0 で追加.

str(x)

Returns the name of the sticker pack.

x == y

Checks if the sticker pack is equal to another sticker pack.

x != y

Checks if the sticker pack is not equal to another sticker pack.

name

The name of the sticker pack.

Type

str

description

The description of the sticker pack.

Type

str

id

The id of the sticker pack.

Type

int

stickers

The stickers of this sticker pack.

Type

List[StandardSticker]

sku_id

The SKU ID of the sticker pack.

Type

int

cover_sticker_id

The ID of the sticker used for the cover of the sticker pack.

Type

int

cover_sticker

The sticker used for the cover of the sticker pack.

Type

StandardSticker

property banner: discord.asset.Asset

The banner asset of the sticker pack.

Type

Asset

StickerItem

Attributes
Methods
class discord.StickerItem

Represents a sticker item.

バージョン 2.0 で追加.

str(x)

Returns the name of the sticker item.

x == y

Checks if the sticker item is equal to another sticker item.

x != y

Checks if the sticker item is not equal to another sticker item.

name

The sticker's name.

Type

str

id

The id of the sticker.

Type

int

format

The format for the sticker's image.

Type

StickerFormatType

url

The URL for the sticker's image.

Type

str

await fetch()

This function is a coroutine.

Attempts to retrieve the full sticker data of the sticker item.

例外

HTTPException -- Retrieving the sticker failed.

戻り値

The retrieved sticker.

戻り値の型

Union[StandardSticker, GuildSticker]

Sticker

class discord.Sticker

Represents a sticker.

バージョン 1.6 で追加.

str(x)

Returns the name of the sticker.

x == y

Checks if the sticker is equal to another sticker.

x != y

Checks if the sticker is not equal to another sticker.

name

The sticker's name.

Type

str

id

The id of the sticker.

Type

int

description

The description of the sticker.

Type

str

pack_id

The id of the sticker's pack.

Type

int

format

The format for the sticker's image.

Type

StickerFormatType

url

The URL for the sticker's image.

Type

str

property created_at: datetime.datetime

Returns the sticker's creation time in UTC.

Type

datetime.datetime

StandardSticker

Methods
class discord.StandardSticker

Represents a sticker that is found in a standard sticker pack.

バージョン 2.0 で追加.

str(x)

Returns the name of the sticker.

x == y

Checks if the sticker is equal to another sticker.

x != y

Checks if the sticker is not equal to another sticker.

name

The sticker's name.

Type

str

id

The id of the sticker.

Type

int

description

The description of the sticker.

Type

str

pack_id

The id of the sticker's pack.

Type

int

format

The format for the sticker's image.

Type

StickerFormatType

tags

A list of tags for the sticker.

Type

List[str]

sort_value

The sticker's sort order within its pack.

Type

int

await pack()

This function is a coroutine.

Retrieves the sticker pack that this sticker belongs to.

例外
戻り値

The retrieved sticker pack.

戻り値の型

StickerPack

GuildSticker

class discord.GuildSticker

Represents a sticker that belongs to a guild.

バージョン 2.0 で追加.

str(x)

Returns the name of the sticker.

x == y

Checks if the sticker is equal to another sticker.

x != y

Checks if the sticker is not equal to another sticker.

name

The sticker's name.

Type

str

id

The id of the sticker.

Type

int

description

The description of the sticker.

Type

str

format

The format for the sticker's image.

Type

StickerFormatType

available

Whether this sticker is available for use.

Type

bool

guild_id

The ID of the guild that this sticker is from.

Type

int

user

The user that created this sticker. This can only be retrieved using Guild.fetch_sticker() and having the manage_emojis_and_stickers permission.

Type

Optional[User]

emoji

The name of a unicode emoji that represents this sticker.

Type

str

guild

The guild that this sticker is from. Could be None if the bot is not in the guild.

バージョン 2.0 で追加.

Type

Optional[Guild]

await edit(*, name=..., description=..., emoji=..., reason=None)

This function is a coroutine.

Edits a GuildSticker for the guild.

パラメータ
  • name (str) -- The sticker's new name. Must be at least 2 characters.

  • description (Optional[str]) -- The sticker's new description. Can be None.

  • emoji (str) -- The name of a unicode emoji that represents the sticker's expression.

  • reason (str) -- The reason for editing this sticker. Shows up on the audit log.

例外
戻り値

The newly modified sticker.

戻り値の型

GuildSticker

await delete(*, reason=None)

This function is a coroutine.

Deletes the custom Sticker from the guild.

You must have manage_emojis_and_stickers permission to do this.

パラメータ

reason (Optional[str]) -- The reason for deleting this sticker. Shows up on the audit log.

例外
  • Forbidden -- You are not allowed to delete stickers.

  • HTTPException -- An error occurred deleting the sticker.

RawMessageDeleteEvent

class discord.RawMessageDeleteEvent

Represents the event payload for a on_raw_message_delete() event.

channel_id

The channel ID where the deletion took place.

Type

int

guild_id

The guild ID where the deletion took place, if applicable.

Type

Optional[int]

message_id

The message ID that got deleted.

Type

int

cached_message

The cached message, if found in the internal message cache.

Type

Optional[Message]

RawBulkMessageDeleteEvent

class discord.RawBulkMessageDeleteEvent

Represents the event payload for a on_raw_bulk_message_delete() event.

message_ids

A set of the message IDs that were deleted.

Type

Set[int]

channel_id

The channel ID where the message got deleted.

Type

int

guild_id

The guild ID where the message got deleted, if applicable.

Type

Optional[int]

cached_messages

The cached messages, if found in the internal message cache.

Type

List[Message]

RawMessageUpdateEvent

class discord.RawMessageUpdateEvent

Represents the payload for a on_raw_message_edit() event.

message_id

The message ID that got updated.

Type

int

channel_id

The channel ID where the update took place.

バージョン 1.3 で追加.

Type

int

guild_id

The guild ID where the message got updated, if applicable.

バージョン 1.7 で追加.

Type

Optional[int]

data

The raw data given by the gateway

Type

dict

cached_message

The cached message, if found in the internal message cache. Represents the message before it is modified by the data in RawMessageUpdateEvent.data.

Type

Optional[Message]

RawReactionActionEvent

class discord.RawReactionActionEvent

Represents the payload for a on_raw_reaction_add() or on_raw_reaction_remove() event.

message_id

The message ID that got or lost a reaction.

Type

int

user_id

The user ID who added the reaction or whose reaction was removed.

Type

int

channel_id

The channel ID where the reaction got added or removed.

Type

int

guild_id

The guild ID where the reaction got added or removed, if applicable.

Type

Optional[int]

emoji

The custom or unicode emoji being used.

Type

PartialEmoji

member

The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.

バージョン 1.3 で追加.

Type

Optional[Member]

event_type

The event type that triggered this action. Can be REACTION_ADD for reaction addition or REACTION_REMOVE for reaction removal.

バージョン 1.3 で追加.

Type

str

RawReactionClearEvent

class discord.RawReactionClearEvent

Represents the payload for a on_raw_reaction_clear() event.

message_id

The message ID that got its reactions cleared.

Type

int

channel_id

The channel ID where the reactions got cleared.

Type

int

guild_id

The guild ID where the reactions got cleared.

Type

Optional[int]

RawReactionClearEmojiEvent

class discord.RawReactionClearEmojiEvent

Represents the payload for a on_raw_reaction_clear_emoji() event.

バージョン 1.3 で追加.

message_id

The message ID that got its reactions cleared.

Type

int

channel_id

The channel ID where the reactions got cleared.

Type

int

guild_id

The guild ID where the reactions got cleared.

Type

Optional[int]

emoji

The custom or unicode emoji being removed.

Type

PartialEmoji

RawIntegrationDeleteEvent

class discord.RawIntegrationDeleteEvent

Represents the payload for a on_raw_integration_delete() event.

バージョン 2.0 で追加.

integration_id

The ID of the integration that got deleted.

Type

int

application_id

The ID of the bot/OAuth2 application for this deleted integration.

Type

Optional[int]

guild_id

The guild ID where the integration got deleted.

Type

int

RawThreadDeleteEvent

class discord.RawThreadDeleteEvent

Represents the payload for a on_raw_thread_delete() event.

バージョン 2.0 で追加.

thread_id

The ID of the thread that got deleted.

Type

int

thread_type

The channel type of the deleted thread.

Type

ChannelType

guild_id

The ID of the guild the thread was deleted in.

Type

int

parent_id

The ID of the channel the thread belonged to.

Type

int

thread

The thread, if it could be found in the internal cache.

Type

Optional[Thread]

PartialWebhookGuild

Attributes
class discord.PartialWebhookGuild

Represents a partial guild for webhooks.

These are typically given for channel follower webhooks.

バージョン 2.0 で追加.

id

The partial guild's ID.

Type

int

name

The partial guild's name.

Type

str

property icon: Optional[discord.asset.Asset]

Returns the guild's icon asset, if available.

Type

Optional[Asset]

PartialWebhookChannel

Attributes
class discord.PartialWebhookChannel

Represents a partial channel for webhooks.

These are typically given for channel follower webhooks.

バージョン 2.0 で追加.

id

The partial channel's ID.

Type

int

name

The partial channel's name.

Type

str

データクラス

Some classes are just there to be data containers, this lists them.

Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes.

ほぼすべてのクラスに __slots__ が定義されています。つまり、データクラスに動的に変数を追加することは不可能です。

The only exception to this rule is Object, which is made with dynamic attributes in mind.

Object

Attributes
class discord.Object(id)

Represents a generic Discord object.

The purpose of this class is to allow you to create 'miniature' versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in strange order and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y

二つのオブジェクトが等しいか比較します。

x != y

二つのオブジェクトが等しいものでないか比較します。

hash(x)

オブジェクトのハッシュを返します。

id

The ID of the object.

Type

int

property created_at: datetime.datetime

Returns the snowflake's creation time in UTC.

Type

datetime.datetime

Embed

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)

Discordの埋め込みを表します。

len(x)

Returns the total size of the embed. Useful for checking if it's within the 6000 character limit.

bool(b)

Returns whether the embed has any data set.

バージョン 2.0 で追加.

Certain properties return an EmbedProxy, a type that acts similar to a regular dict except using dotted access, e.g. embed.author.icon_url. If the attribute is invalid or empty, then a special sentinel value is returned, Embed.Empty.

使いやすさを考慮して、strが渡されることを想定されたすべてのパラメータは、暗黙的にstrにキャストされます。

title

The title of the embed. This can be set during initialisation.

Type

str

type

The type of embed. Usually "rich". This can be set during initialisation. Possible strings for embed types can be found on discord's api docs

Type

str

description

The description of the embed. This can be set during initialisation.

Type

str

url

The URL of the embed. This can be set during initialisation.

Type

str

timestamp

The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.

Type

datetime.datetime

colour

The colour code of the embed. Aliased to color as well. This can be set during initialisation.

Type

Union[Colour, int]

Empty

A special sentinel value used by EmbedProxy and this class to denote that the value or attribute is empty.

Type

Final

classmethod from_dict(data)

Converts a dict to a Embed provided it is in the format that Discord expects it to be in.

You can find out about this format in the official Discord documentation.

パラメータ

data (dict) -- The dictionary to convert into an embed.

copy()

Returns a shallow copy of the embed.

property footer: _EmbedFooterProxy

Returns an EmbedProxy denoting the footer contents.

See set_footer() for possible values you can access.

If the attribute has no value then Empty is returned.

Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.

パラメータ
  • text (str) -- フッターテキスト。

  • icon_url (str) -- The URL of the footer icon. Only HTTP(S) is supported.

Clears embed's footer information.

This function returns the class instance to allow for fluent-style chaining.

バージョン 2.0 で追加.

property image: _EmbedMediaProxy

Returns an EmbedProxy denoting the image contents.

Possible attributes you can access are:

  • url

  • proxy_url

  • width

  • height

If the attribute has no value then Empty is returned.

set_image(*, url)

Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.

バージョン 1.4 で変更: Passing Empty removes the image.

パラメータ

url (str) -- The source URL for the image. Only HTTP(S) is supported.

property thumbnail: _EmbedMediaProxy

Returns an EmbedProxy denoting the thumbnail contents.

Possible attributes you can access are:

  • url

  • proxy_url

  • width

  • height

If the attribute has no value then Empty is returned.

set_thumbnail(*, url)

Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style chaining.

バージョン 1.4 で変更: Passing Empty removes the thumbnail.

パラメータ

url (str) -- The source URL for the thumbnail. Only HTTP(S) is supported.

property video: _EmbedVideoProxy

Returns an EmbedProxy denoting the video contents.

Possible attributes include:

  • url for the video URL.

  • height for the video height.

  • width for the video width.

If the attribute has no value then Empty is returned.

property provider: _EmbedProviderProxy

Returns an EmbedProxy denoting the provider contents.

The only attributes that might be accessed are name and url.

If the attribute has no value then Empty is returned.

property author: _EmbedAuthorProxy

Returns an EmbedProxy denoting the author contents.

See set_author() for possible values you can access.

If the attribute has no value then Empty is returned.

set_author(*, name, url=Embed.Empty, icon_url=Embed.Empty)

Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.

パラメータ
  • name (str) -- The name of the author.

  • url (str) -- The URL for the author.

  • icon_url (str) -- The URL of the author icon. Only HTTP(S) is supported.

remove_author()

Clears embed's author information.

This function returns the class instance to allow for fluent-style chaining.

バージョン 1.4 で追加.

property fields: List[_EmbedFieldProxy]

Returns a list of EmbedProxy denoting the field contents.

See add_field() for possible values you can access.

If the attribute has no value then Empty is returned.

Type

List[Union[EmbedProxy, Empty]]

add_field(*, name, value, inline=True)

Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining.

パラメータ
  • name (str) -- フィールドの名前。

  • value (str) -- フィールドの値。

  • inline (bool) -- フィールドをインライン表示するかどうか。

insert_field_at(index, *, name, value, inline=True)

Inserts a field before a specified index to the embed.

This function returns the class instance to allow for fluent-style chaining.

バージョン 1.2 で追加.

パラメータ
  • index (int) -- The index of where to insert the field.

  • name (str) -- フィールドの名前。

  • value (str) -- フィールドの値。

  • inline (bool) -- フィールドをインライン表示するかどうか。

clear_fields()

埋め込みからすべてのフィールドを削除します。

remove_field(index)

特定のインデックスのフィールドを削除します。

If the index is invalid or out of bounds then the error is silently swallowed.

注釈

When deleting a field by index, the index of the other fields shift to fill the gap just like a regular list.

パラメータ

index (int) -- The index of the field to remove.

set_field_at(index, *, name, value, inline=True)

Modifies a field to the embed object.

The index must point to a valid pre-existing field.

This function returns the class instance to allow for fluent-style chaining.

パラメータ
  • index (int) -- The index of the field to modify.

  • name (str) -- フィールドの名前。

  • value (str) -- フィールドの値。

  • inline (bool) -- フィールドをインライン表示するかどうか。

例外

IndexError -- An invalid index was provided.

to_dict()

Converts this embed object into a dict.

AllowedMentions

class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)

A class that represents what mentions are allowed in a message.

This class can be set during Client initialisation to apply to every message sent. It can also be applied on a per message basis via abc.Messageable.send() for more fine-grained control.

everyone

Whether to allow everyone and here mentions. Defaults to True.

Type

bool

users

Controls the users being mentioned. If True (the default) then users are mentioned based on the message content. If False then users are not mentioned at all. If a list of abc.Snowflake is given then only the users provided will be mentioned, provided those users are in the message content.

Type

Union[bool, List[abc.Snowflake]]

roles

Controls the roles being mentioned. If True (the default) then roles are mentioned based on the message content. If False then roles are not mentioned at all. If a list of abc.Snowflake is given then only the roles provided will be mentioned, provided those roles are in the message content.

Type

Union[bool, List[abc.Snowflake]]

replied_user

Whether to mention the author of the message being replied to. Defaults to True.

バージョン 1.6 で追加.

Type

bool

classmethod all()

A factory method that returns a AllowedMentions with all fields explicitly set to True

バージョン 1.5 で追加.

classmethod none()

A factory method that returns a AllowedMentions with all fields set to False

バージョン 1.5 で追加.

MessageReference

class discord.MessageReference(*, message_id, channel_id, guild_id=None, fail_if_not_exists=True)

Represents a reference to a Message.

バージョン 1.5 で追加.

バージョン 1.6 で変更: This class can now be constructed by users.

message_id

The id of the message referenced.

Type

Optional[int]

channel_id

The channel id of the message referenced.

Type

int

guild_id

The guild id of the message referenced.

Type

Optional[int]

fail_if_not_exists

Whether replying to the referenced message should raise HTTPException if the message no longer exists or Discord could not fetch the message.

バージョン 1.7 で追加.

Type

bool

resolved

The message that this reference resolved to. If this is None then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of type DeletedReferencedMessage.

Currently, this is mainly the replied to message when a user replies to a message.

バージョン 1.6 で追加.

Type

Optional[Union[Message, DeletedReferencedMessage]]

classmethod from_message(message, *, fail_if_not_exists=True)

Creates a MessageReference from an existing Message.

バージョン 1.6 で追加.

パラメータ
  • message (Message) -- The message to be converted into a reference.

  • fail_if_not_exists (bool) --

    Whether replying to the referenced message should raise HTTPException if the message no longer exists or Discord could not fetch the message.

    バージョン 1.7 で追加.

戻り値

A reference to the message.

戻り値の型

MessageReference

property cached_message: Optional[discord.message.Message]

The cached message, if found in the internal message cache.

Type

Optional[Message]

property jump_url: str

Returns a URL that allows the client to jump to the referenced message.

バージョン 1.7 で追加.

Type

str

PartialMessage

Methods
class discord.PartialMessage(*, channel, id)

Represents a partial message to aid with working messages when only a message and channel ID are present.

There are two ways to construct this class. The first one is through the constructor itself, and the second is via the following:

Note that this class is trimmed down and has no rich attributes.

バージョン 1.6 で追加.

x == y

Checks if two partial messages are equal.

x != y

Checks if two partial messages are not equal.

hash(x)

Returns the partial message's hash.

channel

The channel associated with this partial message.

Type

Union[TextChannel, Thread, DMChannel]

id

The message ID.

Type

int

property jump_url: str

Returns a URL that allows the client to jump to this message.

Type

str

await delete(*, delay=None)

This function is a coroutine.

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people's messages, you need the manage_messages permission.

バージョン 1.1 で変更: Added the new delay keyword-only parameter.

パラメータ

delay (Optional[float]) -- If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.

例外
  • Forbidden -- You do not have proper permissions to delete the message.

  • NotFound -- The message was deleted already

  • HTTPException -- Deleting the message failed.

await publish()

This function is a coroutine.

Publishes this message to your announcement channel.

You must have the send_messages permission to do this.

If the message is not your own then the manage_messages permission is also needed.

例外
  • Forbidden -- You do not have the proper permissions to publish this message.

  • HTTPException -- Publishing the message failed.

await pin(*, reason=None)

This function is a coroutine.

Pins the message.

You must have the manage_messages permission to do this in a non-private channel context.

パラメータ

reason (Optional[str]) --

The reason for pinning the message. Shows up on the audit log.

バージョン 1.4 で追加.

例外
  • Forbidden -- You do not have permissions to pin the message.

  • NotFound -- The message or channel was not found or deleted.

  • HTTPException -- Pinning the message failed, probably due to the channel having more than 50 pinned messages.

await unpin(*, reason=None)

This function is a coroutine.

Unpins the message.

You must have the manage_messages permission to do this in a non-private channel context.

パラメータ

reason (Optional[str]) --

The reason for unpinning the message. Shows up on the audit log.

バージョン 1.4 で追加.

例外
  • Forbidden -- You do not have permissions to unpin the message.

  • NotFound -- The message or channel was not found or deleted.

  • HTTPException -- Unpinning the message failed.

await add_reaction(emoji)

This function is a coroutine.

Add a reaction to the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You must have the read_message_history permission to use this. If nobody else has reacted to the message using this emoji, the add_reactions permission is required.

パラメータ

emoji (Union[Emoji, Reaction, PartialEmoji, str]) -- The emoji to react with.

例外
  • HTTPException -- Adding the reaction failed.

  • Forbidden -- You do not have the proper permissions to react to the message.

  • NotFound -- The emoji you specified was not found.

  • InvalidArgument -- The emoji parameter is invalid.

await remove_reaction(emoji, member)

This function is a coroutine.

Remove a reaction by the member from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

If the reaction is not your own (i.e. member parameter is not you) then the manage_messages permission is needed.

The member parameter must represent a member and meet the abc.Snowflake abc.

パラメータ
例外
  • HTTPException -- Removing the reaction failed.

  • Forbidden -- You do not have the proper permissions to remove the reaction.

  • NotFound -- The member or emoji you specified was not found.

  • InvalidArgument -- The emoji parameter is invalid.

await clear_reaction(emoji)

This function is a coroutine.

Clears a specific reaction from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You need the manage_messages permission to use this.

バージョン 1.3 で追加.

パラメータ

emoji (Union[Emoji, Reaction, PartialEmoji, str]) -- The emoji to clear.

例外
  • HTTPException -- Clearing the reaction failed.

  • Forbidden -- You do not have the proper permissions to clear the reaction.

  • NotFound -- The emoji you specified was not found.

  • InvalidArgument -- The emoji parameter is invalid.

await clear_reactions()

This function is a coroutine.

Removes all the reactions from the message.

You need the manage_messages permission to use this.

例外
  • HTTPException -- Removing the reactions failed.

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

await reply(content=None, **kwargs)

This function is a coroutine.

A shortcut method to abc.Messageable.send() to reply to the Message.

バージョン 1.6 で追加.

例外
  • HTTPException -- Sending the message failed.

  • Forbidden -- You do not have the proper permissions to send the message.

  • InvalidArgument -- The files list is not of the appropriate size or you specified both file and files.

戻り値

The message that was sent.

戻り値の型

Message

to_reference(*, fail_if_not_exists=True)

Creates a MessageReference from the current message.

バージョン 1.6 で追加.

パラメータ

fail_if_not_exists (bool) --

Whether replying using the message reference should raise HTTPException if the message no longer exists or Discord could not fetch the message.

バージョン 1.7 で追加.

戻り値

The reference to this message.

戻り値の型

MessageReference

property created_at: datetime.datetime

The partial message's creation time in UTC.

Type

datetime.datetime

guild

The guild that the partial message belongs to, if applicable.

Type

Optional[Guild]

await fetch()

This function is a coroutine.

Fetches the partial message to a full Message.

例外
  • NotFound -- The message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

戻り値

The full message.

戻り値の型

Message

await edit(**fields)

This function is a coroutine.

Edits the message.

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

バージョン 1.7 で変更: discord.Message is returned instead of None if an edit took place.

パラメータ
  • content (Optional[str]) -- The new content to replace the message with. Could be None to remove the content.

  • embed (Optional[Embed]) -- The new embed to replace the original with. Could be None to remove the embed.

  • suppress (bool) -- Whether to suppress embeds for the message. This removes all the embeds if set to True. If set to False this brings the embeds back if they were suppressed. Using this parameter requires manage_messages.

  • delete_after (Optional[float]) -- If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.

  • allowed_mentions (Optional[AllowedMentions]) -- Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

  • view (Optional[View]) --

    The updated view to update this message with. If None is passed then the view is removed.

    バージョン 2.0 で追加.

例外
  • NotFound -- The message was not found.

  • HTTPException -- Editing the message failed.

  • Forbidden -- Tried to suppress a message without permissions or edited a message's content or embed that isn't yours.

戻り値

The message that was edited.

戻り値の型

Optional[Message]

SelectOption

class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)

Represents a select menu's option.

These can be created by users.

バージョン 2.0 で追加.

label

The label of the option. This is displayed to users. Can only be up to 100 characters.

Type

str

value

The value of the option. This is not displayed to users. If not provided when constructed then it defaults to the label. Can only be up to 100 characters.

Type

str

description

An additional description of the option, if any. Can only be up to 100 characters.

Type

Optional[str]

emoji

The emoji of the option, if available.

Type

Optional[Union[str, Emoji, PartialEmoji]]

default

Whether this option is selected by default.

Type

bool

Intents

class discord.Intents(**kwargs)

Wraps up a Discord gateway intent flag.

Similar to Permissions, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the intents keyword argument of Client.

バージョン 1.5 で追加.

x == y

Checks if two flags are equal.

x != y

Checks if two flags are not equal.

hash(x)

Return the flag's hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs.

value

The raw value. You should query flags via the properties rather than using this raw value.

Type

int

classmethod all()

A factory method that creates a Intents with everything enabled.

classmethod none()

A factory method that creates a Intents with everything disabled.

classmethod default()

A factory method that creates a Intents with everything enabled except presences and members.

guilds

Whether guild related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

It is highly advisable to leave this intent enabled for your bot to function.

Type

bool

members

Whether guild member related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

For more information go to the member intent documentation.

注釈

Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.

Type

bool

bans

Whether guild ban related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type

bool

emojis

Alias of emojis_and_stickers.

バージョン 2.0 で変更: Changed to an alias.

Type

bool

emojis_and_stickers

Whether guild emoji and sticker related events are enabled.

バージョン 2.0 で追加.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Type

bool

integrations

Whether guild integration related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type

bool

webhooks

Whether guild webhook related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type

bool

invites

Whether guild invite related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type

bool

voice_states

Whether guild voice state related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

注釈

This intent is required to connect to voice.

Type

bool

presences

Whether guild presence related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

For more information go to the presence intent documentation.

注釈

Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.

Type

bool

messages

Whether guild and direct message related events are enabled.

This is a shortcut to set or get both guild_messages and dm_messages.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Note that due to an implicit relationship this also corresponds to the following events:

Type

bool

guild_messages

Whether guild message related events are enabled.

See also dm_messages for DMs or messages for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Note that due to an implicit relationship this also corresponds to the following events:

Type

bool

dm_messages

Whether direct message related events are enabled.

See also guild_messages for guilds or messages for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Note that due to an implicit relationship this also corresponds to the following events:

Type

bool

reactions

Whether guild and direct message reaction related events are enabled.

This is a shortcut to set or get both guild_reactions and dm_reactions.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Type

bool

guild_reactions

Whether guild message reaction related events are enabled.

See also dm_reactions for DMs or reactions for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Type

bool

dm_reactions

Whether direct message reaction related events are enabled.

See also guild_reactions for guilds or reactions for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Type

bool

typing

Whether guild and direct message typing related events are enabled.

This is a shortcut to set or get both guild_typing and dm_typing.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type

bool

guild_typing

Whether guild and direct message typing related events are enabled.

See also dm_typing for DMs or typing for both.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type

bool

dm_typing

Whether guild and direct message typing related events are enabled.

See also guild_typing for guilds or typing for both.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type

bool

guild_scheduled_events

Whether guild scheduled events related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Type

bool

MemberCacheFlags

class discord.MemberCacheFlags(**kwargs)

Controls the library's cache policy when it comes to members.

This allows for finer grained control over what members are cached. Note that the bot's own member is always cached. This class is passed to the member_cache_flags parameter in Client.

Due to a quirk in how Discord works, in order to ensure proper cleanup of cache resources it is recommended to have Intents.members enabled. Otherwise the library cannot know when a member leaves a guild and is thus unable to cleanup after itself.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

The default value is all flags enabled.

バージョン 1.5 で追加.

x == y

Checks if two flags are equal.

x != y

Checks if two flags are not equal.

hash(x)

Return the flag's hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs.

value

The raw value. You should query flags via the properties rather than using this raw value.

Type

int

classmethod all()

A factory method that creates a MemberCacheFlags with everything enabled.

classmethod none()

A factory method that creates a MemberCacheFlags with everything disabled.

voice

Whether to cache members that are in voice.

This requires Intents.voice_states.

Members that leave voice are no longer cached.

Type

bool

joined

Whether to cache members that joined the guild or are chunked as part of the initial log in flow.

This requires Intents.members.

Members that leave the guild are no longer cached.

Type

bool

classmethod from_intents(intents)

A factory method that creates a MemberCacheFlags based on the currently selected Intents.

パラメータ

intents (Intents) -- The intents to select from.

戻り値

The resulting member cache flags.

戻り値の型

MemberCacheFlags

ApplicationFlags

class discord.ApplicationFlags(**kwargs)

Wraps up the Discord Application flags.

x == y

Checks if two ApplicationFlags are equal.

x != y

Checks if two ApplicationFlags are not equal.

hash(x)

Return the flag's hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

バージョン 2.0 で追加.

value

The raw value. You should query flags via the properties rather than using this raw value.

Type

int

gateway_presence

Returns True if the application is verified and is allowed to receive presence information over the gateway.

Type

bool

gateway_presence_limited

Returns True if the application is allowed to receive limited presence information over the gateway.

Type

bool

gateway_guild_members

Returns True if the application is verified and is allowed to receive guild members information over the gateway.

Type

bool

gateway_guild_members_limited

Returns True if the application is allowed to receive limited guild members information over the gateway.

Type

bool

verification_pending_guild_limit

Returns True if the application is currently pending verification and has hit the guild limit.

Type

bool

embedded

Returns True if the application is embedded within the Discord client.

Type

bool

File

class discord.File(fp, filename=None, description=None, *, spoiler=False)

A parameter object used for abc.Messageable.send() for sending file objects.

注釈

File objects are single use and are not meant to be reused in multiple abc.Messageable.send()s.

fp

A file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open.

注釈

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

To pass binary data, consider usage of io.BytesIO.

Type

Union[os.PathLike, io.BufferedIOBase]

filename

The filename to display when uploading to Discord. If this is not given then it defaults to fp.name or if fp is a string then the filename will default to the string given.

Type

Optional[str]

description

The description for the file, it will be used when attaching the file.

バージョン 2.0 で追加.

Type

Optional[str]

spoiler

Whether the attachment is a spoiler.

Type

bool

Colour

class discord.Colour(value)

Represents a Discord role colour. This class is similar to a (red, green, blue) tuple.

There is an alias for this called Color.

x == y

Checks if two colours are equal.

x != y

Checks if two colours are not equal.

hash(x)

Return the colour's hash.

str(x)

Returns the hex format for the colour.

int(x)

Returns the raw colour value.

value

The raw integer colour value.

Type

int

property r: int

Returns the red component of the colour.

Type

int

property g: int

Returns the green component of the colour.

Type

int

property b: int

Returns the blue component of the colour.

Type

int

to_rgb()

Tuple[int, int, int]: Returns an (r, g, b) tuple representing the colour.

classmethod from_rgb(r, g, b)

Constructs a Colour from an RGB tuple.

classmethod from_hsv(h, s, v)

Constructs a Colour from an HSV tuple.

classmethod default()

A factory method that returns a Colour with a value of 0.

classmethod random(*, seed=None)

A factory method that returns a Colour with a random hue.

注釈

The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.

バージョン 1.6 で追加.

パラメータ

seed (Optional[Union[int, str, float, bytes, bytearray]]) --

The seed to initialize the RNG with. If None is passed the default RNG is used.

バージョン 1.7 で追加.

classmethod teal()

A factory method that returns a Colour with a value of 0x1abc9c.

classmethod dark_teal()

A factory method that returns a Colour with a value of 0x11806a.

classmethod brand_green()

A factory method that returns a Colour with a value of 0x57F287.

バージョン 2.0 で追加.

classmethod green()

A factory method that returns a Colour with a value of 0x2ecc71.

classmethod dark_green()

A factory method that returns a Colour with a value of 0x1f8b4c.

classmethod blue()

A factory method that returns a Colour with a value of 0x3498db.

classmethod dark_blue()

A factory method that returns a Colour with a value of 0x206694.

classmethod purple()

A factory method that returns a Colour with a value of 0x9b59b6.

classmethod dark_purple()

A factory method that returns a Colour with a value of 0x71368a.

classmethod magenta()

A factory method that returns a Colour with a value of 0xe91e63.

classmethod dark_magenta()

A factory method that returns a Colour with a value of 0xad1457.

classmethod gold()

A factory method that returns a Colour with a value of 0xf1c40f.

classmethod dark_gold()

A factory method that returns a Colour with a value of 0xc27c0e.

classmethod orange()

A factory method that returns a Colour with a value of 0xe67e22.

classmethod dark_orange()

A factory method that returns a Colour with a value of 0xa84300.

classmethod brand_red()

A factory method that returns a Colour with a value of 0xED4245.

バージョン 2.0 で追加.

classmethod red()

A factory method that returns a Colour with a value of 0xe74c3c.

classmethod dark_red()

A factory method that returns a Colour with a value of 0x992d22.

classmethod lighter_grey()

A factory method that returns a Colour with a value of 0x95a5a6.

classmethod lighter_gray()

A factory method that returns a Colour with a value of 0x95a5a6.

classmethod dark_grey()

A factory method that returns a Colour with a value of 0x607d8b.

classmethod dark_gray()

A factory method that returns a Colour with a value of 0x607d8b.

classmethod light_grey()

A factory method that returns a Colour with a value of 0x979c9f.

classmethod light_gray()

A factory method that returns a Colour with a value of 0x979c9f.

classmethod darker_grey()

A factory method that returns a Colour with a value of 0x546e7a.

classmethod darker_gray()

A factory method that returns a Colour with a value of 0x546e7a.

classmethod og_blurple()

A factory method that returns a Colour with a value of 0x7289da.

classmethod blurple()

A factory method that returns a Colour with a value of 0x5865F2.

classmethod greyple()

A factory method that returns a Colour with a value of 0x99aab5.

classmethod dark_theme()

A factory method that returns a Colour with a value of 0x36393F. This will appear transparent on Discord's dark theme.

バージョン 1.5 で追加.

classmethod fuchsia()

A factory method that returns a Colour with a value of 0xEB459E.

バージョン 2.0 で追加.

classmethod yellow()

A factory method that returns a Colour with a value of 0xFEE75C.

バージョン 2.0 で追加.

BaseActivity

Attributes
class discord.BaseActivity(**kwargs)

The base activity that all user-settable activities inherit from. A user-settable activity is one that can be used in Client.change_presence().

The following types currently count as user-settable:

Note that although these types are considered user-settable by the library, Discord typically ignores certain combinations of activity depending on what is currently set. This behaviour may change in the future so there are no guarantees on whether Discord will actually let you set these types.

バージョン 1.3 で追加.

property created_at: Optional[datetime.datetime]

When the user started doing this activity in UTC.

バージョン 1.3 で追加.

Type

Optional[datetime.datetime]

Activity

class discord.Activity(**kwargs)

Represents an activity in Discord.

This could be an activity such as streaming, playing, listening or watching.

For memory optimisation purposes, some activities are offered in slimmed down versions:

application_id

The application ID of the game.

Type

Optional[int]

name

The name of the activity.

Type

Optional[str]

url

A stream URL that the activity could be doing.

Type

Optional[str]

type

The type of activity currently being done.

Type

ActivityType

state

The user's current state. For example, "In Game".

Type

Optional[str]

details

The detail of the user's current activity.

Type

Optional[str]

timestamps

A dictionary of timestamps. It contains the following optional keys:

  • start: Corresponds to when the user started doing the activity in milliseconds since Unix epoch.

  • end: Corresponds to when the user will finish doing the activity in milliseconds since Unix epoch.

Type

dict

assets

A dictionary representing the images and their hover text of an activity. It contains the following optional keys:

  • large_image: A string representing the ID for the large image asset.

  • large_text: A string representing the text when hovering over the large image asset.

  • small_image: A string representing the ID for the small image asset.

  • small_text: A string representing the text when hovering over the small image asset.

Type

dict

party

A dictionary representing the activity party. It contains the following optional keys:

  • id: A string representing the party ID.

  • size: A list of up to two integer elements denoting (current_size, maximum_size).

Type

dict

buttons

An list of dictionaries representing custom buttons shown in a rich presence. Each dictionary contains the following keys:

  • label: A string representing the text shown on the button.

  • url: A string representing the URL opened upon clicking the button.

バージョン 2.0 で追加.

Type

List[dict]

emoji

The emoji that belongs to this activity.

Type

Optional[PartialEmoji]

property start: Optional[datetime.datetime]

When the user started doing this activity in UTC, if applicable.

Type

Optional[datetime.datetime]

property end: Optional[datetime.datetime]

When the user will stop doing this activity in UTC, if applicable.

Type

Optional[datetime.datetime]

property large_image_url: Optional[str]

Returns a URL pointing to the large image asset of this activity if applicable.

Type

Optional[str]

property small_image_url: Optional[str]

Returns a URL pointing to the small image asset of this activity if applicable.

Type

Optional[str]

property large_image_text: Optional[str]

Returns the large image asset hover text of this activity if applicable.

Type

Optional[str]

property small_image_text: Optional[str]

Returns the small image asset hover text of this activity if applicable.

Type

Optional[str]

Game

Attributes
class discord.Game(name, **extra)

A slimmed down version of Activity that represents a Discord game.

This is typically displayed via Playing on the official Discord client.

x == y

Checks if two games are equal.

x != y

Checks if two games are not equal.

hash(x)

Returns the game's hash.

str(x)

Returns the game's name.

パラメータ

name (str) -- The game's name.

name

The game's name.

Type

str

property type: discord.enums.ActivityType

Returns the game's type. This is for compatibility with Activity.

It always returns ActivityType.playing.

Type

ActivityType

property start: Optional[datetime.datetime]

When the user started playing this game in UTC, if applicable.

Type

Optional[datetime.datetime]

property end: Optional[datetime.datetime]

When the user will stop playing this game in UTC, if applicable.

Type

Optional[datetime.datetime]

Streaming

class discord.Streaming(*, name, url, **extra)

A slimmed down version of Activity that represents a Discord streaming status.

This is typically displayed via Streaming on the official Discord client.

x == y

Checks if two streams are equal.

x != y

Checks if two streams are not equal.

hash(x)

Returns the stream's hash.

str(x)

Returns the stream's name.

platform

Where the user is streaming from (ie. YouTube, Twitch).

バージョン 1.3 で追加.

Type

Optional[str]

name

The stream's name.

Type

Optional[str]

details

An alias for name

Type

Optional[str]

game

The game being streamed.

バージョン 1.3 で追加.

Type

Optional[str]

url

The stream's URL.

Type

str

assets

A dictionary comprising of similar keys than those in Activity.assets.

Type

dict

property type: discord.enums.ActivityType

Returns the game's type. This is for compatibility with Activity.

It always returns ActivityType.streaming.

Type

ActivityType

property twitch_name

If provided, the twitch name of the user streaming.

This corresponds to the large_image key of the Streaming.assets dictionary if it starts with twitch:. Typically set by the Discord client.

Type

Optional[str]

CustomActivity

Attributes
class discord.CustomActivity(name, *, emoji=None, **extra)

Represents a Custom activity from Discord.

x == y

Checks if two activities are equal.

x != y

Checks if two activities are not equal.

hash(x)

Returns the activity's hash.

str(x)

Returns the custom status text.

バージョン 1.3 で追加.

name

The custom activity's name.

Type

Optional[str]

emoji

The emoji to pass to the activity, if any.

Type

Optional[PartialEmoji]

property type: discord.enums.ActivityType

Returns the activity's type. This is for compatibility with Activity.

It always returns ActivityType.custom.

Type

ActivityType

Permissions

class discord.Permissions(permissions=0, **kwargs)

Wraps up the Discord permission value.

The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.

バージョン 1.3 で変更: You can now use keyword arguments to initialize Permissions similar to update().

x == y

Checks if two permissions are equal.

x != y

Checks if two permissions are not equal.

x <= y

Checks if a permission is a subset of another permission.

x >= y

Checks if a permission is a superset of another permission.

x < y

Checks if a permission is a strict subset of another permission.

x > y

Checks if a permission is a strict superset of another permission.

hash(x)

Return the permission's hash.

iter(x)

Returns an iterator of (perm, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available permissions. You should query permissions via the properties rather than using this raw value.

Type

int

is_subset(other)

Returns True if self has the same or fewer permissions as other.

is_superset(other)

Returns True if self has the same or more permissions as other.

is_strict_subset(other)

Returns True if the permissions on other are a strict subset of those on self.

is_strict_superset(other)

Returns True if the permissions on other are a strict superset of those on self.

classmethod none()

A factory method that creates a Permissions with all permissions set to False.

classmethod all()

A factory method that creates a Permissions with all permissions set to True.

classmethod all_channel()

A Permissions with all channel-specific permissions set to True and the guild-specific ones set to False. The guild-specific permissions are currently:

バージョン 1.7 で変更: Added stream, priority_speaker and use_slash_commands permissions.

classmethod general()

A factory method that creates a Permissions with all "General" permissions from the official Discord UI set to True.

バージョン 1.7 で変更: Permission read_messages is now included in the general permissions, but permissions administrator, create_instant_invite, kick_members, ban_members, change_nickname and manage_nicknames are no longer part of the general permissions.

classmethod membership()

A factory method that creates a Permissions with all "Membership" permissions from the official Discord UI set to True.

バージョン 1.7 で追加.

classmethod text()

A factory method that creates a Permissions with all "Text" permissions from the official Discord UI set to True.

バージョン 1.7 で変更: Permission read_messages is no longer part of the text permissions. Added use_slash_commands permission.

classmethod voice()

A factory method that creates a Permissions with all "Voice" permissions from the official Discord UI set to True.

classmethod stage()

A factory method that creates a Permissions with all "Stage Channel" permissions from the official Discord UI set to True.

バージョン 1.7 で追加.

classmethod stage_moderator()

A factory method that creates a Permissions with all "Stage Moderator" permissions from the official Discord UI set to True.

バージョン 1.7 で追加.

classmethod advanced()

A factory method that creates a Permissions with all "Advanced" permissions from the official Discord UI set to True.

バージョン 1.7 で追加.

update(**kwargs)

Bulk updates this permission object.

Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.

パラメータ

**kwargs -- A list of key/value pairs to bulk update permissions with.

create_instant_invite

Returns True if the user can create instant invites.

Type

bool

kick_members

Returns True if the user can kick users from the guild.

Type

bool

ban_members

Returns True if a user can ban users from the guild.

Type

bool

administrator

Returns True if a user is an administrator. This role overrides all other permissions.

This also bypasses all channel-specific overrides.

Type

bool

manage_channels

Returns True if a user can edit, delete, or create channels in the guild.

This also corresponds to the "Manage Channel" channel-specific override.

Type

bool

manage_guild

Returns True if a user can edit guild properties.

Type

bool

add_reactions

Returns True if a user can add reactions to messages.

Type

bool

view_audit_log

Returns True if a user can view the guild's audit log.

Type

bool

priority_speaker

Returns True if a user can be more easily heard while talking.

Type

bool

stream

Returns True if a user can stream in a voice channel.

Type

bool

read_messages

Returns True if a user can read messages from all or specific text channels.

Type

bool

view_channel

An alias for read_messages.

バージョン 1.3 で追加.

Type

bool

send_messages

Returns True if a user can send messages from all or specific text channels.

Type

bool

send_tts_messages

Returns True if a user can send TTS messages from all or specific text channels.

Type

bool

manage_messages

Returns True if a user can delete or pin messages in a text channel.

注釈

Note that there are currently no ways to edit other people's messages.

Type

bool

Returns True if a user's messages will automatically be embedded by Discord.

Type

bool

attach_files

Returns True if a user can send files in their messages.

Type

bool

read_message_history

Returns True if a user can read a text channel's previous messages.

Type

bool

mention_everyone

Returns True if a user's @everyone or @here will mention everyone in the text channel.

Type

bool

external_emojis

Returns True if a user can use emojis from other guilds.

Type

bool

use_external_emojis

An alias for external_emojis.

バージョン 1.3 で追加.

Type

bool

view_guild_insights

Returns True if a user can view the guild's insights.

バージョン 1.3 で追加.

Type

bool

connect

Returns True if a user can connect to a voice channel.

Type

bool

speak

Returns True if a user can speak in a voice channel.

Type

bool

mute_members

Returns True if a user can mute other users.

Type

bool

deafen_members

Returns True if a user can deafen other users.

Type

bool

move_members

Returns True if a user can move users between other voice channels.

Type

bool

use_voice_activation

Returns True if a user can use voice activation in voice channels.

Type

bool

change_nickname

Returns True if a user can change their nickname in the guild.

Type

bool

manage_nicknames

Returns True if a user can change other user's nickname in the guild.

Type

bool

manage_roles

Returns True if a user can create or edit roles less than their role's position.

This also corresponds to the "Manage Permissions" channel-specific override.

Type

bool

manage_permissions

An alias for manage_roles.

バージョン 1.3 で追加.

Type

bool

manage_webhooks

Returns True if a user can create, edit, or delete webhooks.

Type

bool

manage_emojis

Returns True if a user can create, edit, or delete emojis.

Type

bool

manage_emojis_and_stickers

An alias for manage_emojis.

バージョン 2.0 で追加.

Type

bool

use_slash_commands

Returns True if a user can use slash commands.

バージョン 1.7 で追加.

Type

bool

request_to_speak

Returns True if a user can request to speak in a stage channel.

バージョン 1.7 で追加.

Type

bool

manage_events

Returns True if a user can manage guild events.

バージョン 2.0 で追加.

Type

bool

manage_threads

Returns True if a user can manage threads.

バージョン 2.0 で追加.

Type

bool

create_public_threads

Returns True if a user can create public threads.

バージョン 2.0 で追加.

Type

bool

create_private_threads

Returns True if a user can create private threads.

バージョン 2.0 で追加.

Type

bool

external_stickers

Returns True if a user can use stickers from other guilds.

バージョン 2.0 で追加.

Type

bool

use_external_stickers

An alias for external_stickers.

バージョン 2.0 で追加.

Type

bool

send_messages_in_threads

Returns True if a user can send messages in threads.

バージョン 2.0 で追加.

Type

bool

start_embedded_activities

Returns True if a user can launch activities in a voice channel

バージョン 2.0 で追加.

Type

bool

PermissionOverwrite

class discord.PermissionOverwrite(**kwargs)

A type that is used to represent a channel specific permission.

Unlike a regular Permissions, the default value of a permission is equivalent to None and not False. Setting a value to False is explicitly denying that permission, while setting a value to True is explicitly allowing that permission.

The values supported by this are the same as Permissions with the added possibility of it being set to None.

x == y

Checks if two overwrites are equal.

x != y

Checks if two overwrites are not equal.

iter(x)

Returns an iterator of (perm, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

パラメータ

**kwargs -- Set the value of permissions by their name.

pair()

Tuple[Permissions, Permissions]: Returns the (allow, deny) pair from this overwrite.

classmethod from_pair(allow, deny)

Creates an overwrite from an allow/deny pair of Permissions.

is_empty()

Checks if the permission overwrite is currently empty.

An empty permission overwrite is one that has no overwrites set to True or False.

戻り値

Indicates if the overwrite is empty.

戻り値の型

bool

update(**kwargs)

Bulk updates this permission overwrite object.

Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.

パラメータ

**kwargs -- A list of key/value pairs to bulk update with.

ShardInfo

Attributes
Methods
class discord.ShardInfo

A class that gives information and control over a specific shard.

You can retrieve this object via AutoShardedClient.get_shard() or AutoShardedClient.shards.

バージョン 1.4 で追加.

id

The shard ID for this shard.

Type

int

shard_count

The shard count for this cluster. If this is None then the bot has not started yet.

Type

Optional[int]

is_closed()

bool: Whether the shard connection is currently closed.

await disconnect()

This function is a coroutine.

Disconnects a shard. When this is called, the shard connection will no longer be open.

If the shard is already disconnected this does nothing.

await reconnect()

This function is a coroutine.

Disconnects and then connects the shard again.

await connect()

This function is a coroutine.

Connects a shard. If the shard is already connected this does nothing.

property latency: float

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds for this shard.

Type

float

is_ws_ratelimited()

bool: 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.

バージョン 1.6 で追加.

SystemChannelFlags

class discord.SystemChannelFlags

Wraps up a Discord system channel flag value.

Similar to Permissions, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit the system flags easily.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

x == y

Checks if two flags are equal.

x != y

Checks if two flags are not equal.

hash(x)

Return the flag's hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.

Type

int

join_notifications

Returns True if the system channel is used for member join notifications.

Type

bool

premium_subscriptions

Returns True if the system channel is used for "Nitro boosting" notifications.

Type

bool

guild_reminder_notifications

Returns True if the system channel is used for server setup helpful tips notifications.

バージョン 2.0 で追加.

Type

bool

MessageFlags

class discord.MessageFlags

Wraps up a Discord Message flag value.

See SystemChannelFlags.

x == y

Checks if two flags are equal.

x != y

Checks if two flags are not equal.

hash(x)

Return the flag's hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs.

バージョン 1.3 で追加.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.

Type

int

crossposted

Returns True if the message is the original crossposted message.

Type

bool

is_crossposted

Returns True if the message was crossposted from another channel.

Type

bool

suppress_embeds

Returns True if the message's embeds have been suppressed.

Type

bool

source_message_deleted

Returns True if the source message for this crosspost has been deleted.

Type

bool

urgent

Returns True if the source message is an urgent message.

An urgent message is one sent by Discord Trust and Safety.

Type

bool

has_thread

Returns True if the source message is associated with a thread.

バージョン 2.0 で追加.

Type

bool

ephemeral

Returns True if the source message is ephemeral.

バージョン 2.0 で追加.

Type

bool

PublicUserFlags

class discord.PublicUserFlags

Wraps up the Discord User Public flags.

x == y

Checks if two PublicUserFlags are equal.

x != y

Checks if two PublicUserFlags are not equal.

hash(x)

Return the flag's hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

バージョン 1.4 で追加.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.

Type

int

staff

Returns True if the user is a Discord Employee.

Type

bool

partner

Returns True if the user is a Discord Partner.

Type

bool

hypesquad

Returns True if the user is a HypeSquad Events member.

Type

bool

bug_hunter

Returns True if the user is a Bug Hunter

Type

bool

hypesquad_bravery

Returns True if the user is a HypeSquad Bravery member.

Type

bool

hypesquad_brilliance

Returns True if the user is a HypeSquad Brilliance member.

Type

bool

hypesquad_balance

Returns True if the user is a HypeSquad Balance member.

Type

bool

early_supporter

Returns True if the user is an Early Supporter.

Type

bool

team_user

Returns True if the user is a Team User.

Type

bool

system

Returns True if the user is a system user (i.e. represents Discord officially).

Type

bool

bug_hunter_level_2

Returns True if the user is a Bug Hunter Level 2

Type

bool

verified_bot

Returns True if the user is a Verified Bot.

Type

bool

verified_bot_developer

Returns True if the user is an Early Verified Bot Developer.

Type

bool

early_verified_bot_developer

An alias for verified_bot_developer.

バージョン 1.5 で追加.

Type

bool

discord_certified_moderator

Returns True if the user is a Discord Certified Moderator.

バージョン 2.0 で追加.

Type

bool

all()

List[UserFlags]: Returns all public flags the user has.

Bot UI Kit

The library has helpers to help create component-based UIs.

View

class discord.ui.View(*, timeout=180.0)

Represents a UI view.

This object must be inherited to create a UI within Discord.

バージョン 2.0 で追加.

パラメータ

timeout (Optional[float]) -- Timeout in seconds from last interaction with the UI before no longer accepting input. If None then there is no timeout.

timeout

Timeout from last interaction with the UI before no longer accepting input. If None then there is no timeout.

Type

Optional[float]

children

The list of children attached to this view.

Type

List[Item]

classmethod from_message(message, /, *, timeout=180.0)

Converts a message's components into a View.

The Message.components of a message are read-only and separate types from those in the discord.ui namespace. In order to modify and edit message components they must be converted into a View first.

パラメータ
  • message (discord.Message) -- The message with components to convert into a view.

  • timeout (Optional[float]) -- The timeout of the converted view.

戻り値

The converted view. This always returns a View and not one of its subclasses.

戻り値の型

View

add_item(item)

Adds an item to the view.

パラメータ

item (Item) -- The item to add to the view.

例外
  • TypeError -- An Item was not passed.

  • ValueError -- Maximum number of children has been exceeded (25) or the row the item is trying to be added to is full.

remove_item(item)

Removes an item from the view.

パラメータ

item (Item) -- The item to remove from the view.

clear_items()

Removes all items from the view.

await interaction_check(interaction)

This function is a coroutine.

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns True.

注釈

If an exception occurs within the body then the check is considered a failure and on_error() is called.

パラメータ

interaction (Interaction) -- The interaction that occurred.

戻り値

Whether the view children's callbacks should be called.

戻り値の型

bool

await on_timeout()

This function is a coroutine.

A callback that is called when a view's timeout elapses without being explicitly stopped.

await on_error(error, item, interaction)

This function is a coroutine.

A callback that is called when an item's callback or interaction_check() fails with an error.

The default implementation prints the traceback to stderr.

パラメータ
  • error (Exception) -- The exception that was raised.

  • item (Item) -- The item that failed the dispatch.

  • interaction (Interaction) -- The interaction that led to the failure.

stop()

Stops listening to interaction events from this view.

This operation cannot be undone.

is_finished()

bool: Whether the view has finished interacting.

is_dispatching()

bool: Whether the view has been added for dispatching purposes.

is_persistent()

bool: Whether the view is set up as persistent.

A persistent view has all their components with a set custom_id and a timeout set to None.

await wait()

Waits until the view has finished interacting.

A view is considered finished when stop() is called or it times out.

戻り値

If True, then the view timed out. If False then the view finished normally.

戻り値の型

bool

Item

Attributes
Methods
class discord.ui.Item

Represents the base UI item that all UI components inherit from.

The current UI items supported are:

バージョン 2.0 で追加.

property view: Optional[discord.ui.item.ViewT]

The underlying view for this item.

Type

Optional[View]

await callback(interaction)

This function is a coroutine.

The callback associated with this UI item.

This can be overriden by subclasses.

パラメータ

interaction (Interaction) -- The interaction that triggered this UI item.

Button

Methods
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)

Represents a UI button.

バージョン 2.0 で追加.

パラメータ
  • style (discord.ButtonStyle) -- The style of the button.

  • custom_id (Optional[str]) -- The ID of the button that gets received during an interaction. If this button is for a URL, it does not have a custom ID.

  • url (Optional[str]) -- The URL this button sends you to.

  • disabled (bool) -- Whether the button is disabled or not.

  • label (Optional[str]) -- The label of the button, if any.

  • emoji (Optional[Union[PartialEmoji, Emoji, str]]) -- The emoji of the button, if available.

  • row (Optional[int]) -- The relative row this button belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to None, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).

property style: discord.enums.ButtonStyle

The style of the button.

Type

discord.ButtonStyle

property custom_id: Optional[str]

The ID of the button that gets received during an interaction.

If this button is for a URL, it does not have a custom ID.

Type

Optional[str]

property url: Optional[str]

The URL this button sends you to.

Type

Optional[str]

property disabled: bool

Whether the button is disabled or not.

Type

bool

property label: Optional[str]

The label of the button, if available.

Type

Optional[str]

property emoji: Optional[discord.partial_emoji.PartialEmoji]

The emoji of the button, if available.

Type

Optional[PartialEmoji]

await callback(interaction)

This function is a coroutine.

The callback associated with this UI item.

This can be overriden by subclasses.

パラメータ

interaction (Interaction) -- The interaction that triggered this UI item.

property view: Optional[discord.ui.item.ViewT]

The underlying view for this item.

Type

Optional[View]

discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)

A decorator that attaches a button to a component.

The function being decorated should have three parameters, self representing the discord.ui.View, the discord.ui.Button being pressed and the discord.Interaction you receive.

注釈

Buttons with a URL cannot be created with this function. Consider creating a Button manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.

パラメータ
  • label (Optional[str]) -- The label of the button, if any.

  • custom_id (Optional[str]) -- The ID of the button that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts.

  • style (ButtonStyle) -- The style of the button. Defaults to ButtonStyle.grey.

  • disabled (bool) -- Whether the button is disabled or not. Defaults to False.

  • emoji (Optional[Union[str, Emoji, PartialEmoji]]) -- The emoji of the button. This can be in string form or a PartialEmoji or a full Emoji.

  • row (Optional[int]) -- The relative row this button belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to None, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).

Select

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)

Represents a UI select menu.

This is usually represented as a drop down menu.

In order to get the selected items that the user has chosen, use Select.values.

バージョン 2.0 で追加.

パラメータ
  • custom_id (str) -- The ID of the select menu that gets received during an interaction. If not given then one is generated for you.

  • placeholder (Optional[str]) -- The placeholder text that is shown if nothing is selected, if any.

  • min_values (int) -- The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

  • max_values (int) -- The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

  • options (List[discord.SelectOption]) -- A list of options that can be selected in this menu.

  • disabled (bool) -- Whether the select is disabled or not.

  • row (Optional[int]) -- The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to None, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).

property custom_id: str

The ID of the select menu that gets received during an interaction.

Type

str

property placeholder: Optional[str]

The placeholder text that is shown if nothing is selected, if any.

Type

Optional[str]

property min_values: int

The minimum number of items that must be chosen for this select menu.

Type

int

property max_values: int

The maximum number of items that must be chosen for this select menu.

Type

int

property options: List[discord.components.SelectOption]

A list of options that can be selected in this menu.

Type

List[discord.SelectOption]

add_option(*, label, value=..., description=None, emoji=None, default=False)

Adds an option to the select menu.

To append a pre-existing discord.SelectOption use the append_option() method instead.

パラメータ
  • label (str) -- The label of the option. This is displayed to users. Can only be up to 100 characters.

  • value (str) -- The value of the option. This is not displayed to users. If not given, defaults to the label. Can only be up to 100 characters.

  • description (Optional[str]) -- An additional description of the option, if any. Can only be up to 100 characters.

  • emoji (Optional[Union[str, Emoji, PartialEmoji]]) -- The emoji of the option, if available. This can either be a string representing the custom or unicode emoji or an instance of PartialEmoji or Emoji.

  • default (bool) -- Whether this option is selected by default.

例外

ValueError -- The number of options exceeds 25.

append_option(option)

Appends an option to the select menu.

パラメータ

option (discord.SelectOption) -- The option to append to the select menu.

例外

ValueError -- The number of options exceeds 25.

property disabled: bool

Whether the select is disabled or not.

Type

bool

property values: List[str]

A list of values that have been selected by the user.

Type

List[str]

await callback(interaction)

This function is a coroutine.

The callback associated with this UI item.

This can be overriden by subclasses.

パラメータ

interaction (Interaction) -- The interaction that triggered this UI item.

property view: Optional[discord.ui.item.ViewT]

The underlying view for this item.

Type

Optional[View]

discord.ui.select(*, placeholder=None, custom_id=..., min_values=1, max_values=1, options=..., disabled=False, row=None)

A decorator that attaches a select menu to a component.

The function being decorated should have three parameters, self representing the discord.ui.View, the discord.ui.Select being pressed and the discord.Interaction you receive.

In order to get the selected items that the user has chosen within the callback use Select.values.

パラメータ
  • placeholder (Optional[str]) -- The placeholder text that is shown if nothing is selected, if any.

  • custom_id (str) -- The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts.

  • row (Optional[int]) -- The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to None, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).

  • min_values (int) -- The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

  • max_values (int) -- The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

  • options (List[discord.SelectOption]) -- A list of options that can be selected in this menu.

  • disabled (bool) -- Whether the select is disabled or not. Defaults to False.

例外

The following exceptions are thrown by the library.

exception discord.DiscordException

Base exception class for discord.py

Ideally speaking, this could be caught to handle any exceptions raised from this library.

exception discord.ClientException

Exception that's raised when an operation in the Client fails.

These are usually for exceptions that happened due to user input.

exception discord.LoginFailure

Exception that's raised when the Client.login() function fails to log you in from improper credentials or some other misc. failure.

exception discord.NoMoreItems

Exception that is raised when an async iteration operation has no more items.

exception discord.HTTPException(response, message)

Exception that's raised when an HTTP request operation fails.

response

The response of the failed HTTP request. This is an instance of aiohttp.ClientResponse. In some cases this could also be a requests.Response.

Type

aiohttp.ClientResponse

text

The text of the error. Could be an empty string.

Type

str

status

The status code of the HTTP request.

Type

int

code

The Discord specific error code for the failure.

Type

int

exception discord.Forbidden(response, message)

Exception that's raised for when status code 403 occurs.

HTTPException のサブクラス

exception discord.NotFound(response, message)

Exception that's raised for when status code 404 occurs.

HTTPException のサブクラス

exception discord.DiscordServerError(response, message)

Exception that's raised for when a 500 range status code occurs.

Subclass of HTTPException.

バージョン 1.5 で追加.

exception discord.InvalidData

Exception that's raised when the library encounters unknown or invalid data from Discord.

exception discord.InvalidArgument

Exception that's raised when an argument to a function is invalid some way (e.g. wrong value or wrong type).

This could be considered the analogous of ValueError and TypeError except inherited from ClientException and thus DiscordException.

exception discord.GatewayNotFound

An exception that is raised when the gateway for Discord could not be found

exception discord.ConnectionClosed(socket, *, shard_id, code=None)

Exception that's raised when the gateway connection is closed for reasons that could not be handled internally.

code

The close code of the websocket.

Type

int

reason

The reason provided for the closure.

Type

str

shard_id

The shard ID that got closed if applicable.

Type

Optional[int]

exception discord.PrivilegedIntentsRequired(shard_id)

Exception that's raised when the gateway is requesting privileged intents but they're not ticked in the developer page yet.

Go to https://discord.com/developers/applications/ and enable the intents that are required. Currently these are as follows:

shard_id

The shard ID that got closed if applicable.

Type

Optional[int]

exception discord.InteractionResponded(interaction)

Exception that's raised when sending another interaction response using InteractionResponse when one has already been done before.

An interaction can only respond once.

バージョン 2.0 で追加.

interaction

The interaction that's already been responded to.

Type

Interaction

exception discord.opus.OpusError(code)

An exception that is thrown for libopus related errors.

code

The error code returned.

Type

int

exception discord.opus.OpusNotLoaded

An exception that is thrown for when libopus is not loaded.

Exception Hierarchy