APIリファレンス

ここではdiscord.pyのAPIについて解説します。

注釈

このモジュールはPythonのloggingモジュールを使用して、出力に依存しない方法でエラーや診断の内容を記録します。loggingモジュールが設定されていない場合、これらのログはどこにも出力されません。discord.pyでloggingモジュールを使用する方法の詳細は ログの設定 を参照してください。

クライアント

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

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 (aiohttp.BaseConnector) -- コネクションプーリングに使用するコネクタ。

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

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

  • shard_id (Optional[int]) -- 0から始まり、 shard_count より小さい整数。

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

  • fetch_offline_members (bool) -- 参加しているすべてのギルドのオフラインメンバーも取得するために、 on_ready() を遅延させるかどうかを表します。これが False の場合、オフラインメンバーの取得は行われず、 request_offline_members() を使用してギルドのオフラインメンバーを取得する必要があります。

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

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

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

  • guild_subscriptions (bool) --

    Whether to dispatching of presence or typing events. Defaults to True.

    バージョン 1.3 で追加.

    警告

    If this is set to False then the following features will be disabled:

    In short, this makes it so the only member you can reliably query is the message author. Useful for bots that do not require any state.

  • 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 で追加.

ws

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

loop

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

Type

asyncio.AbstractEventLoop

latency

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

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

Type

float

user

Represents the connected client. None if not logged in.

Type

Optional[ClientUser]

guilds

The guilds that the connected client is a member of.

Type

List[Guild]

emojis

The emojis that the connected client has.

Type

List[Emoji]

cached_messages

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

バージョン 1.1 で追加.

Type

Sequence[Message]

private_channels

The private channels that the connected client is participating on.

注釈

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

Type

List[abc.PrivateChannel]

voice_clients

Represents a list of voice connections.

Type

List[VoiceClient]

is_ready()

クライアントの内部キャッシュを使用できる状態にするかどうかを指定します。

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

This function is a coroutine.

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

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

await request_offline_members(*guilds)

This function is a coroutine.

ギルドのオフラインメンバーを Guild.members キャッシュへ書き込むよう要求します。この関数は通常呼び出されることはありません。 fetch_offline_members パラメータが False の場合にのみ使用してください。

クライアントがWebSocketに接続し、ログインするとき、ギルド内のメンバー数が250よりも大きいならば、Discordはライブラリにオフラインメンバーを提供しません。 Guild.largeTrue かどうかでギルドが大きいかどうかを確認することができます。

パラメータ

*guilds (Guild) -- オフラインメンバーを要求したいギルドのリスト。

Raises

InvalidArgument -- If any guild is unavailable or not large in the collection.

await login(token, *, bot=True)

This function is a coroutine.

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

この関数は、異なる二通りの方法で使用することができます。

警告

ユーザートークンを用いてのログインはDiscordの 利用規約 に違反しているため、アカウントを停止される可能性があります。自己責任で使用してください。

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

  • bot (bool) -- ログインに使用しているアカウントがBotのトークンであるかを指定するキーワード引数。

Raises
  • 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 logout()

This function is a coroutine.

Discordからログアウトし、すべての接続を終了します。

注釈

これは close() の別名です。サブクラス化する場合に外部のクリーンアップを行いたい場合は、代わりに close() を上書きすることをお勧めします。

await connect(*, reconnect=True)

This function is a coroutine.

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

パラメータ

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

Raises
  • 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(*args, **kwargs)

This function is a coroutine.

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

Raises

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(logout())
    # cancel all tasks lingering
finally:
    loop.close()

警告

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

is_closed()

WebSocketが閉じられているかどうかを表します。

activity

The activity being used upon logging in.

Type

Optional[BaseActivity]

users

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

Type

List[User]

get_channel(id)

Returns a channel with the given ID.

パラメータ

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

戻り値

The returned channel or None if not found.

戻り値の型

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

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_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]

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() を使いましょう。

for ... in get_all_members()

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

使用例:

for guild in client.guilds:
    for member in guild.members:
        yield member
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('Hello {.author}!'.format(msg))

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

@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 が発生するまでの秒数。

Raises

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

戻り値

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

戻り値の型

Any

event(coro)

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

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

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

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

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

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

This function is a coroutine.

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

game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
パラメータ
  • activity (Optional[BaseActivity]) -- 実行中のアクティビティ。何も実行していない場合は None です。

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

  • afk (Optional[bool]) -- AFKの状態にするかを示します。これによって、実際に退席中の場合に、Discordクライアントにプッシュ通知をよりよく扱わせることができます。

Raises

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

fetch_guilds(*, limit=100, before=None, after=None)

This function is a coroutine.

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]) -- 取得するギルドの数。 None の場合、あなたがアクセスできるギルドすべてを取得します。ただし、これには時間がかかります。デフォルトは100です。

  • before (Union[abc.Snowflake, datetime.datetime]) -- この日付またはオブジェクトの前のGuildを取得します。もし日付が与えられた場合は、それはUTC時刻を表し、timezone naiveであるdatetimeでないといけません。

  • after (Union[abc.Snowflake, datetime.datetime]) -- この日付またはオブジェクトの後のGuildを取得します。もし日付が与えられた場合は、それはUTC時刻を表し、timezone naiveであるdatetimeでないといけません。

Raises

HTTPException -- Getting the guilds failed.

Yieldする値

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

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。

Raises
戻り値

IDから取得したギルド。

戻り値の型

Guild

await create_guild(name, region=None, icon=None)

This function is a coroutine.

Guild を作成します。

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

パラメータ
Raises
戻り値

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

戻り値の型

Guild

await fetch_invite(url, *, with_counts=True)

This function is a coroutine.

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

注釈

もしあなたがInviteのGuildに参加していない場合、 Invite のguildとchannel属性はそれぞれ PartialInviteGuildPartialInviteChannel になります。

パラメータ
Raises
戻り値

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

戻り値の型

Invite

await delete_invite(invite)

This function is a coroutine.

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

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

パラメータ

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

Raises
  • 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。

Raises
戻り値

ギルドのウィジェット。

戻り値の型

Widget

await application_info()

This function is a coroutine.

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

Raises

HTTPException -- Retrieving the information failed somehow.

戻り値

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

戻り値の型

AppInfo

await fetch_user(user_id)

This function is a coroutine.

IDをもとに User を取得します。Botアカウントでのみ使用できます。そのユーザーとギルドを共有する必要はありませんが、操作の多くはそれを必要とします。

注釈

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

パラメータ

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

Raises
戻り値

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

戻り値の型

User

await fetch_user_profile(user_id)

This function is a coroutine.

Gets an arbitrary user's profile.

注釈

This can only be used by non-bot accounts.

パラメータ

user_id (int) -- プロフィールを取得したいユーザーのID。

Raises
戻り値

ユーザーのプロフィール。

戻り値の型

Profile

await fetch_channel(channel_id)

This function is a coroutine.

指定されたIDを持つ abc.GuildChannel または abc.PrivateChannel を取得します。

注釈

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

バージョン 1.2 で追加.

Raises
  • 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]

await fetch_webhook(webhook_id)

This function is a coroutine.

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

Raises
戻り値

要求したWebhook。

戻り値の型

Webhook

class discord.AutoShardedClient(*args, loop=None, **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]]

latency

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

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

Type

float

latencies

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

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

Type

List[Tuple[int, float]]

await request_offline_members(*guilds)

This function is a coroutine.

ギルドのオフラインメンバーを Guild.members キャッシュへ書き込むよう要求します。この関数は通常呼び出されることはありません。 fetch_offline_members パラメータが False の場合にのみ使用してください。

クライアントがWebSocketに接続し、ログインするとき、ギルド内のメンバー数が250よりも大きいならば、Discordはライブラリにオフラインメンバーを提供しません。 Guild.largeTrue かどうかでギルドが大きいかどうかを確認することができます。

パラメータ

*guilds (Guild) -- オフラインメンバーを要求したいギルドのリスト。

Raises

InvalidArgument -- If any guild is unavailable or not large in the collection.

await close()

This function is a coroutine.

Discordとの接続を閉じます。

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

This function is a coroutine.

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

例:

game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
パラメータ
  • activity (Optional[BaseActivity]) -- 実行中のアクティビティ。何も実行していない場合は None です。

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

  • afk (bool) -- AFKの状態にするかを示します。これによって、実際に退席中の場合に、Discordクライアントにプッシュ通知をよりよく扱わせることができます。

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

Raises

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

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]

icon

The icon hash, if it exists.

Type

Optional[str]

description

The application description.

Type

Optional[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 base64 encoded key for 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

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

cover_image

If this application is a game sold on Discord, this field will be the hash of the image on store embeds

バージョン 1.3 で追加.

Type

Optional[str]

icon_url

Retrieves the application's icon asset.

バージョン 1.3 で追加.

Type

Asset

cover_image_url

Retrieves the cover image on a store embed.

バージョン 1.3 で追加.

Type

Asset

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]

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

icon

The icon hash, if it exists.

Type

Optional[str]

owner_id

The team's owner ID.

Type

int

members

A list of the members in the team

バージョン 1.3 で追加.

Type

List[TeamMember]

icon_url

Retrieves the team's icon asset.

Type

Asset

owner

The team's owner.

Type

Optional[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

ボイス

class discord.VoiceClient

Discordの音声接続を表します。

これを意図的に生成することはできません。通常、 VoiceChannel.connect() などを使用した際に、取得できます。

警告

In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through opus.load_opus(). Otherwise, your AudioSources must be opus encoded (e.g. using FFmpegOpusAudio) or the library will not be able to transmit audio.

session_id

The voice connection session ID.

Type

str

token

The voice connection token.

Type

str

endpoint

The endpoint we are connecting to.

Type

str

channel

The voice channel connected to.

Type

abc.Connectable

loop

The event loop that the voice client is running on.

Type

asyncio.AbstractEventLoop

guild

The guild we're connected to, if applicable.

Type

Optional[Guild]

user

The user connected to voice (i.e. ourselves).

Type

ClientUser

await disconnect(*, force=False)

This function is a coroutine.

ボイスクライアントをボイスチャンネルから切断します。

await move_to(channel)

This function is a coroutine.

別のボイスチャンネルへ移動させます。

パラメータ

channel (abc.Snowflake) -- 移動先のチャンネル。ボイスチャンネルである必要があります。

is_connected()

ボイスチャンネルに接続しているかどうかを表します。

play(source, *, after=None)

AudioSource を再生します。

ファイナライザーである after はソースがなくなったか、エラーが発生した後に呼び出されます。

If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be displayed as if it were raised.

パラメータ
  • source (AudioSource) -- 読み込むオーディオソース。

  • after (Callable[[Exception], Any]) -- The finalizer that is called after the stream is exhausted. This function must have a single parameter, error, that denotes an optional exception that was raised during playing.

Raises
  • ClientException -- Already playing audio or not connected.

  • TypeError -- Source is not a AudioSource or after is not a callable.

  • OpusNotLoaded -- Source is not opus encoded and opus is not loaded.

is_playing()

現在オーディオを再生しているかを表します。

is_paused()

再生中のオーディオを一時停止しているかを表します。

stop()

音声の再生を停止します。

pause()

音声の再生を一時的に停止します。

resume()

音声の再生を再開します。

source

The audio source being played, if playing.

このプロパティは現在再生しているオーディオソースの変更にも使うことが出来ます。

Type

Optional[AudioSource]

send_audio_packet(data, *, encode=True)

データで構成されるオーディオパケットを送信します。

オーディオを再生するには、ボイスチャンネルに接続している必要があります。

パラメータ
  • data (bytes) -- PCM、またはOpusボイスデータを表す bytes-like object

  • encode (bool) -- data をOpusにエンコードする必要があるかを表します。

Raises
class discord.AudioSource

オーディオストリームを表します。

オーディオストリームはOpusにエンコードされていなくても構いませんが、エンコードされていない場合、オーディオフォーマットは16ビットの48KHzステレオPCMである必要があります。

警告

オーディオソースの読み込みは別スレッドで行われます。

read()

20ms分のオーディオを読み込みます。

サブクラスはこれを実装する必要があります。

オーディオの読み取りが終了すると、空の bytes-like object を返してこれを通知します。

is_opus()True を返す場合、20ms分のOpusにエンコードされたオーディオを返さなければいけません。それ以外の場合は、フレームあたり約3,840バイトの20ms相当の16ビット48KHzステレオPCM(20ms分のオーディオ)が必要です。

戻り値

PCMまたはOpusデータを表すバイトライクオブジェクト。

戻り値の型

bytes

is_opus()

オーディオソースがOpusにエンコードされているかを表します。

cleanup()

クリーンアップが必要な時に呼び出されます。

オーディオの再生が終了した後にバッファデータやプロセスをクリアするのに便利です。

class discord.PCMAudio(stream)

生の16ビット48KHzステレオPCMオーディオソースを表します。

stream

A file-like object that reads byte data representing raw PCM.

Type

file object

read()

20ms分のオーディオを読み込みます。

サブクラスはこれを実装する必要があります。

オーディオの読み取りが終了すると、空の bytes-like object を返してこれを通知します。

is_opus()True を返す場合、20ms分のOpusにエンコードされたオーディオを返さなければいけません。それ以外の場合は、フレームあたり約3,840バイトの20ms相当の16ビット48KHzステレオPCM(20ms分のオーディオ)が必要です。

戻り値

PCMまたはOpusデータを表すバイトライクオブジェクト。

戻り値の型

bytes

class discord.FFmpegAudio(source, *, executable='ffmpeg', args, **subprocess_kwargs)

Represents an FFmpeg (or AVConv) based AudioSource.

User created AudioSources using FFmpeg differently from how FFmpegPCMAudio and FFmpegOpusAudio work should subclass this.

バージョン 1.3 で追加.

cleanup()

クリーンアップが必要な時に呼び出されます。

オーディオの再生が終了した後にバッファデータやプロセスをクリアするのに便利です。

class discord.FFmpegPCMAudio(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)

FFmpeg(またはAVConv)のオーディオソース。

与えられた特定の入力ファイルに対してサブプロセスを起動します。

警告

環境変数にffmpegまたはavconv実行可能ファイルがなければなりません。

パラメータ
  • source (Union[str, io.BufferedIOBase]) -- ffmpegが受け取り、PCMバイトへ変換する入力。 pipe がTrueの場合、これはffmpegの標準入力に渡されるファイルライクオブジェクトです。

  • executable (str) -- 使用する実行可能ファイルの名前 (およびパス)。デフォルトでは ffmpeg です。

  • pipe (bool) -- True の場合、 source パラメータがffmpegの標準入力に渡されます。デフォルトでは False です。

  • stderr (Optional[file object]) -- Popenのコンストラクタに渡すファイルライクオブジェクト。 subprocess.PIPE のようなインスタンスにすることも可能です。

  • before_options (Optional[str]) -- -i フラグのまえにffmepgに渡す追加のコマンドライン引数。

  • options (Optional[str]) -- -i フラグのあとにffmepgに渡す追加のコマンドライン引数。

Raises

ClientException -- The subprocess failed to be created.

read()

20ms分のオーディオを読み込みます。

サブクラスはこれを実装する必要があります。

オーディオの読み取りが終了すると、空の bytes-like object を返してこれを通知します。

is_opus()True を返す場合、20ms分のOpusにエンコードされたオーディオを返さなければいけません。それ以外の場合は、フレームあたり約3,840バイトの20ms相当の16ビット48KHzステレオPCM(20ms分のオーディオ)が必要です。

戻り値

PCMまたはOpusデータを表すバイトライクオブジェクト。

戻り値の型

bytes

is_opus()

オーディオソースがOpusにエンコードされているかを表します。

class discord.FFmpegOpusAudio(source, *, bitrate=128, codec=None, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)

FFmpeg(またはAVConv)のオーディオソース。

This launches a sub-process to a specific input file given. However, rather than producing PCM packets like FFmpegPCMAudio does that need to be encoded to opus, this class produces opus packets, skipping the encoding step done by the library.

Alternatively, instead of instantiating this class directly, you can use FFmpegOpusAudio.from_probe() to probe for bitrate and codec information. This can be used to opportunistically skip pointless re-encoding of existing opus audio data for a boost in performance at the cost of a short initial delay to gather the information. The same can be achieved by passing copy to the codec parameter, but only if you know that the input source is opus encoded beforehand.

バージョン 1.3 で追加.

警告

環境変数にffmpegまたはavconv実行可能ファイルがなければなりません。

パラメータ
  • source (Union[str, io.BufferedIOBase]) -- ffmpegが受け取り、PCMバイトへ変換する入力。 pipe がTrueの場合、これはffmpegの標準入力に渡されるファイルライクオブジェクトです。

  • bitrate (int) -- The bitrate in kbps to encode the output to. Defaults to 128.

  • codec (Optional[str]) --

    The codec to use to encode the audio data. Normally this would be just libopus, but is used by FFmpegOpusAudio.from_probe() to opportunistically skip pointlessly re-encoding opus audio data by passing copy as the codec value. Any values other than copy, opus, or libopus will be considered libopus. Defaults to libopus.

    警告

    Do not provide this parameter unless you are certain that the audio input is already opus encoded. For typical use FFmpegOpusAudio.from_probe() should be used to determine the proper value for this parameter.

  • executable (str) -- 使用する実行可能ファイルの名前 (およびパス)。デフォルトでは ffmpeg です。

  • pipe (bool) -- True の場合、 source パラメータがffmpegの標準入力に渡されます。デフォルトでは False です。

  • stderr (Optional[file object]) -- Popenのコンストラクタに渡すファイルライクオブジェクト。 subprocess.PIPE のようなインスタンスにすることも可能です。

  • before_options (Optional[str]) -- -i フラグのまえにffmepgに渡す追加のコマンドライン引数。

  • options (Optional[str]) -- -i フラグのあとにffmepgに渡す追加のコマンドライン引数。

Raises

ClientException -- The subprocess failed to be created.

classmethod await from_probe(source, *, method=None, **kwargs)

This function is a coroutine.

A factory method that creates a FFmpegOpusAudio after probing the input source for audio codec and bitrate information.

サンプル

Use this function to create an FFmpegOpusAudio instance instead of the constructor:

source = await discord.FFmpegOpusAudio.from_probe("song.webm")
voice_client.play(source)

If you are on Windows and don't have ffprobe installed, use the fallback method to probe using ffmpeg instead:

source = await discord.FFmpegOpusAudio.from_probe("song.webm", method='fallback')
voice_client.play(source)

Using a custom method of determining codec and bitrate:

def custom_probe(source, executable):
    # some analysis code here

    return codec, bitrate

source = await discord.FFmpegOpusAudio.from_probe("song.webm", method=custom_probe)
voice_client.play(source)
パラメータ
  • source -- Identical to the source parameter for the constructor.

  • method (Optional[Union[str, Callable[str, str]]]) -- The probing method used to determine bitrate and codec information. As a string, valid values are native to use ffprobe (or avprobe) and fallback to use ffmpeg (or avconv). As a callable, it must take two string arguments, source and executable. Both parameters are the same values passed to this factory function. executable will default to ffmpeg if not provided as a keyword argument.

  • kwargs -- The remaining parameters to be passed to the FFmpegOpusAudio constructor, excluding bitrate and codec.

Raises
  • AttributeError -- Invalid probe method, must be 'native' or 'fallback'.

  • TypeError -- Invalid value for probe parameter, must be str or a callable.

戻り値

An instance of this class.

戻り値の型

FFmpegOpusAudio

classmethod await probe(source, *, method=None, executable=None)

This function is a coroutine.

Probes the input source for bitrate and codec information.

パラメータ
Raises
  • AttributeError -- Invalid probe method, must be 'native' or 'fallback'.

  • TypeError -- Invalid value for probe parameter, must be str or a callable.

戻り値

A 2-tuple with the codec and bitrate of the input source.

戻り値の型

Tuple[Optional[str], Optional[int]]

read()

20ms分のオーディオを読み込みます。

サブクラスはこれを実装する必要があります。

オーディオの読み取りが終了すると、空の bytes-like object を返してこれを通知します。

is_opus()True を返す場合、20ms分のOpusにエンコードされたオーディオを返さなければいけません。それ以外の場合は、フレームあたり約3,840バイトの20ms相当の16ビット48KHzステレオPCM(20ms分のオーディオ)が必要です。

戻り値

PCMまたはOpusデータを表すバイトライクオブジェクト。

戻り値の型

bytes

is_opus()

オーディオソースがOpusにエンコードされているかを表します。

class discord.PCMVolumeTransformer(original, volume=1.0)

前述の AudioSource をボリュームコントロールを持つものに変換します。

これは AudioSource.is_opus()True になっているオーディオソースでは動作しません。

パラメータ
  • original (AudioSource) -- 変換する元のAudioSource。

  • volume (float) -- 設定する初期ボリューム。詳細は volume を参照してください。

Raises
volume

ボリュームを浮動小数点数パーセンテージ (100%の場合は1.0)として取得、または設定します。

cleanup()

クリーンアップが必要な時に呼び出されます。

オーディオの再生が終了した後にバッファデータやプロセスをクリアするのに便利です。

read()

20ms分のオーディオを読み込みます。

サブクラスはこれを実装する必要があります。

オーディオの読み取りが終了すると、空の bytes-like object を返してこれを通知します。

is_opus()True を返す場合、20ms分のOpusにエンコードされたオーディオを返さなければいけません。それ以外の場合は、フレームあたり約3,840バイトの20ms相当の16ビット48KHzステレオPCM(20ms分のオーディオ)が必要です。

戻り値

PCMまたはOpusデータを表すバイトライクオブジェクト。

戻り値の型

bytes

Opusライブラリ

discord.opus.load_opus(name)

libopus共有ライブラリを音声用にロードします。

この関数が呼び出されない場合、ライブラリは ctypes.util.find_library() 関数を使用して利用可能であればロードします。

Not loading a library and attempting to use PCM based AudioSources will lead to voice not working.

この関数は、スローされた例外を伝播します。

警告

ライブラリのbit数は、あなたのPythonインタプリタのbit数と一致していなければなりません。ライブラリが64bitの場合は、Pythonインタプリタも64bitである必要があります。bit数が一致しない場合は、ロード時に例外を投げます。

注釈

Windowsでは、バイナリが自動的に読み込まれるため、この関数を呼び出す必要はありません。

注釈

Windowsでは .dll拡張は必要ありませんが、Linuxではライブラリをロードするために libopus.so.1 のような完全な拡張ライブラリが必要です。しかしながら、Linux上でも通常の場合は ctypes.util.find_library() が自動的にライブラリを検出します。

パラメータ

name (str) -- 共有ライブラリのファイル名。

discord.opus.is_loaded()

load_opus()ctypes.util.find_library() 呼び出しで、opusライブラリが正常にロードされたかどうかをチェックする関数。

ボイス関連の機能を動かすためには、これが True を返す必要があります。

戻り値

opusライブラリがロードされているかを表します。

戻り値の型

bool

イベントリファレンス

この項目では 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_disconnect()

クライアントがDiscordから切断したときに呼び出されます。これはインターネットが切断された、明示的にログアウトした、またはDiscord側から何らかの方法で切断されたというような場合に呼び出される可能性があります。

この関数は何度でも呼び出すことができます。

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_error(event, *args, **kwargs)

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

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

例外を Client クラスの外に伝播させたい場合は、単一の空の The raise statement 文を持つ on_error を定義することができます。発生した例外は、 Clienton_error では決して処理されることはありません。

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

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

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

discord.on_socket_raw_receive(msg)

メッセージが処理される前、WebSocketからメッセージが受信されるたびに呼び出されます。このイベントはメッセージを受信した場合、渡されたデータが処理できないときでも常に呼びだされます。

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

注釈

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

パラメータ

msg (Union[bytes, str]) -- WebSocketライブラリから渡されたメッセージ。バイナリメッセージの場合は bytes 、通常のメッセージの場合は str です。

discord.on_socket_raw_send(payload)

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

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

注釈

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

パラメータ

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

discord.on_typing(channel, user, when)

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

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

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

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

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

  • when (datetime.datetime) -- UTCのnaive datetimeでの、タイピングの開始時刻。

discord.on_message(message)

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

警告

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

パラメータ

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

discord.on_message_delete(message)

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

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

パラメータ

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

discord.on_bulk_message_delete(messages)

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

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

パラメータ

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

discord.on_raw_message_delete(payload)

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

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

パラメータ

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

discord.on_raw_bulk_message_delete(payload)

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

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

パラメータ

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

discord.on_message_edit(before, after)

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

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

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

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

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

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

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

  • The message's embeds were suppressed or unsuppressed.

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

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

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

discord.on_raw_message_edit(payload)

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

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

このイベントの性質は、本質的に生表現のため、データのパラメータは ゲートウェイ によって与えられた生データと一致します。

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

パラメータ

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`を使ってください。

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

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

discord.on_raw_reaction_add(payload)

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

パラメータ

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

discord.on_reaction_remove(reaction, user)

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

注釈

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

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

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

discord.on_raw_reaction_remove(payload)

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

パラメータ

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.

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

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

discord.on_raw_reaction_clear(payload)

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

パラメータ

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.

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

バージョン 1.3 で追加.

パラメータ

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

discord.on_private_channel_delete(channel)
discord.on_private_channel_create(channel)

プライベートチャンネルが削除されたり作成されたときに呼び出されます。

パラメータ

channel (abc.PrivateChannel) -- 作成、または削除されたプライベートチャンネル。

discord.on_private_channel_update(before, after)

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

パラメータ
  • 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 a naive datetime in UTC. Could be None.

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

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

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

パラメータ

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

discord.on_guild_channel_update(before, after)

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

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

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

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

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

discord.on_guild_integrations_update(guild)

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

パラメータ

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

discord.on_webhooks_update(channel)

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

パラメータ

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

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

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

パラメータ

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

discord.on_member_update(before, after)

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

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

  • ステータス

  • activity

  • ニックネーム

  • 役職

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

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

discord.on_user_update(before, after)

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

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

  • アバター

  • ユーザー名

  • discriminator

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

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

discord.on_guild_join(guild)

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

パラメータ

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

discord.on_guild_remove(guild)

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

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

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

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

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

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

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

パラメータ

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

discord.on_guild_update(before, after)

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

  • 名前が変更された

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

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

  • その他

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

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

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

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

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

パラメータ

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

discord.on_guild_role_update(before, after)

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

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

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

discord.on_guild_emojis_update(guild, before, after)

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

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

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

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

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

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

パラメータ

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

discord.on_voice_state_update(member, before, after)

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

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

  • メンバーがボイスチャンネルに参加したとき。

  • メンバーがボイスチャンネルから退出したとき。

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

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

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

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

  • after (VoiceState) -- 更新後のボイス状態。

discord.on_member_ban(guild, user)

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

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

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

discord.on_member_unban(guild, user)

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

パラメータ
  • 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.

パラメータ

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.

パラメータ

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.on_relationship_add(relationship)
discord.on_relationship_remove(relationship)

ClientUserRelationship が追加・削除されたとき呼び出されます。

パラメータ

relationship (Relationship) -- 追加・削除されたRelationship。

discord.on_relationship_update(before, after)

Relationship が更新されたとき、たとえばフレンドをブロックしたり、フレンドが承認されたときに呼び出されます。

パラメータ
  • before (Relationship) -- 以前のフレンドの状態。

  • after (Relationship) -- 更新されたのフレンドの状態。

ユーティリティ関数

discord.utils.find(predicate, seq)

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

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

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

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

パラメータ
  • predicate -- 真偽値を返す関数。

  • seq (iterable) -- 検索するイテラブル。

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)

Discordのsnowflake IDの作成日時をUTCで返します。

discord.utils.oauth_url(client_id, permissions=None, guild=None, redirect_uri=None)

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

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

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

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

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

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、役職とユーザーのメンションをエスケープするヘルパー関数。

注釈

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

パラメータ

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

戻り値

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

戻り値の型

str

discord.utils.resolve_invite(invite)

Resolves an invite from a Invite, URL or ID

パラメータ

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

戻り値

招待コード。

戻り値の型

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.

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

プロフィール

class discord.Profile

Discordの公開プロフィールを表すnamedtuple。

user

このプロフィールを持つ User

premium

このユーザーがプレミアム(つまり: Discord Nitro)を持っているかを示す真偽値。

nitro

premium のエイリアス。

premium_since

プレミアムを有効にした日時を表すtimezone naiveなUTC datetime。利用できない場合は None になります。

staff

ユーザーがDiscordのスタッフかを示す真偽値。

partner

ユーザーがDiscordパートナーかを示す真偽値。

bug_hunter

ユーザーがバグハンターかを示す真偽値。

early_supporter

ユーザーが2018年10月10日以前にNitroを持っていたかを示す真偽値。

hypesquad

ユーザーがDiscord HypeSquadに属しているかを示す真偽値。

hypesquad_houses

ユーザーが所属する HypeSquadHouse のリスト。

team_user

A boolean indicating if the user is in part of a team.

バージョン 1.3 で追加.

system

A boolean indicating if the user is officially part of the Discord urgent message system.

バージョン 1.3 で追加.

mutual_guilds

ClientUser がこのユーザーと共有する Guild の一覧。

connected_accounts

ユーザーが関連付けたアカウントを示す辞書型のリスト。

以下がその例です:

{type: "twitch", id: "92473777", name: "discordapp"}

列挙型

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

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

class discord.ChannelType

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

text

テキストチャンネル。

voice

ボイスチャンネル。

private

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

group

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

category

A category channel.

news

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

store

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

class discord.MessageType

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

default

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

recipient_add

グループのプライベートメッセージ、つまり、 ChannelType.group のプライベートチャンネルの参加者が増えたときのシステムメッセージ。

recipient_remove

グループのプライベートメッセージ、つまり、 ChannelType.group のプライベートチャンネルの参加者が減ったときのシステムメッセージ。

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 で追加.

class discord.ActivityType

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

unknown

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

playing

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

streaming

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

listening

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

watching

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

custom

A custom activity type.

class discord.HypeSquadHouse

ユーザーが属するHypeSquadハウスを指定します。

bravery

Braveryのハウス。

brilliance

Brillianceのハウス。

balance

Balanceのハウス。

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

南アフリカリージョン。

sydney

シドニーリージョン。

us_central

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

us_east

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

us_south

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

us_west

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

vip_amsterdam

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

vip_us_east

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

vip_us_west

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

class discord.VerificationLevel

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

x == y

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

x != y

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

x > y

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

x < y

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

x >= y

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

x <= y

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

none

無制限。

low

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

medium

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

high

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

table_flip

high のエイリアス。

extreme

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

double_table_flip

extreme のエイリアス。

class discord.NotificationLevel

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

all_messages

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

only_mentions

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

class discord.ContentFilter

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

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

Represents the type of action being done for a AuditLogEntry, which is retrievable via Guild.audit_logs().

guild_update

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

  • ギルドのvanity URLの変更

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

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

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

  • ギルドのアイコンの変更

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

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

When this is the action, the type of target is the Guild.

Possible attributes for AuditLogDiff:

channel_create

A new channel was created.

When this is the action, the type of target is either a abc.GuildChannel or Object with an ID.

A more filled out object in the Object case can be found by using after.

Possible attributes for AuditLogDiff:

channel_update

A channel was updated. Things that trigger this include:

  • The channel name or topic was changed

  • The channel bitrate was changed

When this is the action, the type of target is the abc.GuildChannel or Object with an ID.

A more filled out object in the Object case can be found by using after or before.

Possible attributes for AuditLogDiff:

channel_delete

A channel was deleted.

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

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

Possible attributes for AuditLogDiff:

overwrite_create

A channel permission overwrite was created.

When this is the action, the type of target is the abc.GuildChannel or Object with an ID.

When this is the action, the type of extra is either a Role or Member. If the object is not found then it is a Object with an ID being filled, a name, and a type attribute set to either 'role' or 'member' to help dictate what type of ID it is.

Possible attributes for AuditLogDiff:

overwrite_update

A channel permission overwrite was changed, this is typically when the permission values change.

See overwrite_create for more information on how the target and extra fields are set.

Possible attributes for AuditLogDiff:

overwrite_delete

A channel permission overwrite was deleted.

See overwrite_create for more information on how the target and extra fields are set.

Possible attributes for AuditLogDiff:

kick

A member was kicked.

When this is the action, the type of target is the User who got kicked.

When this is the action, changes is empty.

member_prune

A member prune was triggered.

When this is the action, the type of target is set to 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.

When this is the action, changes is empty.

ban

A member was banned.

When this is the action, the type of target is the User who got banned.

When this is the action, changes is empty.

unban

A member was unbanned.

When this is the action, the type of target is the User who got unbanned.

When this is the action, changes is empty.

member_update

A member has updated. This triggers in the following situations:

  • A nickname was changed

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

When this is the action, the type of target is the Member or User who got updated.

Possible attributes for AuditLogDiff:

member_role_update

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

When this is the action, the type of target is the Member or User who got the role.

Possible attributes for 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

A new role was created.

When this is the action, the type of target is the Role or a Object with the ID.

Possible attributes for AuditLogDiff:

role_update

A role was updated. This triggers in the following situations:

  • The name has changed

  • The permissions have changed

  • The colour has changed

  • Its hoist/mentionable state has changed

When this is the action, the type of target is the Role or a Object with the ID.

Possible attributes for AuditLogDiff:

role_delete

A role was deleted.

When this is the action, the type of target is the Role or a Object with the ID.

Possible attributes for AuditLogDiff:

invite_create

An invite was created.

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

Possible attributes for AuditLogDiff:

invite_update

An invite was updated.

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.

Possible attributes for AuditLogDiff:

webhook_create

A webhook was created.

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

Possible attributes for 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.

Possible attributes for AuditLogDiff:

webhook_delete

A webhook was deleted.

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

Possible attributes for 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.

Possible attributes for 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.

Possible attributes for AuditLogDiff:

emoji_delete

An emoji was deleted.

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

Possible attributes for 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 で追加.

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

Specifies the type of Relationship.

注釈

This only applies to users, not bots.

friend

You are friends with this user.

blocked

このユーザーはブロックされています。

incoming_request

フレンド申請が届いています。

outgoing_request

You have sent a friend request to this user.

class discord.UserContentFilter

Represents the options found in Settings > Privacy & Safety > Safe Direct Messaging in the Discord client.

注釈

This only applies to users, not bots.

all_messages

Scan all direct messages from everyone.

friends

Scan all direct messages that aren't from friends.

disabled

Don't scan any direct messages.

class discord.FriendFlags

Represents the options found in Settings > Privacy & Safety > Who Can Add You As A Friend in the Discord client.

注釈

This only applies to users, not bots.

noone

This allows no-one to add you as a friend.

mutual_guilds

This allows guild members to add you as a friend.

mutual_friends

This allows friends of friends to add you as a friend.

guild_and_friends

This is a superset of mutual_guilds and mutual_friends.

everyone

This allows everyone to add you as a friend.

class discord.PremiumType

Represents the user's Discord Nitro subscription type.

注釈

This only applies to users, not bots.

nitro

Represents the Discord Nitro with Nitro-exclusive games.

nitro_classic

Represents the Discord Nitro with no Nitro-exclusive games.

class discord.Theme

Represents the theme synced across all Discord clients.

注釈

This only applies to users, not bots.

light

Represents the Light theme on Discord.

dark

Represents the Dark theme on Discord.

class discord.TeamMembershipState

Represents the membership state of a team member retrieved through Bot.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.

非同期イテレータ

一部の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

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.

戻り値

An async iterator.

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.

戻り値

An async iterator.

監査ログデータ

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.

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

Represents an Audit Log entry.

You retrieve these via Guild.audit_logs().

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

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.

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

str – A name of something.

icon

str – A guild's icon hash. See also Guild.icon.

splash

str – The guild's invite splash hash. See also Guild.splash.

owner

Union[Member, User] – The guild's owner. See also Guild.owner

region

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

afk_channel

Union[VoiceChannel, Object] – 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.

system_channel

Union[TextChannel, Object] – 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.

afk_timeout

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

mfa_level

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

widget_enabled

bool – The guild's widget has been enabled or disabled.

widget_channel

Union[TextChannel, Object] – The widget's channel.

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

verification_level

VerificationLevel – The guild's verification level.

See also Guild.verification_level.

default_notifications

NotificationLevel – The guild's default notification level.

See also Guild.default_notifications.

explicit_content_filter

ContentFilter – The guild's content filter.

See also Guild.explicit_content_filter.

default_message_notifications

int – The guild's default message notification setting.

vanity_url_code

str – The guild's vanity URL.

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

position

int – The position of a Role or abc.GuildChannel.

type

Union[int, str] – The type of channel or channel permission overwrite.

If the type is an int, then it is a type of channel which can be either 0 to indicate a text channel or 1 to indicate a voice channel.

If the type is a str, then it is a type of permission overwrite which can be either 'role' or 'member'.

topic

strTextChannel のトピック。

See also TextChannel.topic.

bitrate

int – The bitrate of a VoiceChannel.

See also VoiceChannel.bitrate.

overwrites

List[Tuple[target, PermissionOverwrite]] – 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.

roles

List[Union[Role, Object]] – 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.

nick

Optional[str] – The nickname of a member.

See also Member.nick

deaf

bool – Whether the member is being server deafened.

See also VoiceState.deaf.

mute

bool – Whether the member is being server muted.

See also VoiceState.mute.

permissions

Permissions – 役職の権限。

See also Role.permissions.

colour
color

Colour – 役職の色。

See also Role.colour

hoist

bool – Whether the role is being hoisted or not.

See also Role.hoist

mentionable

bool – Whether the role is mentionable or not.

See also Role.mentionable

code

str – The invite's code.

See also Invite.code

channel

Union[abc.GuildChannel, Object] – 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.

inviter

User – 招待を作成したユーザー。

See also Invite.inviter.

max_uses

int – 招待の最大使用可能回数。

See also Invite.max_uses.

uses

int – 招待の現在までの使用回数。

See also Invite.uses.

max_age

int – The invite's max age in seconds.

See also Invite.max_age.

temporary

bool – If the invite is a temporary invite.

See also Invite.temporary.

allow
deny

Permissions – The permissions being allowed or denied.

id

int – The ID of the object being changed.

avatar

str – The avatar hash of a member.

See also User.avatar.

slowmode_delay

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

See also TextChannel.slowmode_delay.

Webhookサポート

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

class discord.Webhook(data, *, adapter, state=None)

Represents a 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 have an adapter bound using the library's HTTP session. Those webhooks will have send(), delete() and edit() as coroutines.

The second form involves creating a webhook object manually without having it bound to a websocket connection using the from_url() or partial() classmethods. This form allows finer grained control over how requests are done, allowing you to mix async and sync code using either aiohttp or requests.

For example, creating a webhook from a URL and using aiohttp:

from discord import Webhook, AsyncWebhookAdapter
import aiohttp

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session))
        await webhook.send('Hello World', username='Foo')

Or creating a webhook from an ID and token and using requests:

import requests
from discord import Webhook, RequestsWebhookAdapter

webhook = Webhook.partial(123456, 'abcdefg', adapter=RequestsWebhookAdapter())
webhook.send('Hello World', username='Foo')
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]

avatar

The default avatar of the webhook.

Type

Optional[str]

url

Returns the webhook's url.

classmethod partial(id, token, *, adapter)

Creates a partial Webhook.

A partial webhook is just a webhook object with an ID and a token.

パラメータ
classmethod from_url(url, *, adapter)

Creates a partial Webhook from a webhook URL.

パラメータ
Raises

InvalidArgument -- The URL is invalid.

guild

The guild this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type

Optional[Guild]

channel

The text channel this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type

Optional[TextChannel]

created_at

Returns the webhook's creation time in UTC.

Type

datetime.datetime

avatar_url

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.

This is equivalent to calling avatar_url_as() with the default parameters.

avatar_url_as(*, format=None, size=1024)

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.

The format must be one of 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 1024.

パラメータ
  • format (Optional[str]) -- The format to attempt to convert the avatar to. If the format is None, then it is equivalent to png.

  • size (int) -- The size of the image to display.

Raises

InvalidArgument -- Bad image format passed to format or invalid size.

戻り値

The resulting CDN asset.

戻り値の型

Asset

delete()

This function could be a coroutine.

Deletes this Webhook.

If the webhook is constructed with a RequestsWebhookAdapter then this is not a coroutine.

Raises
  • 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(**kwargs)

This function could be a coroutine.

Edits this Webhook.

If the webhook is constructed with a RequestsWebhookAdapter then this is not a coroutine.

パラメータ
  • name (Optional[str]) -- The webhook's new default name.

  • avatar (Optional[bytes]) -- A bytes-like object representing the webhook's new default avatar.

Raises
send(content=None, *, wait=False, username=None, avatar_url=None, tts=False, file=None, files=None, embed=None, embeds=None)

This function could be a coroutine.

Sends a message using the webhook.

If the webhook is constructed with a RequestsWebhookAdapter then this is not a coroutine.

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 Message 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 (Union[str, Asset]) -- The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used.

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

Raises
  • HTTPException -- Sending the message failed.

  • NotFound -- This webhook was not found.

  • Forbidden -- The authorization token for the webhook is incorrect.

  • InvalidArgument -- You specified both embed and embeds or the length of embeds was invalid or there was no token associated with this webhook.

戻り値

The message that was sent.

戻り値の型

Optional[Message]

execute(*args, **kwargs)

An alias for send().

Adapters

Adapters allow you to change how the request should be handled. They all build on a single interface, WebhookAdapter.request().

class discord.WebhookAdapter

Base class for all webhook adapters.

webhook

The webhook that owns this adapter.

Type

Webhook

request(verb, url, payload=None, multipart=None)

Actually does the request.

サブクラスはこれを実装する必要があります。

パラメータ
  • verb (str) -- The HTTP verb to use for the request.

  • url (str) -- The URL to send the request to. This will have the query parameters already added to it, if any.

  • multipart (Optional[dict]) -- A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under a file key which will have a 3-element tuple denoting (filename, file, content_type).

  • payload (Optional[dict]) -- The JSON to send with the request, if any.

handle_execution_response(data, *, wait)

Transforms the webhook execution response into something more meaningful.

This is mainly used to convert the data into a Message if necessary.

サブクラスはこれを実装する必要があります。

パラメータ
  • data -- The data that was returned from the request.

  • wait (bool) -- Whether the webhook execution was asked to wait or not.

class discord.AsyncWebhookAdapter(session)

A webhook adapter suited for use with aiohttp.

注釈

You are responsible for cleaning up the client session.

パラメータ

session (aiohttp.ClientSession) -- The session to use to send requests.

await request(verb, url, payload=None, multipart=None, *, files=None)

Actually does the request.

サブクラスはこれを実装する必要があります。

パラメータ
  • verb (str) -- The HTTP verb to use for the request.

  • url (str) -- The URL to send the request to. This will have the query parameters already added to it, if any.

  • multipart (Optional[dict]) -- A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under a file key which will have a 3-element tuple denoting (filename, file, content_type).

  • payload (Optional[dict]) -- The JSON to send with the request, if any.

await handle_execution_response(response, *, wait)

Transforms the webhook execution response into something more meaningful.

This is mainly used to convert the data into a Message if necessary.

サブクラスはこれを実装する必要があります。

パラメータ
  • data -- The data that was returned from the request.

  • wait (bool) -- Whether the webhook execution was asked to wait or not.

class discord.RequestsWebhookAdapter(session=None, *, sleep=True)

A webhook adapter suited for use with requests.

Only versions of requests higher than 2.13.0 are supported.

パラメータ
  • session (Optional[requests.Session]) -- The requests session to use for sending requests. If not given then each request will create a new session. Note if a session is given, the webhook adapter will not clean it up for you. You must close the session yourself.

  • sleep (bool) -- Whether to sleep the thread when encountering a 429 or pre-emptive rate limit or a 5xx status code. Defaults to True. If set to False then this will raise an HTTPException instead.

request(verb, url, payload=None, multipart=None, *, files=None)

Actually does the request.

サブクラスはこれを実装する必要があります。

パラメータ
  • verb (str) -- The HTTP verb to use for the request.

  • url (str) -- The URL to send the request to. This will have the query parameters already added to it, if any.

  • multipart (Optional[dict]) -- A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under a file key which will have a 3-element tuple denoting (filename, file, content_type).

  • payload (Optional[dict]) -- The JSON to send with the request, if any.

handle_execution_response(response, *, wait)

Transforms the webhook execution response into something more meaningful.

This is mainly used to convert the data into a Message if necessary.

サブクラスはこれを実装する必要があります。

パラメータ
  • data -- The data that was returned from the request.

  • wait (bool) -- Whether the webhook execution was asked to wait or not.

抽象基底クラス

An abstract base class (also known as an abc) is a class that models can inherit to get their behaviour. The Python implementation of an abc is slightly different in that you can register them at run-time. Abstract base classes cannot be instantiated. They are mainly there for usage with isinstance() and issubclass().

This library has a module related to abstract base classes, some of which are actually from the abc standard module, others which are not.

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

created_at

Returns the model's creation time as a naive datetime in UTC.

Type

datetime.datetime

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 hash the user has.

Type

Optional[str]

bot

If the user is a bot account.

Type

bool

display_name

Returns the user's display name.

Type

str

mention

Returns a string that allows you to mention the given user.

Type

str

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

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

changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

mention

The string that allows you to mention the channel.

Type

str

created_at

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

overwrites

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.

戻り値の型

Mapping[Union[Role, Member], PermissionOverwrite]

category

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

permissions_synced

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(member)

Handles permission resolution for the current Member.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

パラメータ

member (Member) -- The member to resolve permissions for.

戻り値

The resolved permissions for the member.

戻り値の型

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.

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

サンプル

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.

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

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

Raises
  • Forbidden -- You do not have the proper permissions to create this channel.

  • HTTPException -- Creating the channel failed.

await create_invite(*, reason=None, **fields)

This function is a coroutine.

Creates an instant invite.

You must have the create_instant_invite permission to do this.

パラメータ
  • max_age (int) -- How long the invite should last. If it's 0 then the invite doesn't expire. Defaults to 0.

  • max_uses (int) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to 0.

  • temporary (bool) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (bool) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • reason (Optional[str]) -- The reason for creating this invite. Shows up on the audit log.

Raises

HTTPException -- Invite creation failed.

戻り値

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_guild to get this information.

Raises
  • 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]

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 date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC 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.

Raises
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

Yieldする値

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():
    # do expensive stuff here
    await channel.send('done!')
await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=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.

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

パラメータ
  • content (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.

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

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.

This can only be used by bot accounts.

パラメータ

id (int) -- The message ID to look for.

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

Raises

HTTPException -- Retrieving the pinned messages failed.

戻り値

The messages that are currently pinned.

戻り値の型

List[Message]

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:

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

avatar

The avatar hash the user has. Could be None.

Type

Optional[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 is a verified account.

Type

bool

email

The email the user used when registering.

Type

Optional[str]

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

premium

Specifies if the user is a premium user (e.g. has Discord Nitro).

Type

bool

premium_type

Specifies the type of premium a user has (e.g. Nitro or Nitro Classic). Could be None if the user is not premium.

Type

Optional[PremiumType]

get_relationship(user_id)

該当すれば Relationship が返ります。

注釈

This can only be used by non-bot accounts.

パラメータ

user_id (int) -- リレーションシップがあるか確認したいユーザーのID。

戻り値

The relationship if available or None.

戻り値の型

Optional[Relationship]

relationships

Returns all the relationships that the user has.

注釈

This can only be used by non-bot accounts.

Type

List[User]

friends

Returns all the users that the user is friends with.

注釈

This can only be used by non-bot accounts.

Type

List[User]

blocked

Returns all the users that the user has blocked.

注釈

This can only be used by non-bot accounts.

Type

List[User]

await edit(**fields)

This function is a coroutine.

Edits the current profile of the client.

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

注釈

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

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

パラメータ
  • password (str) -- The current password for the client's account. Only applicable to user accounts.

  • new_password (str) -- The new password you wish to change to. Only applicable to user accounts.

  • email (str) -- The new email you wish to change to. Only applicable to user accounts.

  • house (Optional[HypeSquadHouse]) -- The hypesquad house you wish to change to. Could be None to leave the current house. Only applicable to user accounts.

  • username (str) -- The new username you wish to change to.

  • avatar (bytes) -- A bytes-like object representing the image to upload. Could be None to denote no avatar.

Raises
await create_group(*recipients)

This function is a coroutine.

Creates a group direct message with the recipients provided. These recipients must be have a relationship of type RelationshipType.friend.

注釈

This can only be used by non-bot accounts.

パラメータ

*recipients (User) -- An argument list of User to have in your group.

Raises
  • HTTPException -- Failed to create the group direct message.

  • ClientException -- Attempted to create a group with only one recipient. This does not include yourself.

戻り値

The new group channel.

戻り値の型

GroupChannel

await edit_settings(**kwargs)

This function is a coroutine.

Edits the client user's settings.

注釈

This can only be used by non-bot accounts.

パラメータ
  • afk_timeout (int) -- How long (in seconds) the user needs to be AFK until Discord sends push notifications to your mobile device.

  • animate_emojis (bool) -- Whether or not to animate emojis in the chat.

  • convert_emoticons (bool) -- Whether or not to automatically convert emoticons into emojis. e.g. :-) -> 😃

  • default_guilds_restricted (bool) -- Whether or not to automatically disable DMs between you and members of new guilds you join.

  • detect_platform_accounts (bool) -- Whether or not to automatically detect accounts from services like Steam and Blizzard when you open the Discord client.

  • developer_mode (bool) -- Whether or not to enable developer mode.

  • disable_games_tab (bool) -- Whether or not to disable the showing of the Games tab.

  • enable_tts_command (bool) -- Whether or not to allow tts messages to be played/sent.

  • explicit_content_filter (UserContentFilter) -- The filter for explicit content in all messages.

  • friend_source_flags (FriendFlags) -- Who can add you as a friend.

  • gif_auto_play (bool) -- Whether or not to automatically play gifs that are in the chat.

  • guild_positions (List[abc.Snowflake]) -- A list of guilds in order of the guild/guild icons that are on the left hand side of the UI.

  • inline_attachment_media (bool) -- Whether or not to display attachments when they are uploaded in chat.

  • inline_embed_media (bool) -- Whether or not to display videos and images from links posted in chat.

  • locale (str) -- The RFC 3066 language identifier of the locale to use for the language of the Discord client.

  • message_display_compact (bool) -- Whether or not to use the compact Discord display mode.

  • render_embeds (bool) -- Whether or not to render embeds that are sent in the chat.

  • render_reactions (bool) -- Whether or not to render reactions that are added to messages.

  • restricted_guilds (List[abc.Snowflake]) -- A list of guilds that you will not receive DMs from.

  • show_current_game (bool) -- Whether or not to display the game that you are currently playing.

  • status (Status) -- The clients status that is shown to others.

  • theme (Theme) -- The theme of the Discord UI.

  • timezone_offset (int) -- The timezone offset to use.

Raises
戻り値

The client user's updated settings.

戻り値の型

dict

avatar_url

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

これはデフォルトパラメータ(webp/gif フォーマット及びサイズが1024)で avatar_url_as() を呼び出すのと同等の処理です。

avatar_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and 'gif' is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

パラメータ
  • format (Optional[str]) -- アバターのフォーマット。 None の場合はアニメーションアバターなら 「gif」、それ以外は static_format のフォーマットに自動的に変換されます。

  • static_format (Optional[str]) -- アバターがアニメーションでない場合に変換されるフォーマット。デフォルトでは「webp」です。

  • size (int) -- The size of the image to display.

Raises

InvalidArgument -- Bad image format passed to format or static_format, or invalid size.

戻り値

The resulting CDN asset.

戻り値の型

Asset

color

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

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

created_at

Returns the user's creation time in UTC.

This is when the user's Discord account was created.

Type

datetime.datetime

default_avatar

Returns the default avatar for a given user. This is calculated by the user's discriminator.

Type

DefaultAvatar

default_avatar_url

Returns a URL for a user's default avatar.

Type

Asset

display_name

Returns the user's display name.

通常であれば、これはユーザー名がそのまま返りますが、ギルドにてニックネームを設定している場合は、代替としてニックネームが返ります。

Type

str

is_avatar_animated()

Indicates if the user has an animated avatar.

mention

Returns a string that allows you to mention the given user.

Type

str

mentioned_in(message)

指定のメッセージにユーザーに対するメンションが含まれているかを確認します。

パラメータ

message (Message) -- メンションが含まれているかを確認するメッセージ。

permissions_in(channel)

abc.GuildChannel.permissions_for() のエイリアス。

基本的には以下と同等です:

channel.permissions_for(self)
パラメータ

channel (abc.GuildChannel) -- 権限を確認したいチャンネル。

Relationship

class discord.Relationship

Discordのリレーションシップを表します。

フレンドや、ブロックした人などのようなリレーションシップです。Botでないアカウントのみがリレーションシップを持つことが出来ます。

user

The user you have the relationship with.

Type

User

type

The type of relationship you have.

Type

RelationshipType

await delete()

This function is a coroutine.

Deletes the relationship.

Raises

HTTPException -- Deleting the relationship failed.

await accept()

This function is a coroutine.

Accepts the relationship request. e.g. accepting a friend request.

Raises

HTTPException -- Accepting the relationship failed.

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

avatar

The avatar hash the user has. Could be None.

Type

Optional[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 date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC 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.

Raises
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

Yieldする値

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():
    # do expensive stuff here
    await channel.send('done!')
dm_channel

Returns the channel associated with this user if it exists.

これが ``None``を返すなら、あなたは create_dm() コルーチン関数を使って、DMチャンネルを作ることができます。

Type

Optional[DMChannel]

await create_dm()

このユーザーと DMChannel を作ります。

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

relationship

Returns the Relationship with this user if applicable, None otherwise.

注釈

This can only be used by non-bot accounts.

await mutual_friends()

This function is a coroutine.

Gets all mutual friends of this user.

注釈

This can only be used by non-bot accounts.

Raises
  • Forbidden -- Not allowed to get mutual friends of this user.

  • HTTPException -- Getting mutual friends failed.

戻り値

The users that are mutual friends.

戻り値の型

List[User]

is_friend()

Checks if the user is your friend.

注釈

This can only be used by non-bot accounts.

is_blocked()

Checks if the user is blocked.

注釈

This can only be used by non-bot accounts.

await block()

This function is a coroutine.

ユーザーをブロックします。

注釈

This can only be used by non-bot accounts.

Raises
await unblock()

This function is a coroutine.

Unblocks the user.

注釈

This can only be used by non-bot accounts.

Raises
await remove_friend()

This function is a coroutine.

Removes the user as a friend.

注釈

This can only be used by non-bot accounts.

Raises
  • Forbidden -- Not allowed to remove this user as a friend.

  • HTTPException -- Removing the user as a friend failed.

await send_friend_request()

This function is a coroutine.

Sends the user a friend request.

注釈

This can only be used by non-bot accounts.

Raises
  • Forbidden -- Not allowed to send a friend request to the user.

  • HTTPException -- Sending the friend request failed.

await profile()

This function is a coroutine.

Gets the user's profile.

注釈

This can only be used by non-bot accounts.

Raises
戻り値

ユーザーのプロフィール。

戻り値の型

Profile

avatar_url

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

これはデフォルトパラメータ(webp/gif フォーマット及びサイズが1024)で avatar_url_as() を呼び出すのと同等の処理です。

avatar_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and 'gif' is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

パラメータ
  • format (Optional[str]) -- アバターのフォーマット。 None の場合はアニメーションアバターなら 「gif」、それ以外は static_format のフォーマットに自動的に変換されます。

  • static_format (Optional[str]) -- アバターがアニメーションでない場合に変換されるフォーマット。デフォルトでは「webp」です。

  • size (int) -- The size of the image to display.

Raises

InvalidArgument -- Bad image format passed to format or static_format, or invalid size.

戻り値

The resulting CDN asset.

戻り値の型

Asset

color

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

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

created_at

Returns the user's creation time in UTC.

This is when the user's Discord account was created.

Type

datetime.datetime

default_avatar

Returns the default avatar for a given user. This is calculated by the user's discriminator.

Type

DefaultAvatar

default_avatar_url

Returns a URL for a user's default avatar.

Type

Asset

display_name

Returns the user's display name.

通常であれば、これはユーザー名がそのまま返りますが、ギルドにてニックネームを設定している場合は、代替としてニックネームが返ります。

Type

str

fetch_message(id)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

パラメータ

id (int) -- The message ID to look for.

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

is_avatar_animated()

Indicates if the user has an animated avatar.

mention

Returns a string that allows you to mention the given user.

Type

str

mentioned_in(message)

指定のメッセージにユーザーに対するメンションが含まれているかを確認します。

パラメータ

message (Message) -- メンションが含まれているかを確認するメッセージ。

permissions_in(channel)

abc.GuildChannel.permissions_for() のエイリアス。

基本的には以下と同等です:

channel.permissions_for(self)
パラメータ

channel (abc.GuildChannel) -- 権限を確認したいチャンネル。

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.

Raises

HTTPException -- Retrieving the pinned messages failed.

戻り値

The messages that are currently pinned.

戻り値の型

List[Message]

send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=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.

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

パラメータ
  • content (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.

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

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.

id

The attachment ID.

Type

int

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

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.

Raises
戻り値

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.

Raises
  • 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()

This function is a coroutine.

Converts the attachment into a File suitable for sending via abc.Messageable.send().

バージョン 1.3 で追加.

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

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.

bool(x)

Checks if the Asset has a 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.

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

警告

PartialEmoji won't have a connection state if user created, and a URL won't be present if a custom image isn't associated with the asset, e.g. a guild with no custom icon.

バージョン 1.1 で追加.

Raises
戻り値

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.

パラメータ
Raises
戻り値

The number of bytes written.

戻り値の型

int

Message

class discord.Message

Represents a message from Discord.

There should be no need to create one of these manually.

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

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 typically non-important.

embeds

A list of embeds the message has.

Type

List[Embed]

channel

The TextChannel that the message was sent from. Could be a DMChannel or GroupChannel if it's a private message.

Type

Union[abc.Messageable]

call

The call that the message refers to. This is only applicable to messages of type MessageType.call.

Type

Optional[CallMessage]

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]

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 escape markdown. If you want to escape markdown then use utils.escape_markdown() along with this function.

created_at

The message's creation time in UTC.

Type

datetime.datetime

edited_at

A naive UTC datetime object containing the edited time of the message.

Type

Optional[datetime.datetime]

jump_url

Returns a URL that allows the client to jump to this message.

Type

str

is_system()

bool: Whether the message is a system message.

バージョン 1.3 で追加.

system_content

A property that returns the content that is rendered regardless of the Message.type.

In the case of MessageType.default, this just returns the regular Message.content. Otherwise this returns an English message denoting the contents of the system message.

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.

Raises
  • Forbidden -- You do not have proper permissions to delete the message.

  • NotFound -- The message was deleted already

  • HTTPException -- Deleting the message failed.

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

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

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

await publish()

This function is a coroutine.

Publishes this message to your announcement channel.

You must have the manage_messages permission to use this.

注釈

This can only be used by non-bot accounts.

Raises
  • Forbidden -- You do not have the proper permissions to publish this message.

  • HTTPException -- Publishing the message failed.

await pin()

This function is a coroutine.

Pins the message.

You must have the manage_messages permission to do this in a non-private channel context.

Raises
  • 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()

This function is a coroutine.

Unpins the message.

You must have the manage_messages permission to do this in a non-private channel context.

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

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

パラメータ
Raises
  • 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.

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

Raises
  • HTTPException -- Removing the reactions failed.

  • Forbidden -- You do not have the proper permissions to remove all the reactions.

await ack()

This function is a coroutine.

Marks this message as read.

The user must not be a bot user.

Raises

Reaction

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('{0} has reacted with {1.emoji}!'.format(user, reaction))

Flattening into a list:

users = await reaction.users().flatten()
# users is now a list of User...
winner = random.choice(users)
await channel.send('{} has won the raffle.'.format(winner))
パラメータ
  • limit (int) -- The maximum number of results to return. If not provided, returns all the users who reacted to the message.

  • after (abc.Snowflake) -- For pagination, reactions are sorted by member.

Raises

HTTPException -- Getting the users for the reaction failed.

Yieldする値

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.

custom_emoji

If this is a custom emoji.

Type

bool

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.

Raises
  • 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 で追加.

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

CallMessage

class discord.CallMessage

Represents a group call message from Discord.

This is only received in cases where the message type is equivalent to MessageType.call.

ended_timestamp

A naive UTC datetime object that represents the time that the call has ended.

Type

Optional[datetime.datetime]

participants

The list of users that are participating in this call.

Type

List[User]

message

The message associated with this call message.

Type

Message

call_ended

Indicates if the call has ended.

Type

bool

channel

The private channel associated with this message.

Type

GroupChannel

duration

Queries the duration of the call.

If the call has not ended then the current duration will be returned.

戻り値

The timedelta object representing the duration.

戻り値の型

datetime.timedelta

GroupCall

class discord.GroupCall

Represents the actual group call from Discord.

This is accompanied with a CallMessage denoting the information.

call

The call message associated with this group call.

Type

CallMessage

unavailable

Denotes if this group call is unavailable.

Type

bool

ringing

A list of users that are currently being rung to join the call.

Type

List[User]

region

The guild region the group call is being hosted on.

Type

VoiceRegion

connected

A property that returns all users that are currently in this call.

Type

List[User]

channel

Returns the channel the group call is in.

Type

GroupChannel

voice_state_for(user)

Retrieves the VoiceState for a specified User.

If the User has no voice state then this function returns None.

パラメータ

user (User) -- The user to retrieve the voice state for.

戻り値

The voice state associated with this user.

戻り値の型

Optional[VoiceState]

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, ...]

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]

icon

The guild's icon.

Type

Optional[str]

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.

Type

Optional[int]

banner

The guild's banner.

Type

Optional[str]

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. They are currently as follows:

  • VIP_REGIONS: Guild has VIP voice regions

  • VANITY_URL: Guild can have a vanity invite URL (e.g. discord.gg/discord-api)

  • INVITE_SPLASH: Guild's invite page can have a special splash.

  • VERIFIED: Guild is a verified server.

  • PARTNERED: Guild is a partnered server.

  • MORE_EMOJI: Guild is allowed to have more than 50 custom emoji.

  • DISCOVERABLE: Guild shows up in Server Discovery.

  • COMMERCE: Guild can sell things using store channels.

  • PUBLIC: Users can lurk in this guild via Server Discovery.

  • NEWS: Guild can create news channels.

  • BANNER: Guild can upload and use a banner (i.e. banner_url()).

  • ANIMATED_ICON: Guild can upload an animated icon.

  • PUBLIC_DISABLED: Guild cannot be public.

Type

List[str]

splash

The guild's invite splash.

Type

Optional[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

How many users have currently "boosted" this guild.

Type

int

preferred_locale

The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.

Type

Optional[str]

discovery_splash

The guild's discovery splash.

バージョン 1.3 で追加.

Type

str

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('{0.user} did {0.action} to {0.target}'.format(entry))

Getting entries for a specific action:

async for entry in guild.audit_logs(action=discord.AuditLogAction.ban):
    print('{0.user} banned {0.target}'.format(entry))

Getting entries made by a specific user:

entries = await guild.audit_logs(limit=None, user=guild.me).flatten()
await channel.send('I made {} moderation actions.'.format(len(entries)))
パラメータ
  • 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 date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Union[abc.Snowflake, datetime.datetime]) -- Retrieve entries after this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC 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.

Raises
  • Forbidden -- You are not allowed to fetch audit logs

  • HTTPException -- An error occurred while fetching the audit logs.

Yieldする値

AuditLogEntry -- The audit log entry.

channels

A list of channels that belongs to this guild.

Type

List[abc.GuildChannel]

large

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

voice_channels

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]

me

Similar to Client.user except an instance of Member. This is essentially used to get the member version of yourself.

voice_client

Returns the VoiceClient associated with this guild, if any.

text_channels

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]

categories

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(channel_id)

Returns a channel with the given ID.

パラメータ

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

戻り値

The returned channel or None if not found.

戻り値の型

Optional[abc.GuildChannel]

system_channel

Returns the guild's channel used for system messages.

If no channel is set, then this returns None.

Type

Optional[TextChannel]

system_channel_flags

Returns the guild's system channel settings.

Type

SystemChannelFlags

rules_channel

Return's the guild's channel used for the rules. Must be a discoverable guild.

If no channel is set, then this returns None.

バージョン 1.3 で追加.

Type

Optional[TextChannel]

emoji_limit

The maximum number of emoji slots this guild has.

Type

int

bitrate_limit

The maximum bitrate for voice channels this guild can have.

Type

float

filesize_limit

The maximum number of bytes files can have when uploaded to this guild.

Type

int

members

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]

premium_subscribers

A list of members who have "boosted" this guild.

Type

List[Member]

roles

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.

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]

default_role

Gets the @everyone role that all members have by default.

owner

The member that owns the guild.

Type

Member

icon_url

Returns the guild's icon asset.

Type

Asset

is_icon_animated()

bool: Returns True if the guild has an animated icon.

icon_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the guild's icon.

The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and 'gif' is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

パラメータ
  • format (Optional[str]) -- The format to attempt to convert the icon to. If the format is None, then it is automatically detected into either 'gif' or static_format depending on the icon being animated or not.

  • static_format (Optional[str]) -- Format to attempt to convert only non-animated icons to.

  • size (int) -- The size of the image to display.

Raises

InvalidArgument -- Bad image format passed to format or invalid size.

戻り値

The resulting CDN asset.

戻り値の型

Asset

banner_url

Returns the guild's banner asset.

Type

Asset

banner_url_as(*, format='webp', size=2048)

Returns an Asset for the guild's banner.

The format must be one of 'webp', 'jpeg', or 'png'. The size must be a power of 2 between 16 and 4096.

パラメータ
  • format (str) -- The format to attempt to convert the banner to.

  • size (int) -- The size of the image to display.

Raises

InvalidArgument -- Bad image format passed to format or invalid size.

戻り値

The resulting CDN asset.

戻り値の型

Asset

splash_url

Returns the guild's invite splash asset.

Type

Asset

splash_url_as(*, format='webp', size=2048)

Returns an Asset for the guild's invite splash.

The format must be one of 'webp', 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 4096.

パラメータ
  • format (str) -- The format to attempt to convert the splash to.

  • size (int) -- The size of the image to display.

Raises

InvalidArgument -- Bad image format passed to format or invalid size.

戻り値

The resulting CDN asset.

戻り値の型

Asset

discovery_splash_url

Returns the guild's discovery splash asset.

バージョン 1.3 で追加.

Type

Asset

discovery_splash_url_as(*, format='webp', size=2048)

Returns an Asset for the guild's discovery splash.

The format must be one of 'webp', 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 4096.

バージョン 1.3 で追加.

パラメータ
  • format (str) -- The format to attempt to convert the splash to.

  • size (int) -- The size of the image to display.

Raises

InvalidArgument -- Bad image format passed to format or invalid size.

戻り値

The resulting CDN asset.

戻り値の型

Asset

member_count

Returns the true member count regardless of it being loaded fully or not.

chunked

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.

shard_id

Returns the shard ID for this guild if applicable.

Type

int

created_at

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.

戻り値の型

Member

await create_text_channel(name, *, overwrites=None, category=None, reason=None, **options)

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 -- 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 (Optional[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.

Raises
  • 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, *, overwrites=None, category=None, reason=None, **options)

This function is a coroutine.

This is similar to create_text_channel() except makes a VoiceChannel instead, in addition to having the following new parameters.

パラメータ
  • 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.

await create_category(name, *, overwrites=None, reason=None)

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.

await create_category_channel(name, *, overwrites=None, reason=None)

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.

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

Raises

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.

Raises
await edit(*, reason=None, **fields)

This function is a coroutine.

Edits the guild.

You must have the manage_guild permission to edit the guild.

パラメータ
  • name (str) -- The new name of the guild.

  • description (str) -- The new description of the guild. This is only available to guilds that contain VERIFIED in Guild.features.

  • icon (bytes) -- A bytes-like object representing the icon. Only PNG/JPEG supported and GIF for guilds with ANIMATED_ICON feature. 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.

  • splash (bytes) -- A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could be None to denote removing the splash. Only available for partnered guilds with INVITE_SPLASH feature.

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

  • reason (Optional[str]) -- The reason for editing this guild. Shows up on the audit log.

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

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 で追加.

Raises
戻り値

All channels in the guild.

戻り値の型

List[abc.GuildChannel]

fetch_members(*, limit=1000, after=None)

This function is a coroutine.

Retrieves an AsyncIterator that enables receiving the guild's members.

注釈

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 date is provided it must be a timezone-naive datetime representing UTC time.

Raises

HTTPException -- Getting the members failed.

Yieldする値

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...
await fetch_member(member_id)

This function is a coroutine.

Retreives a Member from a guild ID, and a member ID.

注釈

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

パラメータ

member_id (int) -- The member's ID to fetch from.

Raises
戻り値

The member from the member ID.

戻り値の型

Member

await fetch_ban(user)

This function is a coroutine.

Retrieves the BanEntry for a user, which is a namedtuple with a user and reason field. See bans() for more information.

You must have the ban_members permission to get this information.

パラメータ

user (abc.Snowflake) -- The user to get ban information from.

Raises
  • 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 bans()

This function is a coroutine.

Retrieves all the users that are banned from the guild.

This coroutine returns a list of BanEntry objects, which is a namedtuple with a user field to denote the User that got banned along with a reason field specifying why the user was banned that could be set to None.

You must have the ban_members permission to get this information.

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

パラメータ
  • 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.

Raises
戻り値

The number of members pruned. If compute_prune_count is False then this returns None.

戻り値の型

Optional[int]

await webhooks()

This function is a coroutine.

Gets the list of webhooks from this guild.

Requires manage_webhooks permissions.

Raises

Forbidden -- You don't have permissions to get the webhooks.

戻り値

The webhooks for this guild.

戻り値の型

List[Webhook]

await estimate_pruned_members(*, days)

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.

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

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

Raises

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.

Raises
  • 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=None, 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 (Optional[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.

Raises
戻り値

The created emoji.

戻り値の型

Emoji

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 で追加.

Raises

HTTPException -- Retrieving the roles failed.

戻り値

All roles in the guild.

戻り値の型

List[Role]

await create_role(*, reason=None, **fields)

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.

パラメータ
  • name (str) -- The role name. Defaults to 'new role'.

  • permissions (Permissions) -- The permissions to have. Defaults to no permissions.

  • colour (Colour) -- The colour for the role. Defaults to Colour.default(). This is aliased to color as well.

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

Raises
戻り値

The newly created role.

戻り値の型

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.

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

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

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

Raises
  • Forbidden -- You do not have the proper permissions to get this.

  • HTTPException -- Retrieving the vanity invite failed.

戻り値

The special vanity invite.

戻り値の型

Invite

ack()

This function is a coroutine.

Marks every message in this guild as read.

The user must not be a bot user.

Raises
await widget()

This function is a coroutine.

Returns the widget of the guild.

注釈

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

Raises
戻り値

ギルドのウィジェット。

戻り値の型

Widget

await query_members(query, *, limit=5, 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.

警告

Most bots do not need to use this. It's mainly a helper for bots who have disabled guild_subscriptions.

バージョン 1.3 で追加.

パラメータ
  • query (str) -- The string that the username's start with. An empty string requests all members.

  • limit (int) -- The maximum number of members to send back. This must be a number between 1 and 1000.

  • cache (bool) -- Whether to cache the members internally. This makes operations such as get_member() work for those that matched.

Raises

asyncio.TimeoutError -- The query timed out waiting for the members.

戻り値

The list of members that have matched the query.

戻り値の型

List[Member]

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

A datetime object that specifies the date and time in UTC that the member joined the guild for the first time. In certain cases, this can be None.

Type

Optional[datetime.datetime]

activities

The activities that the user is currently doing.

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]

premium_since

A 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 date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC 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.

Raises
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

Yieldする値

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():
    # do expensive stuff here
    await channel.send('done!')
status

The member's overall status. If the value is unknown, then it will be a str instead.

Type

Status

mobile_status

The member's status on a mobile device, if applicable.

Type

Status

desktop_status

The member's status on the desktop client, if applicable.

Type

Status

web_status

The member's status on the web client, if applicable.

Type

Status

is_on_mobile()

A helper function that determines if a member is active on a mobile device.

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

color

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

roles

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]

mention

Returns a string that allows you to mention the member.

Type

str

display_name

Returns the user's display name.

通常であれば、これはユーザー名がそのまま返りますが、ギルドにてニックネームを設定している場合は、代替としてニックネームが返ります。

Type

str

activity

Returns the primary activity the user is currently doing. Could be None if no activity is being done.

注釈

A user may have multiple activities, these can be accessed under activities.

Type

Union[BaseActivity, Spotify]

mentioned_in(message)

Checks if the member is mentioned in the specified message.

パラメータ

message (Message) -- メンションが含まれているかを確認するメッセージ。

permissions_in(channel)

abc.GuildChannel.permissions_for() のエイリアス。

基本的には以下と同等です:

channel.permissions_for(self)
パラメータ

channel (Channel) -- 権限を確認したいチャンネル。

top_role

Returns the member's highest role.

This is useful for figuring where a member stands in the role hierarchy chain.

Type

Role

guild_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 either permissions_in() or abc.GuildChannel.permissions_for().

This does take into consideration guild ownership and the administrator implication.

voice

Returns the member's current voice state.

Type

Optional[VoiceState]

await ban(**kwargs)

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(*, reason=None, **fields)

This function is a coroutine.

Edits the member's data.

Depending on the parameter passed, this requires different permissions listed below:

Parameter

Permission

nick

Permissions.manage_nicknames

mute

Permissions.mute_members

deafen

Permissions.deafen_members

役職

Permissions.manage_roles

voice_channel

Permissions.move_members

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

バージョン 1.1 で変更: Can now pass None to voice_channel to kick a member from voice.

パラメータ
  • 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.

  • roles (Optional[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.

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

パラメータ
  • *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.

Raises
avatar

Equivalent to User.avatar

avatar_url

Equivalent to User.avatar_url

avatar_url_as(*args, **kwargs)

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and 'gif' is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

パラメータ
  • format (Optional[str]) -- アバターのフォーマット。 None の場合はアニメーションアバターなら 「gif」、それ以外は static_format のフォーマットに自動的に変換されます。

  • static_format (Optional[str]) -- アバターがアニメーションでない場合に変換されるフォーマット。デフォルトでは「webp」です。

  • size (int) -- The size of the image to display.

Raises

InvalidArgument -- Bad image format passed to format or static_format, or invalid size.

戻り値

The resulting CDN asset.

戻り値の型

Asset

block(*args, **kwargs)

This function is a coroutine.

ユーザーをブロックします。

注釈

This can only be used by non-bot accounts.

Raises
bot

Equivalent to User.bot

create_dm(*args, **kwargs)

このユーザーと DMChannel を作ります。

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

created_at

Equivalent to User.created_at

default_avatar

Equivalent to User.default_avatar

default_avatar_url

Equivalent to User.default_avatar_url

discriminator

Equivalent to User.discriminator

dm_channel

Equivalent to User.dm_channel

fetch_message(id)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

パラメータ

id (int) -- The message ID to look for.

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

id

Equivalent to User.id

is_avatar_animated(*args, **kwargs)

Indicates if the user has an animated avatar.

is_blocked(*args, **kwargs)

Checks if the user is blocked.

注釈

This can only be used by non-bot accounts.

is_friend(*args, **kwargs)

Checks if the user is your friend.

注釈

This can only be used by non-bot accounts.

mutual_friends(*args, **kwargs)

This function is a coroutine.

Gets all mutual friends of this user.

注釈

This can only be used by non-bot accounts.

Raises
  • Forbidden -- Not allowed to get mutual friends of this user.

  • HTTPException -- Getting mutual friends failed.

戻り値

The users that are mutual friends.

戻り値の型

List[User]

name

Equivalent to User.name

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.

Raises

HTTPException -- Retrieving the pinned messages failed.

戻り値

The messages that are currently pinned.

戻り値の型

List[Message]

profile(*args, **kwargs)

This function is a coroutine.

Gets the user's profile.

注釈

This can only be used by non-bot accounts.

Raises
戻り値

ユーザーのプロフィール。

戻り値の型

Profile

relationship

Equivalent to User.relationship

remove_friend(*args, **kwargs)

This function is a coroutine.

Removes the user as a friend.

注釈

This can only be used by non-bot accounts.

Raises
  • Forbidden -- Not allowed to remove this user as a friend.

  • HTTPException -- Removing the user as a friend failed.

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.

パラメータ
  • *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.

Raises
send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=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.

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

パラメータ
  • content (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.

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

send_friend_request(*args, **kwargs)

This function is a coroutine.

Sends the user a friend request.

注釈

This can only be used by non-bot accounts.

Raises
  • Forbidden -- Not allowed to send a friend request to the user.

  • HTTPException -- Sending the friend request failed.

system

Equivalent to User.system

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.

unblock(*args, **kwargs)

This function is a coroutine.

Unblocks the user.

注釈

This can only be used by non-bot accounts.

Raises

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

type

Returns the activity's type. This is for compatibility with Activity.

It always returns ActivityType.listening.

created_at

When the user started listening in UTC.

バージョン 1.3 で追加.

Type

Optional[datetime.datetime]

colour

Returns the Spotify integration colour, as a Colour.

There is an alias for this named color()

color

Returns the Spotify integration colour, as a Colour.

There is an alias for this named colour()

name

The activity's name. This will always return "Spotify".

Type

str

title

The title of the song being played.

Type

str

artists

The artists of the song being played.

Type

List[str]

artist

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

album

The album that the song being played belongs to.

Type

str

album_cover_url

The album cover image URL from Spotify's CDN.

Type

str

track_id

The track ID used by Spotify to identify this song.

Type

str

start

When the user started playing this song in UTC.

Type

datetime.datetime

end

When the user will stop playing this song in UTC.

Type

datetime.datetime

duration

The duration of the song being played.

Type

datetime.timedelta

party_id

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

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[VoiceChannel]

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]

created_at

Returns the emoji's creation time in UTC.

Type

datetime.datetime

url

Returns the asset of the emoji.

Type

Asset

roles

A list of roles that is allowed to use this emoji.

If roles is empty, the emoji is unrestricted.

Type

List[Role]

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.

Raises
await edit(*, name=None, roles=None, reason=None)

This function is a coroutine.

Edits the custom emoji.

You must have manage_emojis permission to do this.

パラメータ
  • name (str) -- The new emoji name.

  • roles (Optional[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 editing this emoji. Shows up on the audit log.

Raises

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]

is_custom_emoji()

Checks if this is a custom non-Unicode emoji.

is_unicode_emoji()

Checks if this is a Unicode emoji.

url

Returns an asset of the emoji, if it is custom.

Type

Asset

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.

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

is_default()

Checks if the role is the default role.

permissions

Returns the role's permissions.

Type

Permissions

colour

Returns the role colour. An alias exists under color.

Type

Colour

color

Returns the role colour. An alias exists under color.

Type

Colour

created_at

Returns the role's creation time in UTC.

Type

datetime.datetime

mention

Returns a string that allows you to mention a role.

Type

str

members

Returns all the members with this role.

Type

List[Member]

await edit(*, reason=None, **fields)

This function is a coroutine.

Edits the role.

You must have the manage_roles permission to use this.

All fields are optional.

パラメータ
  • name (str) -- The new role name to change to.

  • permissions (Permissions) -- The new permissions to change to.

  • colour (Colour) -- The new colour to change to. (aliased to color as well)

  • hoist (bool) -- Indicates if the role should be shown separately in the 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.

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

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.

Raises

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

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 date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC 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.

Raises
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

Yieldする値

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():
    # do expensive stuff here
    await channel.send('done!')
type

The channel's Discord type.

Type

ChannelType

permissions_for(member)

Handles permission resolution for the current Member.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

パラメータ

member (Member) -- The member to resolve permissions for.

戻り値

The resolved permissions for the member.

戻り値の型

Permissions

members

Returns all members that can see this channel.

Type

List[Member]

is_nsfw()

Checks if the channel is NSFW.

is_news()