APIリファレンス¶
ここではdiscord.pyのAPIについて解説します。
注釈
このモジュールはPythonのloggingモジュールを使用して、出力に依存しない方法でエラーや診断の内容を記録します。loggingモジュールが設定されていない場合、これらのログはどこにも出力されません。discord.pyでloggingモジュールを使用する方法の詳細は ログの設定 を参照してください。
Clients¶
クライアント¶
- asyncapplication_info
- asyncbefore_identify_hook
- asyncchange_presence
- defclear
- asyncclose
- asyncconnect
- asynccreate_guild
- asyncdelete_invite
- @event
- asyncfetch_channel
- asyncfetch_guild
- deffetch_guilds
- asyncfetch_invite
- asyncfetch_template
- asyncfetch_user
- asyncfetch_webhook
- asyncfetch_widget
- defget_all_channels
- defget_all_members
- defget_channel
- defget_emoji
- defget_guild
- defget_user
- defis_closed
- defis_ready
- defis_ws_ratelimited
- asynclogin
- asyncon_error
- defrun
- asyncstart
- asyncwait_for
- asyncwait_until_ready
-
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 inNone
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
]) -- Integer starting at0
and less thanshard_count
.shard_count (Optional[
int
]) -- Shardの総数。application_id (
int
) -- The client's application ID.intents (
Intents
) --The intents that you want to enable for the session. This is a way of disabling and enabling certain gateway events from triggering and being sent. If not given, defaults to a regularly constructed
Intents
class.バージョン 1.5 で追加.
member_cache_flags (
MemberCacheFlags
) --Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible with the currently selected intents.
バージョン 1.5 で追加.
chunk_guilds_at_startup (
bool
) --Indicates if
on_ready()
should be delayed to chunk all guilds at start-up if necessary. This operation is incredibly slow for large amounts of guilds. The default isTrue
ifIntents.members
isTrue
.バージョン 1.5 で追加.
status (Optional[
Status
]) -- Discordにログインした際の、開始時ステータス。activity (Optional[
BaseActivity
]) -- Discordにログインした際の、開始時アクティビティ。allowed_mentions (Optional[
AllowedMentions
]) --Control how the client handles mentions by default on every message sent.
バージョン 1.4 で追加.
heartbeat_timeout (
float
) -- HEARTBEAT_ACKを受信できない際に、WebSocketをタイムアウトさせて再起動するまでの最大秒数。最初のパケットの処理に時間がかかり、接続を切断できないというような状況時に便利です。デフォルトでは60秒に設定されています。guild_ready_timeout (
float
) --The maximum number of seconds to wait for the GUILD_CREATE stream to end before preparing the member cache and firing READY. The default timeout is 2 seconds.
バージョン 1.4 で追加.
assume_unsync_clock (
bool
) --Whether to assume the system clock is unsynced. This applies to the ratelimit handling code. If this is set to
True
, the default, then the library uses the time to reset a rate limit bucket given by Discord. If this isFalse
then your system clock is used to calculate how long to sleep for. If this is set toFalse
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.
-
async for ... in
fetch_guilds
(*, limit=100, before=None, after=None)¶ Botが所属するGuildを取得できる、
AsyncIterator
を取得します。注釈
これを使った場合、各
Guild
のGuild.owner
、Guild.icon
、Guild.id
、Guild.name
のみ取得できます。注釈
これはAPIを呼び出します。通常は
guilds
を代わりに使用してください。サンプル
使い方
async for guild in client.fetch_guilds(limit=150): print(guild.name)
リストへフラット化
guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild...
すべてのパラメータがオプションです。
- パラメータ
limit (Optional[
int
]) -- The number of guilds to retrieve. IfNone
, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to100
.before (Union[
abc.Snowflake
,datetime.datetime
]) -- Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Union[
abc.Snowflake
,datetime.datetime
]) -- Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- 例外
HTTPException -- Getting the guilds failed.
- 列挙
Guild
-- データを解析したGuild。
-
latency
¶ Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
これはDiscord WebSocketプロトコルの待ち時間とも言えます。
- Type
-
is_ws_ratelimited
()¶ bool
: Whether the websocket is currently rate limited.This can be useful to know when deciding whether you should query members using HTTP or via the gateway.
バージョン 1.6 で追加.
-
user
¶ Represents the connected client.
None
if not logged in.- Type
Optional[
ClientUser
]
-
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.
These are usually
VoiceClient
instances.- Type
List[
VoiceProtocol
]
-
application_id
¶ The client's application ID.
If this is not passed via
__init__
then this is retrieved through the gateway when an event contains the data. Usually afteron_connect()
is called.- Type
Optional[
int
]
-
await
on_error
(event_method, *args, **kwargs)¶ This function is a coroutine.
クライアントによって提供されるデフォルトのエラーハンドラ。
デフォルトでは、これは
sys.stderr
に出力されますが、異なる実装によって上書きされる可能性があります。詳細についてはon_error()
を確認してください。
-
await
before_identify_hook
(shard_id, *, initial=False)¶ This function is a coroutine.
A hook that is called before IDENTIFYing a session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients.
The default implementation sleeps for 5 seconds.
バージョン 1.4 で追加.
-
await
login
(token)¶ This function is a coroutine.
指定された資格情報を使用してクライアントにログインします。
- パラメータ
token (
str
) -- 認証用のトークン。このライブラリが処理するため、トークンの頭に何も付けないでください。- 例外
LoginFailure -- The wrong credentials are passed.
HTTPException -- An unknown HTTP related error occurred, usually when it isn't 200 or the known incorrect credentials passing status code.
-
await
connect
(*, reconnect=True)¶ This function is a coroutine.
WebSocket接続を作成し、Discordからのメッセージをリッスンできるようにします。これはイベントシステム全体とライブラリの様々な機能を実行するループです。WebSocket接続が終了するまで、制御は再開されません。
- パラメータ
reconnect (
bool
) -- インターネットの障害やDiscord側の特定の障害が発生した際に再接続を試みるかどうかを表します。不正な状態へつながることによる特定の切断(無効なシャーディングペイロードや不正なトークンなど)は処理されません。- 例外
GatewayNotFound -- If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.
ConnectionClosed -- The websocket connection has been terminated.
-
clear
()¶ Botの内部状態をクリアします。
これが実行されると、Botは「再オープン」されたとみなされます。そのため、
is_closed()
やis_ready()
はFalse
を返し、内部のキャッシュもクリアされます。
-
await
start
(token, *, reconnect=True)¶ This function is a coroutine.
login()
+connect()
を簡略化したコルーチン。- 例外
TypeError -- An unexpected keyword argument was received.
-
run
(*args, **kwargs)¶ イベントループの初期化を抽象化するブロッキングコール。
イベントループをより詳細に制御するには、この関数を使用しないでください。
start()
またはconnect()
+login()
を使用してください。おおよそ次のものに相当:
try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(close()) # cancel all tasks lingering finally: loop.close()
警告
この関数はブロッキングを行うため、必ず最後に呼び出してください。この関数を呼び出した後に呼び出されるイベントや関数は、Botが停止するまで実行されません。
-
activity
¶ The activity being used upon logging in.
- Type
Optional[
BaseActivity
]
-
allowed_mentions
¶ The allowed mention configuration.
バージョン 1.4 で追加.
- Type
Optional[
AllowedMentions
]
-
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.
-
get_user
(id)¶ Returns a user with the given ID.
-
get_emoji
(id)¶ Returns an emoji with the given ID.
-
for ... in
get_all_channels
()¶ クライアントが「アクセス」できるすべての
abc.GuildChannel
のジェネレータを取得します。使用例:
for guild in client.guilds: for channel in guild.channels: yield channel
注釈
abc.GuildChannel
を受け取ったからと言って、そのチャンネルで発言ができるという意味ではありません。発言可能なチャンネルのみを取得したいのなら、abc.GuildChannel.permissions_for()
を使いましょう。- 列挙
abc.GuildChannel
-- A channel the client can 'access'.
-
for ... in
get_all_members
()¶ クライアントが参照可能なすべての
Member
のジェネレータを返します。使用例:
for guild in client.guilds: for member in guild.members: yield member
- 列挙
Member
-- A member the client can see.
-
wait_for
(event, *, check=None, timeout=None)¶ This function is a coroutine.
WebSocketイベントがディスパッチされるまで待機します。
メッセージの送信者が、メッセージに返信したり、リアクションをつけたり、編集したりする、自己完結型の処理に利用できます。
timeout
パラメータはasyncio.wait_for()
に渡されます。デフォルトではタイムアウトしません。タイムアウトした際にasyncio.TimeoutError
が発生するのは、使いやすさを考慮したためです。イベントが複数の引数を返す場合は、それらを含む
tuple
が代わりに返ります。イベントとそのパラメーターについては ドキュメント を参照してください。この関数は 条件を満たす最初のイベント を返します。
サンプル
ユーザーからの返信を待つ場合:
@client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send(f'Hello {msg.author}!')
メッセージ送信者がサムズアップリアクションを付けるのを待つ場合:
@client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that 👍 reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '👍' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('👎') else: await channel.send('👍')
- パラメータ
event (
str
) -- イベント名は イベントリファレンス に似ていますが接頭詞のon_
が必要ありません。check (Optional[Callable[...,
bool
]]) -- 待っているものに該当するかを確認する関数。引数は待機しているイベントのパラメータを満たしている必要があります。timeout (Optional[
float
]) -- タイムアウトしてasyncio.TimeoutError
が発生するまでの秒数。
- 例外
asyncio.TimeoutError -- If a timeout is provided and it was reached.
- 戻り値
単一の引数、あるいは イベントリファレンス のパラメータを反映した複数の引数の値を含む
tuple
が返ります。返る引数がない場合もあります。- 戻り値の型
Any
-
event
(coro)¶ リッスンするイベントを登録するデコレータ。
イベントの詳細については 以下のドキュメント を参照してください。
イベントは コルーチン でなければいけません。違う場合は
TypeError
が発生します。サンプル
@client.event async def on_ready(): print('Ready!')
- 例外
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クライアントにプッシュ通知をよりよく扱わせることができます。
- 例外
InvalidArgument -- If the
activity
parameter is not the proper type.
-
await
fetch_template
(code)¶ This function is a coroutine.
Gets a
Template
from a discord.new URL or code.- パラメータ
code (Union[
Template
,str
]) -- The Discord Template Code or URL (must be a discord.new URL).- 例外
NotFound -- The template is invalid.
HTTPException -- Getting the template failed.
- 戻り値
The template from the URL/code.
- 戻り値の型
-
await
fetch_guild
(guild_id)¶ This function is a coroutine.
IDから
Guild
を取得します。注釈
Using this, you will not receive
Guild.channels
,Guild.members
,Member.activity
andMember.voice
perMember
.注釈
このメソッドはAPIを呼び出します。通常は
get_guild()
を代わりとして使用してください。- パラメータ
guild_id (
int
) -- 取得したいギルドのID。- 例外
Forbidden -- You do not have access to the guild.
HTTPException -- Getting the guild failed.
- 戻り値
IDから取得したギルド。
- 戻り値の型
-
await
create_guild
(name, region=None, icon=None, *, code=None)¶ This function is a coroutine.
Guild
を作成します。10以上のギルドに参加しているBotアカウントはギルドの作成ができません。
- パラメータ
name (
str
) -- ギルドの名前。region (
VoiceRegion
) -- ボイスチャンネルの通信サーバーのリージョンです。デフォルトはVoiceRegion.us_west
です。icon (
bytes
) -- アイコンを表す bytes-like object です。ClientUser.edit()
で、予期されるデータの詳細を確認してください。code (Optional[
str
]) --The code for a template to create the guild with.
バージョン 1.4 で追加.
- 例外
HTTPException -- Guild creation failed.
InvalidArgument -- Invalid icon image format given. Must be PNG or JPG.
- 戻り値
作成されたギルド。キャッシュに追加されるギルドとは別物です。
- 戻り値の型
-
await
fetch_invite
(url, *, with_counts=True)¶ This function is a coroutine.
Invite
をdiscord.gg URLやIDから取得します。注釈
If the invite is for a guild you have not joined, the guild and channel attributes of the returned
Invite
will bePartialInviteGuild
andPartialInviteChannel
respectively.- パラメータ
url (Union[
Invite
,str
]) -- Discordの招待ID、またはURL(discord.gg URLである必要があります)。with_counts (
bool
) -- 招待にカウントの情報を含めるかどうか。これによりInvite.approximate_member_count
とInvite.approximate_presence_count
が追加されます。
- 例外
NotFound -- The invite has expired or is invalid.
HTTPException -- Getting the invite failed.
- 戻り値
URL/IDから取得した招待。
- 戻り値の型
-
await
delete_invite
(invite)¶ This function is a coroutine.
Invite
や、招待のURL、IDを削除します。これを行うには、関連付けられたGuildにて、
manage_channels
権限が必要です。- パラメータ
- 例外
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。- 例外
Forbidden -- The widget for this guild is disabled.
HTTPException -- Retrieving the widget failed.
- 戻り値
ギルドのウィジェット。
- 戻り値の型
-
await
application_info
()¶ This function is a coroutine.
Botのアプリケーション情報を取得します。
- 例外
HTTPException -- Retrieving the information failed somehow.
- 戻り値
Botのアプリケーション情報。
- 戻り値の型
-
await
fetch_user
(user_id)¶ This function is a coroutine.
IDをもとに
User
を取得します。Botアカウントでのみ使用できます。そのユーザーとギルドを共有する必要はありませんが、操作の多くはそれを必要とします。注釈
このメソッドはAPIを呼び出します。通常は
get_user()
を代わりとして使用してください。- パラメータ
user_id (
int
) -- 取得したいユーザーのID。- 例外
NotFound -- A user with this ID does not exist.
HTTPException -- Fetching the user failed.
- 戻り値
あなたがリクエストしたユーザー。
- 戻り値の型
-
await
fetch_channel
(channel_id)¶ This function is a coroutine.
指定されたIDを持つ
abc.GuildChannel
またはabc.PrivateChannel
を取得します。注釈
このメソッドはAPIを呼び出します。通常は
get_channel()
を代わりとして使用してください。バージョン 1.2 で追加.
- 例外
InvalidData -- An unknown channel type was received from Discord.
HTTPException -- Retrieving the channel failed.
NotFound -- Invalid Channel ID.
Forbidden -- You do not have permission to fetch this channel.
- 戻り値
IDから取得したチャンネル。
- 戻り値の型
Union[
abc.GuildChannel
,abc.PrivateChannel
]
AutoShardedClient¶
- asyncchange_presence
- asyncclose
- asyncconnect
- defget_shard
- defis_ws_ratelimited
-
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
までのシャードを起動します。-
latency
¶ Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
これは
Client.latency()
と同様に機能しますが、すべてのシャードの平均待ち時間を使用する点が異なります。シャードの待ち時間のリストを取得するにはlatencies
プロパティを参照してください。準備ができていない場合はnan
を返します。- Type
-
latencies
¶ A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
これは、
(shard_id, latency)
の要素を持つタプルのリストを返します。
-
get_shard
(shard_id)¶ Optional[
ShardInfo
]: Gets the shard information at a given shard ID orNone
if not found.
-
shards
¶ Returns a mapping of shard IDs to their respective info object.
- Type
Mapping[int,
ShardInfo
]
-
await
connect
(*, reconnect=True)¶ This function is a coroutine.
WebSocket接続を作成し、Discordからのメッセージをリッスンできるようにします。これはイベントシステム全体とライブラリの様々な機能を実行するループです。WebSocket接続が終了するまで、制御は再開されません。
- パラメータ
reconnect (
bool
) -- インターネットの障害やDiscord側の特定の障害が発生した際に再接続を試みるかどうかを表します。不正な状態へつながることによる特定の切断(無効なシャーディングペイロードや不正なトークンなど)は処理されません。- 例外
GatewayNotFound -- If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.
ConnectionClosed -- The websocket connection has been terminated.
-
await
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がアクセスできるすべてのシャードのプレゼンスが変更されます。
- 例外
InvalidArgument -- If the
activity
parameter is not of proper type.
-
is_ws_ratelimited
()¶ bool
: Whether the websocket is currently rate limited.This can be useful to know when deciding whether you should query members using HTTP or via the gateway.
This implementation checks if any of the shards are rate limited. For more granular control, consider
ShardInfo.is_ws_ratelimited()
.バージョン 1.6 で追加.
-
Application Info¶
AppInfo¶
-
class
discord.
AppInfo
¶ Discordが提供するBotのアプリケーション情報を表します。
-
bot_public
¶ Whether the bot can be invited by anyone or if it is locked to the application owner.
- Type
-
bot_require_code_grant
¶ Whether the bot requires the completion of the full oauth2 code grant flow to join.
- Type
-
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
-
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
]
-
terms_of_service_url
¶ The application's terms of service URL, if set.
バージョン 2.0 で追加.
- Type
Optional[
str
]
-
Team¶
-
class
discord.
Team
¶ Represents an application team for a bot provided by Discord.
-
members
¶ A list of the members in the team
バージョン 1.3 で追加.
- Type
List[
TeamMember
]
-
owner
¶ The team's owner.
- Type
Optional[
TeamMember
]
-
TeamMember¶
-
class
discord.
TeamMember
¶ Represents a team member in a team.
-
x == y
Checks if two team members are equal.
-
x != y
Checks if two team members are not equal.
-
hash(x)
Return the team member's hash.
-
str(x)
Returns the team member's name with discriminator.
バージョン 1.3 で追加.
-
discriminator
¶ The team member's discriminator. This is given when the username has conflicts.
- Type
-
membership_state
¶ The membership state of the member (e.g. invited or accepted)
- Type
-
イベントリファレンス¶
This section outlines the different types of events listened by Client
.
イベントを登録する方法は二通りあります。一つ目は Client.event()
を使用する方法です。二つ目は Client
を継承してサブクラスを作り、イベントをオーバーライドする方法です。この方法を用いた場合は以下のようになります:
import discord
class MyClient(discord.Client):
async def on_message(self, message):
if message.author == self.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello World!')
イベントハンドラが例外を発生させると、それを処理するために on_error()
が呼び出されます。 デフォルトではトレースバックが出力され、例外は無視されます。
警告
すべてのイベントは coroutine である必要があります。 coroutine でない場合、予期せぬエラーが発生する可能性があります。関数をコルーチンにするには、関数定義の際に async def
を使用してください。
-
discord.
on_connect
()¶ クライアントがDiscordに正常に接続できたときに呼び出されます。クライアントの準備が完了していることと同義ではありません。
on_ready()
を参照してください。on_ready()
での警告も適用されます。
-
discord.
on_shard_connect
(shard_id)¶ Similar to
on_connect()
except used byAutoShardedClient
to denote when a particular shard ID has connected to Discord.バージョン 1.4 で追加.
- パラメータ
shard_id (
int
) -- The shard ID that has connected.
-
discord.
on_disconnect
()¶ Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.
This function can be called many times without a corresponding
on_connect()
call.
-
discord.
on_shard_disconnect
(shard_id)¶ Similar to
on_disconnect()
except used byAutoShardedClient
to denote when a particular shard ID has disconnected from Discord.バージョン 1.4 で追加.
- パラメータ
shard_id (
int
) -- The shard ID that has disconnected.
-
discord.
on_ready
()¶ クライアントがDiscordから受信したデータの準備を完了した際に呼び出されます。通常はログインが成功したあと、
Client.guilds
とそれに関連するものの準備が完了したときです。警告
このイベントは、最初に呼び出されるイベントとは限りません。同時に、このイベントは 一度だけ呼ばれるという保証もできません 。このライブラリは、再接続ロジックを実装しているためリジューム要求が失敗するたびにこのイベントが呼び出されることになります。
-
discord.
on_shard_ready
(shard_id)¶ 特定の Shard IDが準備完了になったかを確認するために
AutoShardedClient
で使用される以外はon_ready()
とほとんど同じです。- パラメータ
shard_id (
int
) -- 準備が完了したShard ID。
-
discord.
on_resumed
()¶ クライアントがセッションを再開したときに呼び出されます。
-
discord.
on_shard_resumed
(shard_id)¶ Similar to
on_resumed()
except used byAutoShardedClient
to denote when a particular shard ID has resumed a session.バージョン 1.4 で追加.
- パラメータ
shard_id (
int
) -- The shard ID that has resumed.
-
discord.
on_error
(event, *args, **kwargs)¶ イベントがキャッチされない例外を発生させた場合、通常はトレースバックがstderrに出力され、その例外は無視されます。何らかの理由でこの動作を変更して、自分自身で例外処理を行いたい場合は、このイベントをオーバーライドすることができます。これを行った場合、トレースバックを出力するというデフォルトの動作は行われません。
発生した例外の情報と、例外事態は
sys.exc_info()
への標準呼び出しで取得できます。例外を
Client
クラスの外に伝播させたい場合は、単一の空の The raise statement 文を持つon_error
を定義することができます。発生した例外は、Client
のon_error
では決して処理されることはありません。注釈
on_error
will only be dispatched toClient.event()
.It will not be received by
Client.wait_for()
, or, if used, Bots listeners such aslisten()
orlistener()
.- パラメータ
event (
str
) -- 例外を発生させたイベントの名前。args -- 例外を発生させたイベントの位置引数。
kwargs -- 例外を発生させたイベントのキーワード引数。
-
discord.
on_socket_raw_receive
(msg)¶ メッセージが処理される前、WebSocketからメッセージが受信されるたびに呼び出されます。このイベントはメッセージを受信した場合、渡されたデータが処理できないときでも常に呼びだされます。
これはWebSocketストリームを取得してデバッグする時のみに役に立ちます。
注釈
これは、クライアントWebSocketから受信したメッセージ専用です。音声WebSocketではこのイベントは実行されません。
-
discord.
on_socket_raw_send
(payload)¶ メッセージが送信される前にWebSocketで送信操作が行われるたびに呼び出されます。渡されるパラメータはWebSocketに送信されているメッセージです。
これはWebSocketストリームを取得してデバッグする時のみに役に立ちます。
注釈
This is only for the messages sent from the client WebSocket. The voice WebSocket will not trigger this event.
-
discord.
on_typing
(channel, user, when)¶ 誰かがメッセージを入力し始めたときに呼び出されます。
channelパラメータは
abc.Messageable
インスタンスにすることができます。TextChannel
、GroupChannel
、またはDMChannel
のいずれかです。channel
がTextChannel
である場合、user
パラメータはMember
、それ以外の場合はUser
です。This requires
Intents.typing
to be enabled.- パラメータ
channel (
abc.Messageable
) -- 入力が行われたチャンネル。when (
datetime.datetime
) -- When the typing started as an aware datetime in UTC.
-
discord.
on_message
(message)¶ Message
が作成され送信されたときに呼び出されます。This requires
Intents.messages
to be enabled.警告
Botのメッセージとプライベートメッセージはこのイベントを通して送信されます。Botのプログラムによっては「再帰呼び出し」を続けることになります。Botが自分自身に返信しないようにするためにはユーザーIDを確認する方法が考えられます。この問題はBotが抱えるものではありません。
- パラメータ
message (
Message
) -- 現在のメッセージ。
-
discord.
on_message_delete
(message)¶ メッセージが削除された際に呼び出されます。メッセージが内部のメッセージキャッシュに見つからない場合、このイベントは呼び出されません。これはメッセージが古すぎるか、クライアントが通信の多いギルドに参加している場合に発生します。
If this occurs increase the
Client.max_messages
attribute or use theon_raw_message_delete()
event instead.This requires
Intents.messages
to be enabled.- パラメータ
message (
Message
) -- 削除されたメッセージ。
-
discord.
on_bulk_message_delete
(messages)¶ メッセージが一括削除されたときに呼び出されます。メッセージが内部のメッセージキャッシュに見つからない場合、このイベントは呼び出されません。個々のメッセージが見つからない場合でも、このイベントは呼び出されますが、見つからなかったメッセージはメッセージのリストに含まれません。これはメッセージが古すぎるか、クライアントが通信の多いギルドに参加している場合に発生します。
If this occurs increase the
Client.max_messages
attribute or use theon_raw_bulk_message_delete()
event instead.This requires
Intents.messages
to be enabled.- パラメータ
messages (List[
Message
]) -- 削除されたメッセージのリスト。
-
discord.
on_raw_message_delete
(payload)¶ メッセージが削除されたときに呼び出されます。
on_message_delete()
とは異なり、削除されたメッセージが内部キャッシュに存在するか否かにかかわらず呼び出されます。メッセージがメッセージキャッシュ内に見つかった場合、
RawMessageDeleteEvent.cached_message
を介してアクセスすることができます。This requires
Intents.messages
to be enabled.- パラメータ
payload (
RawMessageDeleteEvent
) -- 生のイベントペイロードデータ。
-
discord.
on_raw_bulk_message_delete
(payload)¶ メッセージが一括削除されたときに呼び出されます。
on_bulk_message_delete()
とは異なり、削除されたメッセージが内部キャッシュに存在するか否かにかかわらず呼び出されます。メッセージがメッセージキャッシュ内に見つかった場合、
RawBulkMessageDeleteEvent.cached_messages
を介してアクセスすることができます。This requires
Intents.messages
to be enabled.- パラメータ
payload (
RawBulkMessageDeleteEvent
) -- 生のイベントペイロードデータ。
-
discord.
on_message_edit
(before, after)¶ Message
が更新イベントを受け取ったときに呼び出されます。メッセージが内部のメッセージキャッシュに見つからない場合、このイベントは呼び出されません。これはメッセージが古すぎるか、クライアントが通信の多いギルドに参加している場合に発生します。If this occurs increase the
Client.max_messages
attribute or use theon_raw_message_edit()
event instead.以下の非網羅的ケースがこのイベントを発生させます:
メッセージをピン留め、または解除した。
メッセージの内容を変更した。
メッセージが埋め込みを受け取った。
パフォーマンス上の理由から、埋め込みのサーバーはこれを「一貫した」方法では行いません。
The message's embeds were suppressed or unsuppressed.
通話呼び出しメッセージの参加者や終了時刻が変わった。
This requires
Intents.messages
to be enabled.
-
discord.
on_raw_message_edit
(payload)¶ メッセージが編集されたときに呼び出されます。
on_message_edit()
とは異なり、これは内部のメッセージキャッシュの状態に関係なく呼び出されます。If the message is found in the message cache, it can be accessed via
RawMessageUpdateEvent.cached_message
. The cached message represents the message before it has been edited. For example, if the content of a message is modified and triggers theon_raw_message_edit()
coroutine, theRawMessageUpdateEvent.cached_message
will return aMessage
object that represents the message before the content was modified.Due to the inherently raw nature of this event, the data parameter coincides with the raw data given by the gateway.
データのペイロードが部分的であるため、データにアクセスするときは気をつけてください。部分的なデータの主な場合のひとつは、``'content'``にアクセスできない場合です。Discordの埋め込みサーバーによって、埋め込みが更新される、"埋め込み"しか変わっていない編集がそうです。
This requires
Intents.messages
to be enabled.- パラメータ
payload (
RawMessageUpdateEvent
) -- 生のイベントペイロードデータ。
-
discord.
on_reaction_add
(reaction, user)¶ Called when a message has a reaction added to it. Similar to
on_message_edit()
, if the message is not found in the internal message cache, then this event will not be called. Consider usingon_raw_reaction_add()
instead.This requires
Intents.reactions
to be enabled.注釈
This doesn't require
Intents.members
within a guild context, but due to Discord not providing updated user information in a direct message it's required for direct messages to receive this event. Consider usingon_raw_reaction_add()
if you need this and do not otherwise want to enable the members intent.
-
discord.
on_raw_reaction_add
(payload)¶ メッセージにリアクションが追加されたときに呼び出されます。
on_reaction_add()
とは異なり、これは内部のメッセージキャッシュの状態に関係なく呼び出されます。This requires
Intents.reactions
to be enabled.- パラメータ
payload (
RawReactionActionEvent
) -- 生のイベントペイロードデータ。
-
discord.
on_reaction_remove
(reaction, user)¶ メッセージのリアクションが取り除かれたときに呼び出されます。on_message_editのように、内部のメッセージキャッシュにメッセージがないときには、このイベントは呼び出されません。
注釈
リアクションの付いたメッセージを取得するには、:attr:`Reaction.message`を使ってください。
This requires both
Intents.reactions
andIntents.members
to be enabled.注釈
Consider using
on_raw_reaction_remove()
if you need this and do not want to enable the members intent.
-
discord.
on_raw_reaction_remove
(payload)¶ メッセージからリアクションが削除されたときに呼び出されます。
on_reaction_remove()
とは異なり、これは内部メッセージキャッシュの状態に関係なく呼び出されます。This requires
Intents.reactions
to be enabled.- パラメータ
payload (
RawReactionActionEvent
) -- 生のイベントペイロードデータ。
-
discord.
on_reaction_clear
(message, reactions)¶ Called when a message has all its reactions removed from it. Similar to
on_message_edit()
, if the message is not found in the internal message cache, then this event will not be called. Consider usingon_raw_reaction_clear()
instead.This requires
Intents.reactions
to be enabled.
-
discord.
on_raw_reaction_clear
(payload)¶ メッセージからリアクションがすべて削除されたときに呼び出されます。
on_reaction_clear()
とは異なり、これは内部メッセージキャッシュの状態に関係なく呼び出されます。This requires
Intents.reactions
to be enabled.- パラメータ
payload (
RawReactionClearEvent
) -- 生のイベントペイロードデータ。
-
discord.
on_reaction_clear_emoji
(reaction)¶ Called when a message has a specific reaction removed from it. Similar to
on_message_edit()
, if the message is not found in the internal message cache, then this event will not be called. Consider usingon_raw_reaction_clear_emoji()
instead.This requires
Intents.reactions
to be enabled.バージョン 1.3 で追加.
- パラメータ
reaction (
Reaction
) -- The reaction that got cleared.
-
discord.
on_raw_reaction_clear_emoji
(payload)¶ Called when a message has a specific reaction removed from it. Unlike
on_reaction_clear_emoji()
this is called regardless of the state of the internal message cache.This requires
Intents.reactions
to be enabled.バージョン 1.3 で追加.
- パラメータ
payload (
RawReactionClearEmojiEvent
) -- 生のイベントペイロードデータ。
-
discord.
on_interaction
(interaction)¶ Called when an interaction happened.
This currently happens due to slash command invocations.
バージョン 2.0 で追加.
- パラメータ
interaction (
Interaction
) -- The interaction data.
-
discord.
on_private_channel_update
(before, after)¶ プライベートグループDMが更新されたとき呼び出されます。 例: 名前やトピックの変更。
This requires
Intents.messages
to be enabled.- パラメータ
before (
GroupChannel
) -- 更新されたグループチャンネルの更新前情報。after (
GroupChannel
) -- 更新されたグループチャンネルの更新後情報。
-
discord.
on_private_channel_pins_update
(channel, last_pin)¶ プライベートチャンネルのメッセージがピン留めされたりはずされたりしたときに呼ばれます。
- パラメータ
channel (
abc.PrivateChannel
) -- ピン留めが更新されたプライベートチャンネル。last_pin (Optional[
datetime.datetime
]) -- The latest message that was pinned as an aware datetime in UTC. Could beNone
.
-
discord.
on_guild_channel_delete
(channel)¶ -
discord.
on_guild_channel_create
(channel)¶ ギルドのチャンネルが削除・作成されたとき呼び出されます。
ギルドは
guild
で取得できます。This requires
Intents.guilds
to be enabled.- パラメータ
channel (
abc.GuildChannel
) -- 作成、または削除されたギルドチャンネル。
-
discord.
on_guild_channel_update
(before, after)¶ ギルドチャンネルが更新されるたびに呼び出されます。例えば名前、トピック、権限の変更などです。
This requires
Intents.guilds
to be enabled.- パラメータ
before (
abc.GuildChannel
) -- 更新されたギルドの更新前情報。after (
abc.GuildChannel
) -- 更新されたギルドの更新後情報。
-
discord.
on_guild_channel_pins_update
(channel, last_pin)¶ ギルドチャンネルのメッセージがピン留めされたり、解除されたりしたときに呼び出されます。
This requires
Intents.guilds
to be enabled.- パラメータ
channel (
abc.GuildChannel
) -- ピン留めが更新されたギルドチャンネル。last_pin (Optional[
datetime.datetime
]) -- The latest message that was pinned as an aware datetime in UTC. Could beNone
.
-
discord.
on_guild_integrations_update
(guild)¶ バージョン 1.4 で追加.
ギルドの連携サービスが作成、更新、削除されるたびに呼び出されます。
This requires
Intents.integrations
to be enabled.- パラメータ
guild (
Guild
) -- 連携サービスが更新されたギルド。
-
discord.
on_webhooks_update
(channel)¶ ギルドチャンネルのWebhookが作成、更新、削除されたときに呼び出されます。
This requires
Intents.webhooks
to be enabled.- パラメータ
channel (
abc.GuildChannel
) -- Webhookが更新されたチャンネル。
-
discord.
on_member_join
(member)¶ -
discord.
on_member_remove
(member)¶ Member
がGuild
に参加したり退出したりしたときに呼び出されます。This requires
Intents.members
to be enabled.- パラメータ
member (
Member
) -- 参加、または脱退したメンバー。
-
discord.
on_member_update
(before, after)¶ Member
がプロフィールを編集したとき呼び出されます。これらのうちひとつ以上が変更されたとき呼び出されます:
ステータス
activity
ニックネーム
roles
pending
This requires
Intents.members
to be enabled.
-
discord.
on_user_update
(before, after)¶ User
がプロフィールを編集したとき呼び出されます。これらのうちひとつ以上が変更されたとき呼び出されます:
アバター
ユーザー名
識別子
This requires
Intents.members
to be enabled.
-
discord.
on_guild_join
(guild)¶ Client
によってGuild
が作成された。またはClient
がギルドに参加したときに呼び出されます。This requires
Intents.guilds
to be enabled.- パラメータ
guild (
Guild
) -- 参加したギルド。
-
discord.
on_guild_remove
(guild)¶ Client
がGuild
から削除されたときに呼び出されます。これは以下の状況時に呼び出されますが、これに限ったものではありません:
クライアントがBANされた。
クライアントがキックされた。
クライアントがギルドから退出した。
クライアント、またはギルドオーナーがギルドを削除した。
このイベントが呼び出されるためには、
Client
がギルドに参加している必要があります。(つまり、Client.guilds
にギルドが存在しなければならない)This requires
Intents.guilds
to be enabled.- パラメータ
guild (
Guild
) -- 削除されたギルド。
-
discord.
on_guild_update
(before, after)¶ Guild
が更新されたときに呼び出されます。例えば:名前が変更された
AFKチャンネルが変更された
AFKのタイムアウト時間が変更された
その他
This requires
Intents.guilds
to be enabled.
-
discord.
on_guild_role_create
(role)¶ -
discord.
on_guild_role_delete
(role)¶ Guild
でRole
が新しく作成されたか、削除されたときに呼び出されます。ギルドを取得するには
Role.guild
を使用してください。This requires
Intents.guilds
to be enabled.- パラメータ
role (
Role
) -- 作成、または削除された役職。
-
discord.
on_guild_role_update
(before, after)¶ Role
がギルド全体で変更されたときに呼び出されます。This requires
Intents.guilds
to be enabled.
-
discord.
on_guild_emojis_update
(guild, before, after)¶ Guild
にEmoji
が追加、または削除されたときに呼び出されます。This requires
Intents.emojis
to be enabled.
-
discord.
on_guild_available
(guild)¶ ギルドが利用可能・不可能になったときに呼び出されます。ギルドは
Client.guilds
キャッシュに存在していないといけません。This requires
Intents.guilds
to be enabled.- パラメータ
guild -- 利用状況が変わった:class:Guild。
-
discord.
on_voice_state_update
(member, before, after)¶ Member
がVoiceState
を変更したとき呼び出されます。これらの場合に限りませんが、例を挙げると、以下の場合に呼び出されます:
メンバーがボイスチャンネルに参加したとき。
メンバーがボイスチャンネルから退出したとき。
メンバーが自身でマイクやスピーカーをミュートしたとき。
メンバーがギルドの管理者によってマイクやスピーカーをミュートされたとき。
This requires
Intents.voice_states
to be enabled.- パラメータ
member (
Member
) -- ボイスの状態が変わった Member 。before (
VoiceState
) -- 更新前のボイス状態。after (
VoiceState
) -- 更新後のボイス状態。
-
discord.
on_member_ban
(guild, user)¶ ユーザーが
Guild
からBANされたとき呼び出されます。This requires
Intents.bans
to be enabled.
-
discord.
on_member_unban
(guild, user)¶ User
がGuild
のBANを解除されたとき呼び出されます。This requires
Intents.bans
to be enabled.
-
discord.
on_invite_create
(invite)¶ Called when an
Invite
is created. You must have themanage_channels
permission to receive this.バージョン 1.3 で追加.
注釈
There is a rare possibility that the
Invite.guild
andInvite.channel
attributes will be ofObject
rather than the respective models.This requires
Intents.invites
to be enabled.- パラメータ
invite (
Invite
) -- The invite that was created.
-
discord.
on_invite_delete
(invite)¶ Called when an
Invite
is deleted. You must have themanage_channels
permission to receive this.バージョン 1.3 で追加.
注釈
There is a rare possibility that the
Invite.guild
andInvite.channel
attributes will be ofObject
rather than the respective models.Outside of those two attributes, the only other attribute guaranteed to be filled by the Discord gateway for this event is
Invite.code
.This requires
Intents.invites
to be enabled.- パラメータ
invite (
Invite
) -- The invite that was deleted.
-
discord.
on_group_join
(channel, user)¶ -
discord.
on_group_remove
(channel, user)¶ 誰かが
GroupChannel
に参加、または脱退したときに呼び出されます。- パラメータ
channel (
GroupChannel
) -- ユーザーが参加または脱退したグループ。user (
User
) -- 参加または脱退したユーザー。
ユーティリティ関数¶
-
discord.utils.
find
(predicate, seq)¶ 与えられた関数を満たす最初の要素を返すヘルパー。例:
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
は、名前が'Mighty'である最初に見つかった
Member
を返します。見つからない場合はNone
を返します。これは、適切な値を見つけると止まる点で、
filter()
と異なります。- パラメータ
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)¶ - パラメータ
id (
int
) -- The snowflake ID.- 戻り値
An aware datetime in UTC representing the creation time of the snowflake.
- 戻り値の型
-
discord.utils.
oauth_url
(client_id, permissions=None, guild=None, redirect_uri=None, scopes=None)¶ ボットをギルドに招待するOAuth2 URLを返すヘルパー関数。
- パラメータ
client_id (
str
) -- ボットのクライアントID。permissions (
Permissions
) -- 要求する権限。もし与えられていない場合、権限を要求しません。guild (
Guild
) -- 利用できる場合は、認証画面であらかじめ選択されるギルド。redirect_uri (
str
) -- 任意の有効なリダイレクトURI。scopes (Iterable[
str
]) --An optional valid list of scopes. Defaults to
('bot',)
.バージョン 1.7 で追加.
- 戻り値
The OAuth2 URL for inviting the bot into guilds.
- 戻り値の型
-
discord.utils.
remove_markdown
(text, *, ignore_links=True)¶ A helper function that removes markdown characters.
バージョン 1.7 で追加.
注釈
This function is not markdown aware and may remove meaning from the original text. For example, if the input contains
10 * 5
then it will be converted into10 5
.- パラメータ
- 戻り値
The text with the markdown special characters removed.
- 戻り値の型
-
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
です。
- 戻り値
マークダウンの特殊文字をスラッシュでエスケープしたテキスト。
- 戻り値の型
-
discord.utils.
escape_mentions
(text)¶ everyone、here、役職とユーザーのメンションをエスケープするヘルパー関数。
注釈
チャンネルのメンションはエスケープしません。
注釈
For more granular control over what mentions should be escaped within messages, refer to the
AllowedMentions
class.
-
discord.utils.
resolve_template
(code)¶ Resolves a template code from a
Template
, URL or code.バージョン 1.4 で追加.
-
await
discord.utils.
sleep_until
(when, result=None)¶ This function is a coroutine.
Sleep until a specified time.
If the time supplied is in the past this function will yield instantly.
バージョン 1.3 で追加.
- パラメータ
when (
datetime.datetime
) -- The timestamp in which to sleep until. If the datetime is naive then it is assumed to be local time.result (Any) -- If provided is returned to the caller when the coroutine completes.
-
discord.utils.
utcnow
()¶ A helper function to return an aware UTC datetime representing the current time.
This should be preferred to
datetime.datetime.utcnow()
since it is an aware datetime, compared to the naive datetime in the standard library.バージョン 2.0 で追加.
- 戻り値
The current aware datetime in UTC.
- 戻り値の型
列挙型¶
APIは、文字列が将来変わることに備え、文字列を直書きするのを防ぐために、いくらかの文字列の列挙型を提供します。
列挙型はすべて enum.Enum
の動作を模倣した内部クラスのサブクラスです。
-
class
discord.
ChannelType
¶ 特定チャンネルのチャンネルタイプ。
-
text
¶ テキストチャンネル。
-
voice
¶ ボイスチャンネル。
-
private
¶ プライベートのテキストチャンネル。ダイレクトメッセージとも呼ばれています。
-
group
¶ プライベートのグループDM。
-
category
¶ A category channel.
-
news
¶ ギルドのニュースチャンネル。
-
store
¶ ギルドのストアチャンネル。
-
stage_voice
¶ A guild stage voice channel.
バージョン 1.7 で追加.
-
-
class
discord.
MessageType
¶ Message
のタイプを指定します。これは、メッセージが通常のものかシステムメッセージかを判断するのに使用できます。-
x == y
Checks if two messages are equal.
-
x != y
Checks if two messages are not equal.
-
default
¶ デフォルトのメッセージ。これは通常のメッセージと同じです。
-
recipient_add
¶ グループのプライベートメッセージ、つまり、
ChannelType.group
のプライベートチャンネルの参加者が増えたときのシステムメッセージ。
-
recipient_remove
¶ グループのプライベートメッセージ、つまり、
ChannelType.group
のプライベートチャンネルの参加者が減ったときのシステムメッセージ。
-
call
¶ 通話の状態を示すシステムメッセージ。例: 不在着信、通話の開始、その他。
-
channel_name_change
¶ チャンネル名の変更を示すシステムメッセージ。
-
channel_icon_change
¶ チャンネルのアイコンの変更を示すシステムメッセージ。
-
pins_add
¶ ピン留めの追加を示すシステムメッセージ。
-
new_member
¶ ギルドの新規メンバーの参加を示すシステムメッセージ。
メンバーがギルドを「ニトロブースト」したことを表すシステムメッセージ。
メンバーがギルドを「ニトロブースト」し、それによってギルドがレベル1に到達したことを表すシステムメッセージ。
メンバーがギルドを「ニトロブースト」し、それによってギルドがレベル2に到達したことを表すシステムメッセージ。
メンバーがギルドを「ニトロブースト」し、それによってギルドがレベル3に到達したことを表すシステムメッセージ。
-
channel_follow_add
¶ The system message denoting that an announcement channel has been followed.
バージョン 1.3 で追加.
-
guild_stream
¶ The system message denoting that a member is streaming in the guild.
バージョン 1.7 で追加.
-
guild_discovery_disqualified
¶ The system message denoting that the guild is no longer eligible for Server Discovery.
バージョン 1.7 で追加.
-
guild_discovery_requalified
¶ The system message denoting that the guild has become eligible again for Server Discovery.
バージョン 1.7 で追加.
-
guild_discovery_grace_period_initial_warning
¶ The system message denoting that the guild has failed to meet the Server Discovery requirements for one week.
バージョン 1.7 で追加.
-
guild_discovery_grace_period_final_warning
¶ The system message denoting that the guild has failed to meet the Server Discovery requirements for 3 weeks in a row.
バージョン 1.7 で追加.
-
reply
¶ The message type denoting that the author is replying to a message.
バージョン 2.0 で追加.
-
application_command
¶ The system message denoting that an application (or "slash") command was executed.
バージョン 2.0 で追加.
-
-
class
discord.
ActivityType
¶ Activity
のタイプを指定します。これはアクティビティをどう解釈するか確認するために使われます。-
unknown
¶ 不明なアクティビティタイプ。これは通常起こらないはずです。
-
playing
¶ プレイ中のアクティビティタイプ。
-
streaming
¶ 放送中のアクティビティタイプ。
-
listening
¶ 再生中のアクティビティタイプ。
-
watching
¶ 視聴中のアクティビティタイプ。
-
custom
¶ A custom activity type.
-
competing
¶ A competing activity type.
バージョン 1.5 で追加.
-
-
class
discord.
InteractionType
¶ Specifies the type of
Interaction
.バージョン 2.0 で追加.
-
ping
¶ Represents Discord pinging to see if the interaction response server is alive.
-
application_command
¶ Represents a slash command interaction.
-
-
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
¶ 南アフリカリージョン。
-
south_korea
¶ The South Korea region.
-
sydney
¶ シドニーリージョン。
-
us_central
¶ 中央アメリカのリージョン。
-
us_east
¶ アメリカ西部のリージョン。
-
us_south
¶ アメリカ南部のリージョン。
-
us_west
¶ アメリカ東部のリージョン。
-
vip_amsterdam
¶ VIPギルド用のアムステルダムリージョン。
-
vip_us_east
¶ VIPギルド用のアメリカ東部リージョン。
-
vip_us_west
¶ VIPギルド用のアメリカ西部リージョン。
-
-
class
discord.
VerificationLevel
¶ Guild
の認証レベルを指定します。これは、メンバーがギルドにメッセージを送信できるようになるまでの条件です。-
x == y
認証レベルが等しいか確認します。
-
x != y
認証レベルが等しくないか確認します。
-
x > y
認証レベルがあるレベルより厳しいか確認します。
-
x < y
認証レベルがあるレベルより緩いか確認します。
-
x >= y
認証レベルがあるレベルと同じ、又は厳しいか確認します。
-
x <= y
認証レベルがあるレベルと同じ、又は緩いか確認します。
-
none
¶ 無制限。
-
low
¶ メンバーはDiscordアカウントのメール認証を済ませないといけません。
-
medium
¶ メンバーはメール認証をし、かつアカウント登録から5分経過しないといけません。
-
high
¶ メンバーはメール認証をし、Discordのアカウント登録から5分経過し、かつ10分以上ギルドに所属していないといけません。
-
extreme
¶ メンバーはDiscordアカウントの電話番号認証を済ませないといけません。
-
-
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
¶ メンバーが取り込み中。
-
invisible
¶ メンバーがオンライン状態を隠す。実際には、これは
Client.change_presence()
でプレゼンスを送信する時のみ使用します。ユーザーのプレゼンスを受け取った場合、これはoffline
に置き換えられます。
-
-
class
discord.
AuditLogAction
¶ AuditLogEntry
で行われた動作の種類を取得します。AuditLogEntryはGuild.audit_logs()
で取得可能です。-
guild_update
¶ ギルドが更新された。このトリガーとなるものは以下のとおりです。
ギルドのvanity URLの変更
ギルドの招待時のスプラッシュ画像の変更
ギルドのAFKチャンネル、またはタイムアウトの変更
ギルドの音声通話のサーバーリージョンの変更
ギルドのアイコンの変更
ギルドの管理設定の変更
ギルドのウィジェットに関連するものの変更
これが上記のactionならば、
target
のtypeは :class:`Guild`になります。AuditLogDiff
から、以下の属性を参照できます:
-
channel_create
¶ チャンネルが作成されました。
これが上記のactionならば、
target
のtypeは、IDが設定されているabc.GuildChannel
か、Object
のいずれかになります。Object
の場合、after
を使用して、より詳細な情報を持つオブジェクトを見つけることができます。AuditLogDiff
から、以下の属性を参照できます:
-
channel_update
¶ チャンネルが更新されました。これのトリガーとなるものは以下の通りです。
チャンネルのチャンネルトピックの変更、または名前の変更。
チャンネルのビットレートの変更。
これが上記のactionならば、
target
のtypeは、IDが設定されているabc.GuildChannel
か、Object
のいずれかになります。Object
の場合、after
またはbefore
を使用して、より詳細な情報を持つオブジェクトを見つけることができます。AuditLogDiff
から、以下の属性を参照できます:
-
channel_delete
¶ チャンネルの削除。
これが上記のactionならば、
target
のtypeは、IDが設定されているObject
になります。A more filled out object can be found by using the
before
object.AuditLogDiff
から、以下の属性を参照できます:
-
overwrite_create
¶ チャンネルにおける権限の上書き設定の作成。
これが上記のactionならば、
target
のtypeは、IDが設定されているabc.GuildChannel
か、Object
のいずれかになります。この場合には、
extra
はRole
かMember
です。もしオブジェクトが見つからない場合はid、name、'role'
か'member'
である``type`` 属性があるObject
です。AuditLogDiff
から、以下の属性を参照できます:
-
overwrite_update
¶ チャンネルの権限の上書きが変更されました。典型的な例は、権限が変更された場合です。
overwrite_create
に、target
とextra
についての説明があります。AuditLogDiff
から、以下の属性を参照できます:
-
overwrite_delete
¶ チャンネルにおける権限の上書き設定の削除。
overwrite_create
に、target
とextra
についての説明があります。AuditLogDiff
から、以下の属性を参照できます:
-
kick
¶ メンバーのキック。
これが上記のactionならば、
target
のtypeはキックされたユーザーに該当するUser
になります。これが上記のactionなら、
changes
は空になります。
-
member_prune
¶ 非アクティブメンバーの一括キック。
これが上記のactionならば、
target
のtypeはNone
に設定されます。When this is the action, the type of
extra
is set to an unspecified proxy object with two attributes:delete_members_days
: An integer specifying how far the prune was.members_removed
: An integer specifying how many members were removed.
これが上記のactionなら、
changes
は空になります。
-
ban
¶ メンバーのBAN。
これが上記のactionならば、
target
のtypeはBANされたユーザーに該当するUser
になります。これが上記のactionなら、
changes
は空になります。
-
unban
¶ メンバーのBANの解除。
これが上記のactionならば、
target
のtypeはBANが解除されたユーザーに該当するUser
になります。これが上記のactionなら、
changes
は空になります。
-
member_update
¶ メンバーの何らかの更新。これのトリガーとなるのは以下の場合です:
メンバーのニックネームの変更。
They were server muted or deafened (or it was undo'd)
これが上記のactionならば、
target
のtypeは、更新の行われたMember
あるいはUser
になります。AuditLogDiff
から、以下の属性を参照できます:
-
member_role_update
¶ A member's role has been updated. This triggers when a member either gains a role or losses a role.
これが上記のactionならば、
target
のtypeは、役職の更新が行われたMember
あるいはUser
になります。AuditLogDiff
から、以下の属性を参照できます:
-
member_move
¶ A member's voice channel has been updated. This triggers when a member is moved to a different voice channel.
When this is the action, the type of
extra
is set to an unspecified proxy object with two attributes:channel
: ATextChannel
orObject
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 theMember
orUser
which was added to the guild.バージョン 1.3 で追加.
-
role_create
¶ 新しい役職の作成。
これが上記のactionならば、
target
のtypeは、IDが設定されているRole
か、Object
のいずれかになります。AuditLogDiff
から、以下の属性を参照できます:
-
role_update
¶ 役職の何らかの更新。これのトリガーとなるのは以下の場合です:
名前の更新。
The permissions have changed
The colour has changed
Its hoist/mentionable state has changed
これが上記のactionならば、
target
のtypeは、IDが設定されているRole
か、Object
のいずれかになります。AuditLogDiff
から、以下の属性を参照できます:
-
role_delete
¶ 役職の削除。
これが上記のactionならば、
target
のtypeは、IDが設定されているRole
か、Object
のいずれかになります。AuditLogDiff
から、以下の属性を参照できます:
-
invite_create
¶ 招待の作成。
これが上記のactionならば、
target
のtypeは作成された招待に該当するInvite
になります。AuditLogDiff
から、以下の属性を参照できます:
-
invite_delete
¶ An invite was deleted.
When this is the action, the type of
target
is theInvite
that was deleted.AuditLogDiff
から、以下の属性を参照できます:
-
webhook_create
¶ A webhook was created.
When this is the action, the type of
target
is theObject
with the webhook ID.AuditLogDiff
から、以下の属性を参照できます:
-
webhook_update
¶ A webhook was updated. This trigger in the following situations:
The webhook name changed
The webhook channel changed
When this is the action, the type of
target
is theObject
with the webhook ID.AuditLogDiff
から、以下の属性を参照できます:
-
webhook_delete
¶ A webhook was deleted.
When this is the action, the type of
target
is theObject
with the webhook ID.AuditLogDiff
から、以下の属性を参照できます:
-
emoji_create
¶ An emoji was created.
When this is the action, the type of
target
is theEmoji
orObject
with the emoji ID.AuditLogDiff
から、以下の属性を参照できます:
-
emoji_update
¶ An emoji was updated. This triggers when the name has changed.
When this is the action, the type of
target
is theEmoji
orObject
with the emoji ID.AuditLogDiff
から、以下の属性を参照できます:
-
emoji_delete
¶ An emoji was deleted.
When this is the action, the type of
target
is theObject
with the emoji ID.AuditLogDiff
から、以下の属性を参照できます:
-
message_delete
¶ A message was deleted by a moderator. Note that this only triggers if the message was deleted by someone other than the author.
When this is the action, the type of
target
is theMember
orUser
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
: ATextChannel
orObject
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 theTextChannel
orObject
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 theMember
orUser
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
: ATextChannel
orObject
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 theMember
orUser
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
: ATextChannel
orObject
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 theObject
with the integration ID of the integration which was created.バージョン 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.
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.
-
-
class
discord.
ExpireBehaviour
¶ Represents the behaviour the
Integration
should perform when a user's subscription has finished.There is an alias for this called
ExpireBehavior
.バージョン 1.4 で追加.
-
remove_role
¶ This will remove the
Integration.role
from the user when their subscription is finished.
-
kick
¶ This will kick the user when their subscription is finished.
-
-
class
discord.
DefaultAvatar
¶ Represents the default avatar of a Discord
User
-
blurple
¶ Represents the default avatar with the color blurple. See also
Colour.blurple
-
grey
¶ Represents the default avatar with the color grey. See also
Colour.greyple
-
green
¶ Represents the default avatar with the color green. See also
Colour.green
-
orange
¶ Represents the default avatar with the color orange. See also
Colour.orange
-
red
¶ Represents the default avatar with the color red. See also
Colour.red
-
非同期イテレータ¶
一部の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 orNone
.
-
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.
- 戻り値の型
-
chunk
(max_size)¶ Collects items into chunks of up to a given maximum size. Another
AsyncIterator
is returned which collects items intolist
s of a given size. The maximum chunk size must be a positive integer.バージョン 1.6 で追加.
Collecting groups of users:
async for leader, *users in reaction.users().chunk(3): ...
警告
The last chunk collected may not be as large as
max_size
.- パラメータ
max_size -- The size of individual chunks.
- 戻り値の型
-
map
(func)¶ This is similar to the built-in
map
function. AnotherAsyncIterator
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.
- 戻り値の型
-
filter
(predicate)¶ This is similar to the built-in
filter
function. AnotherAsyncIterator
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.
- 戻り値の型
-
監査ログデータ¶
Working with Guild.audit_logs()
is a complicated process with a lot of machinery
involved. The library attempts to make it easy to use and friendly. In order to accomplish
this goal, it must make use of a couple of data classes that aid in this goal.
AuditLogEntry¶
-
class
discord.
AuditLogEntry
(*, users, data, guild)¶ Represents an Audit Log entry.
You retrieve these via
Guild.audit_logs()
.-
x == y
Checks if two entries are equal.
-
x != y
Checks if two entries are not equal.
-
hash(x)
Returns the entry's hash.
バージョン 1.7 で変更: Audit log entries are now comparable and hashable.
-
action
¶ The action that was done.
- Type
-
target
¶ The target that got changed. The exact type of this depends on the action being done.
- Type
Any
-
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. SeeAuditLogAction
for which actions have this field filled out.- Type
Any
-
created_at
¶ Returns the entry's creation time in UTC.
- Type
-
category
¶ The category of the action, if applicable.
- Type
Optional[
AuditLogActionCategory
]
-
changes
¶ The list of changes this entry has.
- Type
-
before
¶ The target's prior state.
- Type
-
after
¶ The target's subsequent state.
- Type
-
AuditLogChanges¶
-
class
discord.
AuditLogChanges
¶ An audit log change set.
-
before
¶ The old value. The attribute has the type of
AuditLogDiff
.Depending on the
AuditLogActionCategory
retrieved bycategory
, the data retrieved by this attribute differs:
-
after
¶ The new value. The attribute has the type of
AuditLogDiff
.Depending on the
AuditLogActionCategory
retrieved bycategory
, the data retrieved by this attribute differs:
-
AuditLogDiff¶
- afk_channel
- afk_timeout
- allow
- avatar
- bitrate
- channel
- code
- color
- colour
- deaf
- default_message_notifications
- default_notifications
- deny
- explicit_content_filter
- hoist
- icon
- id
- inviter
- max_age
- max_uses
- mentionable
- mfa_level
- mute
- name
- nick
- overwrites
- owner
- permissions
- position
- region
- roles
- rtc_region
- slowmode_delay
- splash
- system_channel
- temporary
- topic
- type
- uses
- vanity_url_code
- verification_level
- video_quality_mode
- widget_channel
- widget_enabled
-
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.
-
icon
¶ A guild's icon hash. See also
Guild.icon
.- Type
-
splash
¶ The guild's invite splash hash. See also
Guild.splash
.- Type
-
owner
¶ The guild's owner. See also
Guild.owner
-
region
¶ The guild's voice region. See also
Guild.region
.- Type
-
afk_channel
¶ The guild's AFK channel.
If this could not be found, then it falls back to a
Object
with the ID being set.See
Guild.afk_channel
.- Type
Union[
VoiceChannel
,Object
]
-
system_channel
¶ The guild's system channel.
If this could not be found, then it falls back to a
Object
with the ID being set.See
Guild.system_channel
.- Type
Union[
TextChannel
,Object
]
-
afk_timeout
¶ The guild's AFK timeout. See
Guild.afk_timeout
.- Type
-
mfa_level
¶ The guild's MFA level. See
Guild.mfa_level
.- Type
-
widget_channel
¶ The widget's channel.
If this could not be found then it falls back to a
Object
with the ID being set.- Type
Union[
TextChannel
,Object
]
-
verification_level
¶ The guild's verification level.
See also
Guild.verification_level
.- Type
-
default_notifications
¶ The guild's default notification level.
See also
Guild.default_notifications
.- Type
-
explicit_content_filter
¶ The guild's content filter.
See also
Guild.explicit_content_filter
.- Type
-
vanity_url_code
¶ The guild's vanity URL.
See also
Guild.vanity_invite()
andGuild.edit()
.- Type
-
position
¶ The position of a
Role
orabc.GuildChannel
.- Type
-
type
¶ The type of channel or channel permission overwrite.
If the type is an
int
, then it is a type of channel which can be either0
to indicate a text channel or1
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
¶ The topic of a
TextChannel
.See also
TextChannel.topic
.- Type
-
bitrate
¶ The bitrate of a
VoiceChannel
.See also
VoiceChannel.bitrate
.- Type
-
overwrites
¶ A list of permission overwrite tuples that represents a target and a
PermissionOverwrite
for said target.The first element is the object being targeted, which can either be a
Member
orUser
orRole
. If this object is not found then it is aObject
with an ID being filled and atype
attribute set to either'role'
or'member'
to help decide what type of ID it is.- Type
List[Tuple[target,
PermissionOverwrite
]]
-
roles
¶ A list of roles being added or removed from a member.
If a role is not found then it is a
Object
with the ID and name being filled in.
-
nick
¶ The nickname of a member.
See also
Member.nick
- Type
Optional[
str
]
-
deaf
¶ Whether the member is being server deafened.
See also
VoiceState.deaf
.- Type
-
mute
¶ Whether the member is being server muted.
See also
VoiceState.mute
.- Type
-
permissions
¶ The permissions of a role.
See also
Role.permissions
.- Type
-
colour
¶ -
color
¶ The colour of a role.
See also
Role.colour
- Type
-
hoist
¶ Whether the role is being hoisted or not.
See also
Role.hoist
- Type
-
mentionable
¶ Whether the role is mentionable or not.
See also
Role.mentionable
- Type
-
code
¶ The invite's code.
See also
Invite.code
- Type
-
channel
¶ A guild channel.
If the channel is not found then it is a
Object
with the ID being set. In some cases the channel name is also set.- Type
Union[
abc.GuildChannel
,Object
]
-
inviter
¶ The user who created the invite.
See also
Invite.inviter
.- Type
-
max_uses
¶ The invite's max uses.
See also
Invite.max_uses
.- Type
-
uses
¶ The invite's current uses.
See also
Invite.uses
.- Type
-
max_age
¶ The invite's max age in seconds.
See also
Invite.max_age
.- Type
-
temporary
¶ If the invite is a temporary invite.
See also
Invite.temporary
.- Type
-
avatar
¶ The avatar hash of a member.
See also
User.avatar
.- Type
-
slowmode_delay
¶ The number of seconds members have to wait before sending another message in the channel.
See also
TextChannel.slowmode_delay
.- Type
-
rtc_region
¶ The region for the voice channel’s voice communication. A value of
None
indicates automatic voice region detection.See also
VoiceChannel.rtc_region
.- Type
-
video_quality_mode
¶ The camera video quality for the voice channel's participants.
See also
VoiceChannel.video_quality_mode
.- Type
-
Webhookサポート¶
discord.py offers support for creating, editing, and executing webhooks through the Webhook
class.
Webhook¶
- clsWebhook.from_url
- clsWebhook.partial
- asyncdelete
- asyncdelete_message
- asyncedit
- asyncedit_message
- asyncfetch
- asyncfetch_message
- asyncsend
-
class
discord.
Webhook
¶ Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as
Guild.webhooks()
andTextChannel.webhooks()
. The ones received by the library will automatically be bound using the library's internal HTTP session.The second form involves creating a webhook object manually using the
from_url()
orpartial()
classmethods.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', session=session) await webhook.send('Hello World', username='Foo')
For a synchronous counterpart, see
SyncWebhook
.-
x == y
Checks if two webhooks are equal.
-
x != y
Checks if two webhooks are not equal.
-
hash(x)
Returns the webhooks's hash.
バージョン 1.4 で変更: Webhooks are now comparable and hashable.
-
type
¶ The type of the webhook.
バージョン 1.3 で追加.
- Type
-
token
¶ The authentication token of the webhook. If this is
None
then the webhook cannot be used to make requests.- Type
Optional[
str
]
-
user
¶ The user this webhook was created by. If the webhook was received without authentication then this will be
None
.- Type
Optional[
abc.User
]
-
source_guild
¶ The guild of the channel that this webhook is following. Only given if
type
isWebhookType.channel_follower
.バージョン 2.0 で追加.
- Type
Optional[
PartialWebhookGuild
]
-
source_channel
¶ The channel that this webhook is following. Only given if
type
isWebhookType.channel_follower
.バージョン 2.0 で追加.
- Type
Optional[
PartialWebhookChannel
]
-
classmethod
partial
(id, token, *, session, bot_token=None)¶ Creates a partial
Webhook
.- パラメータ
id (
int
) -- The ID of the webhook.token (
str
) -- The authentication token of the webhook.session (
aiohttp.ClientSession
) -- The session to use to send requests with. Note that the library does not manage the session and will not close it.bot_token (Optional[
str
]) -- The bot authentication token for authenticated requests involving the webhook.
- 戻り値
A partial
Webhook
. A partial webhook is just a webhook object with an ID and a token.- 戻り値の型
-
classmethod
from_url
(url, *, session, bot_token=None)¶ Creates a partial
Webhook
from a webhook URL.- パラメータ
url (
str
) -- The URL of the webhook.session (
aiohttp.ClientSession
) -- The session to use to send requests with. Note that the library does not manage the session and will not close it.bot_token (Optional[
str
]) -- The bot authentication token for authenticated requests involving the webhook.
- 例外
InvalidArgument -- The URL is invalid.
- 戻り値
A partial
Webhook
. A partial webhook is just a webhook object with an ID and a token.- 戻り値の型
-
await
fetch
(*, prefer_auth=True)¶ This function is a coroutine.
Fetches the current webhook.
This could be used to get a full webhook from a partial webhook.
注釈
When fetching with an unauthenticated webhook, i.e.
is_authenticated()
returnsFalse
, then the returned webhook does not contain any user information.- パラメータ
prefer_auth (
bool
) -- Whether to use the bot token over the webhook token if available. Defaults toTrue
.- 例外
HTTPException -- Could not fetch the webhook
NotFound -- Could not find the webhook by this ID
InvalidArgument -- This webhook does not have a token associated with it.
- 戻り値
The fetched webhook.
- 戻り値の型
-
await
delete
(*, reason=None, prefer_auth=True)¶ This function is a coroutine.
Deletes this Webhook.
- パラメータ
- 例外
HTTPException -- Deleting the webhook failed.
NotFound -- This webhook does not exist.
Forbidden -- You do not have permissions to delete this webhook.
InvalidArgument -- This webhook does not have a token associated with it.
-
await
edit
(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)¶ This function is a coroutine.
Edits this Webhook.
- パラメータ
name (Optional[
str
]) -- The webhook's new default name.avatar (Optional[
bytes
]) -- A bytes-like object representing the webhook's new default avatar.channel (Optional[
abc.Snowflake
]) -- The webhook's new channel. This requires an authenticated webhook.reason (Optional[
str
]) --The reason for editing this webhook. Shows up on the audit log.
バージョン 1.4 で追加.
prefer_auth (
bool
) -- Whether to use the bot token over the webhook token if available. Defaults toTrue
.
- 例外
HTTPException -- Editing the webhook failed.
NotFound -- This webhook does not exist.
InvalidArgument -- This webhook does not have a token associated with it or it tried editing a channel without authentication.
-
await
send
(content=..., *, username=..., avatar_url=..., tts=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., wait=False)¶ This function is a coroutine.
Sends a message using the webhook.
The content must be a type that can convert to a string through
str(content)
.To upload a single file, the
file
parameter should be used with a singleFile
object.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type. You cannot mix theembed
parameter with theembeds
parameter, which must be alist
ofEmbed
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 fromNone
to aWebhookMessage
if set toTrue
.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 withfiles
parameter.files (List[
File
]) -- A list of files to send with the content. This cannot be mixed with thefile
parameter.embed (
Embed
) -- The rich embed for the content to send. This cannot be mixed withembeds
parameter.embeds (List[
Embed
]) -- A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembed
parameter.allowed_mentions (
AllowedMentions
) --Controls the mentions being processed in this message.
バージョン 1.4 で追加.
- 例外
HTTPException -- Sending the message failed.
NotFound -- This webhook was not found.
Forbidden -- The authorization token for the webhook is incorrect.
TypeError -- You specified both
embed
andembeds
orfile
andfiles
ValueError -- The length of
embeds
was invalidInvalidArgument -- There was no token associated with this webhook.
- 戻り値
The message that was sent.
- 戻り値の型
Optional[
WebhookMessage
]
-
await
fetch_message
(id)¶ This function is a coroutine.
Retrieves a single
WebhookMessage
owned by this webhook.バージョン 2.0 で追加.
- パラメータ
id (
int
) -- The message ID to look for.- 例外
NotFound -- The specified message was not found.
Forbidden -- You do not have the permissions required to get a message.
HTTPException -- Retrieving the message failed.
InvalidArgument -- There was no token associated with this webhook.
- 戻り値
The message asked for.
- 戻り値の型
-
await
edit_message
(message_id, *, content=..., embeds=..., embed=..., file=..., files=..., allowed_mentions=None)¶ This function is a coroutine.
Edits a message owned by this webhook.
This is a lower level interface to
WebhookMessage.edit()
in case you only have an ID.バージョン 1.6 で追加.
- パラメータ
message_id (
int
) -- The message ID to edit.content (Optional[
str
]) -- The content to edit the message with orNone
to clear it.embeds (List[
Embed
]) -- A list of embeds to edit the message with.embed (Optional[
Embed
]) -- The embed to edit the message with.None
suppresses the embeds. This should not be mixed with theembeds
parameter.file (
File
) -- The file to upload. This cannot be mixed withfiles
parameter.files (List[
File
]) -- A list of files to send with the content. This cannot be mixed with thefile
parameter.allowed_mentions (
AllowedMentions
) -- Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.
- 例外
HTTPException -- Editing the message failed.
Forbidden -- Edited a message that is not yours.
TypeError -- You specified both
embed
andembeds
orfile
andfiles
ValueError -- The length of
embeds
was invalidInvalidArgument -- There was no token associated with this webhook.
-
await
delete_message
(message_id)¶ This function is a coroutine.
Deletes a message owned by this webhook.
This is a lower level interface to
WebhookMessage.delete()
in case you only have an ID.バージョン 1.6 で追加.
- パラメータ
message_id (
int
) -- The message ID to delete.- 例外
HTTPException -- Deleting the message failed.
Forbidden -- Deleted a message that is not yours.
-
WebhookMessage¶
-
class
discord.
WebhookMessage
¶ Represents a message sent from your webhook.
This allows you to edit or delete a message sent by your webhook.
This inherits from
discord.Message
with changes toedit()
anddelete()
to work.バージョン 1.6 で追加.
-
await
edit
(content=..., embeds=..., embed=..., file=..., files=..., allowed_mentions=None)¶ This function is a coroutine.
Edits the message.
バージョン 1.6 で追加.
- パラメータ
content (Optional[
str
]) -- The content to edit the message with orNone
to clear it.embeds (List[
Embed
]) -- A list of embeds to edit the message with.embed (Optional[
Embed
]) -- The embed to edit the message with.None
suppresses the embeds. This should not be mixed with theembeds
parameter.file (
File
) -- The file to upload. This cannot be mixed withfiles
parameter.files (List[
File
]) -- A list of files to send with the content. This cannot be mixed with thefile
parameter.allowed_mentions (
AllowedMentions
) -- Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.
- 例外
HTTPException -- Editing the message failed.
Forbidden -- Edited a message that is not yours.
TypeError -- You specified both
embed
andembeds
orfile
andfiles
ValueError -- The length of
embeds
was invalidInvalidArgument -- There was no token associated with this webhook.
-
await
delete
(*, delay=None)¶ This function is a coroutine.
Deletes the message.
- パラメータ
delay (Optional[
float
]) -- If provided, the number of seconds to wait before deleting the message. The waiting is done in the background and deletion failures are ignored.- 例外
Forbidden -- You do not have proper permissions to delete the message.
NotFound -- The message was deleted already.
HTTPException -- Deleting the message failed.
-
await
SyncWebhook¶
- clsSyncWebhook.from_url
- clsSyncWebhook.partial
- defdelete
- defdelete_message
- defedit
- defedit_message
- deffetch
- deffetch_message
- defsend
-
class
discord.
SyncWebhook
¶ Represents a synchronous Discord webhook.
For an asynchronous counterpart, see
Webhook
.-
x == y
Checks if two webhooks are equal.
-
x != y
Checks if two webhooks are not equal.
-
hash(x)
Returns the webhooks's hash.
バージョン 1.4 で変更: Webhooks are now comparable and hashable.
-
type
¶ The type of the webhook.
バージョン 1.3 で追加.
- Type
-
token
¶ The authentication token of the webhook. If this is
None
then the webhook cannot be used to make requests.- Type
Optional[
str
]
-
user
¶ The user this webhook was created by. If the webhook was received without authentication then this will be
None
.- Type
Optional[
abc.User
]
-
source_guild
¶ The guild of the channel that this webhook is following. Only given if
type
isWebhookType.channel_follower
.バージョン 2.0 で追加.
- Type
Optional[
PartialWebhookGuild
]
-
source_channel
¶ The channel that this webhook is following. Only given if
type
isWebhookType.channel_follower
.バージョン 2.0 で追加.
- Type
Optional[
PartialWebhookChannel
]
-
classmethod
partial
(id, token, *, session=..., bot_token=None)¶ Creates a partial
Webhook
.- パラメータ
id (
int
) -- The ID of the webhook.token (
str
) -- The authentication token of the webhook.session (
requests.Session
) -- The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, therequests
auto session creation functions are used instead.bot_token (Optional[
str
]) -- The bot authentication token for authenticated requests involving the webhook.
- 戻り値
A partial
Webhook
. A partial webhook is just a webhook object with an ID and a token.- 戻り値の型
-
classmethod
from_url
(url, *, session=..., bot_token=None)¶ Creates a partial
Webhook
from a webhook URL.- パラメータ
url (
str
) -- The URL of the webhook.session (
requests.Session
) -- The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, therequests
auto session creation functions are used instead.bot_token (Optional[
str
]) -- The bot authentication token for authenticated requests involving the webhook.
- 例外
InvalidArgument -- The URL is invalid.
- 戻り値
A partial
Webhook
. A partial webhook is just a webhook object with an ID and a token.- 戻り値の型
-
fetch
(*, prefer_auth=True)¶ Fetches the current webhook.
This could be used to get a full webhook from a partial webhook.
注釈
When fetching with an unauthenticated webhook, i.e.
is_authenticated()
returnsFalse
, then the returned webhook does not contain any user information.- パラメータ
prefer_auth (
bool
) -- Whether to use the bot token over the webhook token if available. Defaults toTrue
.- 例外
HTTPException -- Could not fetch the webhook
NotFound -- Could not find the webhook by this ID
InvalidArgument -- This webhook does not have a token associated with it.
- 戻り値
The fetched webhook.
- 戻り値の型
-
delete
(*, reason=None, prefer_auth=True)¶ Deletes this Webhook.
- パラメータ
- 例外
HTTPException -- Deleting the webhook failed.
NotFound -- This webhook does not exist.
Forbidden -- You do not have permissions to delete this webhook.
InvalidArgument -- This webhook does not have a token associated with it.
-
edit
(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)¶ Edits this Webhook.
- パラメータ
name (Optional[
str
]) -- The webhook's new default name.avatar (Optional[
bytes
]) -- A bytes-like object representing the webhook's new default avatar.channel (Optional[
abc.Snowflake
]) -- The webhook's new channel. This requires an authenticated webhook.reason (Optional[
str
]) --The reason for editing this webhook. Shows up on the audit log.
バージョン 1.4 で追加.
prefer_auth (
bool
) -- Whether to use the bot token over the webhook token if available. Defaults toTrue
.
- 例外
HTTPException -- Editing the webhook failed.
NotFound -- This webhook does not exist.
InvalidArgument -- This webhook does not have a token associated with it or it tried editing a channel without authentication.
-
send
(content=..., *, username=..., avatar_url=..., tts=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., wait=False)¶ Sends a message using the webhook.
The content must be a type that can convert to a string through
str(content)
.To upload a single file, the
file
parameter should be used with a singleFile
object.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type. You cannot mix theembed
parameter with theembeds
parameter, which must be alist
ofEmbed
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 fromNone
to aWebhookMessage
if set toTrue
.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 withfiles
parameter.files (List[
File
]) -- A list of files to send with the content. This cannot be mixed with thefile
parameter.embed (
Embed
) -- The rich embed for the content to send. This cannot be mixed withembeds
parameter.embeds (List[
Embed
]) -- A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembed
parameter.allowed_mentions (
AllowedMentions
) --Controls the mentions being processed in this message.
バージョン 1.4 で追加.
- 例外
HTTPException -- Sending the message failed.
NotFound -- This webhook was not found.
Forbidden -- The authorization token for the webhook is incorrect.
TypeError -- You specified both
embed
andembeds
orfile
andfiles
ValueError -- The length of
embeds
was invalidInvalidArgument -- There was no token associated with this webhook.
- 戻り値
The message that was sent.
- 戻り値の型
Optional[
SyncWebhookMessage
]
-
fetch_message
(id)¶ Retrieves a single
SyncWebhookMessage
owned by this webhook.バージョン 2.0 で追加.
- パラメータ
id (
int
) -- The message ID to look for.- 例外
NotFound -- The specified message was not found.
Forbidden -- You do not have the permissions required to get a message.
HTTPException -- Retrieving the message failed.
InvalidArgument -- There was no token associated with this webhook.
- 戻り値
The message asked for.
- 戻り値の型
-
edit_message
(message_id, *, content=..., embeds=..., embed=..., file=..., files=..., allowed_mentions=None)¶ Edits a message owned by this webhook.
This is a lower level interface to
WebhookMessage.edit()
in case you only have an ID.バージョン 1.6 で追加.
- パラメータ
message_id (
int
) -- The message ID to edit.content (Optional[
str
]) -- The content to edit the message with orNone
to clear it.embeds (List[
Embed
]) -- A list of embeds to edit the message with.embed (Optional[
Embed
]) -- The embed to edit the message with.None
suppresses the embeds. This should not be mixed with theembeds
parameter.file (
File
) -- The file to upload. This cannot be mixed withfiles
parameter.files (List[
File
]) -- A list of files to send with the content. This cannot be mixed with thefile
parameter.allowed_mentions (
AllowedMentions
) -- Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.
- 例外
HTTPException -- Editing the message failed.
Forbidden -- Edited a message that is not yours.
TypeError -- You specified both
embed
andembeds
orfile
andfiles
ValueError -- The length of
embeds
was invalidInvalidArgument -- There was no token associated with this webhook.
-
delete_message
(message_id)¶ Deletes a message owned by this webhook.
This is a lower level interface to
WebhookMessage.delete()
in case you only have an ID.バージョン 1.6 で追加.
- パラメータ
message_id (
int
) -- The message ID to delete.- 例外
HTTPException -- Deleting the message failed.
Forbidden -- Deleted a message that is not yours.
-
SyncWebhookMessage¶
-
class
discord.
SyncWebhookMessage
¶ Represents a message sent from your webhook.
This allows you to edit or delete a message sent by your webhook.
This inherits from
discord.Message
with changes toedit()
anddelete()
to work.バージョン 2.0 で追加.
-
edit
(content=..., embeds=..., embed=..., file=..., files=..., allowed_mentions=None)¶ Edits the message.
- パラメータ
content (Optional[
str
]) -- The content to edit the message with orNone
to clear it.embeds (List[
Embed
]) -- A list of embeds to edit the message with.embed (Optional[
Embed
]) -- The embed to edit the message with.None
suppresses the embeds. This should not be mixed with theembeds
parameter.file (
File
) -- The file to upload. This cannot be mixed withfiles
parameter.files (List[
File
]) -- A list of files to send with the content. This cannot be mixed with thefile
parameter.allowed_mentions (
AllowedMentions
) -- Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.
- 例外
HTTPException -- Editing the message failed.
Forbidden -- Edited a message that is not yours.
TypeError -- You specified both
embed
andembeds
orfile
andfiles
ValueError -- The length of
embeds
was invalidInvalidArgument -- There was no token associated with this webhook.
-
delete
(*, delay=None)¶ Deletes the message.
- パラメータ
delay (Optional[
float
]) -- If provided, the number of seconds to wait before deleting the message. This blocks the thread.- 例外
Forbidden -- You do not have proper permissions to delete the message.
NotFound -- The message was deleted already.
HTTPException -- Deleting the message failed.
-
抽象基底クラス¶
An abstract base class (also known as an abc
) is a class that models can inherit
to get their behaviour. Abstract base classes should not be instantiated.
They are mainly there for usage with isinstance()
and issubclass()
.
This library has a module related to abstract base classes, in which all the ABCs are subclasses of
typing.Protocol
.
Snowflake¶
-
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
.-
created_at
¶ Returns the model's creation time as an aware datetime in UTC.
- Type
-
User¶
PrivateChannel¶
GuildChannel¶
- asyncclone
- asynccreate_invite
- asyncdelete
- asyncinvites
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
-
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
.注釈
This ABC is not decorated with
typing.runtime_checkable()
, so will failisinstance()
/issubclass()
checks.-
position
¶ The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type
-
changed_roles
¶ Returns a list of roles that have been overridden from their default values in the
roles
attribute.- Type
List[
Role
]
-
created_at
¶ Returns the channel's creation time in UTC.
- Type
-
overwrites_for
(obj)¶ Returns the channel-specific overwrites for a member or a role.
-
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 aMember
and the value is the overwrite as aPermissionOverwrite
.- 戻り値
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
-
permissions_for
(obj, /)¶ Handles permission resolution for the
Member
orRole
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
If a
Role
is passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The default role permission overwrites
The permission overwrites of the role used as a parameter
バージョン 2.0 で変更: The object passed in can now be a role object.
-
await
delete
(*, reason=None)¶ This function is a coroutine.
Deletes the channel.
You must have
manage_channels
permission to use this.- パラメータ
reason (Optional[
str
]) -- The reason for deleting this channel. Shows up on the audit log.- 例外
Forbidden -- You do not have proper permissions to delete the channel.
NotFound -- The channel was not found or was already deleted.
HTTPException -- Deleting the channel failed.
-
await
set_permissions
(target, *, overwrite=see - below, reason=None, **permissions)¶ This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
target
parameter should either be aMember
or aRole
that belongs to guild.The
overwrite
parameter, if given, must either beNone
orPermissionOverwrite
. For convenience, you can pass in keyword arguments denotingPermissions
attributes. If this is done, then you cannot mix the keyword arguments with theoverwrite
parameter.If the
overwrite
parameter isNone
, 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, orNone
to delete the overwrite.**permissions -- A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite
.reason (Optional[
str
]) -- The reason for doing this action. Shows up on the audit log.
- 例外
Forbidden -- You do not have permissions to edit channel specific permissions.
HTTPException -- Editing channel specific permissions failed.
NotFound -- The role or member being edited is not part of the guild.
InvalidArgument -- The overwrite parameter invalid or the target type was not
Role
orMember
.
-
await
clone
(*, name=None, reason=None)¶ This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.バージョン 1.1 で追加.
- パラメータ
- 例外
Forbidden -- You do not have the proper permissions to create this channel.
HTTPException -- Creating the channel failed.
- 戻り値
The channel that was created.
- 戻り値の型
-
await
move
(**kwargs)¶ This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
edit()
should be used instead.You must have the
manage_channels
permission to do this.注釈
Voice channels will always be sorted below text channels. This is a Discord limitation.
バージョン 1.7 で追加.
- パラメータ
beginning (
bool
) -- Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend
,before
, andafter
.end (
bool
) -- Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning
,before
, andafter
.before (
Snowflake
) -- The channel that should be before our current channel. This is mutually exclusive withbeginning
,end
, andafter
.after (
Snowflake
) -- The channel that should be after our current channel. This is mutually exclusive withbeginning
,end
, andbefore
.offset (
int
) -- The number of channels to offset the move by. For example, an offset of2
withbeginning=True
would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning
,end
,before
, andafter
parameters.category (Optional[
Snowflake
]) -- The category to move this channel under. IfNone
is given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool
) -- Whether to sync the permissions with the category (if given).reason (
str
) -- The reason for the move.
- 例外
InvalidArgument -- An invalid position was given or a bad mix of arguments were passed.
Forbidden -- You do not have permissions to move the channel.
HTTPException -- Moving the channel failed.
-
await
create_invite
(*, reason=None, **fields)¶ This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invite
permission to do this.- パラメータ
max_age (
int
) -- How long the invite should last in seconds. If it's 0 then the invite doesn't expire. Defaults to0
.max_uses (
int
) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to0
.temporary (
bool
) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (
bool
) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.reason (Optional[
str
]) -- The reason for creating this invite. Shows up on the audit log.
- 例外
HTTPException -- Invite creation failed.
NotFound -- The channel that was passed is a category or an invalid channel.
- 戻り値
The invite that was created.
- 戻り値の型
-
await
invites
()¶ This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channels
to get this information.- 例外
Forbidden -- You do not have proper permissions to get the information.
HTTPException -- An error occurred while fetching the information.
- 戻り値
The list of invites that are currently active.
- 戻り値の型
List[
Invite
]
-
Messageable¶
- asyncfetch_message
- defhistory
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
-
class
discord.abc.
Messageable
¶ An ABC that details the common operations on a model that can send messages.
The following implement this ABC:
注釈
This ABC is not decorated with
typing.runtime_checkable()
, so will failisinstance()
/issubclass()
checks.-
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. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) -- Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) -- Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) -- Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) -- If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- 例外
Forbidden -- You do not have permissions to get channel message history.
HTTPException -- The request to get message history failed.
- 列挙
Message
-- The message with the message data parsed.
-
async with
typing
()¶ Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
注釈
This is both a regular context manager and an async context manager. This means that both
with
andasync 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, allowed_mentions=None, reference=None, mention_author=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 toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects. Specifying both parameters will lead to an exception.If the
embed
parameter is provided, it must be of typeEmbed
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.allowed_mentions (
AllowedMentions
) --Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.バージョン 1.4 で追加.
reference (Union[
Message
,MessageReference
]) --A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.バージョン 1.6 で追加.
mention_author (Optional[
bool
]) --If set, overrides the
replied_user
attribute ofallowed_mentions
.バージョン 1.6 で追加.
- 例外
HTTPException -- Sending the message failed.
Forbidden -- You do not have the proper permissions to send the message.
InvalidArgument -- The
files
list is not of the appropriate size, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- 戻り値
The message that was sent.
- 戻り値の型
-
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.- 例外
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.
- 戻り値の型
-
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 completeMessage.reactions
data.- 例外
HTTPException -- Retrieving the pinned messages failed.
- 戻り値
The messages that are currently pinned.
- 戻り値の型
List[
Message
]
-
async for ... in
Connectable¶
-
class
discord.abc.
Connectable
¶ An ABC that details the common operations on a channel that can connect to a voice server.
The following implement this ABC:
注釈
This ABC is not decorated with
typing.runtime_checkable()
, so will failisinstance()
/issubclass()
checks.
Discordモデル¶
モデルはDiscordから受け取るクラスであり、ユーザーによって作成されることを想定していません。
危険
下記のクラスは、 ユーザーによって作成されることを想定しておらず 、中には 読み取り専用 のものもあります。
つまり、独自の User
を作成は行うべきではなく、また、 User
インスタンスの値の変更もするべきではありません。
このようなモデルクラスのインスタンスを取得したい場合は、 キャッシュを経由して取得する必要があります。一般的な方法としては utils.find()
関数を用いるか、 イベントリファレンス の特定のイベントから受け取る方法が挙げられます。
注釈
ほぼすべてのクラスに __slots__ が定義されています。つまり、データクラスに動的に変数を追加することは不可能です。
ClientUser¶
- asyncedit
- defmentioned_in
-
class
discord.
ClientUser
¶ あなたのDiscordユーザーを表します。
-
x == y
二つのユーザーが等しいかを比較します。
-
x != y
二つのユーザーが等しいものではないか比較します。
-
hash(x)
ユーザーのハッシュ値を返します。
-
str(x)
ユーザー名とディスクリミネータを返します。
-
system
¶ Specifies if the user is a system user (i.e. represents Discord officially).
バージョン 1.3 で追加.
- Type
-
await
edit
(*, username=None, avatar=None)¶ This function is a coroutine.
現在のクライアントのプロフィールを編集します。
注釈
アバターをアップロードする際には、アップロードする画像を表す bytes-like object を渡す必要があります。これをファイルを介して行う場合、ファイルを
open('some_filename', 'rb')
で開き、 bytes-like object はfp.read()
で取得できます。The only image formats supported for uploading is JPEG and PNG.
- パラメータ
username (
str
) -- 変更する際の新しいユーザー名。avatar (
bytes
) -- アップロードする画像を表す bytes-like object 。アバターをなしにしたい場合はNone
を設定することが出来ます。
- 例外
HTTPException -- Editing your profile failed.
InvalidArgument -- Wrong image format passed for
avatar
.
-
avatar
¶ 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.
- Type
-
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
¶ 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
-
created_at
¶ Returns the user's creation time in UTC.
This is when the user's Discord account was created.
- Type
-
default_avatar
¶ Returns the default avatar for a given user. This is calculated by the user's discriminator.
- Type
-
display_name
¶ Returns the user's display name.
通常であれば、これはユーザー名がそのまま返りますが、ギルドにてニックネームを設定している場合は、代替としてニックネームが返ります。
- Type
-
mentioned_in
(message)¶ 指定のメッセージにユーザーに対するメンションが含まれているかを確認します。
-
public_flags
¶ The publicly available flags the user has.
- Type
-
User¶
- asynccreate_dm
- asyncfetch_message
- defhistory
- defmentioned_in
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
-
class
discord.
User
¶ Represents a Discord user.
-
x == y
二つのユーザーが等しいかを比較します。
-
x != y
二つのユーザーが等しいものではないか比較します。
-
hash(x)
ユーザーのハッシュ値を返します。
-
str(x)
ユーザー名とディスクリミネータを返します。
-
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. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) -- Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) -- Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) -- Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) -- If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- 例外
Forbidden -- You do not have permissions to get channel message history.
HTTPException -- The request to get message history failed.
- 列挙
Message
-- The message with the message data parsed.
-
async with
typing
()¶ Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
注釈
This is both a regular context manager and an async context manager. This means that both
with
andasync 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
]
-
mutual_guilds
¶ The guilds that the user shares with the client.
注釈
This will only return mutual guilds within the client's internal cache.
バージョン 1.7 で追加.
- Type
List[
Guild
]
-
await
create_dm
()¶ This function is a coroutine.
このユーザーと
DMChannel
を作ります。This should be rarely called, as this is done transparently for most people.
- 戻り値
The channel that was created.
- 戻り値の型
-
avatar
¶ 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.
- Type
-
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
¶ 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
-
created_at
¶ Returns the user's creation time in UTC.
This is when the user's Discord account was created.
- Type
-
default_avatar
¶ Returns the default avatar for a given user. This is calculated by the user's discriminator.
- Type
-
display_name
¶ Returns the user's display name.
通常であれば、これはユーザー名がそのまま返りますが、ギルドにてニックネームを設定している場合は、代替としてニックネームが返ります。
- Type
-
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.- 例外
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.
- 戻り値の型
-
mentioned_in
(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 completeMessage.reactions
data.- 例外
HTTPException -- Retrieving the pinned messages failed.
- 戻り値
The messages that are currently pinned.
- 戻り値の型
List[
Message
]
-
public_flags
¶ The publicly available flags the user has.
- Type
-
await
send
(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=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 toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects. Specifying both parameters will lead to an exception.If the
embed
parameter is provided, it must be of typeEmbed
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.allowed_mentions (
AllowedMentions
) --Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.バージョン 1.4 で追加.
reference (Union[
Message
,MessageReference
]) --A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.バージョン 1.6 で追加.
mention_author (Optional[
bool
]) --If set, overrides the
replied_user
attribute ofallowed_mentions
.バージョン 1.6 で追加.
- 例外
HTTPException -- Sending the message failed.
Forbidden -- You do not have the proper permissions to send the message.
InvalidArgument -- The
files
list is not of the appropriate size, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- 戻り値
The message that was sent.
- 戻り値の型
-
Attachment¶
- defis_spoiler
- asyncread
- asyncsave
- asyncto_file
-
class
discord.
Attachment
¶ Represents an attachment from Discord.
-
str(x)
Returns the URL of the attachment.
-
x == y
Checks if the attachment is equal to another attachment.
-
x != y
Checks if the attachment is not equal to another attachment.
-
hash(x)
Returns the hash of the attachment.
バージョン 1.7 で変更: Attachment can now be casted to
str
and is hashable.-
height
¶ The attachment's height, in pixels. Only applicable to images and videos.
- Type
Optional[
int
]
-
url
¶ The attachment URL. If the message this attachment was attached to is deleted, then this will 404.
- Type
-
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
-
content_type
¶ The attachment's media type
バージョン 1.7 で追加.
- Type
Optional[
str
]
-
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 useproxy_url
rather thanurl
when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.
- 例外
HTTPException -- Saving the attachment failed.
NotFound -- The attachment was deleted.
- 戻り値
The number of bytes written.
- 戻り値の型
-
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 useproxy_url
rather thanurl
when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.- 例外
HTTPException -- Downloading the attachment failed.
Forbidden -- You do not have permissions to access this attachment
NotFound -- The attachment was deleted.
- 戻り値
The contents of the attachment.
- 戻り値の型
-
await
to_file
(*, use_cached=False, spoiler=False)¶ This function is a coroutine.
Converts the attachment into a
File
suitable for sending viaabc.Messageable.send()
.バージョン 1.3 で追加.
- パラメータ
use_cached (
bool
) --Whether to use
proxy_url
rather thanurl
when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.バージョン 1.4 で追加.
spoiler (
bool
) --Whether the file is a spoiler.
バージョン 1.4 で追加.
- 例外
HTTPException -- Downloading the attachment failed.
Forbidden -- You do not have permissions to access this attachment
NotFound -- The attachment was deleted.
- 戻り値
The attachment as a file suitable for sending.
- 戻り値の型
-
Asset¶
- defis_animated
- asyncread
- defreplace
- asyncsave
- defwith_format
- defwith_size
- defwith_static_format
-
class
discord.
Asset
¶ Represents a CDN asset on Discord.
-
str(x)
Returns the URL of the CDN asset.
-
len(x)
Returns the length of the CDN asset's URL.
-
x == y
Checks if the asset is equal to another asset.
-
x != y
Checks if the asset is not equal to another asset.
-
hash(x)
Returns the hash of the asset.
-
replace
(size=Ellipsis, format=Ellipsis, static_format=Ellipsis)¶ Returns a new asset with the passed components replaced.
- パラメータ
- 例外
InvalidArgument -- An invalid size or format was passed.
- 戻り値
The newly updated asset.
- 戻り値の型
-
with_size
(size)¶ Returns a new asset with the specified size.
- パラメータ
size (
int
) -- The new size of the asset.- 例外
InvalidArgument -- The asset had an invalid size.
- 戻り値
The new updated asset.
- 戻り値の型
-
with_format
(format)¶ Returns a new asset with the specified format.
- パラメータ
format (
str
) -- The new format of the asset.- 例外
InvalidArgument -- The asset had an invalid format.
- 戻り値
The new updated asset.
- 戻り値の型
-
with_static_format
(format)¶ Returns a new asset with the specified static format.
This only changes the format if the underlying asset is not animated. Otherwise, the asset is not changed.
- パラメータ
format (
str
) -- The new static format of the asset.- 例外
InvalidArgument -- The asset had an invalid format.
- 戻り値
The new updated asset.
- 戻り値の型
-
await
read
()¶ This function is a coroutine.
Retrieves the content of this asset as a
bytes
object.- 例外
DiscordException -- There was no internal connection state.
HTTPException -- Downloading the asset failed.
NotFound -- The asset was deleted.
- 戻り値
The content of the asset.
- 戻り値の型
-
await
save
(fp, *, seek_begin=True)¶ This function is a coroutine.
Saves this asset into a file-like object.
- パラメータ
fp (Union[
io.BufferedIOBase
,os.PathLike
]) -- The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead.seek_begin (
bool
) -- Whether to seek to the beginning of the file after saving is successfully done.
- 例外
DiscordException -- There was no internal connection state.
HTTPException -- Downloading the asset failed.
NotFound -- The asset was deleted.
- 戻り値
The number of bytes written.
- 戻り値の型
-
Message¶
- activity
- application
- attachments
- author
- channel
- channel_mentions
- clean_content
- content
- created_at
- edited_at
- embeds
- flags
- guild
- id
- jump_url
- mention_everyone
- mentions
- nonce
- pinned
- raw_channel_mentions
- raw_mentions
- raw_role_mentions
- reactions
- reference
- role_mentions
- stickers
- system_content
- tts
- type
- webhook_id
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asyncdelete
- asyncedit
- defis_system
- asyncpin
- asyncpublish
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
-
class
discord.
Message
¶ Represents a message from Discord.
-
x == y
Checks if two messages are equal.
-
x != y
Checks if two messages are not equal.
-
hash(x)
Returns the message's hash.
-
tts
¶ Specifies if the message was done with text-to-speech. This can only be accurately received in
on_message()
due to a discord limitation.- Type
-
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
A
Member
that sent the message. Ifchannel
is a private channel or the user has the left the guild, then it is aUser
instead.- Type
-
nonce
¶ The value used by the discord guild and the client to verify that the message is successfully sent. This is not stored long term within Discord's servers and is only used ephemerally.
-
channel
¶ The
TextChannel
that the message was sent from. Could be aDMChannel
orGroupChannel
if it's a private message.- Type
Union[
abc.Messageable
]
-
reference
¶ The message that this message references. This is only applicable to messages of type
MessageType.pins_add
, crossposted messages created by a followed channel integration, or message replies.バージョン 1.5 で追加.
- Type
Optional[
MessageReference
]
-
mention_everyone
¶ Specifies if the message mentions everyone.
注釈
This does not check if the
@everyone
or the@here
text is in the message itself. Rather this boolean indicates if either the@everyone
or the@here
text is in the message and it did end up mentioning.- Type
-
mentions
¶ A list of
Member
that were mentioned. If the message is in a private message then the list will be ofUser
instead. For messages that are not of typeMessageType.default
, this array can be used to aid in system messages. For more information, seesystem_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
]
-
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
]
-
flags
¶ Extra features of the message.
バージョン 1.3 で追加.
- Type
-
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
]
-
raw_mentions
¶ A property that returns an array of user IDs matched with the syntax of
<@user_id>
in the message content.This allows you to receive the user IDs of mentioned users even in a private message context.
- Type
List[
int
]
-
raw_channel_mentions
¶ A property that returns an array of channel IDs matched with the syntax of
<#channel_id>
in the message content.- Type
List[
int
]
-
raw_role_mentions
¶ A property that returns an array of role IDs matched with the syntax of
<@&role_id>
in the message content.- Type
List[
int
]
-
clean_content
¶ A property that returns the content in a "cleaned up" manner. This basically means that mentions are transformed into the way the client shows it. e.g.
<#id>
will transform into#name
.This will also transform @everyone and @here mentions into non-mentions.
注釈
This does not affect markdown. If you want to escape or remove markdown then use
utils.escape_markdown()
orutils.remove_markdown()
respectively, along with this function.- Type
-
created_at
¶ The message's creation time in UTC.
- Type
-
edited_at
¶ An aware UTC datetime object containing the edited time of the message.
- Type
Optional[
datetime.datetime
]
-
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 regularMessage.content
. Otherwise this returns an English message denoting the contents of the system message.- Type
-
await
delete
(*, delay=None)¶ This function is a coroutine.
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people's messages, you need the
manage_messages
permission.バージョン 1.1 で変更: Added the new
delay
keyword-only parameter.- パラメータ
delay (Optional[
float
]) -- If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.- 例外
Forbidden -- You do not have proper permissions to delete the message.
NotFound -- The message was deleted already
HTTPException -- Deleting the message failed.
-
await
edit
(**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 beNone
to remove the content.embed (Optional[
Embed
]) -- The new embed to replace the original with. Could beNone
to remove the embed.suppress (
bool
) -- Whether to suppress embeds for the message. This removes all the embeds if set toTrue
. If set toFalse
this brings the embeds back if they were suppressed. Using this parameter requiresmanage_messages
.delete_after (Optional[
float
]) -- If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.allowed_mentions (Optional[
AllowedMentions
]) --Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.バージョン 1.4 で追加.
- 例外
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.
If the message is not your own then the
manage_messages
permission is needed.- 例外
Forbidden -- You do not have the proper permissions to publish this message.
HTTPException -- Publishing the message failed.
-
await
pin
(*, reason=None)¶ This function is a coroutine.
Pins the message.
You must have the
manage_messages
permission to do this in a non-private channel context.- パラメータ
reason (Optional[
str
]) --The reason for pinning the message. Shows up on the audit log.
バージョン 1.4 で追加.
- 例外
Forbidden -- You do not have permissions to pin the message.
NotFound -- The message or channel was not found or deleted.
HTTPException -- Pinning the message failed, probably due to the channel having more than 50 pinned messages.
-
await
unpin
(*, reason=None)¶ This function is a coroutine.
Unpins the message.
You must have the
manage_messages
permission to do this in a non-private channel context.- パラメータ
reason (Optional[
str
]) --The reason for unpinning the message. Shows up on the audit log.
バージョン 1.4 で追加.
- 例外
Forbidden -- You do not have permissions to unpin the message.
NotFound -- The message or channel was not found or deleted.
HTTPException -- Unpinning the message failed.
-
await
add_reaction
(emoji)¶ This function is a coroutine.
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.You must have the
read_message_history
permission to use this. If nobody else has reacted to the message using this emoji, theadd_reactions
permission is required.- パラメータ
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) -- The emoji to react with.- 例外
HTTPException -- Adding the reaction failed.
Forbidden -- You do not have the proper permissions to react to the message.
NotFound -- The emoji you specified was not found.
InvalidArgument -- The emoji parameter is invalid.
-
await
remove_reaction
(emoji, member)¶ This function is a coroutine.
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.If the reaction is not your own (i.e.
member
parameter is not you) then themanage_messages
permission is needed.The
member
parameter must represent a member and meet theabc.Snowflake
abc.- パラメータ
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) -- The emoji to remove.member (
abc.Snowflake
) -- The member for which to remove the reaction.
- 例外
HTTPException -- Removing the reaction failed.
Forbidden -- You do not have the proper permissions to remove the reaction.
NotFound -- The member or emoji you specified was not found.
InvalidArgument -- The emoji parameter is invalid.
-
await
clear_reaction
(emoji)¶ This function is a coroutine.
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.You need the
manage_messages
permission to use this.バージョン 1.3 で追加.
- パラメータ
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) -- The emoji to clear.- 例外
HTTPException -- Clearing the reaction failed.
Forbidden -- You do not have the proper permissions to clear the reaction.
NotFound -- The emoji you specified was not found.
InvalidArgument -- The emoji parameter is invalid.
-
await
clear_reactions
()¶ This function is a coroutine.
Removes all the reactions from the message.
You need the
manage_messages
permission to use this.- 例外
HTTPException -- Removing the reactions failed.
Forbidden -- You do not have the proper permissions to remove all the reactions.
-
await
reply
(content=None, **kwargs)¶ This function is a coroutine.
A shortcut method to
abc.Messageable.send()
to reply to theMessage
.バージョン 1.6 で追加.
- 例外
HTTPException -- Sending the message failed.
Forbidden -- You do not have the proper permissions to send the message.
InvalidArgument -- The
files
list is not of the appropriate size or you specified bothfile
andfiles
.
- 戻り値
The message that was sent.
- 戻り値の型
-
to_reference
(*, fail_if_not_exists=True)¶ Creates a
MessageReference
from the current message.バージョン 1.6 で追加.
- パラメータ
fail_if_not_exists (
bool
) --Whether replying using the message reference should raise
HTTPException
if the message no longer exists or Discord could not fetch the message.バージョン 1.7 で追加.
- 戻り値
The reference to this message.
- 戻り値の型
-
DeletedReferencedMessage¶
-
class
discord.
DeletedReferencedMessage
¶ A special sentinel type that denotes whether the resolved message referenced message had since been deleted.
The purpose of this class is to separate referenced messages that could not be fetched and those that were previously fetched but have since been deleted.
バージョン 1.6 で追加.
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
]
-
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 theabc.Snowflake
abc.サンプル
使い方
# I do not actually recommend doing this. async for user in reaction.users(): await channel.send(f'{user} has reacted with {reaction.emoji}!')
Flattening into a list:
users = await reaction.users().flatten() # users is now a list of User... winner = random.choice(users) await channel.send(f'{winner} has won the raffle.')
- パラメータ
limit (
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.
- 例外
HTTPException -- Getting the users for the reaction failed.
- 列挙
Union[
User
,Member
] -- The member (if retrievable) or the user that has reacted to this message. The case where it can be aMember
is in a guild message context. Sometimes it can be aUser
if the member has left the guild.
-
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 themanage_messages
permission is needed.The
user
parameter must represent a user or member and meet theabc.Snowflake
abc.- パラメータ
user (
abc.Snowflake
) -- The user or member from which to remove the reaction.- 例外
HTTPException -- Removing the reaction failed.
Forbidden -- You do not have the proper permissions to remove the reaction.
NotFound -- The user you specified, or the reaction's message was not found.
-
await
clear
()¶ This function is a coroutine.
Clears this reaction from the message.
You need the
manage_messages
permission to use this.バージョン 1.3 で追加.
- 例外
HTTPException -- Clearing the reaction failed.
Forbidden -- You do not have the proper permissions to clear the reaction.
NotFound -- The emoji you specified was not found.
InvalidArgument -- The emoji parameter is invalid.
-
Guild¶
- afk_channel
- afk_timeout
- banner
- bitrate_limit
- categories
- channels
- chunked
- created_at
- default_notifications
- default_role
- description
- discovery_splash
- emoji_limit
- emojis
- explicit_content_filter
- features
- filesize_limit
- icon
- id
- large
- max_members
- max_presences
- max_video_channel_users
- me
- member_count
- members
- mfa_level
- name
- nsfw
- owner
- owner_id
- preferred_locale
- premium_subscriber_role
- premium_subscribers
- premium_subscription_count
- premium_tier
- public_updates_channel
- region
- roles
- rules_channel
- self_role
- shard_id
- splash
- stage_channels
- system_channel
- system_channel_flags
- text_channels
- unavailable
- verification_level
- voice_channels
- voice_client
- defaudit_logs
- asyncban
- asyncbans
- defby_category
- asyncchange_voice_state
- asyncchunk
- asynccreate_category
- asynccreate_category_channel
- asynccreate_custom_emoji
- asynccreate_integration
- asynccreate_role
- asynccreate_stage_channel
- asynccreate_template
- asynccreate_text_channel
- asynccreate_voice_channel
- asyncdelete
- asyncedit
- asyncedit_role_positions
- asyncestimate_pruned_members
- asyncfetch_ban
- asyncfetch_channels
- asyncfetch_emoji
- asyncfetch_emojis
- asyncfetch_member
- deffetch_members
- asyncfetch_roles
- defget_channel
- defget_member
- defget_member_named
- defget_role
- asyncintegrations
- asyncinvites
- asynckick
- asyncleave
- asyncprune_members
- asyncquery_members
- asynctemplates
- asyncunban
- asyncvanity_invite
- asyncwebhooks
- asyncwidget
-
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.
-
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
-
afk_channel
¶ The channel that denotes the AFK channel.
None
if it doesn't exist.- Type
Optional[
VoiceChannel
]
-
owner_id
¶ The guild owner's ID. Use
Guild.owner
instead.- Type
Indicates if the guild is unavailable. If this is
True
then the reliability of other attributes outside ofGuild.id
is slim and they might all beNone
. It is best to not do anything with the guild if it is unavailable.Check the
on_guild_unavailable()
andon_guild_available()
events.- Type
-
max_members
¶ The maximum amount of members for the guild.
注釈
This attribute is only available via
Client.fetch_guild()
.- Type
Optional[
int
]
-
max_video_channel_users
¶ The maximum amount of users in a video channel.
バージョン 1.4 で追加.
- Type
Optional[
int
]
-
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
-
verification_level
¶ The guild's verification level.
- Type
-
explicit_content_filter
¶ The guild's explicit content filter.
- Type
-
default_notifications
¶ The guild's notification settings.
- Type
-
features
¶ A list of features that the guild has. They are currently as follows:
VIP_REGIONS
: Guild has VIP voice regionsVANITY_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.FEATURABLE
: Guild is able to be featured in Server Discovery.COMMUNITY
: Guild is a community server.COMMERCE
: Guild can sell things using store channels.PUBLIC
: Guild is a public guild.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.WELCOME_SCREEN_ENABLED
: Guild has enabled the welcome screenMEMBER_VERIFICATION_GATE_ENABLED
: Guild has Membership Screening enabled.PREVIEW_ENABLED
: Guild can be viewed before being accepted via Membership Screening.
- Type
List[
str
]
The premium tier for this guild. Corresponds to "Nitro Server" in the official UI. The number goes from 0 to 3 inclusive.
- Type
The number of "boosts" this guild currently has.
- Type
-
preferred_locale
¶ The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.
- Type
Optional[
str
]
-
async for ... in
fetch_members
(*, limit=1000, after=None)¶ Retrieves an
AsyncIterator
that enables receiving the guild's members. In order to use this,Intents.members()
must be enabled.注釈
This method is an API call. For general usage, consider
members
instead.バージョン 1.3 で追加.
すべてのパラメータがオプションです。
- パラメータ
limit (Optional[
int
]) -- The number of members to retrieve. Defaults to 1000. PassNone
to fetch all members. Note that this is potentially slow.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) -- Retrieve members after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- 例外
ClientException -- The members intent is not enabled.
HTTPException -- Getting the members failed.
- 列挙
Member
-- The member with the member data parsed.
サンプル
使い方
async for member in guild.fetch_members(limit=150): print(member.name)
リストへフラット化
members = await guild.fetch_members(limit=150).flatten() # members is now a list of Member...
-
async for ... in
audit_logs
(*, limit=100, before=None, after=None
-