APIリファレンス¶
ここではdiscord.pyのAPIについて解説します。
注釈
このモジュールはPythonのloggingモジュールを使用して、出力に依存しない方法でエラーや診断の内容を記録します。loggingモジュールが設定されていない場合、これらのログはどこにも出力されません。discord.pyでloggingモジュールを使用する方法の詳細は ログの設定 を参照してください。
クライアント¶
-
class
discord.
Client
(*, loop=None, **options)¶ Discordに接続するクライアント接続を表します。このクラスは、DiscordのWebSocket、及びAPIとの対話に使用されます。
多くのオプションを
Client
に渡すことが可能です。- パラメータ
max_messages (Optional[
int
]) -- 内部のメッセージキャッシュに格納するメッセージの最大数。デフォルトでは5000に設定されています。 None あるいは100未満の値を渡すと、渡された値の代わりにデフォルトの値が使用されます。loop (Optional[event loop]) -- 非同期操作に使用する event loop デフォルトは
None
です。この場合、デフォルトのイベントループはasyncio.get_event_loop()
を介して使用されます。connector (aiohttp.BaseConnector) -- コネクションプーリングに使用する connector 。
proxy (Optional[
str
]) -- プロキシのURL。proxy_auth (Optional[aiohttp.BasicAuth]) -- プロキシのHTTP Basic認証を表すオブジェクト。
shard_id (Optional[
int
]) -- 0から始まり、shard_countより小さい整数。shard_count (Optional[
int
]) -- Shardの総数。fetch_offline_members (
bool
) -- 参加しているすべてのギルドのオフラインメンバーも取得するために、on_ready()
を遅延させるかどうかを表します。これがFalse
の場合、オフラインメンバーの取得は行われず、request_offline_members()
を使用してギルドのオフラインメンバーを取得する必要があります。status (Optional[
Status
]) -- Discordにログインした際の、開始時ステータス。activity (Optional[Union[
Activity
,Game
,Streaming
]]) -- Discordにログインした際の、開始時アクティビティ。heartbeat_timeout (
float
) -- HEARTBEAT_ACKを受信できない際に、WebSocketをタイムアウトさせて再起動するまでの最大秒数。最初のパケットの処理に時間がかかり、接続を切断できないというような状況時に便利です。デフォルトでは60秒に設定されています。
-
ws
¶ クライアントが現在接続しているWebSocketゲートウェイ。Noneでもかまいません。
-
loop
¶ クライアントがHTTP要求とWebSocket操作に使用する event loop 。
-
private_channels
¶ List[
abc.PrivateChannel
] -- 接続されたクライアントが参加しているプライベートチャンネル。注釈
Discordでのプライベートチャンネルの取扱いは内部的に処理されているため、これは最新のプライベートチャンネルから最大128個までしか取得できません。
-
voice_clients
¶ List[
VoiceClient
] -- 音声接続のリストを表します。
-
clear
()¶ ボットの内部状態をクリアします。
これが実行されると、Botは「再オープン」されたとみなされます。そのため、
is_closed()
やis_ready()
はFalse
を返し、内部のキャッシュもクリアされます。
-
run
(*args, **kwargs)¶ event loop の初期化を抽象化するブロッキングコール。
イベントループをより詳細に制御するには、この関数を使用しないでください。
start()
またはconnect()
+login()
を使用してください。おおよそ次のものに相当:
try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # cancel all tasks lingering finally: loop.close()
警告
この関数はブロッキングを行うため、必ず最後に呼び出してください。この関数を呼び出した後に呼び出されるイベントや関数は、Botが停止するまで実行されません。
-
get_channel
(id)¶ 渡されたIDを持つ
abc.GuildChannel
、またはabc.PrivateChannel
を返します。見つからない場合は、Noneを返します。
-
get_all_channels
()¶ クライアントが「アクセス」できるすべての
abc.GuildChannel
のジェネレータを取得します。使用例:
for guild in client.guilds: for channel in guild.channels: yield channel
注釈
abc.GuildChannel
を受け取ったからと言って、そのチャンネルで発言ができるという意味ではありません。発現可能なチャンネルのみを取得したいのなら、abc.GuildChannel.permissions_for()
を使いましょう。
-
get_all_members
()¶ クライアントが参照可能なすべての
Member
のジェネレータを返します。使用例:
for guild in client.guilds: for member in guild.members: yield member
-
wait_for
(event, *, check=None, timeout=None)¶ This function is a coroutine.
WebSocketイベントがディスパッチされるまで待機します。
メッセージの送信者が、メッセージに返信したり、リアクションをつけたり、編集したりする、自己完結型の処理に利用できます。
timeout
パラメータはasyncio.wait_for()
に渡されます。デフォルトではタイムアウトしません。タイムアウトした際にasyncio.TimeoutError
が発生するのは、使いやすさを考慮したためです。In case the event returns multiple arguments, a
tuple
containing those arguments is returned instead. Please check the documentation for a list of events and their parameters.この関数は 条件を満たす最初のイベント を返します。
例
ユーザーからの返信を待つ場合:
@client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send('Hello {.author}!'.format(msg))
メッセージ送信者がサムズアップリアクションを付けるのを待つ場合:
@client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that 👍 reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '👍' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('👎') else: await channel.send('👍')
- パラメータ
event (
str
) -- イベント名は event reference に似ていますが接頭詞のon_
が必要ありません。check (Optional[predicate]) -- 待っているものに該当するかを確認する関数。引数は待機しているイベントのパラメータを満たしている必要があります。
timeout (Optional[
float
]) -- タイムアウトしてasyncio.TimeoutError
が発生するまでの秒数。
- 例外
asyncio.TimeoutError
-- タイムアウトが設定されていて、かつその時間が経過した。- 戻り値
Returns no arguments, a single argument, or a
tuple
of multiple arguments that mirrors the parameters passed in the event reference.- 戻り値の型
Any
-
event
(coro)¶ リッスンするイベントを登録するデコレータ。
イベントの詳細については documentation below を参照してください。
The events must be a coroutine, if not,
TypeError
is raised.例
@client.event async def on_ready(): print('Ready!')
- 例外
TypeError
-- The coroutine passed is not actually a coroutine.
-
fetch_guilds
(*, limit=100, before=None, after=None)¶ This function is a coroutine.
Retrieves an
AsyncIterator
that enables receiving your guilds.注釈
Using this, you will only receive
Guild.owner
,Guild.icon
,Guild.id
, andGuild.name
perGuild
.All parameters are optional.
- パラメータ
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 to 100.before (
Snowflake
or datetime) -- Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.after (
Snowflake
or datetime) -- Retrieve guilds after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.
- 例外
HTTPException
-- Getting the guilds failed.- Yields
Guild
-- The guild with the guild data parsed.
例
Usage
async for guild in client.fetch_guilds(limit=150): print(guild.name)
Flattening into a list
guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild...
-
coroutine
application_info
()¶ This function is a coroutine.
Botのアプリケーション情報を取得します。
- 例外
HTTPException
-- 何らかの要因で情報の取得に失敗した。- 戻り値
アプリケーション情報を表す名前付きタプル。
- 戻り値の型
-
coroutine
change_presence
(*, activity=None, status=None, afk=False)¶ This function is a coroutine.
クライアントのプレゼンスを変更します。
activityパラメータは現在実行中のアクティビティを表す
Activity
オブジェクト(文字列ではありません)です。これはスリムなダウンバージョン、Game
やStreaming
でも構いません。例
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
- パラメータ
activity (Optional[Union[
Game
,Streaming
,Activity
]]) -- 実行中のアクティビティ。何も実行していない場合はNone
です。status (Optional[
Status
]) -- 変更したいステータスを表します。Noneの場合はStatus.online
が使用されます。afk (
bool
) -- Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying.
- 例外
InvalidArgument
--activity
に渡された値が適切な型でない。
-
coroutine
connect
(*, reconnect=True)¶ This function is a coroutine.
WebSocket接続を作成し、Discordからのメッセージをリッスンできるようにします。これはイベントシステム全体とライブラリの様々な機能を実行するループです。WebSocket接続が終了するまで、制御は再開されません。
- パラメータ
reconnect (
bool
) -- インターネットの障害やDiscord側の特定の障害が発生した際に再接続を試みるかどうかを表します。不正な状態へつながることによる特定の切断(無効なシャーディングペイロードや不正なトークンなど)は処理されません。- 例外
GatewayNotFound
-- Discordに接続するゲートウェイが見つからない。通常、これが発生した場合はAPIの停止が考えられます。ConnectionClosed
-- websocket接続が終了した。
-
coroutine
create_guild
(name, region=None, icon=None)¶ This function is a coroutine.
Guild
を作成します。10以上のギルドに参加しているBotアカウントはギルドの作成ができません。
- パラメータ
name (
str
) -- ギルドの名前。region (
VoiceRegion
) -- ボイスチャンネルの通信サーバーのリージョン。デフォルトではVoiceRegion.us_west
です。icon (
bytes
) -- アイコンを表す bytes-like object 。何が渡されることを想定しているかについてはedit()
を参照してください。
- 例外
HTTPException
-- ギルドの作成に失敗した。InvalidArgument
-- アイコン画像として無効なフォーマットの画像が渡された。PNGかJPGで指定してください。
- 戻り値
作成されたギルド。キャッシュに追加されるギルドとは別物です。
- 戻り値の型
-
coroutine
delete_invite
(invite)¶ This function is a coroutine.
招待の
Invite
、URL、IDを取り消します。これを行うためには、そのギルドの
manage_channels
権限が必要です。- パラメータ
- 例外
Forbidden
-- 招待を取り消す権限が無い。NotFound
-- 招待が無効、あるいは期限切れになっている。HTTPException
-- 招待の取り消しに失敗した。
-
coroutine
fetch_guild
(guild_id)¶ This function is a coroutine.
Retrieves a
Guild
from an ID.注釈
Using this, you will not receive
Guild.channels
,Guild.members
,Member.activity
andMember.voice
perMember
.- パラメータ
guild_id (
int
) -- The guild's ID to fetch from.- 例外
Forbidden
-- You do not have access to the guild.HTTPException
-- Getting the guild failed.
- 戻り値
The guild from the ID.
- 戻り値の型
-
coroutine
fetch_invite
(url, *, with_counts=True)¶ This function is a coroutine.
discord.gg URL、またはIDから
Invite
を取得します。注釈
招待がまだ参加していないギルドのものであった場合、返る
Invite
の guild と channel はそれぞれPartialInviteGuild
とPartialInviteChannel
になります。- パラメータ
url (
str
) -- discordの招待ID、またはURL(discord.gg URLである必要があります)。with_counts (
bool
) -- 招待にカウント情報を含めるかどうか。これによりInvite.approximate_member_count
とInvite.approximate_presence_count
に取得した値が代入されます。
- 例外
NotFound
-- 招待の有効期限が切れている、または無効。HTTPException
-- 招待の取得に失敗した。
- 戻り値
URL/IDから取得した招待。
- 戻り値の型
-
coroutine
fetch_user
(user_id)¶ This function is a coroutine.
IDをもとにユーザーを取得します。これはBotアカウントでのみ使用可能です。情報を得るためにそのユーザーとギルドを共有する必要はありませんが、多くの操作が必要になります。
- パラメータ
user_id (
int
) -- 取得したいユーザーのID。- 例外
NotFound
-- 指定のIDを持つユーザーが存在しない。HTTPException
-- ユーザーの取得に失敗した。
- 戻り値
あなたがリクエストしたユーザー。
- 戻り値の型
-
coroutine
fetch_user_profile
(user_id)¶ This function is a coroutine.
任意のユーザーのプロフィールを取得します。これはBotアカウント以外でのみ使用可能です。
- パラメータ
user_id (
int
) -- プロフィールを取得したいユーザーのID。- 例外
Forbidden
-- プロフィールを取得することが許可されていない。HTTPException
-- プロフィールの取得に失敗した。
- 戻り値
ユーザーのプロフィール。
- 戻り値の型
-
coroutine
fetch_webhook
(webhook_id)¶ This function is a coroutine.
特定のIDの
Webhook
を取得します。- 例外
HTTPException
-- Webhookの取得に失敗した。NotFound
-- WebhookのIDが無効。Forbidden
-- このWebhookを取得する権限がない。
- 戻り値
要求したWebhook。
- 戻り値の型
-
coroutine
fetch_widget
(guild_id)¶ This function is a coroutine.
Gets a
Widget
from a guild ID.注釈
The guild must have the widget enabled to get this information.
- パラメータ
guild_id (
int
) -- The ID of the guild.- 例外
Forbidden
-- The widget for this guild is disabled.HTTPException
-- Retrieving the widget failed.
- 戻り値
The guild's widget.
- 戻り値の型
-
coroutine
login
(token, *, bot=True)¶ This function is a coroutine.
指定された資格情報を使用してクライアントにログインします。
この関数は、異なる二通りの方法で使用することができます。
警告
ユーザートークンを用いてのログインはDiscordの 利用規約 に違反しているため、アカウントを停止される可能性があります。自己責任で使用してください。
- パラメータ
- 例外
LoginFailure
-- 誤った資格情報が渡された。HTTPException
-- 不明なHTTP関連のエラーが発生した。通常、ステータスコードが200でないか、既知の誤った資格情報がステータスコードを渡しています。
-
coroutine
on_error
(event_method, *args, **kwargs)¶ This function is a coroutine.
クライアントによって提供されるデフォルトのエラーハンドラ。
デフォルトでは、これは
sys.stderr
に出力されますが、異なる実装によって上書きされる可能性があります。詳細についてはdiscord.on_error()
を確認してください。
-
coroutine
request_offline_members
(*guilds)¶ This function is a coroutine.
ギルドのオフラインメンバーを
Guild.members
キャッシュへ書き込むよう要求します。この関数は通常呼び出されることはありません。fetch_offline_members
パラメータがFalse
の場合にのみ使用してください。クライアントがWebSocketに接続し、ログインするとき、ギルド内のメンバー数が250よりも大きいならば、Discordはライブラリにオフラインメンバーを提供しません。
Guild.large
がTrue
かどうかでギルドが大きいかどうかを確認することができます。- パラメータ
*guilds (
Guild
) -- オフラインメンバーを要求したいギルドのリスト。- 例外
InvalidArgument
-- いずれかのギルドが利用できない、またはコレクション内のギルドが大きくない。
-
user
¶ Optional[
ClientUser
] -- 接続しているクライアントを表します。接続していない場合はNoneです。
-
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
¶ float
-- HEARTBEATとHEARTBEAT_ACK間の待ち時間を秒単位で測定します。これは
Client.latency()
と同様に機能しますが、すべてのシャードの平均待ち時間を使用する点が異なります。シャードの待ち時間のリストを取得するにはlatencies
プロパティを参照してください。準備ができていない場合はnan
を返します。
-
latencies
¶ List[Tuple[
int
,float
]] -- HEARTBEATとHEARTBEAT_ACK間の待ち時間を秒単位で表したリスト。これは、
(shard_id, latency)
の要素を持つタプルのリストを返します。
-
coroutine
change_presence
(*, activity=None, status=None, afk=False, shard_id=None)¶ This function is a coroutine.
クライアントのプレゼンスを変更します。
activityパラメータは現在実行中のアクティビティを表す
Activity
オブジェクト(文字列ではありません)です。これはスリムなダウンバージョン、Game
やStreaming
でも構いません。例:
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
- パラメータ
activity (Optional[Union[
Game
,Streaming
,Activity
]]) -- 実行中のアクティビティ。何も実行していない場合はNone
です。status (Optional[
Status
]) -- 変更したいステータスを表します。Noneの場合はStatus.online
が使用されます。afk (
bool
) -- Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying.shard_id (Optional[
int
]) -- プレゼンスを変更したいシャードのshard_id。指定されていない、またはNone
が渡された場合はBotがアクセスできるすべてのシャードのプレゼンスが変更されます。
- 例外
InvalidArgument
--activity
に渡された値が適切な型でない。
-
coroutine
request_offline_members
(*guilds)¶ This function is a coroutine.
ギルドのオフラインメンバーを
Guild.members
キャッシュへ書き込むよう要求します。この関数は通常呼び出されることはありません。fetch_offline_members
パラメータがFalse
の場合にのみ使用してください。クライアントがWebSocketに接続し、ログインするとき、ギルド内のメンバー数が250よりも大きいならば、Discordはライブラリにオフラインメンバーを提供しません。
Guild.large
がTrue
かどうかでギルドが大きいかどうかを確認することができます。- パラメータ
*guilds (
Guild
) -- オフラインメンバーを要求したいギルドのリスト。- 例外
InvalidArgument
-- いずれかのギルドが利用できない、またはコレクション内のギルドが大きくない。
-
-
class
discord.
AppInfo
(state, data)¶ Represents the application info for the bot provided by Discord.
-
bot_public
¶ bool
-- Whether the bot can be invited by anyone or if it is locked to the application owner.
-
ボイス¶
-
class
discord.
VoiceClient
(state, timeout, channel)¶ Discordの音声接続を表します。
これを意図的に生成することはできません。通常、
VoiceChannel.connect()
などを使用した際に、取得できます。-
channel
¶ abc.Connectable
-- 接続しているボイスチャンネル。
-
loop
¶ ボイスクライアントが実行されているイベントループ。
-
user
¶ ClientUser
-- ボイスチャンネルに接続しているユーザー。(つまり、自分自身)
-
play
(source, *, after=None)¶ AudioSource
を再生します。ファイナライザーである
after
はソースがなくなったか、エラーが発生した後に呼び出されます。オーディオプレイヤーの実行中にエラーが発生した場合、例外はキャッチされ、プレイヤーは停止します。
- パラメータ
source (
AudioSource
) -- 読み込むオーディオソース。after -- ファイナライザーはストリームが空になると呼び出されます。発生した例外はすべて破棄されます。この関数には再生中に発生したオプションの例外を表す一つのパラメータ
error
が必要です。
- 例外
ClientException
-- すでにオーディオを再生しているか、VCに接続していない。TypeError
-- sourceがAudioSource
でないか、afterが呼び出し可能でない。
-
is_playing
()¶ 現在オーディオを再生しているかを表します。
-
is_paused
()¶ 再生中のオーディオを一時停止しているかを表します。
-
coroutine
move_to
(channel)¶ This function is a coroutine.
別のボイスチャンネルへ移動させます。
- パラメータ
channel (
abc.Snowflake
) -- 移動先のチャンネル。ボイスチャンネルである必要があります。
-
stop
()¶ 音声の再生を停止します。
-
pause
()¶ 音声の再生を一時的に停止します。
-
resume
()¶ 音声の再生を再開します。
-
source
¶ Optional[
AudioSource
] -- 再生中の場合、再生しているオーディオソースを返します。このプロパティは現在再生しているオーディオソースの変更にも使うことが出来ます。
-
send_audio_packet
(data, *, encode=True)¶ データで構成されるオーディオパケットを送信します。
オーディオを再生するには、ボイスチャンネルに接続している必要があります。
- パラメータ
data (bytes) -- PCM、またはOpusボイスデータを表す bytes-like object 。
encode (bool) --
data
をOpusにエンコードする必要があるかを表します。
- 例外
ClientException
-- ボイスチャンネルに接続していない。OpusError
-- dataのエンコードに失敗した。
-
-
class
discord.
AudioSource
¶ オーディオストリームを表します。
オーディオストリームはOpusにエンコードされていなくても構いませんが、エンコードされていない場合、オーディオフォーマットは16ビットの48KHzステレオPCMである必要があります。
警告
オーディオソースの読み込みは別スレッドで行われます。
-
read
()¶ 20ms分のオーディオを読み込みます。
サブクラスはこれを実装する必要があります。
オーディオの読み取りが終了すると、空の bytes-like object を返してこれを通知します。
is_opus()
がTrue
を返す場合、20ms分のOpusにエンコードされたオーディオを返さなければいけません。それ以外の場合は、フレームあたり約3,840バイトの20ms相当の16ビット48KHzステレオPCM(20ms分のオーディオ)が必要です。- 戻り値
PCMまたはOpusデータを表すバイトライクオブジェクト。
- 戻り値の型
-
is_opus
()¶ オーディオソースがOpusにエンコードされているかを表します。
デフォルトでは
False
です。
-
cleanup
()¶ クリーンアップが必要な時に呼び出されます。
オーディオの再生が終了した後にバッファデータやプロセスをクリアするのに便利です。
-
-
class
discord.
PCMAudio
(stream)¶ 生の16ビット48KHzステレオPCMオーディオソースを表します。
-
stream
¶ ファイルライクオブジェクト -- 生のPCMを表したバイトデータを読み取るファイルライクオブジェクト。
-
read
()¶ 20ms分のオーディオを読み込みます。
サブクラスはこれを実装する必要があります。
オーディオの読み取りが終了すると、空の bytes-like object を返してこれを通知します。
is_opus()
がTrue
を返す場合、20ms分のOpusにエンコードされたオーディオを返さなければいけません。それ以外の場合は、フレームあたり約3,840バイトの20ms相当の16ビット48KHzステレオPCM(20ms分のオーディオ)が必要です。- 戻り値
PCMまたはOpusデータを表すバイトライクオブジェクト。
- 戻り値の型
-
-
class
discord.
FFmpegPCMAudio
(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)¶ FFmpeg(またはAVConv)のオーディオソース。
与えられた特定の入力ファイルに対してサブプロセスを起動します。
警告
環境変数にffmpegまたはavconv実行可能ファイルがなければなりません。
- パラメータ
source (Union[
str
, BinaryIO]) -- ffmpegが受け取り、PCMバイトへ変換する入力。pipe
がTrueの場合、これはffmpegの標準入力に渡されるファイルライクオブジェクトです。executable (
str
) -- 使用する実行可能ファイルの名前 (およびパス)。デフォルトではffmpeg
です。pipe (
bool
) -- Trueの場合、source
パラメータがffmpegの標準入力に渡されます。デフォルトではFalse
です。stderr (Optional[BinaryIO]) -- Popenのコンストラクタに渡すファイルライクオブジェクト。
subprocess.PIPE
のようなインスタンスにすることも可能です。options (Optional[
str
]) ---i
フラグのあとにffmepgに渡す追加のコマンドライン引数。before_options (Optional[
str
]) ---i
フラグのまえにffmepgに渡す追加のコマンドライン引数。
- 例外
ClientException
-- サブプロセスの作成に失敗した。
-
read
()¶ 20ms分のオーディオを読み込みます。
サブクラスはこれを実装する必要があります。
オーディオの読み取りが終了すると、空の bytes-like object を返してこれを通知します。
is_opus()
がTrue
を返す場合、20ms分のOpusにエンコードされたオーディオを返さなければいけません。それ以外の場合は、フレームあたり約3,840バイトの20ms相当の16ビット48KHzステレオPCM(20ms分のオーディオ)が必要です。- 戻り値
PCMまたはOpusデータを表すバイトライクオブジェクト。
- 戻り値の型
-
cleanup
()¶ クリーンアップが必要な時に呼び出されます。
オーディオの再生が終了した後にバッファデータやプロセスをクリアするのに便利です。
-
class
discord.
PCMVolumeTransformer
(original, volume=1.0)¶ 前述の
AudioSource
をボリュームコントロールを持つものに変換します。これは
AudioSource.is_opus()
がTrue
になっているオーディオソースでは動作しません。- パラメータ
original (
AudioSource
) -- 変換する元のAudioSource。
- 例外
TypeError
-- オーディオソースでない。ClientException
-- オーディオソースがopusエンコード済み。
-
volume
¶ ボリュームを浮動小数点数パーセンテージ (100%の場合は1.0)として取得、または設定します。
-
cleanup
()¶ クリーンアップが必要な時に呼び出されます。
オーディオの再生が終了した後にバッファデータやプロセスをクリアするのに便利です。
-
read
()¶ 20ms分のオーディオを読み込みます。
サブクラスはこれを実装する必要があります。
オーディオの読み取りが終了すると、空の bytes-like object を返してこれを通知します。
is_opus()
がTrue
を返す場合、20ms分のOpusにエンコードされたオーディオを返さなければいけません。それ以外の場合は、フレームあたり約3,840バイトの20ms相当の16ビット48KHzステレオPCM(20ms分のオーディオ)が必要です。- 戻り値
PCMまたはOpusデータを表すバイトライクオブジェクト。
- 戻り値の型
Opusライブラリ¶
-
discord.opus.
load_opus
(name)¶ libopus共有ライブラリを音声用にロードします。
この関数が呼び出されない場合、ライブラリは ctypes.util.find_library 関数を使用して利用可能であればロードします。
ライブラリをロードしないと音声が機能しなくなります。
この関数は、スローされた例外を伝播します。
注釈
On Windows, this function should not need to be called as the binaries are automatically loaded.
警告
ライブラリのbit数は、あなたのPythonインタプリタのbit数と一致していなければなりません。ライブラリが64bitの場合は、Pythonインタプリタも64bitである必要があります。bit数が一致しない場合は、ロード時に例外を投げます。
注釈
Windowsでは .dll拡張は必要ありませんが、Linuxではライブラリをロードするために
libopus.so.1
のような完全な拡張ライブラリが必要です。しかしながら、Linux上でも通常の場合は find library が自動的にライブラリを検出します。- パラメータ
name (
str
) -- 共有ライブラリのファイル名。
-
discord.opus.
is_loaded
()¶ load_opus()
のctypes.util.find_library
呼び出しで、opusライブラリが正常にロードされたかどうかをチェックする関数。ボイス関連の機能を動かすためには、これが
True
を返す必要があります。- 戻り値
opusライブラリがロードされているかを表します。
- 戻り値の型
イベントリファレンス¶
この項目では Client
が受け取る様々なイベントについて説明します。
イベントを登録する方法は二通りあります。一つ目は Client.event()
を使用する方法です。二つ目は Client
を継承してサブクラスを作り、イベントをオーバーライドする方法です。この方法を用いた場合は以下のようになります:
import discord
class MyClient(discord.Client):
async def on_message(self, message):
if message.author == self.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello World!')
イベントハンドラが例外を発生させると、それを処理するために on_error()
が呼び出されます。 デフォルトではトレースバックが出力され、例外は無視されます。
警告
すべてのイベントは coroutine である必要があります。 coroutine でない場合、予期せぬエラーが発生する可能性があります。関数をコルーチンにするには、関数定義の際に async def
を使用してください。
-
discord.
on_connect
()¶ クライアントがDiscordに正常に接続できた際に呼び出されます。クライアントの準備が完了していることと同義ではありません。
on_ready()
を参照してください。on_ready()
での警告も適用されます。
-
discord.
on_disconnect
()¶ Called when the client has disconnected from Discord. This could happen either through the internet being disconnected, explicit calls to logout, or Discord terminating the connection one way or the other.
This function can be called many times.
-
discord.
on_ready
()¶ クライアントがDiscordから受信したデータの準備を完了した際に呼び出されます。通常はログインが成功したあと、
Client.guilds
とそれに関連するものの準備が完了したときです。警告
このイベントは、最初に呼び出されるイベントとは限りません。同時に、このイベントは 一度だけ呼ばれるという保証もできません 。このライブラリは、再接続ロジックを実装しているためリジューム要求が失敗するたびにこのイベントが呼び出されることになります。
-
discord.
on_shard_ready
(shard_id)¶ 特定の Shard IDが準備完了になったかを確認するために
AutoShardedClient
で使用される以外はon_ready()
とほとんど同じです。- パラメータ
shard_id -- 準備が完了したShard ID。
-
discord.
on_resumed
()¶ クライアントがセッションを再開したときに呼び出されます。
-
discord.
on_error
(event, *args, **kwargs)¶ Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to
sys.exc_info()
.If you want exception to propagate out of the
Client
class you can define anon_error
handler consisting of a single emptyraise
statement. Exceptions raised byon_error
will not be handled in any way byClient
.- パラメータ
event -- 例外を発生させたイベントの名前。
args -- 例外を発生させたイベントの位置引数。
kwargs -- The keyword arguments for the event that raised the exception.
-
discord.
on_socket_raw_receive
(msg)¶ メッセージが処理される前、WebSocketからメッセージが受信されるたびに呼び出されます。このイベントはメッセージを受信した場合、渡されたデータが処理できないときでも常に呼びだされます。
これはWebSocketストリームを取得してデバッグする時のみに役に立ちます。
注釈
これは、クライアントWebSocketから受信したメッセージ専用です。音声WebSocketではこのイベントは実行されません。
-
discord.
on_socket_raw_send
(payload)¶ メッセージが送信される前にWebSocketで送信操作が行われるたびに呼び出されます。渡されるパラメータはWebSocketに送信されているメッセージです。
これはWebSocketストリームを取得してデバッグする時のみに役に立ちます。
注釈
これは、クライアントWebSocketから受信したメッセージ専用です。音声WebSocketではこのイベントは実行されません。
-
discord.
on_typing
(channel, user, when)¶ 誰かがメッセージを入力し始めたときに呼び出されます。
channelパラメータは
abc.Messageable
インスタンスにすることができます。TextChannel
、GroupChannel
、またはDMChannel
のいずれかです。channel
がTextChannel
である場合、user
パラメータはMember
、それ以外の場合はUser
です。- パラメータ
channel -- 入力が行われたチャンネル。
user -- 入力を始めたユーザー。
when -- 入力を開始した時間を示す
datetime.datetime
オブジェクト。
-
discord.
on_message
(message)¶ Message
が作成され送信されたときに呼び出されます。警告
Botのメッセージとプライベートメッセージはこのイベントを通して送信されます。Botのプログラムによっては「再帰呼び出し」を続けることになります。Botが自分自身に返信しないようにするためにはユーザーIDを確認する方法が考えられます。この問題はBotが抱えるものではありません。
- パラメータ
message -- 現在のメッセージの
Message
インスタンス。
-
discord.
on_message_delete
(message)¶ Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the
Client.max_messages
attribute.- パラメータ
message -- 削除されたメッセージの
Message
インスタンス。
-
discord.
on_bulk_message_delete
(messages)¶ Called when messages are bulk deleted. If none of the messages deleted are found in the internal message cache, then this event will not be called. If individual messages were not found in the internal message cache, this event will still be called, but the messages not found will not be included in the messages list. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the
Client.max_messages
attribute.
-
discord.
on_raw_message_delete
(payload)¶ メッセージが削除された際に呼び出されます。
on_message_delete()
とは異なり、削除されたメッセージが内部キャッシュに存在するか否かにかかわらず呼び出されます。If the message is found in the message cache, it can be accessed via:attr:RawMessageDeleteEvent.cached_message
- パラメータ
payload (
RawMessageDeleteEvent
) -- 生のイベントペイロードデータ。
-
discord.
on_raw_bulk_message_delete
(payload)¶ Called when a bulk delete is triggered. Unlike
on_bulk_message_delete()
, this is called regardless of the messages being in the internal message cache or not.If the messages are found in the message cache, they can be accessed via
RawBulkMessageDeleteEvent.cached_messages
- パラメータ
payload (
RawBulkMessageDeleteEvent
) -- 生のイベントペイロードデータ。
-
discord.
on_message_edit
(before, after)¶ Called when a
Message
receives an update event. If the message is not found in the internal message cache, then these events will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.If this occurs increase the
Client.max_messages
attribute.以下の非網羅的ケースがこのイベントを発生させます:
メッセージをピン留め、または解除した。
メッセージの内容を変更した。
メッセージが埋め込みを受け取った。
パフォーマンス上の理由から、埋め込みのサーバーはこれを「一貫した」方法では行いません。
A call message has received an update to its participants or ending time.
-
discord.
on_raw_message_edit
(payload)¶ メッセージが編集された際に呼び出されます。
on_message_edit()
とは異なり、これは内部のメッセージキャッシュの状態に関係なく呼び出されます。このイベントの性質は、本質的に生表現のため、データのパラメータは gateway によって与えられた生データと一致します。
Since the data payload can be partial, care must be taken when accessing stuff in the dictionary. One example of a common case of partial data is when the
'content'
key is inaccessible. This denotes an "embed" only edit, which is an edit in which only the embeds are updated by the Discord embed server.- パラメータ
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.注釈
To get the
Message
being reacted, access it viaReaction.message
.
-
discord.
on_raw_reaction_add
(payload)¶ Called when a message has a reaction added. Unlike
on_reaction_add()
, this is called regardless of the state of the internal message cache.- パラメータ
payload (
RawReactionActionEvent
) -- 生のイベントペイロードデータ。
-
discord.
on_reaction_remove
(reaction, user)¶ Called when a message has a 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.
注釈
To get the message being reacted, access it via
Reaction.message
.
-
discord.
on_raw_reaction_remove
(payload)¶ Called when a reaction has a reaction removed. Unlike
on_reaction_remove()
, this is called regardless of the state of the internal message cache.- パラメータ
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.
-
discord.
on_raw_reaction_clear
(payload)¶ Called when a message has all its reactions removed. Unlike
on_reaction_clear()
, this is called regardless of the state of the internal message cache.- パラメータ
payload (
RawReactionClearEvent
) -- 生のイベントペイロードデータ。
-
discord.
on_private_channel_delete
(channel)¶ -
discord.
on_private_channel_create
(channel)¶ Called whenever a private channel is deleted or created.
- パラメータ
channel -- The
abc.PrivateChannel
that got created or deleted.
-
discord.
on_private_channel_update
(before, after)¶ Called whenever a private group DM is updated. e.g. changed name or topic.
- パラメータ
before -- The
GroupChannel
that got updated with the old info.after -- The
GroupChannel
that got updated with the updated info.
-
discord.
on_private_channel_pins_update
(channel, last_pin)¶ Called whenever a message is pinned or unpinned from a private channel.
- パラメータ
channel -- The
abc.PrivateChannel
that had it's pins updated.last_pin -- A
datetime.datetime
object representing when the latest message was pinned orNone
if there are no pins.
-
discord.
on_guild_channel_delete
(channel)¶ -
discord.
on_guild_channel_create
(channel)¶ Called whenever a guild channel is deleted or created.
Note that you can get the guild from
guild
.- パラメータ
channel -- The
abc.GuildChannel
that got created or deleted.
-
discord.
on_guild_channel_update
(before, after)¶ Called whenever a guild channel is updated. e.g. changed name, topic, permissions.
- パラメータ
before -- The
abc.GuildChannel
that got updated with the old info.after -- The
abc.GuildChannel
that got updated with the updated info.
-
discord.
on_guild_channel_pins_update
(channel, last_pin)¶ Called whenever a message is pinned or unpinned from a guild channel.
- パラメータ
channel -- The
abc.GuildChannel
that had it's pins updated.last_pin -- A
datetime.datetime
object representing when the latest message was pinned orNone
if there are no pins.
-
discord.
on_guild_integrations_update
(guild)¶ Called whenever an integration is created, modified, or removed from a guild.
- パラメータ
guild -- The
Guild
that had its integrations updated.
-
discord.
on_webhooks_update
(channel)¶ Called whenever a webhook is created, modified, or removed from a guild channel.
- パラメータ
channel -- The
abc.GuildChannel
that had its webhooks updated.
-
discord.
on_member_join
(member)¶ -
discord.
on_member_remove
(member)¶ Called when a
Member
leaves or joins aGuild
.- パラメータ
member -- The
Member
that joined or left.
-
discord.
on_member_update
(before, after)¶ Called when a
Member
updates their profile.This is called when one or more of the following things change:
status
game playing
nickname
roles
-
discord.
on_user_update
(before, after)¶ Called when a
User
updates their profile.This is called when one or more of the following things change:
avatar
username
discriminator
-
discord.
on_guild_join
(guild)¶ Client
によってGuild
が作成された。またはClient
がギルドに参加した際に呼び出されます。- パラメータ
guild -- 参加した
Guild
。
-
discord.
on_guild_remove
(guild)¶ Client
がGuild
から削除された際に呼び出されます。これは以下の状況時に呼び出されますが、これに限ったものではありません:
クライアントがBANされた。
クライアントがキックされた。
クライアントがギルドから退出した。
クライアント、またはギルドオーナーがギルドを削除した。
このイベントが呼び出されるためには、
Client
がギルドに参加している必要があります。(つまり、Client.guilds
にギルドが存在しなければならない)- パラメータ
guild -- 削除された
Guild
。
-
discord.
on_guild_update
(before, after)¶ Guild
が更新された際に呼び出されます。例えば:名前が変更された
AFKチャンネルが変更された
AFKのタイムアウト時間が変更された
その他
-
discord.
on_guild_role_create
(role)¶ -
discord.
on_guild_role_delete
(role)¶ Guild
でRole
が新しく作成されたか、削除された際に呼び出されます。ギルドを取得するには
Role.guild
を使用してください。- パラメータ
role -- 作成、または削除された
Role
。
-
discord.
on_guild_emojis_update
(guild, before, after)¶
-
discord.
on_guild_available
(guild)¶ Called when a guild becomes available or unavailable. The guild must have existed in the
Client.guilds
cache.- パラメータ
guild -- The
Guild
that has changed availability.
-
discord.
on_voice_state_update
(member, before, after)¶ Called when a
Member
changes theirVoiceState
.The following, but not limited to, examples illustrate when this event is called:
A member joins a voice room.
A member leaves a voice room.
A member is muted or deafened by their own accord.
A member is muted or deafened by a guild administrator.
- パラメータ
member -- The
Member
whose voice states changed.before -- The
VoiceState
prior to the changes.after -- The
VoiceState
after to the changes.
-
discord.
on_member_unban
(guild, user)¶
-
discord.
on_group_join
(channel, user)¶ -
discord.
on_group_remove
(channel, user)¶ Called when someone joins or leaves a group, i.e. a
PrivateChannel
with aPrivateChannel.type
ofChannelType.group
.- パラメータ
channel -- ユーザーが参加または脱退したグループ。
user -- 参加または脱退したユーザー。
-
discord.
on_relationship_add
(relationship)¶ -
discord.
on_relationship_remove
(relationship)¶ Called when a
Relationship
is added or removed from theClientUser
.- パラメータ
relationship -- The relationship that was added or removed.
-
discord.
on_relationship_update
(before, after)¶ Called when a
Relationship
is updated, e.g. when you block a friend or a friendship is accepted.- パラメータ
before -- The previous relationship status.
after -- The updated relationship status.
ユーティリティ関数¶
-
discord.utils.
find
(predicate, seq)¶ A helper to return the first element found in the sequence that meets the predicate. For example:
member = find(lambda m: m.name == 'Mighty', channel.guild.members)
would find the first
Member
whose name is 'Mighty' and return it. If an entry is not found, thenNone
is returned.This is different from filter due to the fact it stops the moment it finds a valid entry.
- パラメータ
predicate -- A function that returns a boolean-like result.
seq (iterable) -- The iterable to search through.
-
discord.utils.
get
(iterable, **attrs)¶ A helper that returns the first element in the iterable that meets all the traits passed in
attrs
. This is an alternative fordiscord.utils.find()
.When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by
x.y
) then pass inx__y
as the keyword argument.If nothing is found that matches the attributes passed, then
None
is returned.例
Basic usage:
member = discord.utils.get(message.guild.members, name='Foo')
Multiple attribute matching:
channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)
Nested attribute matching:
channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
- パラメータ
iterable -- An iterable to search through.
**attrs -- Keyword arguments that denote attributes to search with.
-
discord.utils.
snowflake_time
(id)¶ Returns the creation date in UTC of a discord id.
-
discord.utils.
oauth_url
(client_id, permissions=None, guild=None, redirect_uri=None)¶ A helper function that returns the OAuth2 URL for inviting the bot into guilds.
- パラメータ
client_id (
str
) -- The client ID for your bot.permissions (
Permissions
) -- The permissions you're requesting. If not given then you won't be requesting any permissions.guild (
Guild
) -- The guild to pre-select in the authorization screen, if available.redirect_uri (
str
) -- An optional valid redirect URI.
-
discord.utils.
escape_markdown
(text, *, as_needed=False, ignore_links=True)¶ A helper function that escapes Discord's markdown.
- パラメータ
text (
str
) -- The text to escape markdown from.as_needed (
bool
) -- Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it's not necessary, e.g.**hello**
is escaped into\*\*hello**
instead of\*\*hello\*\*
. Note however that this can open you up to some clever syntax abuse. Defaults toFalse
.ignore_links (
bool
) -- Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as_
then it will be left alone. This option is not supported withas_needed
. Defaults toTrue
.
- 戻り値
The text with the markdown special characters escaped with a slash.
- 戻り値の型
プロフィール¶
-
class
discord.
Profile
¶ A namedtuple representing a user's Discord public profile.
A boolean indicating if the user has premium (i.e. Discord Nitro).
A naive UTC datetime indicating how long the user has been premium since. This could be
None
if not applicable.
-
staff
¶ A boolean indicating if the user is Discord Staff.
-
partner
¶ A boolean indicating if the user is a Discord Partner.
-
bug_hunter
¶ A boolean indicating if the user is a Bug Hunter.
-
early_supporter
¶ A boolean indicating if the user has had premium before 10 October, 2018.
-
hypesquad
¶ A boolean indicating if the user is in Discord HypeSquad.
-
hypesquad_houses
¶ A list of
HypeSquadHouse
that the user is in.
-
mutual_guilds
¶ A list of
Guild
that theClientUser
shares with this user.
-
connected_accounts
¶ A list of dict objects indicating the accounts the user has connected.
An example entry can be seen below:
{type: "twitch", id: "92473777", name: "discordapp"}
列挙型¶
The API provides some enumerations for certain types of strings to avoid the API from being stringly typed in case the strings change in the future.
すべての列挙型が enum のサブクラスです。
-
class
discord.
ChannelType
¶ 特定チャンネルのチャンネルタイプ。
-
text
¶ テキストチャンネル。
-
voice
¶ ボイスチャンネル。
-
private
¶ A private text channel. Also called a direct message.
-
group
¶ A private group text channel.
-
news
¶ A guild news channel.
-
store
¶ A guild store channel.
-
-
class
discord.
MessageType
¶ Specifies the type of
Message
. This is used to denote if a message is to be interpreted as a system message or a regular message.-
default
¶ The default message type. This is the same as regular messages.
-
recipient_add
¶ The system message when a recipient is added to a group private message, i.e. a private channel of type
ChannelType.group
.
-
recipient_remove
¶ The system message when a recipient is removed from a group private message, i.e. a private channel of type
ChannelType.group
.
-
call
¶ The system message denoting call state, e.g. missed call, started call, etc.
-
channel_name_change
¶ The system message denoting that a channel's name has been changed.
-
channel_icon_change
¶ The system message denoting that a channel's icon has been changed.
-
pins_add
¶ The system message denoting that a pinned message has been added to a channel.
-
new_member
¶ The system message denoting that a new member has joined a Guild.
-
-
class
discord.
ActivityType
¶ Specifies the type of
Activity
. This is used to check how to interpret the activity itself.-
unknown
¶ An unknown activity type. This should generally not happen.
-
playing
¶ A "Playing" activity type.
-
streaming
¶ A "Streaming" activity type.
-
listening
¶ A "Listening" activity type.
-
watching
¶ A "Watching" activity type.
-
-
class
discord.
HypeSquadHouse
¶ Specifies the HypeSquad house a user belongs to.
-
bravery
¶ The "Bravery" house.
-
brilliance
¶ The "Brilliance" house.
-
balance
¶ The "Balance" house.
-
-
class
discord.
VoiceRegion
¶ Specifies the region a voice server belongs to.
-
amsterdam
¶ The Amsterdam region.
-
brazil
¶ The Brazil region.
-
eu_central
¶ The EU Central region.
-
eu_west
¶ The EU West region.
-
frankfurt
¶ The Frankfurt region.
-
hongkong
¶ The Hong Kong region.
-
japan
¶ The Japan region.
-
london
¶ The London region.
-
russia
¶ The Russia region.
-
singapore
¶ The Singapore region.
-
southafrica
¶ The South Africa region.
-
sydney
¶ The Sydney region.
-
us_central
¶ The US Central region.
-
us_east
¶ The US East region.
-
us_south
¶ The US South region.
-
us_west
¶ The US West region.
-
vip_amsterdam
¶ The Amsterdam region for VIP guilds.
-
vip_us_east
¶ The US East region for VIP guilds.
-
vip_us_west
¶ The US West region for VIP guilds.
-
-
class
discord.
VerificationLevel
¶ Specifies a
Guild
's verification level, which is the criteria in which a member must meet before being able to send messages to the guild.-
x == y
Checks if two verification levels are equal.
-
x != y
Checks if two verification levels are not equal.
-
x > y
Checks if a verification level is higher than another.
-
x < y
Checks if a verification level is lower than another.
-
x >= y
Checks if a verification level is higher or equal to another.
-
x <= y
Checks if a verification level is lower or equal to another.
-
none
¶ No criteria set.
-
low
¶ Member must have a verified email on their Discord account.
-
medium
¶ Member must have a verified email and be registered on Discord for more than five minutes.
-
high
¶ Member must have a verified email, be registered on Discord for more than five minutes, and be a member of the guild itself for more than ten minutes.
-
extreme
¶ Member must have a verified phone on their Discord account.
-
-
class
discord.
NotificationLevel
¶ Specifies whether a
Guild
has notifications on for all messages or mentions only by default.-
all_messages
¶ Members receive notifications for every message regardless of them being mentioned.
-
only_mentions
¶ Members receive notifications for messages they are mentioned in.
-
-
class
discord.
ContentFilter
¶ Specifies a
Guild
's explicit content filter, which is the machine learning algorithms that Discord uses to detect if an image contains pornography or otherwise explicit content.-
x == y
Checks if two content filter levels are equal.
-
x != y
Checks if two content filter levels are not equal.
-
x > y
Checks if a content filter level is higher than another.
-
x < y
Checks if a content filter level is lower than another.
-
x >= y
Checks if a content filter level is higher or equal to another.
-
x <= y
Checks if a content filter level is lower or equal to another.
-
disabled
¶ The guild does not have the content filter enabled.
-
no_role
¶ The guild has the content filter enabled for members without a role.
-
all_members
¶ The guild has the content filter enabled for every member.
-
-
class
discord.
Status
¶ Specifies a
Member
's status.-
online
¶ The member is online.
-
offline
¶ The member is offline.
-
idle
¶ The member is idle.
-
dnd
¶ The member is "Do Not Disturb".
-
invisible
¶ The member is "invisible". In reality, this is only used in sending a presence a la
Client.change_presence()
. When you receive a user's presence this will beoffline
instead.
-
-
class
discord.
RelationshipType
¶ Specifies the type of
Relationship
-
friend
¶ You are friends with this user.
-
blocked
¶ You have blocked this user.
-
incoming_request
¶ The user has sent you a friend request.
-
outgoing_request
¶ You have sent a friend request to this user.
-
-
class
discord.
AuditLogAction
¶ Represents the type of action being done for a
AuditLogEntry
, which is retrievable viaGuild.audit_logs()
.-
guild_update
¶ The guild has updated. Things that trigger this include:
Changing the guild vanity URL
Changing the guild invite splash
Changing the guild AFK channel or timeout
Changing the guild voice server region
Changing the guild icon
Changing the guild moderation settings
Changing things related to the guild widget
When this is the action, the type of
target
is theGuild
.Possible attributes for
AuditLogDiff
:
-
channel_create
¶ A new channel was created.
When this is the action, the type of
target
is either aabc.GuildChannel
orObject
with an ID.A more filled out object in the
Object
case can be found by usingafter
.Possible attributes for
AuditLogDiff
:
-
channel_update
¶ A channel was updated. Things that trigger this include:
The channel name or topic was changed
The channel bitrate was changed
When this is the action, the type of
target
is theabc.GuildChannel
orObject
with an ID.A more filled out object in the
Object
case can be found by usingafter
orbefore
.Possible attributes for
AuditLogDiff
:
-
channel_delete
¶ A channel was deleted.
When this is the action, the type of
target
is anObject
with an ID.A more filled out object can be found by using the
before
object.Possible attributes for
AuditLogDiff
:
-
overwrite_create
¶ A channel permission overwrite was created.
When this is the action, the type of
target
is theabc.GuildChannel
orObject
with an ID.When this is the action, the type of
extra
is either aRole
orMember
. If the object is not found then it is aObject
with an ID being filled, a name, and atype
attribute set to either'role'
or'member'
to help dictate what type of ID it is.Possible attributes for
AuditLogDiff
:
-
overwrite_update
¶ A channel permission overwrite was changed, this is typically when the permission values change.
See
overwrite_create
for more information on how thetarget
andextra
fields are set.Possible attributes for
AuditLogDiff
:
-
overwrite_delete
¶ A channel permission overwrite was deleted.
See
overwrite_create
for more information on how thetarget
andextra
fields are set.Possible attributes for
AuditLogDiff
:
-
kick
¶ A member was kicked.
When this is the action, the type of
target
is theUser
who got kicked.When this is the action,
changes
is empty.
-
member_prune
¶ A member prune was triggered.
When this is the action, the type of
target
is set to None.When this is the action, the type of
extra
is set to an unspecified proxy object with two attributes:delete_members_days
: An integer specifying how far the prune was.members_removed
: An integer specifying how many members were removed.
When this is the action,
changes
is empty.
-
ban
¶ A member was banned.
When this is the action, the type of
target
is theUser
who got banned.When this is the action,
changes
is empty.
-
unban
¶ A member was unbanned.
When this is the action, the type of
target
is theUser
who got unbanned.When this is the action,
changes
is empty.
-
member_update
¶ A member has updated. This triggers in the following situations:
A nickname was changed
They were server muted or deafened (or it was undo'd)
When this is the action, the type of
target
is theMember
orUser
who got updated.Possible attributes for
AuditLogDiff
:
-
member_role_update
¶ A member's role has been updated. This triggers when a member either gains a role or losses a role.
When this is the action, the type of
target
is theMember
orUser
who got the role.Possible attributes for
AuditLogDiff
:
-
role_create
¶ A new role was created.
When this is the action, the type of
target
is theRole
or aObject
with the ID.Possible attributes for
AuditLogDiff
:
-
role_update
¶ A role was updated. This triggers in the following situations:
The name has changed
The permissions have changed
The colour has changed
Its hoist/mentionable state has changed
When this is the action, the type of
target
is theRole
or aObject
with the ID.Possible attributes for
AuditLogDiff
:
-
role_delete
¶ A role was deleted.
When this is the action, the type of
target
is theRole
or aObject
with the ID.Possible attributes for
AuditLogDiff
:
-
invite_create
¶ An invite was created.
When this is the action, the type of
target
is theInvite
that was created.Possible attributes for
AuditLogDiff
:
-
invite_update
¶ An invite was updated.
When this is the action, the type of
target
is theInvite
that was updated.
-
invite_delete
¶ An invite was deleted.
When this is the action, the type of
target
is theInvite
that was deleted.Possible attributes for
AuditLogDiff
:
-
webhook_create
¶ A webhook was created.
When this is the action, the type of
target
is theObject
with the webhook ID.Possible attributes for
AuditLogDiff
:
-
webhook_update
¶ A webhook was updated. This trigger in the following situations:
The webhook name changed
The webhook channel changed
When this is the action, the type of
target
is theObject
with the webhook ID.Possible attributes for
AuditLogDiff
:
-
webhook_delete
¶ A webhook was deleted.
When this is the action, the type of
target
is theObject
with the webhook ID.Possible attributes for
AuditLogDiff
:
-
emoji_create
¶ An emoji was created.
When this is the action, the type of
target
is theEmoji
orObject
with the emoji ID.Possible attributes for
AuditLogDiff
:
-
emoji_update
¶ An emoji was updated. This triggers when the name has changed.
When this is the action, the type of
target
is theEmoji
orObject
with the emoji ID.Possible attributes for
AuditLogDiff
:
-
emoji_delete
¶ An emoji was deleted.
When this is the action, the type of
target
is theObject
with the emoji ID.Possible attributes for
AuditLogDiff
:
-
message_delete
¶ A message was deleted by a moderator. Note that this only triggers if the message was deleted by either bulk delete or deletion 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.
-
-
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.
-
非同期イテレータ¶
Some API functions return an "async iterator". An async iterator is something that is capable of being used in an async for statement.
These async iterators can be used as follows:
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. Note that this is only available in Python 3.5 or higher.
-
coroutine
next
()¶ This function is a coroutine.
Advances the iterator by one, if possible. If no more items are found then this raises
NoMoreItems
.
-
coroutine
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')
-
coroutine
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. Can be a coroutine.
- 戻り値
The first element that returns
True
for the predicate orNone
.
-
coroutine
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.
- 戻り値の型
-
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.
- 戻り値
An async iterator.
-
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.
- 戻り値
An async iterator.
-
サーバーログデータ¶
Working with Guild.audit_logs()
is a complicated process with a lot of machinery
involved. The library attempts to make it easy to use and friendly. In order to accomplish
this goal, it must make use of a couple of data classes that aid in this goal.
-
class
discord.
AuditLogEntry
(*, users, data, guild)¶ Represents an Audit Log entry.
You retrieve these via
Guild.audit_logs()
.-
action
¶ AuditLogAction
-- The action that was done.
-
user
¶ abc.User
-- The user who initiated this action. Usually aMember
, unless gone then it's aUser
.
-
target
¶ Any -- The target that got changed. The exact type of this depends on the action being done.
-
extra
¶ Any -- 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.
-
created_at
¶ Returns the entry's creation time in UTC.
-
category
¶ Optional[
AuditLogActionCategory
] -- The category of the action, if applicable.
-
changes
¶ AuditLogChanges
-- The list of changes this entry has.
-
before
¶ AuditLogDiff
-- The target's prior state.
-
after
¶ AuditLogDiff
-- The target's subsequent state.
-
-
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:Category
Description
All attributes are set to
None
.All attributes are set the value before deletion.
All attributes are set the value before updating.
None
No attributes are set.
-
after
¶ The new value. The attribute has the type of
AuditLogDiff
.Depending on the
AuditLogActionCategory
retrieved bycategory
, the data retrieved by this attribute differs:Category
Description
All attributes are set to the created value
All attributes are set to
None
All attributes are set the value after updating.
None
No attributes are set.
-
-
class
discord.
AuditLogDiff
¶ Represents an audit log "change" object. A change object has dynamic attributes that depend on the type of action being done. Certain actions map to certain attributes being set.
Note that accessing an attribute that does not match the specified action will lead to an attribute error.
To get a list of attributes that have been set, you can iterate over them. To see a list of all possible attributes that could be set based on the action being done, check the documentation for
AuditLogAction
, otherwise check the documentation below for all attributes that are possible.-
iter(diff)
Return an iterator over (attribute, value) tuple of this diff.
-
icon
¶ str
– A guild's icon hash. See alsoGuild.icon
.
-
splash
¶ str
– The guild's invite splash hash. See alsoGuild.splash
.
-
owner
¶ Union[
Member
,User
] – The guild's owner. See alsoGuild.owner
-
region
¶ GuildRegion
– The guild's voice region. See alsoGuild.region
.
-
afk_channel
¶ Union[
VoiceChannel
,Object
] – The guild's AFK channel.If this could not be found, then it falls back to a
Object
with the ID being set.See
Guild.afk_channel
.
-
system_channel
¶ Union[
TextChannel
,Object
] – The guild's system channel.If this could not be found, then it falls back to a
Object
with the ID being set.See
Guild.system_channel
.
-
afk_timeout
¶ int
– The guild's AFK timeout. SeeGuild.afk_timeout
.
-
mfa_level
¶ int
- The guild's MFA level. SeeGuild.mfa_level
.
-
widget_channel
¶ Union[
TextChannel
,Object
] – The widget's channel.If this could not be found then it falls back to a
Object
with the ID being set.
-
verification_level
¶ VerificationLevel
– The guild's verification level.See also
Guild.verification_level
.
-
default_notifications
¶ NotificationLevel
– The guild's default notification level.See also
Guild.default_notifications
.
-
explicit_content_filter
¶ ContentFilter
– The guild's content filter.See also
Guild.explicit_content_filter
.
-
vanity_url_code
¶ str
– The guild's vanity URL.See also
Guild.vanity_invite()
andGuild.change_vanity_invite()
.
-
position
¶ int
– The position of aRole
orabc.GuildChannel
.
-
type
¶ Union[int, str] – The type of channel or channel permission overwrite.
If the type is an
int
, then it is a type of channel which can be 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
¶ str
–TextChannel
のトピック。See also
TextChannel.topic
.
-
bitrate
¶ int
– The bitrate of aVoiceChannel
.See also
VoiceChannel.bitrate
.
-
overwrites
¶ List[Tuple[target,
PermissionOverwrite
]] – A list of permission overwrite tuples that represents a target and aPermissionOverwrite
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.
-
roles
¶ List[Union[
Role
,Object
]] – A list of roles being added or removed from a member.If a role is not found then it is a
Object
with the ID and name being filled in.
-
nick
¶ Optional[str] – The nickname of a member.
See also
Member.nick
-
deaf
¶ bool
– Whether the member is being server deafened.See also
VoiceState.deaf
.
-
mute
¶ bool
– Whether the member is being server muted.See also
VoiceState.mute
.
-
permissions
¶ Permissions
– 役職の権限。See also
Role.permissions
.
-
colour
¶ -
color
¶ Colour
– 役職の色。See also
Role.colour
-
hoist
¶ bool
– Whether the role is being hoisted or not.See also
Role.hoist
-
mentionable
¶ bool
– Whether the role is mentionable or not.See also
Role.mentionable
-
code
¶ str
– The invite's code.See also
Invite.code
-
channel
¶ Union[
abc.GuildChannel
,Object
] – A guild channel.If the channel is not found then it is a
Object
with the ID being set. In some cases the channel name is also set.
-
inviter
¶ User
– 招待を作成したユーザー。See also
Invite.inviter
.
-
max_uses
¶ int
– 招待の最大使用可能回数。See also
Invite.max_uses
.
-
uses
¶ int
– 招待の現在までの使用回数。See also
Invite.uses
.
-
max_age
¶ int
– The invite's max age in seconds.See also
Invite.max_age
.
-
temporary
¶ bool
– If the invite is a temporary invite.See also
Invite.temporary
.
-
allow
¶ -
deny
¶ Permissions
– The permissions being allowed or denied.
-
avatar
¶ str
– The avatar hash of a member.See also
User.avatar
.
-
slowmode_delay
¶ int
– The number of seconds members have to wait before sending another message in the channel.See also
TextChannel.slowmode_delay
.
-
Webhookサポート¶
discord.py offers support for creating, editing, and executing webhooks through the Webhook
class.
-
class
discord.
Webhook
(data, *, adapter, state=None)¶ Represents a Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as
Guild.webhooks()
andTextChannel.webhooks()
. The ones received by the library will automatically have an adapter bound using the library's HTTP session. Those webhooks will havesend()
,delete()
andedit()
as coroutines.The second form involves creating a webhook object manually without having it bound to a websocket connection using the
from_url()
orpartial()
classmethods. This form allows finer grained control over how requests are done, allowing you to mix async and sync code using eitheraiohttp
orrequests
.For example, creating a webhook from a URL and using
aiohttp
:from discord import Webhook, AsyncWebhookAdapter import aiohttp async def foo(): async with aiohttp.ClientSession() as session: webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session)) await webhook.send('Hello World', username='Foo')
Or creating a webhook from an ID and token and using
requests
:import requests from discord import Webhook, RequestsWebhookAdapter webhook = Webhook.partial(123456, 'abcdefg', adapter=RequestsWebhookAdapter()) webhook.send('Hello World', username='Foo')
-
user
¶ Optional[
abc.User
] -- The user this webhook was created by. If the webhook was received without authentication then this will beNone
.
-
url
¶ Returns the webhook's url.
-
classmethod
partial
(id, token, *, adapter)¶ Creates a partial
Webhook
.A partial webhook is just a webhook object with an ID and a token.
- パラメータ
id (
int
) -- The ID of the webhook.token (
str
) -- The authentication token of the webhook.adapter (
WebhookAdapter
) -- The webhook adapter to use when sending requests. This is typicallyAsyncWebhookAdapter
foraiohttp
orRequestsWebhookAdapter
forrequests
.
-
classmethod
from_url
(url, *, adapter)¶ Creates a partial
Webhook
from a webhook URL.- パラメータ
url (
str
) -- The URL of the webhook.adapter (
WebhookAdapter
) -- The webhook adapter to use when sending requests. This is typicallyAsyncWebhookAdapter
foraiohttp
orRequestsWebhookAdapter
forrequests
.
- 例外
InvalidArgument
-- URLが無効。
-
guild
¶ Optional[
Guild
] -- The guild this webhook belongs to.If this is a partial webhook, then this will always return
None
.
-
channel
¶ Optional[
TextChannel
] -- The text channel this webhook belongs to.If this is a partial webhook, then this will always return
None
.
-
created_at
¶ Returns the webhook's creation time in UTC.
-
avatar_url
¶ Returns a friendly URL version of the avatar the webhook has.
If the webhook does not have a traditional avatar, their default avatar URL is returned instead.
This is equivalent to calling
avatar_url_as()
with the default parameters.
-
avatar_url_as
(*, format=None, size=1024)¶ Returns a friendly URL version of the avatar the webhook has.
If the webhook does not have a traditional avatar, their default avatar URL is returned instead.
The format must be one of 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 1024.
- パラメータ
- 例外
InvalidArgument
--format
に誤った形式が渡されている、あるいはsize
に無効な値が渡されている。- 戻り値
The resulting CDN asset.
- 戻り値の型
-
delete
()¶ This function could be a coroutine.
Deletes this Webhook.
If the webhook is constructed with a
RequestsWebhookAdapter
then this is not a coroutine.- 例外
HTTPException
-- Webhookの削除に失敗した。NotFound
-- Webhookが存在していない。Forbidden
-- Webhookを削除するための権限がない。
-
edit
(**kwargs)¶ This function could be a coroutine.
Edits this Webhook.
If the webhook is constructed with a
RequestsWebhookAdapter
then this is not a coroutine.- パラメータ
name (Optional[
str
]) -- The webhook's new default name.avatar (Optional[
bytes
]) -- A bytes-like object representing the webhook's new default avatar.
- 例外
HTTPException
-- Webhookの編集に失敗した。NotFound
-- Webhookが存在していない。Forbidden
-- Webhookを編集するための権限がない。
-
send
(content=None, *, wait=False, username=None, avatar_url=None, tts=False, file=None, files=None, embed=None, embeds=None)¶ This function could be a coroutine.
Sends a message using the webhook.
If the webhook is constructed with a
RequestsWebhookAdapter
then this is not a coroutine.The content must be a type that can convert to a string through
str(content)
.To upload a single file, the
file
parameter should be used with a 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 aMessage
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.
- 例外
HTTPException
-- メッセージの送信に失敗した。NotFound
-- Webhookが見つからなかった。Forbidden
-- Webhookの認証トークンが正しくない。InvalidArgument
--embed``と``embeds``を指定した、あるいは ``embeds
の長さが無効。
- 戻り値
The message that was sent.
- 戻り値の型
Optional[
Message
]
-
Adapters¶
Adapters allow you to change how the request should be handled. They all build on a single
interface, WebhookAdapter.request()
.
-
class
discord.
WebhookAdapter
¶ Base class for all webhook adapters.
-
request
(verb, url, payload=None, multipart=None)¶ Actually does the request.
サブクラスはこれを実装する必要があります。
- パラメータ
verb (
str
) -- The HTTP verb to use for the request.url (
str
) -- The URL to send the request to. This will have the query parameters already added to it, if any.multipart (Optional[
dict
]) -- A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under afile
key which will have a 3-elementtuple
denoting(filename, file, content_type)
.payload (Optional[
dict
]) -- The JSON to send with the request, if any.
-
handle_execution_response
(data, *, wait)¶ Transforms the webhook execution response into something more meaningful.
This is mainly used to convert the data into a
Message
if necessary.サブクラスはこれを実装する必要があります。
- パラメータ
data -- The data that was returned from the request.
wait (
bool
) -- Whether the webhook execution was asked to wait or not.
-
-
class
discord.
AsyncWebhookAdapter
(session)¶ A webhook adapter suited for use with aiohttp.
注釈
You are responsible for cleaning up the client session.
- パラメータ
session (aiohttp.ClientSession) -- The session to use to send requests.
-
coroutine
handle_execution_response
(response, *, wait)¶ Transforms the webhook execution response into something more meaningful.
This is mainly used to convert the data into a
Message
if necessary.サブクラスはこれを実装する必要があります。
- パラメータ
data -- The data that was returned from the request.
wait (
bool
) -- Whether the webhook execution was asked to wait or not.
-
coroutine
request
(verb, url, payload=None, multipart=None, *, files=None)¶ Actually does the request.
サブクラスはこれを実装する必要があります。
- パラメータ
verb (
str
) -- The HTTP verb to use for the request.url (
str
) -- The URL to send the request to. This will have the query parameters already added to it, if any.multipart (Optional[
dict
]) -- A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under afile
key which will have a 3-elementtuple
denoting(filename, file, content_type)
.payload (Optional[
dict
]) -- The JSON to send with the request, if any.
-
class
discord.
RequestsWebhookAdapter
(session=None, *, sleep=True)¶ A webhook adapter suited for use with
requests
.Only versions of requests higher than 2.13.0 are supported.
- パラメータ
session (Optional[requests.Session]) -- The requests session to use for sending requests. If not given then each request will create a new session. Note if a session is given, the webhook adapter will not clean it up for you. You must close the session yourself.
sleep (
bool
) -- Whether to sleep the thread when encountering a 429 or pre-emptive rate limit or a 5xx status code. Defaults toTrue
. If set toFalse
then this will raise anHTTPException
instead.
-
request
(verb, url, payload=None, multipart=None, *, files=None)¶ Actually does the request.
サブクラスはこれを実装する必要があります。
- パラメータ
verb (
str
) -- The HTTP verb to use for the request.url (
str
) -- The URL to send the request to. This will have the query parameters already added to it, if any.multipart (Optional[
dict
]) -- A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under afile
key which will have a 3-elementtuple
denoting(filename, file, content_type)
.payload (Optional[
dict
]) -- The JSON to send with the request, if any.
-
handle_execution_response
(response, *, wait)¶ Transforms the webhook execution response into something more meaningful.
This is mainly used to convert the data into a
Message
if necessary.サブクラスはこれを実装する必要があります。
- パラメータ
data -- The data that was returned from the request.
wait (
bool
) -- Whether the webhook execution was asked to wait or not.
抽象基底クラス¶
An abstract base class (also known as an abc
) is a class that models can inherit
to get their behaviour. The Python implementation of an abc is
slightly different in that you can register them at run-time. Abstract base classes cannot be instantiated.
They are mainly there for usage with isinstance
and issubclass
.
This library has a module related to abstract base classes, some of which are actually from the abc
standard
module, others which are not.
-
class
discord.abc.
Snowflake
¶ An ABC that details the common operations on a Discord model.
Almost all Discord models meet this abstract base class.
-
created_at
¶ Returns the model's creation time in UTC.
-
-
class
discord.abc.
User
¶ An ABC that details the common operations on a Discord user.
The following implement this ABC:
ClientUser
Member
This ABC must also implement
abc.Snowflake
.-
display_name
¶ Returns the user's display name.
-
mention
¶ Returns a string that allows you to mention the given user.
-
class
discord.abc.
PrivateChannel
¶ An ABC that details the common operations on a private Discord channel.
The following implement this ABC:
DMChannel
GroupChannel
This ABC must also implement
abc.Snowflake
.-
me
¶ ClientUser
-- The user presenting yourself.
-
class
discord.abc.
GuildChannel
¶ An ABC that details the common operations on a Discord guild channel.
The following implement this ABC:
TextChannel
VoiceChannel
CategoryChannel
This ABC must also implement
abc.Snowflake
.-
guild
¶ Guild
-- チャンネルが属するギルド。
-
position
¶ int
-- The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
-
changed_roles
¶ Returns a
list
ofRoles
that have been overridden from their default values in theGuild.roles
attribute.
-
created_at
¶ Returns the channel's creation time in UTC.
-
overwrites_for
(obj)¶ Returns the channel-specific overwrites for a member or a role.
- パラメータ
obj -- The
Role
orabc.User
denoting whose overwrite to get.- 戻り値
The permission overwrites for this object.
- 戻り値の型
PermissionOverwrite
-
overwrites
¶ Returns all of the channel's overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Role
or aMember
and the key is the overwrite as aPermissionOverwrite
.- 戻り値
The channel's permission overwrites.
- 戻り値の型
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
-
category
¶ Optional[
CategoryChannel
] -- The category this channel belongs to.If there is no category then this is
None
.
-
permissions_for
(member)¶ Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- パラメータ
member (
Member
) -- The member to resolve permissions for.- 戻り値
The resolved permissions for the member.
- 戻り値の型
Permissions
-
coroutine
create_invite
(*, reason=None, **fields)¶ This function is a coroutine.
Creates an instant invite.
You must have
create_instant_invite
permission to do this.- パラメータ
max_age (
int
) -- How long the invite should last. If it's 0 then the invite doesn't expire. Defaults to 0.max_uses (
int
) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to 0.temporary (
bool
) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.unique (
bool
) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.reason (Optional[
str
]) -- The reason for creating this invite. Shows up on the audit log.
- 例外
HTTPException
-- 招待の作成に失敗した。- 戻り値
The invite that was created.
- 戻り値の型
Invite
-
coroutine
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
-- チャンネルを削除するための権限がない。NotFound
-- チャンネルが見つからなかった、あるいは既に削除されている。HTTPException
-- チャンネルの削除に失敗した。
-
coroutine
invites
()¶ This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_guild
to get this information.- 例外
Forbidden
-- 情報を取得するための権限がない。HTTPException
-- 情報の取得中にエラーが発生した。
- 戻り値
The list of invites that are currently active.
- 戻り値の型
List[
Invite
]
-
coroutine
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 = PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- パラメータ
target -- The
Member
orRole
to overwrite permissions for.overwrite (
PermissionOverwrite
) -- The permissions to allow and deny to the target.**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
-- チャンネルの権限を編集するための権限がない。HTTPException
-- チャンネルの権限の編集に失敗した。NotFound
-- 編集中の役職、あるいはメンバーがギルドの一部でない。InvalidArgument
-- overwriteパラメータが無効であるか、targetの型がRole
とMember
のどちらかでない。
-
class
discord.abc.
Messageable
¶ An ABC that details the common operations on a model that can send messages.
The following implement this ABC:
TextChannel
DMChannel
GroupChannel
Member
Context
This ABC must also implement
abc.Snowflake
.-
async-for
history
(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ Return an
AsyncIterator
that enables receiving the destination's message history.これを行うためには、そのチャンネルの
read_message_history
権限が必要です。例
Usage
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...
All parameters are optional.
- パラメータ
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 (
Message
ordatetime.datetime
) -- Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (
Message
ordatetime.datetime
) -- Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (
Message
ordatetime.datetime
) -- Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) -- If set to true, return messages in oldest->newest order. Defaults to True ifafter
is specified, otherwise False.
- 例外
Forbidden
-- You do not have permissions to get channel message history.HTTPException
-- The request to get message history failed.
- Yields
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!')
-
coroutine
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.
- 戻り値の型
-
coroutine
pins
()¶ This function is a coroutine.
Returns a
list
ofMessage
that are currently pinned.- 例外
HTTPException
-- Retrieving the pinned messages failed.
-
coroutine
send
(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None)¶ This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set 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 -- 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.
- 例外
HTTPException
-- Sending the message failed.Forbidden
-- You do not have the proper permissions to send the message.InvalidArgument
-- Thefiles
list is not of the appropriate size or you specified bothfile
andfiles
.
- 戻り値
The message that was sent.
- 戻り値の型
-
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:
VoiceChannel
Discordモデル¶
モデルはDiscordから受け取るクラスであり、ユーザーによって作成されることを想定していません。
危険
下記のクラスは、 ユーザーによって作成されることを想定しておらず 、中には 読み取り専用 のものもあります。
つまり、独自の User
を作成は行うべきではなく、また、 User
インスタンスの値の変更もするべきではありません。
このようなモデルクラスのインスタンスを取得したい場合は、 キャッシュを経由して取得する必要があります。一般的な方法としては utils.find()
関数を用いるか、 イベントリファレンス の特定のイベントから受け取る方法が挙げられます。
注釈
ほぼすべてのクラスに __slots__
が定義されています。つまり、データクラスに動的に変数を追加することは不可能です。
__slots__
の詳細は 公式のPythonドキュメント を参照してください。
クライアントユーザー¶
-
class
discord.
ClientUser
¶ あなたのDiscordユーザーを表します。
-
x == y
二つのユーザーが等しいかを比較します。
-
x != y
二つのユーザーが等しいものではないか比較します。
-
hash(x)
ユーザーのハッシュ値を返します。
-
str(x)
ユーザー名とディスクリミネータを返します。
bool
-- ユーザーがプレミアムユーザー (例えば Discord Nitro) であるかを表します。
PremiumType
-- Specifies the type of premium a user has (e.g. Nitro or Nitro Classic). Could be None if the user is not premium.
-
get_relationship
(user_id)¶ 該当すれば
Relationship
が返ります。- パラメータ
user_id (
int
) -- リレーションシップがあるか確認したいユーザーのID。- 戻り値
該当すればリレーションシップが返り、それ以外は
None
が返ります。- 戻り値の型
Optional[
Relationship
]
-
relationships
¶ ユーザーの
Relationship
のlist
が返ります。
-
avatar_url
¶ ユーザーのアバターのURLを返します。
ユーザーがアバターを設定していない場合、デフォルトのアバターのURLが返ります。
これはデフォルトパラメータ(webp/gif フォーマット及びサイズが1024)で
avatar_url_as()
を呼び出すのと同等の処理です。
-
avatar_url_as
(*, format=None, static_format='webp', size=1024)¶ ユーザーのアバターのURLを返します。
ユーザーがアバターを設定していない場合、デフォルトのアバターのURLが返ります。
フォーマットは「webp」「jpeg」「jpg」「png」または「gif」である必要があり、「gif」はアニメーションアバターにのみ使用可能です。サイズは2の累乗値かつ16以上1024以下である必要があります。
- パラメータ
- 例外
InvalidArgument
--format
またはstatic_format
が正しくない、あるいはsize
に無効な値が渡された。- 戻り値
The resulting CDN asset.
- 戻り値の型
-
color
¶ レンダリング済みカラーを表す
Colour
を返すプロパティ。これは常にColour.default()
を返します。これには別名のプロパティがあります。
-
colour
¶ レンダリング済みカラーを表す
Colour
を返すプロパティ。これは常にColour.default()
を返します。これには別名のプロパティがあります。
-
coroutine
create_group
(*recipients)¶ This function is a coroutine.
与えられたrecipientsを含むグループダイレクトメッセージを作成します。これを実行するにはrecipientsとの間に
RelationshipType.friend
のリレーションシップを持っていなければなりません。Botアカウントはグループを作成することは出来ません。
- パラメータ
- 例外
HTTPException
-- グループダイレクトメッセージの作成に失敗した。参加人数が一人のグループを作成しようとした。人数に自分自身は含まれません。
- 戻り値
新しいグループチャンネル。
- 戻り値の型
-
created_at
¶ ユーザーの作成された時間をUTCで返します。
これはユーザーのDiscordアカウントが作成された時間です。
-
default_avatar
¶ ユーザーのデフォルトのアバターを追加します。これはユーザーのタグから算出されます。
-
default_avatar_url
¶ ユーザーのデフォルトアバターのURLを返します。
-
display_name
¶ Returns the user's display name.
通常であれば、これはユーザー名がそのまま返りますが、ギルドにてニックネームを設定している場合は、代替としてニックネームが返ります。
-
coroutine
edit
(**fields)¶ This function is a coroutine.
現在のクライアントのプロフィールを編集します。
Botアカウントである場合はpasswordフィールドはオプションとなります。それ以外の場合は必須です。
注釈
アバターをアップロードする際には、アップロードする画像を表す bytes-like object を渡す必要があります。これをファイルを介して行う場合、ファイルを
open('some_filename', 'rb')
で開き、 bytes-like object はfp.read()
で取得できます。アップロードでサポートされる画像形式はJPEGとPNGのみです。
- パラメータ
password (
str
) -- クライアントの現在のパスワード。ユーザーアカウントでのみ適用可能です。new_password (
str
) -- 変更する際の新しいパスワード。ユーザーアカウントでのみ適用可能です。email (
str
) -- 変更する際の新しいEメールアドレス。ユーザーアカウントでのみ適用可能です。house (Optional[
HypeSquadHouse
]) -- 変更する際の新しいHypesquad house。現在のhouseから脱退したい場合はNone
を指定してください。ユーザアカウントでのみ適用可能です。username (
str
) -- 変更する際の新しいユーザー名。avatar (
bytes
) -- アップロードする画像を表す bytes-like object 。アバターをなしにしたい場合はNone
を設定することが出来ます。
- 例外
HTTPException
-- プロフィールの編集に失敗した。InvalidArgument
--avatar
に誤った形式の画像が渡された。ClientException
-- Botではないアカウントでpasswordが指定されていない。 HouseフィールドがHypeSquadHouseでない。
-
coroutine
edit_settings
(**kwargs)¶ This function is a coroutine.
Edits the client user's settings. Only applicable to user accounts.
- パラメータ
afk_timeout (
int
) -- How long (in seconds) the user needs to be AFK until Discord sends push notifications to your mobile device.animate_emojis (
bool
) -- Whether or not to animate emojis in the chat.convert_emoticons (
bool
) -- Whether or not to automatically convert emoticons into emojis. e.g. :-) -> 😃default_guilds_restricted (
bool
) -- Whether or not to automatically disable DMs between you and members of new guilds you join.detect_platform_accounts (
bool
) -- Whether or not to automatically detect accounts from services like Steam and Blizzard when you open the Discord client.developer_mode (
bool
) -- Whether or not to enable developer mode.disable_games_tab (
bool
) -- Whether or not to disable the showing of the Games tab.enable_tts_command (
bool
) -- Whether or not to allow tts messages to be played/sent.explicit_content_filter (
UserContentFilter
) -- The filter for explicit content in all messages.friend_source_flags (
FriendFlags
) -- Who can add you as a friend.gif_auto_play (
bool
) -- Whether or not to automatically play gifs that are in the chat.guild_positions (List[
abc.Snowflake
]) -- A list of guilds in order of the guild/guild icons that are on the left hand side of the UI.inline_attachment_media (
bool
) -- Whether or not to display attachments when they are uploaded in chat.inline_embed_media (
bool
) -- Whether or not to display videos and images from links posted in chat.locale (
str
) -- The RFC 3066 language identifier of the locale to use for the language of the Discord client.message_display_compact (
bool
) -- Whether or not to use the compact Discord display mode.render_embeds (
bool
) -- Whether or not to render embeds that are sent in the chat.render_reactions (
bool
) -- Whether or not to render reactions that are added to messages.restricted_guilds (List[
abc.Snowflake
]) -- A list of guilds that you will not receive DMs from.show_current_game (
bool
) -- Whether or not to display the game that you are currently playing.status (
Status
) -- The clients status that is shown to others.theme (
Theme
) -- The theme of the Discord UI.timezone_offset (
int
) -- The timezone offset to use.
- 例外
HTTPException
-- Editing the settings failed.Forbidden
-- The client is a bot user and not a user account.
- 戻り値
The client user's updated settings.
- 戻り値の型
-
mention
¶ Returns a string that allows you to mention the given user.
-
mentioned_in
(message)¶ 指定のメッセージにユーザーに対するメンションが含まれているかを確認します。
- パラメータ
message (
Message
) -- メンションが含まれているかを確認するメッセージ。
-
permissions_in
(channel)¶ abc.GuildChannel.permissions_for()
のエイリアス。基本的には以下と同等です:
channel.permissions_for(self)
- パラメータ
channel (
abc.GuildChannel
) -- 権限を確認したいチャンネル。
-
リレーションシップ¶
-
class
discord.
Relationship
¶ Discordのリレーションシップを表します。
フレンドや、ブロックした人などのようなリレーションシップです。Botでないアカウントのみがリレーションシップを持つことが出来ます。
-
type
¶ RelationshipType
-- リレーションシップのタイプ。
-
coroutine
accept
()¶ This function is a coroutine.
Accepts the relationship request. e.g. accepting a friend request.
- 例外
HTTPException
-- Accepting the relationship failed.
-
coroutine
delete
()¶ This function is a coroutine.
Deletes the relationship.
- 例外
HTTPException
-- Deleting the relationship failed.
-
ユーザー¶
-
class
discord.
User
¶ Represents a Discord user.
-
x == y
二つのユーザーが等しいかを比較します。
-
x != y
二つのユーザーが等しいものではないか比較します。
-
hash(x)
ユーザーのハッシュ値を返します。
-
str(x)
ユーザー名とディスクリミネータを返します。
-
async-for
history
(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ Return an
AsyncIterator
that enables receiving the destination's message history.これを行うためには、そのチャンネルの
read_message_history
権限が必要です。例
Usage
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...
All parameters are optional.
- パラメータ
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 (
Message
ordatetime.datetime
) -- Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (
Message
ordatetime.datetime
) -- Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (
Message
ordatetime.datetime
) -- Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) -- If set to true, return messages in oldest->newest order. Defaults to True ifafter
is specified, otherwise False.
- 例外
Forbidden
-- You do not have permissions to get channel message history.HTTPException
-- The request to get message history failed.
- Yields
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
DMChannel
associated with this user if it exists.これが ``None``を返すなら、あなたは
create_dm()
コルーチン関数を使って、DMチャンネルを作ることができます。
-
relationship
¶ Returns the
Relationship
with this user if applicable,None
otherwise.
-
avatar_url
¶ ユーザーのアバターのURLを返します。
ユーザーがアバターを設定していない場合、デフォルトのアバターのURLが返ります。
これはデフォルトパラメータ(webp/gif フォーマット及びサイズが1024)で
avatar_url_as()
を呼び出すのと同等の処理です。
-
avatar_url_as
(*, format=None, static_format='webp', size=1024)¶ ユーザーのアバターのURLを返します。
ユーザーがアバターを設定していない場合、デフォルトのアバターのURLが返ります。
フォーマットは「webp」「jpeg」「jpg」「png」または「gif」である必要があり、「gif」はアニメーションアバターにのみ使用可能です。サイズは2の累乗値かつ16以上1024以下である必要があります。
- パラメータ
- 例外
InvalidArgument
--format
またはstatic_format
が正しくない、あるいはsize
に無効な値が渡された。- 戻り値
The resulting CDN asset.
- 戻り値の型
-
coroutine
block
()¶ This function is a coroutine.
ユーザーをブロックします。
- 例外
Forbidden
-- このユーザーをブロックすることが認められていない。HTTPException
-- ユーザーのブロックに失敗した。
-
color
¶ レンダリング済みカラーを表す
Colour
を返すプロパティ。これは常にColour.default()
を返します。これには別名のプロパティがあります。
-
colour
¶ レンダリング済みカラーを表す
Colour
を返すプロパティ。これは常にColour.default()
を返します。これには別名のプロパティがあります。
-
coroutine
create_dm
()¶ このユーザーと
DMChannel
を作ります。This should be rarely called, as this is done transparently for most people.
-
created_at
¶ ユーザーの作成された時間をUTCで返します。
これはユーザーのDiscordアカウントが作成された時間です。
-
default_avatar
¶ ユーザーのデフォルトのアバターを追加します。これはユーザーのタグから算出されます。
-
default_avatar_url
¶ ユーザーのデフォルトアバターのURLを返します。
-
display_name
¶ Returns the user's display name.
通常であれば、これはユーザー名がそのまま返りますが、ギルドにてニックネームを設定している場合は、代替としてニックネームが返ります。
-
coroutine
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.
- 戻り値の型
-
mention
¶ Returns a string that allows you to mention the given user.
-
mentioned_in
(message)¶ 指定のメッセージにユーザーに対するメンションが含まれているかを確認します。
- パラメータ
message (
Message
) -- メンションが含まれているかを確認するメッセージ。
-
coroutine
mutual_friends
()¶ This function is a coroutine.
Gets all mutual friends of this user. This can only be used by non-bot accounts
- 例外
Forbidden
-- Not allowed to get mutual friends of this user.HTTPException
-- Getting mutual friends failed.
- 戻り値
The users that are mutual friends.
- 戻り値の型
List[
User
]
-
permissions_in
(channel)¶ abc.GuildChannel.permissions_for()
のエイリアス。基本的には以下と同等です:
channel.permissions_for(self)
- パラメータ
channel (
abc.GuildChannel
) -- 権限を確認したいチャンネル。
-
coroutine
pins
()¶ This function is a coroutine.
Returns a
list
ofMessage
that are currently pinned.- 例外
HTTPException
-- Retrieving the pinned messages failed.
-
coroutine
profile
()¶ This function is a coroutine.
Gets the user's profile. This can only be used by non-bot accounts.
- 例外
Forbidden
-- プロフィールを取得することが許可されていない。HTTPException
-- プロフィールの取得に失敗した。
- 戻り値
ユーザーのプロフィール。
- 戻り値の型
-
coroutine
remove_friend
()¶ This function is a coroutine.
Removes the user as a friend.
- 例外
Forbidden
-- Not allowed to remove this user as a friend.HTTPException
-- Removing the user as a friend failed.
-
coroutine
send
(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None)¶ This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set 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 -- 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.
- 例外
HTTPException
-- Sending the message failed.Forbidden
-- You do not have the proper permissions to send the message.InvalidArgument
-- Thefiles
list is not of the appropriate size or you specified bothfile
andfiles
.
- 戻り値
The message that was sent.
- 戻り値の型
-
coroutine
send_friend_request
()¶ This function is a coroutine.
Sends the user a friend request.
- 例外
Forbidden
-- Not allowed to send a friend request to the user.HTTPException
-- Sending the friend request failed.
-
coroutine
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.
-
coroutine
unblock
()¶ This function is a coroutine.
Unblocks the user.
- 例外
Forbidden
-- Not allowed to unblock this user.HTTPException
-- Unblocking the user failed.
-
アタッチメント¶
-
class
discord.
Attachment
¶ Represents an attachment from Discord.
-
url
¶ str
-- The attachment URL. If the message this attachment was attached to is deleted, then this will 404.
-
proxy_url
¶ str
-- The proxy URL. This is a cached version of theurl
in the case of images. When the message is deleted, this URL might be valid for a few minutes or not valid at all.
-
coroutine
save
(fp, *, seek_begin=True, use_cached=False)¶ This function is a coroutine.
Saves this attachment into a file-like object.
- パラメータ
fp (Union[BinaryIO,
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 type of attachments.
- 例外
HTTPException
-- Saving the attachment failed.NotFound
-- The attachment was deleted.
- 戻り値
The number of bytes written.
- 戻り値の型
-
Asset¶
-
class
discord.
Asset
¶ Represents a CDN asset on Discord.
-
str(x)
Returns the URL of the CDN asset.
-
len(x)
Returns the length of the CDN asset's URL.
-
bool(x)
Checks if the Asset has a URL.
-
coroutine
save
(fp, *, seek_begin=True)¶ This function is a coroutine.
Saves this asset into a file-like object.
- パラメータ
fp (Union[BinaryIO,
os.PathLike
]) -- Same as inAttachment.save()
.seek_begin (
bool
) -- Same as inAttachment.save()
.
- 例外
DiscordException
-- There was no valid URL or internal connection state.注釈
PartialEmoji
will not have a state if you make your own instance viaPartialEmoji(animated=False, name='x', id=2345678)
.The URL will not be provided if there is no custom image.
HTTPException
-- Saving the asset failed.NotFound
-- The asset was deleted.
- 戻り値
The number of bytes written.
- 戻り値の型
-
メッセージ¶
-
class
discord.
Message
¶ Represents a message from Discord.
There should be no need to create one of these manually.
-
type
¶ MessageType
-- 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 forsystem_content
.
A
Member
that sent the message. Ifchannel
is a private channel or the user has the left the guild, then it is aUser
instead.
-
nonce
¶ The value used by the discord guild and the client to verify that the message is successfully sent. This is typically non-important.
-
channel
¶ The
TextChannel
that the message was sent from. Could be aDMChannel
orGroupChannel
if it's a private message.
-
call
¶ Optional[
CallMessage
] -- The call that the message refers to. This is only applicable to messages of typeMessageType.call
.
-
mention_everyone
¶ bool
-- 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.
-
mentions
¶ list
-- A list ofMember
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.
-
channel_mentions
¶ list
-- A list ofabc.GuildChannel
that were mentioned. If the message is in a private message then the list is always empty.
-
role_mentions
¶ list
-- A list ofRole
that were mentioned. If the message is in a private message then the list is always empty.
-
webhook_id
¶ Optional[
int
] -- If this message was sent by a webhook, then this is the webhook ID's that sent this message.
-
attachments
¶ List[
Attachment
] -- A list of attachments given to a message.
-
reactions
¶ List[
Reaction
] -- Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
-
activity
¶ Optional[
dict
] -- 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.
-
application
¶ Optional[
dict
] -- 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.
-
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.
-
raw_channel_mentions
¶ A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content.
-
raw_role_mentions
¶ A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content.
-
clean_content
¶ A property that returns the content in a "cleaned up" manner. This basically means that mentions are transformed into the way the client shows it. e.g.
<#id>
will transform into#name
.This will also transform @everyone and @here mentions into non-mentions.
注釈
This does not escape markdown. If you want to escape markdown then use
utils.escape_markdown()
along with this function.
-
created_at
¶ datetime.datetime -- The message's creation time in UTC.
-
edited_at
¶ Optional[datetime.datetime] -- A naive UTC datetime object containing the edited time of the message.
-
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.
-
coroutine
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
.これを行うためには、そのチャンネルの
read_message_history
権限が必要です。 もし、他の人がその絵文字でリアクションしていない場合、さらにadd_reactions
権限が必要です。- パラメータ
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.
-
coroutine
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.
-
coroutine
delete
()¶ 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.- 例外
Forbidden
-- You do not have proper permissions to delete the message.HTTPException
-- Deleting the message failed.
-
coroutine
edit
(**fields)¶ This function is a coroutine.
Edits the message.
The content must be able to be transformed into a string via
str(content)
.- パラメータ
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.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.
- 例外
HTTPException
-- Editing the message failed.
-
coroutine
pin
()¶ This function is a coroutine.
Pins the message.
You must have the
manage_messages
permission to do this in a non-private channel context.- 例外
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.
-
coroutine
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.
-
coroutine
unpin
()¶ This function is a coroutine.
Unpins the message.
You must have the
manage_messages
permission to do this in a non-private channel context.- 例外
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.
-
ack
()¶ This function is a coroutine.
Marks this message as read.
The user must not be a bot user.
- 例外
HTTPException
-- Acking failed.ClientException
-- You must not be a bot user.
-
リアクション¶
-
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.
-
async-for
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.例
Usage
# I do not actually recommend doing this. async for user in reaction.users(): await channel.send('{0} has reacted with {1.emoji}!'.format(user, reaction))
Flattening into a list:
users = await reaction.users().flatten() # users is now a list... winner = random.choice(users) await channel.send('{} has won the raffle.'.format(winner))
- パラメータ
limit (
int
) -- The maximum number of results to return. If not provided, returns all the users who reacted to the message.after (
abc.Snowflake
) -- For pagination, reactions are sorted by member.
- 例外
HTTPException
-- Getting the users for the reaction failed.- Yields
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.
-
coroutine
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 thediscord.permissions.Permissions.manage_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.
-
コールメッセージ¶
-
class
discord.
CallMessage
¶ Represents a group call message from Discord.
This is only received in cases where the message type is equivalent to
MessageType.call
.-
ended_timestamp
¶ Optional[datetime.datetime] -- A naive UTC datetime object that represents the time that the call has ended.
-
channel
¶ GroupChannel
-- The private channel associated with this message.
-
duration
¶ Queries the duration of the call.
If the call has not ended then the current duration will be returned.
- 戻り値
The timedelta object representing the duration.
- 戻り値の型
-
グループコール¶
-
class
discord.
GroupCall
¶ Represents the actual group call from Discord.
This is accompanied with a
CallMessage
denoting the information.-
call
¶ CallMessage
-- The call message associated with this group call.
bool
-- Denotes if this group call is unavailable.
-
region
¶ VoiceRegion
-- The guild region the group call is being hosted on.
-
channel
¶ GroupChannel
-- Returns the channel the group call is in.
-
voice_state_for
(user)¶ Retrieves the
VoiceState
for a specifiedUser
.If the
User
has no voice state then this function returnsNone
.- パラメータ
user (
User
) -- The user to retrieve the voice state for.- 戻り値
The voice state associated with this user.
- 戻り値の型
Optional[
VoiceState
]
-
ギルド¶
-
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
¶ VoiceRegion
-- The region the guild belongs on. There is a chance that the region will be astr
if the value is not recognised by the enumerator.
-
afk_channel
¶ Optional[
VoiceChannel
] -- The channel that denotes the AFK channel. None if it doesn't exist.
-
owner_id
¶ int
-- ギルドのオーナーのID。代替としてGuild.owner
を使用してください。
bool
-- Indicates if the guild is unavailable. If this isTrue
then the reliability of other attributes outside ofGuild.id()
is slim and they might all be None. It is best to not do anything with the guild if it is unavailable.Check the
on_guild_unavailable()
andon_guild_available()
events.
Optional[
str
] -- The guild's banner.
-
mfa_level
¶ int
-- 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.
-
verification_level
¶ VerificationLevel
-- The guild's verification level.
-
explicit_content_filter
¶ ContentFilter
-- The guild's explicit content filter.
-
default_notifications
¶ NotificationLevel
-- The guild's notification settings.
-
features
¶ List[
str
] -- A list of features that the guild has. They are currently as follows:VIP_REGIONS
: Guild has VIP voice regionsVANITY_URL
: Guild has a vanity invite URL (e.g. discord.gg/discord-api)INVITE_SPLASH
: Guild's invite page has a special splash.VERIFIED
: Guild is a "verified" server.MORE_EMOJI
: Guild is allowed to have more than 50 custom emoji.
-
async-for
audit_logs
(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)¶ Return an
AsyncIterator
that enables receiving the guild's audit logs.You must have the
view_audit_log
permission to use this.例
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print('{0.user} did {0.action} to {0.target}'.format(entry))
Getting entries for a specific action:
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print('{0.user} banned {0.target}'.format(entry))
Getting entries made by a specific user:
entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send('I made {} moderation actions.'.format(len(entries)))
- パラメータ
limit (Optional[
int
]) -- The number of entries to retrieve. IfNone
retrieve all entries.before (Union[
abc.Snowflake
, datetime]) -- Retrieve entries before this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Union[
abc.Snowflake
, datetime]) -- Retrieve entries after this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time.oldest_first (
bool
) -- If set to true, return entries in oldest->newest order. Defaults to True ifafter
is specified, otherwise False.user (
abc.Snowflake
) -- The moderator to filter entries from.action (
AuditLogAction
) -- The action to filter with.
- 例外
Forbidden
-- You are not allowed to fetch audit logsHTTPException
-- An error occurred while fetching the audit logs.
- Yields
AuditLogEntry
-- The audit log entry.
-
channels
¶ List[
abc.GuildChannel
] -- A list of channels that belongs to this guild.
-
large
¶ bool
-- Indicates if the guild is a 'large' guild.A large guild is defined as having more than
large_threshold
count members, which for this library is set to the maximum of 250.
-
voice_channels
¶ List[
VoiceChannel
] -- A list of voice channels that belongs to this guild.This is sorted by the position and are in UI order from top to bottom.
-
me
¶ Similar to
Client.user
except an instance ofMember
. This is essentially used to get the member version of yourself.
-
voice_client
¶ Returns the
VoiceClient
associated with this guild, if any.
-
text_channels
¶ List[
TextChannel
] -- A list of text channels that belongs to this guild.This is sorted by the position and are in UI order from top to bottom.
-
categories
¶ List[
CategoryChannel
] -- A list of categories that belongs to this guild.This is sorted by the position and are in UI order from top to bottom.
-
by_category
()¶ Returns every
CategoryChannel
and their associated channels.These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
None
.- 戻り値
The categories and their associated channels.
- 戻り値の型
List[Tuple[Optional[
CategoryChannel
], List[abc.GuildChannel
]]]
-
get_channel
(channel_id)¶ Returns a
abc.GuildChannel
with the given ID. If not found, returns None.
-
default_role
¶ Gets the @everyone role that all members have by default.
-
icon_url
¶ Returns the URL version of the guild's icon. Returns an empty string if it has no icon.
-
icon_url_as
(*, format='webp', size=1024)¶ Returns a friendly URL version of the guild's icon. Returns an empty string if it has no icon.
The format must be one of 'webp', 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 4096.
- パラメータ
- 例外
InvalidArgument
--format
に誤った形式が渡されている、あるいはsize
に無効な値が渡されている。- 戻り値
The resulting CDN asset.
- 戻り値の型
Returns the URL version of the guild's banner. Returns an empty string if it has no banner.
Returns a friendly URL version of the guild's banner. Returns an empty string if it has no banner.
The format must be one of 'webp', 'jpeg', or 'png'. The size must be a power of 2 between 16 and 4096.
- パラメータ
- 例外
InvalidArgument
--format
に誤った形式が渡されている、あるいはsize
に無効な値が渡されている。- 戻り値
The resulting CDN asset.
- 戻り値の型
-
splash_url
¶ Returns the URL version of the guild's invite splash. Returns an empty string if it has no splash.
-
splash_url_as
(*, format='webp', size=2048)¶ Returns a friendly URL version of the guild's invite splash. Returns an empty string if it has no splash.
The format must be one of 'webp', 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 4096.
- パラメータ
- 例外
InvalidArgument
--format
に誤った形式が渡されている、あるいはsize
に無効な値が渡されている。- 戻り値
The resulting CDN asset.
- 戻り値の型
-
member_count
¶ Returns the true member count regardless of it being loaded fully or not.
-
chunked
¶ Returns a boolean indicating if the guild is "chunked".
A chunked guild means that
member_count
is equal to the number of members stored in the internalmembers
cache.If this value returns
False
, then you should request for offline members.
-
shard_id
¶ Returns the shard ID for this guild if applicable.
-
created_at
¶ Returns the guild's creation time in UTC.
-
get_member_named
(name)¶ Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. "Jake#0001" or "Jake" will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found,
None
is returned.
-
coroutine
create_category_channel
(name, *, overwrites=None, reason=None)¶ This function is a coroutine.
Same as
create_text_channel()
except makes aCategoryChannel
instead.注釈
The
category
parameter is not supported in this function since categories cannot have categories.
-
system_channel
¶ Optional[
TextChannel
] -- Returns the guild's channel used for system messages.Currently this is only for new member joins. If no channel is set, then this returns
None
.
-
coroutine
ban
(user, *, reason=None, delete_message_days=1)¶ This function is a coroutine.
Bans a user from the guild.
The user must meet the
abc.Snowflake
abc.You must have the
ban_members
permission to do this.- パラメータ
user (
abc.Snowflake
) -- The user to ban from their guild.delete_message_days (
int
) -- The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 7.reason (Optional[
str
]) -- The reason the user got banned.
- 例外
Forbidden
-- You do not have the proper permissions to ban.HTTPException
-- Banning failed.
-
coroutine
bans
()¶ This function is a coroutine.
Retrieves all the users that are banned from the guild.
This coroutine returns a
list
of BanEntry objects, which is a namedtuple with auser
field to denote theUser
that got banned along with areason
field specifying why the user was banned that could be set toNone
.You must have the
ban_members
permission to get this information.- 例外
Forbidden
-- 情報を取得するための権限がない。HTTPException
-- 情報の取得中にエラーが発生した。
- 戻り値
A list of BanEntry objects.
- 戻り値の型
List[BanEntry]
-
coroutine
create_category
(name, *, overwrites=None, reason=None)¶ This function is a coroutine.
Same as
create_text_channel()
except makes aCategoryChannel
instead.注釈
The
category
parameter is not supported in this function since categories cannot have categories.
-
coroutine
create_custom_emoji
(*, name, image, roles=None, reason=None)¶ This function is a coroutine.
Creates a custom
Emoji
for the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJI
feature which extends the limit to 200.You must have the
manage_emojis
permission to do this.- パラメータ
name (
str
) -- The emoji name. Must be at least 2 characters.image (
bytes
) -- The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.roles (Optional[List[
Role
]]) -- Alist
ofRole
s that can use this emoji. Leave empty to make it available to everyone.reason (Optional[
str
]) -- The reason for creating this emoji. Shows up on the audit log.
- 例外
Forbidden
-- You are not allowed to create emojis.HTTPException
-- An error occurred creating an emoji.
- 戻り値
The created emoji.
- 戻り値の型
-
coroutine
create_role
(*, reason=None, **fields)¶ This function is a coroutine.
Creates a
Role
for the guild.All fields are optional.
You must have the
manage_roles
permission to do this.- パラメータ
name (
str
) -- The role name. Defaults to 'new role'.permissions (
Permissions
) -- The permissions to have. Defaults to no permissions.colour (
Colour
) -- The colour for the role. Defaults toColour.default()
. This is aliased tocolor
as well.hoist (
bool
) -- Indicates if the role should be shown separately in the member list. Defaults to False.mentionable (
bool
) -- Indicates if the role should be mentionable by others. Defaults to False.reason (Optional[
str
]) -- The reason for creating this role. Shows up on the audit log.
- 例外
Forbidden
-- You do not have permissions to create the role.HTTPException
-- Creating the role failed.InvalidArgument
-- An invalid keyword argument was given.
- 戻り値
The newly created role.
- 戻り値の型
-
coroutine
create_text_channel
(name, *, overwrites=None, category=None, reason=None, **options)¶ This function is a coroutine.
Creates a
TextChannel
for the guild.Note that you need the
manage_channels
permission to create the channel.The
overwrites
parameter can be used to create a 'secret' channel upon creation. This parameter expects adict
of overwrites with the target (either aMember
or aRole
) as the key and aPermissionOverwrite
as the value.注釈
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()
will be required to update the position of the channel in the channel list.例
Creating a basic channel:
channel = await guild.create_text_channel('cool-channel')
Creating a "secret" channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True) } channel = await guild.create_text_channel('secret', overwrites=overwrites)
- パラメータ
name (
str
) -- The channel's name.overwrites -- A
dict
of target (either a role or a member) toPermissionOverwrite
to apply upon creation of a channel. Useful for creating secret channels.category (Optional[
CategoryChannel
]) -- The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int
) -- The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (Optional[
str
]) -- The new channel's topic.slowmode_delay (
int
) -- Specifies the slowmode rate limit for user in this channel. The maximum value possible is 120.nsfw (
bool
) -- To mark the channel as NSFW or not.reason (Optional[
str
]) -- The reason for creating this channel. Shows up on the audit log.
- 例外
Forbidden
-- You do not have the proper permissions to create this channel.HTTPException
-- Creating the channel failed.InvalidArgument
-- The permission overwrite information is not in proper form.
- 戻り値
The channel that was just created.
- 戻り値の型
-
coroutine
create_voice_channel
(name, *, overwrites=None, category=None, reason=None, **options)¶ This function is a coroutine.
This is similar to
create_text_channel()
except makes aVoiceChannel
instead, in addition to having the following new parameters.
-
coroutine
delete
()¶ This function is a coroutine.
Deletes the guild. You must be the guild owner to delete the guild.
- 例外
HTTPException
-- Deleting the guild failed.Forbidden
-- You do not have permissions to delete the guild.
-
coroutine
edit
(*, reason=None, **fields)¶ This function is a coroutine.
Edits the guild.
You must have the
manage_guild
permission to edit the guild.- パラメータ
name (
str
) -- The new name of the guild.description (
str
) -- The new description of the guild. This is only available to guilds that contain VERIFIED inGuild.features
.icon (
bytes
) -- A bytes-like object representing the icon. Only PNG/JPEG supported. Could beNone
to denote removal of the icon.banner (
bytes
) -- A bytes-like object representing the banner. Could beNone
to denote removal of the banner.splash (
bytes
) -- A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could beNone
to denote removing the splash. Only available for partnered guilds withINVITE_SPLASH
feature.region (
VoiceRegion
) -- The new region for the guild's voice communication.afk_channel (Optional[
VoiceChannel
]) -- The new channel that is the AFK channel. Could beNone
for no AFK channel.afk_timeout (
int
) -- The number of seconds until someone is moved to the AFK channel.owner (
Member
) -- The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this.verification_level (
VerificationLevel
) -- The new verification level for the guild.default_notifications (
NotificationLevel
) -- The new default notification level for the guild.explicit_content_filter (
ContentFilter
) -- The new explicit content filter for the guild.vanity_code (
str
) -- The new vanity code for the guild.system_channel (Optional[
TextChannel
]) -- The new channel that is used for the system channel. Could beNone
for no system channel.reason (Optional[
str
]) -- The reason for editing this guild. Shows up on the audit log.
- 例外
Forbidden
-- You do not have permissions to edit the guild.HTTPException
-- Editing the guild failed.InvalidArgument
-- The image format passed in toicon
is invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.
-
coroutine
estimate_pruned_members
(*, days)¶ This function is a coroutine.
Similar to
prune_members()
except instead of actually pruning members, it returns how many members it would prune from the guild had it been called.- パラメータ
days (
int
) -- The number of days before counting as inactive.- 例外
Forbidden
-- You do not have permissions to prune members.HTTPException
-- An error occurred while fetching the prune members estimate.InvalidArgument
-- An integer was not passed fordays
.
- 戻り値
The number of members estimated to be pruned.
- 戻り値の型
-
coroutine
fetch_ban
(user)¶ This function is a coroutine.
Retrieves the
BanEntry
for a user, which is a namedtuple with auser
andreason
field. Seebans()
for more information.You must have the
ban_members
permission to get this information.- パラメータ
user (
abc.Snowflake
) -- The user to get ban information from.- 例外
Forbidden
-- 情報を取得するための権限がない。NotFound
-- This user is not banned.HTTPException
-- 情報の取得中にエラーが発生した。
- 戻り値
The BanEntry object for the specified user.
- 戻り値の型
BanEntry
-
coroutine
fetch_emoji
(emoji_id)¶ This function is a coroutine.
Retrieves a custom
Emoji
from the guild.- パラメータ
emoji_id (
int
) -- The emoji's ID.- 例外
NotFound
-- The emoji requested could not be found.HTTPException
-- An error occurred fetching the emoji.
- 戻り値
The retrieved emoji.
- 戻り値の型
-
coroutine
fetch_emojis
()¶ This function is a coroutine.
Retrieves all custom
Emoji
s from the guild.- 例外
HTTPException
-- An error occurred fetching the emojis.- 戻り値
The retrieved emojis.
- 戻り値の型
List[
Emoji
]
-
coroutine
fetch_member
(member_id)¶ This function is a coroutine.
Retreives a
Member
from a guild ID, and a member ID.- パラメータ
member_id (
int
) -- The member's ID to fetch from.- 例外
Forbidden
-- You do not have access to the guild.HTTPException
-- Getting the guild failed.
- 戻り値
The member from the member ID.
- 戻り値の型
-
coroutine
invites
()¶ This function is a coroutine.
Returns a list of all active instant invites from the guild.
You must have the
manage_guild
permission to get this information.- 例外
Forbidden
-- 情報を取得するための権限がない。HTTPException
-- 情報の取得中にエラーが発生した。
- 戻り値
The list of invites that are currently active.
- 戻り値の型
List[
Invite
]
-
coroutine
kick
(user, *, reason=None)¶ This function is a coroutine.
Kicks a user from the guild.
The user must meet the
abc.Snowflake
abc.You must have the
kick_members
permission to do this.- パラメータ
user (
abc.Snowflake
) -- The user to kick from their guild.reason (Optional[
str
]) -- The reason the user got kicked.
- 例外
Forbidden
-- You do not have the proper permissions to kick.HTTPException
-- Kicking failed.
-
coroutine
leave
()¶ This function is a coroutine.
Leaves the guild.
注釈
You cannot leave the guild that you own, you must delete it instead via
delete()
.- 例外
HTTPException
-- Leaving the guild failed.
-
coroutine
prune_members
(*, days, reason=None)¶ This function is a coroutine.
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
days
number of days and they have no roles.You must have the
kick_members
permission to use this.To check how many members you would prune without actually pruning, see the
estimate_pruned_members()
function.- パラメータ
- 例外
Forbidden
-- You do not have permissions to prune members.HTTPException
-- An error occurred while pruning members.InvalidArgument
-- An integer was not passed fordays
.
- 戻り値
The number of members pruned.
- 戻り値の型
-
coroutine
unban
(user, *, reason=None)¶ This function is a coroutine.
Unbans a user from the guild.
The user must meet the
abc.Snowflake
abc.You must have the
ban_members
permission to do this.- パラメータ
user (
abc.Snowflake
) -- The user to unban.reason (Optional[
str
]) -- The reason for doing this action. Shows up on the audit log.
- 例外
Forbidden
-- You do not have the proper permissions to unban.HTTPException
-- Unbanning failed.
-
coroutine
vanity_invite
()¶ This function is a coroutine.
Returns the guild's special vanity invite.
The guild must be partnered, i.e. have 'VANITY_URL' in
features
.You must have the
manage_guild
permission to use this as well.- 例外
Forbidden
-- You do not have the proper permissions to get this.HTTPException
-- Retrieving the vanity invite failed.
- 戻り値
The special vanity invite.
- 戻り値の型
-
coroutine
webhooks
()¶ This function is a coroutine.
Gets the list of webhooks from this guild.
Requires
manage_webhooks
permissions.
-
coroutine
widget
()¶ This function is a coroutine.
Returns the widget of the guild.
注釈
The guild must have the widget enabled to get this information.
- 例外
Forbidden
-- The widget for this guild is disabled.HTTPException
-- Retrieving the widget failed.
- 戻り値
The guild's widget.
- 戻り値の型
-
roles
¶ Returns a
list
of the guild's roles in hierarchy order.The first element of this list will be the lowest role in the hierarchy.
-
ack
()¶ This function is a coroutine.
Marks every message in this guild as read.
The user must not be a bot user.
- 例外
HTTPException
-- Acking failed.ClientException
-- You must not be a bot user.
-
メンバー¶
-
class
discord.
Member
¶ Represents a Discord member to a
Guild
.This implements a lot of the functionality of
User
.-
x == y
Checks if two members are equal. Note that this works with
User
instances too.
-
x != y
Checks if two members are not equal. Note that this works with
User
instances too.
-
hash(x)
Returns the member's hash.
-
str(x)
Returns the member's name with the discriminator.
-
joined_at
¶ Optional[
datetime.datetime
] -- A datetime object that specifies the date and time in UTC that the member joined the guild for the first time. In certain cases, this can beNone
.
-
activities
¶ Tuple[Union[
Game
,Streaming
,Spotify
,Activity
]] -- The activities that the user is currently doing.
-
async-for
history
(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ Return an
AsyncIterator
that enables receiving the destination's message history.これを行うためには、そのチャンネルの
read_message_history
権限が必要です。例
Usage
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...
All parameters are optional.
- パラメータ
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 (
Message
ordatetime.datetime
) -- Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (
Message
ordatetime.datetime
) -- Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (
Message
ordatetime.datetime
) -- Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) -- If set to true, return messages in oldest->newest order. Defaults to True ifafter
is specified, otherwise False.
- 例外
Forbidden
-- You do not have permissions to get channel message history.HTTPException
-- The request to get message history failed.
- Yields
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!')
-
status
¶ Status
-- The member's overall status. If the value is unknown, then it will be astr
instead.
-
colour
¶ A property that returns a
Colour
denoting the rendered colour for the member. If the default colour is the one rendered then an instance ofColour.default()
is returned.これには別名のプロパティがあります。
-
color
¶ A property that returns a
Colour
denoting the rendered colour for the member. If the default colour is the one rendered then an instance ofColour.default()
is returned.これには別名のプロパティがあります。
-
mention
¶ Returns a string that mentions the member.
-
display_name
¶ Returns the user's display name.
通常であれば、これはユーザー名がそのまま返りますが、ギルドにてニックネームを設定している場合は、代替としてニックネームが返ります。
-
activity
¶ Returns a class Union[
Game
,Streaming
,Spotify
,Activity
] for the primary activity the user is currently doing. Could be None if no activity is being done.注釈
A user may have multiple activities, these can be accessed under
activities
.
-
mentioned_in
(message)¶ Checks if the member is mentioned in the specified message.
- パラメータ
message (
Message
) -- メンションが含まれているかを確認するメッセージ。
-
permissions_in
(channel)¶ abc.GuildChannel.permissions_for()
のエイリアス。基本的には以下と同等です:
channel.permissions_for(self)
- パラメータ
channel (
Channel
) -- 権限を確認したいチャンネル。
-
top_role
¶ Returns the member's highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
-
guild_permissions
¶ Returns the member's guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use either
permissions_in()
orabc.GuildChannel.permissions_for()
.This does take into consideration guild ownership and the administrator implication.
-
voice
¶ Optional[
VoiceState
] -- Returns the member's current voice state.
-
coroutine
add_roles
(*roles, reason=None, atomic=True)¶ This function is a coroutine.
Gives the member a number of
Role
s.You must have the
manage_roles
permission to use this.- パラメータ
*roles (
Snowflake
) -- An argument list ofabc.Snowflake
representing aRole
to give to the member.reason (Optional[
str
]) -- The reason for adding these roles. Shows up on the audit log.atomic (bool) -- Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- 例外
Forbidden
-- You do not have permissions to add these roles.HTTPException
-- Adding roles failed.
-
avatar
¶ Equivalent to
User.avatar
-
avatar_url
¶ Equivalent to
User.avatar_url
-
avatar_url_as
(*args, **kwargs)¶ ユーザーのアバターのURLを返します。
ユーザーがアバターを設定していない場合、デフォルトのアバターのURLが返ります。
フォーマットは「webp」「jpeg」「jpg」「png」または「gif」である必要があり、「gif」はアニメーションアバターにのみ使用可能です。サイズは2の累乗値かつ16以上1024以下である必要があります。
- パラメータ
- 例外
InvalidArgument
--format
またはstatic_format
が正しくない、あるいはsize
に無効な値が渡された。- 戻り値
The resulting CDN asset.
- 戻り値の型
-
coroutine
ban
(**kwargs)¶ This function is a coroutine.
Bans this member. Equivalent to
Guild.ban()
-
block
(*args, **kwargs)¶ This function is a coroutine.
ユーザーをブロックします。
- 例外
Forbidden
-- このユーザーをブロックすることが認められていない。HTTPException
-- ユーザーのブロックに失敗した。
-
create_dm
(*args, **kwargs)¶ このユーザーと
DMChannel
を作ります。This should be rarely called, as this is done transparently for most people.
-
created_at
¶ Equivalent to
User.created_at
-
default_avatar
¶ Equivalent to
User.default_avatar
-
default_avatar_url
¶ Equivalent to
User.default_avatar_url
-
discriminator
¶ Equivalent to
User.discriminator
-
dm_channel
¶ Equivalent to
User.dm_channel
-
coroutine
edit
(*, reason=None, **fields)¶ This function is a coroutine.
Edits the member's data.
Depending on the parameter passed, this requires different permissions listed below:
Parameter
Permission
nick
mute
deafen
roles
voice_channel
All parameters are optional.
- パラメータ
nick (Optional[
str
]) -- The member's new nickname. UseNone
to remove the nickname.mute (Optional[
bool
]) -- Indicates if the member should be guild muted or un-muted.deafen (Optional[
bool
]) -- Indicates if the member should be guild deafened or un-deafened.roles (Optional[List[
Roles
]]) -- The member's new list of roles. This replaces the roles.voice_channel (Optional[
VoiceChannel
]) -- The voice channel to move the member to.reason (Optional[
str
]) -- The reason for editing this member. Shows up on the audit log.
- 例外
Forbidden
-- You do not have the proper permissions to the action requested.HTTPException
-- The operation failed.
-
coroutine
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.
- 戻り値の型
-
coroutine
kick
(*, reason=None)¶ This function is a coroutine.
Kicks this member. Equivalent to
Guild.kick()
-
coroutine
move_to
(channel, *, reason=None)¶ This function is a coroutine.
Moves a member to a new voice channel (they must be connected first).
You must have the
move_members
permission to use this.This raises the same exceptions as
edit()
.- パラメータ
channel (
VoiceChannel
) -- The new voice channel to move the member to.reason (Optional[
str
]) -- The reason for doing this action. Shows up on the audit log.
-
mutual_friends
(*args, **kwargs)¶ This function is a coroutine.
Gets all mutual friends of this user. This can only be used by non-bot accounts
- 例外
Forbidden
-- Not allowed to get mutual friends of this user.HTTPException
-- Getting mutual friends failed.
- 戻り値
The users that are mutual friends.
- 戻り値の型
List[
User
]
-
coroutine
pins
()¶ This function is a coroutine.
Returns a
list
ofMessage
that are currently pinned.- 例外
HTTPException
-- Retrieving the pinned messages failed.
-
profile
(*args, **kwargs)¶ This function is a coroutine.
Gets the user's profile. This can only be used by non-bot accounts.
- 例外
Forbidden
-- プロフィールを取得することが許可されていない。HTTPException
-- プロフィールの取得に失敗した。
- 戻り値
ユーザーのプロフィール。
- 戻り値の型
-
relationship
¶ Equivalent to
User.relationship
-
remove_friend
(*args, **kwargs)¶ This function is a coroutine.
Removes the user as a friend.
- 例外
Forbidden
-- Not allowed to remove this user as a friend.HTTPException
-- Removing the user as a friend failed.
-
coroutine
remove_roles
(*roles, reason=None, atomic=True)¶ This function is a coroutine.
Removes
Role
s from this member.You must have the
manage_roles
permission to use this.- パラメータ
*roles (
Snowflake
) -- An argument list ofabc.Snowflake
representing aRole
to remove from the member.reason (Optional[
str
]) -- The reason for removing these roles. Shows up on the audit log.atomic (
bool
) -- Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- 例外
Forbidden
-- You do not have permissions to remove these roles.HTTPException
-- Removing the roles failed.
-
roles
¶ A
list
ofRole
that the member belongs to. Note that the first element of this list is always the default '@everyone' role.These roles are sorted by their position in the role hierarchy.
-
coroutine
send
(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None)¶ This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set 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 -- 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.
- 例外
HTTPException
-- Sending the message failed.Forbidden
-- You do not have the proper permissions to send the message.InvalidArgument
-- Thefiles
list is not of the appropriate size or you specified bothfile
andfiles
.
- 戻り値
The message that was sent.
- 戻り値の型
-
send_friend_request
(*args, **kwargs)¶ This function is a coroutine.
Sends the user a friend request.
- 例外
Forbidden
-- Not allowed to send a friend request to the user.HTTPException
-- Sending the friend request failed.
-
coroutine
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.
-
coroutine
unban
(*, reason=None)¶ This function is a coroutine.
Unbans this member. Equivalent to
Guild.unban()
-
unblock
(*args, **kwargs)¶ This function is a coroutine.
Unblocks the user.
- 例外
Forbidden
-- Not allowed to unblock this user.HTTPException
-- Unblocking the user failed.
-
Spotify¶
-
class
discord.
Spotify
¶ Represents a Spotify listening activity from Discord. This is a special case of
Activity
that makes it easier to work with the Spotify integration.-
x == y
Checks if two activities are equal.
-
x != y
Checks if two activities are not equal.
-
hash(x)
Returns the activity's hash.
-
str(x)
Returns the string 'Spotify'.
-
type
¶ Returns the activity's type. This is for compatibility with
Activity
.It always returns
ActivityType.listening
.
-
colour
¶ Returns the Spotify integration colour, as a
Colour
.There is an alias for this named
color()
-
color
¶ Returns the Spotify integration colour, as a
Colour
.There is an alias for this named
colour()
-
artist
¶ str
-- The artist of the song being played.This does not attempt to split the artist information into multiple artists. Useful if there's only a single artist.
-
start
¶ datetime.datetime
-- When the user started playing this song in UTC.
-
end
¶ datetime.datetime
-- When the user will stop playing this song in UTC.
-
duration
¶ datetime.timedelta
-- The duration of the song being played.
-
ボイスステート¶
-
class
discord.
VoiceState
¶ Represents a Discord user's voice state.
-
channel
¶ VoiceChannel
-- The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.
-
絵文字¶
-
class
discord.
Emoji
¶ Represents a custom emoji.
Depending on the way this object was created, some of the attributes can have a value of
None
.-
x == y
Checks if two emoji are the same.
-
x != y
Checks if two emoji are not the same.
-
hash(x)
Return the emoji's hash.
-
iter(x)
Returns an iterator of
(field, value)
pairs. This allows this class to be used as an iterable in list/dict/etc constructions.
-
str(x)
Returns the emoji rendered for discord.
-
require_colons
¶ bool
-- If colons are required to use this emoji in the client (:PJSalt: vs PJSalt).
-
user
¶ Optional[
User
] -- The user that created the emoji. This can only be retrieved usingGuild.fetch_emoji()
.
-
created_at
¶ Returns the emoji's creation time in UTC.
-
url
¶ Returns a URL version of the emoji.
-
coroutine
delete
(*, reason=None)¶ This function is a coroutine.
Deletes the custom emoji.
You must have
manage_emojis
permission to do this.- パラメータ
reason (Optional[
str
]) -- The reason for deleting this emoji. Shows up on the audit log.- 例外
Forbidden
-- You are not allowed to delete emojis.HTTPException
-- An error occurred deleting the emoji.
-
coroutine
edit
(*, name, roles=None, reason=None)¶ This function is a coroutine.
カスタム絵文字を編集します。
You must have
manage_emojis
permission to do this.- パラメータ
- 例外
Forbidden
-- You are not allowed to edit emojis.HTTPException
-- An error occurred editing the emoji.
-
PartialEmoji¶
-
class
discord.
PartialEmoji
¶ Represents a "partial" emoji.
This model will be given in two scenarios:
"Raw" data events such as
on_raw_reaction_add()
Custom emoji that the bot cannot see from e.g.
Message.reactions
-
x == y
Checks if two emoji are the same.
-
x != y
Checks if two emoji are not the same.
-
hash(x)
Return the emoji's hash.
-
str(x)
Returns the emoji rendered for discord.
-
name
¶ str
-- The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji.
-
is_custom_emoji
()¶ Checks if this is a custom non-Unicode emoji.
-
is_unicode_emoji
()¶ Checks if this is a Unicode emoji.
役職¶
-
class
discord.
Role
¶ Represents a Discord role in a
Guild
.-
x == y
Checks if two roles are equal.
-
x != y
Checks if two roles are not equal.
-
x > y
Checks if a role is higher than another in the hierarchy.
-
x < y
Checks if a role is lower than another in the hierarchy.
-
x >= y
Checks if a role is higher or equal to another in the hierarchy.
-
x <= y
Checks if a role is lower or equal to another in the hierarchy.
-
hash(x)
役職のハッシュを返します。
-
str(x)
役職の名前を返します。
-
permissions
¶ Permissions
-- 役職の権限を表します。
-
position
¶ int
-- The position of the role. This number is usually positive. The bottom role has a position of 0.
-
managed
¶ bool
-- Indicates if the role is managed by the guild through some form of integrations such as Twitch.
-
is_default
()¶ Checks if the role is the default role.
-
created_at
¶ Returns the role's creation time in UTC.
-
mention
¶ Returns a string that allows you to mention a role.
-
coroutine
delete
(*, reason=None)¶ This function is a coroutine.
Deletes the role.
You must have the
manage_roles
permission to use this.- パラメータ
reason (Optional[
str
]) -- The reason for deleting this role. Shows up on the audit log.- 例外
Forbidden
-- You do not have permissions to delete the role.HTTPException
-- Deleting the role failed.
-
coroutine
edit
(*, reason=None, **fields)¶ This function is a coroutine.
Edits the role.
You must have the
manage_roles
permission to use this.All fields are optional.
- パラメータ
name (
str
) -- The new role name to change to.permissions (
Permissions
) -- The new permissions to change to.colour (
Colour
) -- The new colour to change to. (aliased to color as well)hoist (
bool
) -- Indicates if the role should be shown separately in the member list.mentionable (
bool
) -- Indicates if the role should be mentionable by others.position (
int
) -- The new role's position. This must be below your top role's position or it will fail.reason (Optional[
str
]) -- The reason for editing this role. Shows up on the audit log.
- 例外
Forbidden
-- You do not have permissions to change the role.HTTPException
-- Editing the role failed.InvalidArgument
-- An invalid position was given or the default role was asked to be moved.
-
テキストチャンネル¶
-
class
discord.
TextChannel
¶ Represents a Discord guild text channel.
-
x == y
Checks if two channels are equal.
-
x != y
Checks if two channels are not equal.
-
hash(x)
Returns the channel's hash.
-
str(x)
Returns the channel's name.
-
position
¶ int
-- The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
-
last_message_id
¶ Optional[
int
] -- The last message ID of the message sent to this channel. It may not point to an existing or valid message.
-
slowmode_delay
¶ int
-- The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots and users withmanage_channels
ormanage_messages
bypass slowmode.
-
async-for
history
(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ Return an
AsyncIterator
that enables receiving the destination's message history.これを行うためには、そのチャンネルの
read_message_history
権限が必要です。例
Usage
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...
All parameters are optional.
- パラメータ
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 (
Message
ordatetime.datetime
) -- Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (
Message
ordatetime.datetime
) -- Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (
Message
ordatetime.datetime
) -- Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) -- If set to true, return messages in oldest->newest order. Defaults to True ifafter
is specified, otherwise False.
- 例外
Forbidden
-- You do not have permissions to get channel message history.HTTPException
-- The request to get message history failed.
- Yields
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!')
-
permissions_for
(member)¶ Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- パラメータ
member (
Member
) -- The member to resolve permissions for.- 戻り値
The resolved permissions for the member.
- 戻り値の型
-
is_nsfw
()¶ Checks if the channel is NSFW.
-
is_news
()¶ Checks if the channel is a news channel.
-
last_message
¶ Fetches the last message from this channel in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()
orfetch_message()
with thelast_message_id
attribute.- 戻り値
The last message in this channel or
None
if not found.- 戻り値の型
Optional[
Message
]
-
category
¶ Optional[
CategoryChannel
] -- The category this channel belongs to.If there is no category then this is
None
.
-
changed_roles
¶ Returns a
list
ofRoles
that have been overridden from their default values in theGuild.roles
attribute.
-
coroutine
create_invite
(*, reason=None, **fields)¶ This function is a coroutine.
Creates an instant invite.
You must have
create_instant_invite
permission to do this.- パラメータ
max_age (
int
) -- How long the invite should last. If it's 0 then the invite doesn't expire. Defaults to 0.max_uses (
int
) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to 0.temporary (
bool
) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.unique (
bool
) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.reason (Optional[
str
]) -- The reason for creating this invite. Shows up on the audit log.
- 例外
HTTPException
-- 招待の作成に失敗した。- 戻り値
The invite that was created.
- 戻り値の型
-
coroutine
create_webhook
(*, name, avatar=None)¶ This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhooks
permissions.- パラメータ
name (
str
) -- The webhook's name.avatar (Optional[
bytes
]) -- A bytes-like object representing the webhook's default avatar. This operates similarly toedit()
.
- 例外
HTTPException
-- Creating the webhook failed.Forbidden
-- You do not have permissions to create a webhook.
- 戻り値
The created webhook.
- 戻り値の型
-
created_at
¶ Returns the channel's creation time in UTC.
-
coroutine
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
-- チャンネルを削除するための権限がない。NotFound
-- チャンネルが見つからなかった、あるいは既に削除されている。HTTPException
-- チャンネルの削除に失敗した。
-
coroutine
delete_messages
(messages)¶ This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()
except it bulk deletes multiple messages.As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it's more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the
manage_messages
permission to use this.Usable only by bot accounts.
- パラメータ
messages (Iterable[
abc.Snowflake
]) -- An iterable of messages denoting which ones to bulk delete.- 例外
ClientException
-- The number of messages to delete was more than 100.Forbidden
-- You do not have proper permissions to delete the messages or you're not using a bot account.HTTPException
-- Deleting the messages failed.
-
coroutine
edit
(*, reason=None, **options)¶ This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.- パラメータ
name (
str
) -- The new channel name.topic (
str
) -- The new channel's topic.position (
int
) -- The new channel's position.nsfw (
bool
) -- To mark the channel as NSFW or not.sync_permissions (
bool
) -- Whether to sync permissions with the channel's new or pre-existing category. Defaults toFalse
.category (Optional[
CategoryChannel
]) -- The new category for this channel. Can beNone
to remove the category.slowmode_delay (
int
) -- Specifies the slowmode rate limit for user in this channel. A value of 0 disables slowmode. The maximum value possible is 120.reason (Optional[
str
]) -- The reason for editing this channel. Shows up on the audit log.
- 例外
InvalidArgument
-- positionが0より小さい、またはチャンネル数より大きい。Forbidden
-- チャンネルの編集に必要な権限がない。HTTPException
-- チャンネルの編集に失敗した。
-
coroutine
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.
- 戻り値の型
-
coroutine
invites
()¶ This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_guild
to get this information.- 例外
Forbidden
-- 情報を取得するための権限がない。HTTPException
-- 情報の取得中にエラーが発生した。
- 戻り値
The list of invites that are currently active.
- 戻り値の型
List[
Invite
]
-
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 key is the overwrite as aPermissionOverwrite
.- 戻り値
The channel's permission overwrites.
- 戻り値の型
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
-
overwrites_for
(obj)¶ Returns the channel-specific overwrites for a member or a role.
-
coroutine
pins
()¶ This function is a coroutine.
Returns a
list
ofMessage
that are currently pinned.- 例外
HTTPException
-- Retrieving the pinned messages failed.
-
coroutine
purge
(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)¶ This function is a coroutine.
check
に渡された基準を満たすメッセージを削除します。もし、check
に何も渡されなかった場合には、全てのメッセージが削除されます。メッセージを削除する場合、それが自分のものであったとしても、削除するには(ユーザーアカウントでない限り)
manage_messages
の権限が必要です。メッセージの履歴を取得するためにはread_message_history
も必要になります。内部的には、一括削除が可能かどうか、アカウントがユーザーボットかどうかなど、満たされる条件に応じて異なる数の方法で実行します。
例
Deleting bot's messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send('Deleted {} message(s)'.format(len(deleted)))
- パラメータ
limit (Optional[
int
]) -- The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (predicate) -- The function used to check if a message should be deleted. It must take a
Message
as its sole parameter.before --
history()
でのbefore
と同じです。after --
history()
でのafter
と同じです。around --
history()
でのaround
と同じです。oldest_first --
history()
でのoldest_first
と同じです。bulk (class:bool) -- If True, use bulk delete. bulk=False is useful for mass-deleting a bot's own messages without manage_messages. When True, will fall back to single delete if current account is a user bot, or if messages are older than two weeks.
- 例外
Forbidden
-- You do not have proper permissions to do the actions required.HTTPException
-- Purging the messages failed.
- 戻り値
The list of messages that were deleted.
- 戻り値の型
List[
Message
]
-
coroutine
send
(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None)¶ This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set 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 -- 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.
- 例外
HTTPException
-- Sending the message failed.Forbidden
-- You do not have the proper permissions to send the message.InvalidArgument
-- Thefiles
list is not of the appropriate size or you specified bothfile
andfiles
.
- 戻り値
The message that was sent.
- 戻り値の型
-
coroutine
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 = PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- パラメータ
overwrite (
PermissionOverwrite
) -- The permissions to allow and deny to the target.**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
-- チャンネルの権限を編集するための権限がない。HTTPException
-- チャンネルの権限の編集に失敗した。NotFound
-- 編集中の役職、あるいはメンバーがギルドの一部でない。InvalidArgument
-- overwriteパラメータが無効であるか、targetの型がRole
とMember
のどちらかでない。
-
coroutine
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.
-
coroutine
webhooks
()¶ This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhooks
permissions.
-
ボイスチャンネル¶
-
class
discord.
VoiceChannel
¶ Discordサーバーのボイスチャンネルを表します。
-
x == y
Checks if two channels are equal.
-
x != y
Checks if two channels are not equal.
-
hash(x)
Returns the channel's hash.
-
str(x)
Returns the channel's name.
-
position
¶ int
-- The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
-
permissions_for
(member)¶ Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- パラメータ
member (
Member
) -- The member to resolve permissions for.- 戻り値
The resolved permissions for the member.
- 戻り値の型
-
category
¶ Optional[
CategoryChannel
] -- The category this channel belongs to.If there is no category then this is
None
.
-
changed_roles
¶ Returns a
list
ofRoles
that have been overridden from their default values in theGuild.roles
attribute.
-
coroutine
connect
(*, timeout=60.0, reconnect=True)¶ This function is a coroutine.
Connects to voice and creates a
VoiceClient
to establish your connection to the voice server.- パラメータ
- 例外
asyncio.TimeoutError
-- Could not connect to the voice channel in time.ClientException
-- You are already connected to a voice channel.OpusNotLoaded
-- The opus library has not been loaded.
- 戻り値
A voice client that is fully connected to the voice server.
- 戻り値の型
-
coroutine
create_invite
(*, reason=None, **fields)¶ This function is a coroutine.
Creates an instant invite.
You must have
create_instant_invite
permission to do this.- パラメータ
max_age (
int
) -- How long the invite should last. If it's 0 then the invite doesn't expire. Defaults to 0.max_uses (
int
) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to 0.temporary (
bool
) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.unique (
bool
) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.reason (Optional[
str
]) -- The reason for creating this invite. Shows up on the audit log.
- 例外
HTTPException
-- 招待の作成に失敗した。- 戻り値
The invite that was created.
- 戻り値の型
-
created_at
¶ Returns the channel's creation time in UTC.
-
coroutine
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
-- チャンネルを削除するための権限がない。NotFound
-- チャンネルが見つからなかった、あるいは既に削除されている。HTTPException
-- チャンネルの削除に失敗した。
-
coroutine
edit
(*, reason=None, **options)¶ This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.- パラメータ
name (
str
) -- チャンネルの名前。bitrate (
int
) -- チャンネルのビットレート。user_limit (
int
) -- チャンネルのユーザー人数制限。position (
int
) -- The new channel's position.sync_permissions (
bool
) -- Whether to sync permissions with the channel's new or pre-existing category. Defaults toFalse
.category (Optional[
CategoryChannel
]) -- The new category for this channel. Can beNone
to remove the category.reason (Optional[
str
]) -- The reason for editing this channel. Shows up on the audit log.
- 例外
Forbidden
-- チャンネルの編集に必要な権限がない。HTTPException
-- チャンネルの編集に失敗した。
-
coroutine
invites
()¶ This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_guild
to get this information.- 例外
Forbidden
-- 情報を取得するための権限がない。HTTPException
-- 情報の取得中にエラーが発生した。
- 戻り値
The list of invites that are currently active.
- 戻り値の型
List[
Invite
]
-
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 key is the overwrite as aPermissionOverwrite
.- 戻り値
The channel's permission overwrites.
- 戻り値の型
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
-
overwrites_for
(obj)¶ Returns the channel-specific overwrites for a member or a role.
-
coroutine
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 = PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- パラメータ
overwrite (
PermissionOverwrite
) -- The permissions to allow and deny to the target.**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
-- チャンネルの権限を編集するための権限がない。HTTPException
-- チャンネルの権限の編集に失敗した。NotFound
-- 編集中の役職、あるいはメンバーがギルドの一部でない。InvalidArgument
-- overwriteパラメータが無効であるか、targetの型がRole
とMember
のどちらかでない。
-
カテゴリチャンネル¶
-
class
discord.
CategoryChannel
¶ Discordのチャンネルカテゴリを表します。
These are useful to group channels to logical compartments.
-
x == y
Checks if two channels are equal.
-
x != y
Checks if two channels are not equal.
-
hash(x)
カテゴリのハッシュを返します。
-
str(x)
カテゴリの名前を返します。
-
position
¶ int
-- The position in the category list. This is a number that starts at 0. e.g. the top category is position 0.
-
is_nsfw
()¶ カテゴリがNSFWであるかを返します。
-
channels
¶ List[
abc.GuildChannel
] -- Returns the channels that are under this category.These are sorted by the official Discord UI, which places voice channels below the text channels.
-
text_channels
¶ List[
TextChannel
] -- Returns the text channels that are under this category.
-
voice_channels
¶ List[
VoiceChannel
] -- Returns the voice channels that are under this category.
-
category
¶ Optional[
CategoryChannel
] -- The category this channel belongs to.If there is no category then this is
None
.
-
changed_roles
¶ Returns a
list
ofRoles
that have been overridden from their default values in theGuild.roles
attribute.
-
coroutine
create_invite
(*, reason=None, **fields)¶ This function is a coroutine.
Creates an instant invite.
You must have
create_instant_invite
permission to do this.- パラメータ
max_age (
int
) -- How long the invite should last. If it's 0 then the invite doesn't expire. Defaults to 0.max_uses (
int
) -- How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to 0.temporary (
bool
) -- Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.unique (
bool
) -- Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.reason (Optional[
str
]) -- The reason for creating this invite. Shows up on the audit log.
- 例外
HTTPException
-- 招待の作成に失敗した。- 戻り値
The invite that was created.
- 戻り値の型
-
coroutine
create_text_channel
(name, *, overwrites=None, reason=None, **options)¶ This function is a coroutine.
A shortcut method to
Guild.create_text_channel()
to create aTextChannel
in the category.
-
coroutine
create_voice_channel
(name, *, overwrites=None, reason=None, **options)¶ This function is a coroutine.
A shortcut method to
Guild.create_voice_channel()
to create aVoiceChannel
in the category.
-
created_at
¶ Returns the channel's creation time in UTC.
-
coroutine
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
-- チャンネルを削除するための権限がない。NotFound
-- チャンネルが見つからなかった、あるいは既に削除されている。HTTPException
-- チャンネルの削除に失敗した。
-
coroutine
edit
(*, reason=None, **options)¶ This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.- パラメータ
- 例外
InvalidArgument
-- If position is less than 0 or greater than the number of categories.Forbidden
-- カテゴリの編集に必要な権限を持っていない。HTTPException
-- カテゴリの編集に失敗した。
-
coroutine
invites
()¶ This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_guild
to get this information.- 例外
Forbidden
-- 情報を取得するための権限がない。HTTPException
-- 情報の取得中にエラーが発生した。
- 戻り値
The list of invites that are currently active.
- 戻り値の型
List[
Invite
]
-
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 key is the overwrite as aPermissionOverwrite
.- 戻り値
The channel's permission overwrites.
- 戻り値の型
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
-
overwrites_for
(obj)¶ Returns the channel-specific overwrites for a member or a role.
-
permissions_for
(member)¶ Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- パラメータ
member (
Member
) -- The member to resolve permissions for.- 戻り値
The resolved permissions for the member.
- 戻り値の型
-
coroutine
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 = PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- パラメータ
overwrite (
PermissionOverwrite
) -- The permissions to allow and deny to the target.**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
-- チャンネルの権限を編集するための権限がない。HTTPException
-- チャンネルの権限の編集に失敗した。NotFound
-- 編集中の役職、あるいはメンバーがギルドの一部でない。InvalidArgument
-- overwriteパラメータが無効であるか、targetの型がRole
とMember
のどちらかでない。
-
DMチャンネル¶
-
class
discord.
DMChannel
¶ Represents a Discord direct message channel.
-
x == y
Checks if two channels are equal.
-
x != y
Checks if two channels are not equal.
-
hash(x)
Returns the channel's hash.
-
str(x)
Returns a string representation of the channel
-
me
¶ ClientUser
-- The user presenting yourself.
-
async-for
history
(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ Return an
AsyncIterator
that enables receiving the destination's message history.これを行うためには、そのチャンネルの
read_message_history
権限が必要です。例
Usage
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...
All parameters are optional.
- パラメータ
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 (
Message
ordatetime.datetime
) -- Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (
Message
ordatetime.datetime
) -- Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (
Message
ordatetime.datetime
) -- Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) -- If set to true, return messages in oldest->newest order. Defaults to True ifafter
is specified, otherwise False.
- 例外
Forbidden
-- You do not have permissions to get channel message history.HTTPException
-- The request to get message history failed.
- Yields
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!')
-
created_at
¶ Returns the direct message channel's creation time in UTC.
-
permissions_for
(user=None)¶ Handles permission resolution for a
User
.This function is there for compatibility with other channel types.
Actual direct messages do not really have the concept of permissions.
This returns all the Text related permissions set to true except:
send_tts_messages: You cannot send TTS messages in a DM.
manage_messages: You cannot delete others messages in a DM.
- パラメータ
user (
User
) -- The user to check permissions for. This parameter is ignored but kept for compatibility.- 戻り値
The resolved permissions.
- 戻り値の型
-
coroutine
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.
- 戻り値の型
-
coroutine
pins
()¶ This function is a coroutine.
Returns a
list
ofMessage
that are currently pinned.- 例外
HTTPException
-- Retrieving the pinned messages failed.
-
coroutine
send
(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None)¶ This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set 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 -- 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.
- 例外
HTTPException
-- Sending the message failed.Forbidden
-- You do not have the proper permissions to send the message.InvalidArgument
-- Thefiles
list is not of the appropriate size or you specified bothfile
andfiles
.
- 戻り値
The message that was sent.
- 戻り値の型
-
グループチャンネル¶
-
class
discord.
GroupChannel
¶ Represents a Discord group channel.
-
x == y
Checks if two channels are equal.
-
x != y
Checks if two channels are not equal.
-
hash(x)
Returns the channel's hash.
-
str(x)
Returns a string representation of the channel
-
me
¶ ClientUser
-- The user presenting yourself.
-
async-for
history
(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ Return an
AsyncIterator
that enables receiving the destination's message history.これを行うためには、そのチャンネルの
read_message_history
権限が必要です。例
Usage
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...
All parameters are optional.
- パラメータ
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 (
Message
ordatetime.datetime
) -- Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (
Message
ordatetime.datetime
) -- Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (
Message
ordatetime.datetime
) -- Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) -- If set to true, return messages in oldest->newest order. Defaults to True ifafter
is specified, otherwise False.
- 例外
Forbidden
-- You do not have permissions to get channel message history.HTTPException
-- The request to get message history failed.
- Yields
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!')
-
coroutine
add_recipients
(*recipients)¶ This function is a coroutine.
Adds recipients to this group.
A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the user of type
RelationshipType.friend
.- パラメータ
*recipients (
User
) -- An argument list of users to add to this group.- 例外
HTTPException
-- Adding a recipient to this group failed.
-
created_at
¶ Returns the channel's creation time in UTC.
-
coroutine
edit
(**fields)¶ This function is a coroutine.
Edits the group.
- パラメータ
name (Optional[
str
]) -- The new name to change the group to. Could beNone
to remove the name.icon (Optional[
bytes
]) -- A bytes-like object representing the new icon. Could beNone
to remove the icon.
- 例外
HTTPException
-- グループの編集に失敗した。
-
coroutine
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.
- 戻り値の型
-
coroutine
leave
()¶ This function is a coroutine.
Leave the group.
If you are the only one in the group, this deletes it as well.
- 例外
HTTPException
-- グループからの退出に失敗した。
-
coroutine
pins
()¶ This function is a coroutine.
Returns a
list
ofMessage
that are currently pinned.- 例外
HTTPException
-- Retrieving the pinned messages failed.
-
coroutine
remove_recipients
(*recipients)¶ This function is a coroutine.
Removes recipients from this group.
- パラメータ
*recipients (
User
) -- An argument list of users to remove from this group.- 例外
HTTPException
-- Removing a recipient from this group failed.
-
coroutine
send
(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None)¶ This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set 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 -- 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.
- 例外
HTTPException
-- Sending the message failed.Forbidden
-- You do not have the proper permissions to send the message.InvalidArgument
-- Thefiles
list is not of the appropriate size or you specified bothfile
andfiles
.
- 戻り値
The message that was sent.
- 戻り値の型
-
coroutine
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.
-
permissions_for
(user)¶ Handles permission resolution for a
User
.This function is there for compatibility with other channel types.
Actual direct messages do not really have the concept of permissions.
This returns all the Text related permissions set to true except:
send_tts_messages: You cannot send TTS messages in a DM.
manage_messages: You cannot delete others messages in a DM.
This also checks the kick_members permission if the user is the owner.
- パラメータ
user (
User
) -- The user to check permissions for.- 戻り値
The resolved permissions for the user.
- 戻り値の型
-
PartialInviteGuild¶
-
class
discord.
PartialInviteGuild
¶ Represents a "partial" invite guild.
This model will be given when the user is not part of the guild the
Invite
resolves to.-
x == y
Checks if two partial guilds are the same.
-
x != y
Checks if two partial guilds are not the same.
-
hash(x)
Return the partial guild's hash.
-
str(x)
Returns the partial guild's name.
-
verification_level
¶ VerificationLevel
-- The partial guild's verification level.
-
features
¶ List[
str
] -- A list of features the guild has. SeeGuild.features
for more information.
Optional[
str
] -- The partial guild's banner.
-
created_at
¶ Returns the guild's creation time in UTC.
-
icon_url
¶ Returns the URL version of the guild's icon. Returns an empty string if it has no icon.
-
icon_url_as
(*, format='webp', size=1024)¶ Asset
: The same operation asGuild.icon_url_as()
.
Returns the URL version of the guild's banner. Returns an empty string if it has no banner.
Asset
: The same operation asGuild.banner_url_as()
.
-
splash_url
¶ Returns the URL version of the guild's invite splash. Returns an empty string if it has no splash.
-
splash_url_as
(*, format='webp', size=2048)¶ Asset
: The same operation asGuild.splash_url_as()
.
-
PartialInviteChannel¶
-
class
discord.
PartialInviteChannel
¶ Represents a "partial" invite channel.
This model will be given when the user is not part of the guild the
Invite
resolves to.-
x == y
Checks if two partial channels are the same.
-
x != y
Checks if two partial channels are not the same.
-
hash(x)
Return the partial channel's hash.
-
str(x)
Returns the partial channel's name.
-
type
¶ ChannelType
-- The partial channel's type.
-
created_at
¶ Returns the channel's creation time in UTC.
-
招待¶
-
class
discord.
Invite
¶ Represents a Discord
Guild
orabc.GuildChannel
invite.Depending on the way this object was created, some of the attributes can have a value of
None
.-
x == y
Checks if two invites are equal.
-
x != y
Checks if two invites are not equal.
-
hash(x)
Returns the invite hash.
-
str(x)
Returns the invite URL.
-
max_age
¶ int
-- How long the before the invite expires in seconds. A value of 0 indicates that it doesn't expire.
-
guild
¶ Union[
Guild
,PartialInviteGuild
] -- The guild the invite is for.
-
created_at
¶ datetime.datetime -- A datetime object denoting the time the invite was created.
-
temporary
¶ bool
-- Indicates that the invite grants temporary membership. If True, members who joined via this invite will be kicked upon disconnect.
-
approximate_presence_count
¶ Optional[
int
] -- The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded.
-
channel
¶ Union[
abc.GuildChannel
,PartialInviteChannel
] -- The channel the invite is for.
-
id
¶ Returns the proper code portion of the invite.
-
url
¶ A property that retrieves the invite URL.
-
coroutine
delete
(*, reason=None)¶ This function is a coroutine.
Revokes the instant invite.
You must have the
manage_channels
permission to do this.- パラメータ
reason (Optional[
str
]) -- The reason for deleting this invite. Shows up on the audit log.- 例外
Forbidden
-- 招待を取り消す権限が無い。NotFound
-- 招待が無効、あるいは期限切れになっている。HTTPException
-- 招待の取り消しに失敗した。
-
WidgetChannel¶
-
class
discord.
WidgetChannel
¶ Represents a "partial" widget channel.
-
x == y
Checks if two partial channels are the same.
-
x != y
Checks if two partial channels are not the same.
-
hash(x)
Return the partial channel's hash.
-
str(x)
Returns the partial channel's name.
-
created_at
¶ Returns the channel's creation time in UTC.
-
WidgetMember¶
-
class
discord.
WidgetMember
¶ Represents a "partial" member of the widget's guild.
-
x == y
Checks if two widget members are the same.
-
x != y
Checks if two widget members are not the same.
-
hash(x)
Return the widget member's hash.
-
str(x)
Returns the widget member's name#discriminator.
-
connected_channel
¶ Optional[
VoiceChannel
] -- Which channel the member is connected to.
-
avatar_url
¶ ユーザーのアバターのURLを返します。
ユーザーがアバターを設定していない場合、デフォルトのアバターのURLが返ります。
これはデフォルトパラメータ(webp/gif フォーマット及びサイズが1024)で
avatar_url_as()
を呼び出すのと同等の処理です。
-
avatar_url_as
(*, format=None, static_format='webp', size=1024)¶ ユーザーのアバターのURLを返します。
ユーザーがアバターを設定していない場合、デフォルトのアバターのURLが返ります。
フォーマットは「webp」「jpeg」「jpg」「png」または「gif」である必要があり、「gif」はアニメーションアバターにのみ使用可能です。サイズは2の累乗値かつ16以上1024以下である必要があります。
- パラメータ
- 例外
InvalidArgument
--format
またはstatic_format
が正しくない、あるいはsize
に無効な値が渡された。- 戻り値
The resulting CDN asset.
- 戻り値の型
-
color
¶ レンダリング済みカラーを表す
Colour
を返すプロパティ。これは常にColour.default()
を返します。これには別名のプロパティがあります。
-
colour
¶ レンダリング済みカラーを表す
Colour
を返すプロパティ。これは常にColour.default()
を返します。これには別名のプロパティがあります。
-
created_at
¶ ユーザーの作成された時間をUTCで返します。
これはユーザーのDiscordアカウントが作成された時間です。
-
default_avatar
¶ ユーザーのデフォルトのアバターを追加します。これはユーザーのタグから算出されます。
-
default_avatar_url
¶ ユーザーのデフォルトアバターのURLを返します。
-
mention
¶ Returns a string that allows you to mention the given user.
-
mentioned_in
(message)¶ 指定のメッセージにユーザーに対するメンションが含まれているかを確認します。
- パラメータ
message (
Message
) -- メンションが含まれているかを確認するメッセージ。
-
permissions_in
(channel)¶ abc.GuildChannel.permissions_for()
のエイリアス。基本的には以下と同等です:
channel.permissions_for(self)
- パラメータ
channel (
abc.GuildChannel
) -- 権限を確認したいチャンネル。
-
Widget¶
-
class
discord.
Widget
¶ Represents a
Guild
widget.-
x == y
Checks if two widgets are the same.
-
x != y
Checks if two widgets are not the same.
-
str(x)
Returns the widget's JSON URL.
-
channels
¶ Optional[List[
WidgetChannel
]] -- The accessible voice channels in the guild.
-
members
¶ Optional[List[
Member
]] -- The online members in the server. Offline members do not appear in the widget.
-
created_at
¶ datetime.datetime
-- Returns the member's creation time in UTC.
-
coroutine
fetch_invite
(*, with_counts=True)¶ This function is a coroutine.
Retrieves an
Invite
from a invite URL or ID. This is the same asClient.get_invite()
; the invite code is abstracted away.- パラメータ
with_counts (
bool
) -- 招待にカウント情報を含めるかどうか。これによりInvite.approximate_member_count
とInvite.approximate_presence_count
に取得した値が代入されます。- 戻り値
URL/IDから取得した招待。
- 戻り値の型
-
RawMessageDeleteEvent¶
-
class
discord.
RawMessageDeleteEvent
¶ Represents the event payload for a
on_raw_message_delete()
event.
RawBulkMessageDeleteEvent¶
-
class
discord.
RawBulkMessageDeleteEvent
¶ Represents the event payload for a
on_raw_bulk_message_delete()
event.
RawMessageUpdateEvent¶
RawReactionActionEvent¶
-
class
discord.
RawReactionActionEvent
¶ Represents the payload for a
on_raw_reaction_add()
oron_raw_reaction_remove()
event.-
emoji
¶ PartialEmoji
-- The custom or unicode emoji being used.
-
RawReactionClearEvent¶
-
class
discord.
RawReactionClearEvent
¶ Represents the payload for a
on_raw_reaction_clear()
event.
データクラス¶
Some classes are just there to be data containers, this lists them.
Unlike models you are allowed to create these yourself, even if they can also be used to hold attributes.
ほぼすべてのクラスに __slots__
が定義されています。つまり、データクラスに動的に変数を追加することは不可能です。
The only exception to this rule is Object
, which is made with
dynamic attributes in mind.
__slots__
の詳細は 公式のPythonドキュメント を参照してください。
Object¶
-
class
discord.
Object
(id)¶ Represents a generic Discord object.
The purpose of this class is to allow you to create 'miniature' versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in strange order and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
-
x == y
二つのオブジェクトが等しいか比較します。
-
x != y
二つのオブジェクトが等しいものでないか比較します。
-
hash(x)
オブジェクトのハッシュを返します。
-
created_at
¶ Returns the snowflake's creation time in UTC.
-
Embed¶
-
class
discord.
Embed
(**kwargs)¶ Discordの埋め込みを表します。
-
len(x)
Returns the total size of the embed. Useful for checking if it's within the 6000 character limit.
オブジェクトの作成時、次の属性を設定することができます:
あるプロパティは
EmbedProxy
を返します。これはドットを用いて属性にアクセスすることを除くとdict
と同様の働きをする型です。例えば、embed.author.icon_url
のようになります。属性が無効または空の場合、特別なセンチネル値、Embed.Empty
が返ります。使いやすさを考慮して、strが渡されることを想定されたすべてのパラメータは、暗黙的にstrにキャストされます。
-
timestamp
¶ datetime.datetime -- The timestamp of the embed content. This could be a naive or aware datetime.
-
Empty
¶ A special sentinel value used by
EmbedProxy
and this class to denote that the value or attribute is empty.
-
classmethod
from_dict
(data)¶ Converts a
dict
to aEmbed
provided it is in the format that Discord expects it to be in.You can find out about this format in the official Discord documentation.
- パラメータ
data (
dict
) -- The dictionary to convert into an embed.
-
copy
()¶ Returns a shallow copy of the embed.
Returns an
EmbedProxy
denoting the footer contents.See
set_footer()
for possible values you can access.If the attribute has no value then
Empty
is returned.
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
-
image
¶ Returns an
EmbedProxy
denoting the image contents.Possible attributes you can access are:
url
proxy_url
width
height
If the attribute has no value then
Empty
is returned.
-
set_image
(*, url)¶ Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
- パラメータ
url (
str
) -- The source URL for the image. Only HTTP(S) is supported.
-
thumbnail
¶ Returns an
EmbedProxy
denoting the thumbnail contents.Possible attributes you can access are:
url
proxy_url
width
height
If the attribute has no value then
Empty
is returned.
-
set_thumbnail
(*, url)¶ Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
- パラメータ
url (
str
) -- The source URL for the thumbnail. Only HTTP(S) is supported.
-
video
¶ Returns an
EmbedProxy
denoting the video contents.Possible attributes include:
url
for the video URL.height
for the video height.width
for the video width.
If the attribute has no value then
Empty
is returned.
-
provider
¶ Returns an
EmbedProxy
denoting the provider contents.The only attributes that might be accessed are
name
andurl
.If the attribute has no value then
Empty
is returned.
Returns an
EmbedProxy
denoting the author contents.See
set_author()
for possible values you can access.If the attribute has no value then
Empty
is returned.
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
-
fields
¶ Returns a
list
ofEmbedProxy
denoting the field contents.See
add_field()
for possible values you can access.If the attribute has no value then
Empty
is returned.
-
add_field
(*, name, value, inline=True)¶ Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
-
clear_fields
()¶ 埋め込みからすべてのフィールドを削除します。
-
remove_field
(index)¶ 特定のインデックスのフィールドを削除します。
If the index is invalid or out of bounds then the error is silently swallowed.
注釈
When deleting a field by index, the index of the other fields shift to fill the gap just like a regular list.
- パラメータ
index (
int
) -- The index of the field to remove.
-
set_field_at
(index, *, name, value, inline=True)¶ Modifies a field to the embed object.
The index must point to a valid pre-existing field.
This function returns the class instance to allow for fluent-style chaining.
- パラメータ
- 例外
IndexError
-- 無効なindexが渡された。
-
to_dict
()¶ Converts this embed object into a dict.
-
File¶
-
class
discord.
File
(fp, filename=None, *, spoiler=False)¶ A parameter object used for
abc.Messageable.send()
for sending file objects.-
fp
¶ Union[
str
, BinaryIO] -- A file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open.注釈
If the file-like object passed is opened via
open
then the modes 'rb' should be used.To pass binary data, consider usage of
io.BytesIO
.
-
Colour¶
-
class
discord.
Colour
(value)¶ Represents a Discord role colour. This class is similar to an (red, green, blue)
tuple
.There is an alias for this called Color.
-
x == y
Checks if two colours are equal.
-
x != y
Checks if two colours are not equal.
-
hash(x)
Return the colour's hash.
-
str(x)
Returns the hex format for the colour.
-
r
¶ Returns the red component of the colour.
-
g
¶ Returns the green component of the colour.
-
b
¶ Returns the blue component of the colour.
-
to_rgb
()¶ Returns an (r, g, b) tuple representing the colour.
-
Activity¶
-
class
discord.
Activity
(**kwargs)¶ Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
-
type
¶ ActivityType
-- The type of activity currently being done.
-
timestamps
¶ dict
-- A dictionary of timestamps. It contains the following optional keys:start
: Corresponds to when the user started doing the activity in milliseconds since Unix epoch.end
: Corresponds to when the user will finish doing the activity in milliseconds since Unix epoch.
-
assets
¶ dict
-- A dictionary representing the images and their hover text of an activity. It contains the following optional keys:large_image
: A string representing the ID for the large image asset.large_text
: A string representing the text when hovering over the large image asset.small_image
: A string representing the ID for the small image asset.small_text
: A string representing the text when hovering over the small image asset.
-
party
¶ dict
-- A dictionary representing the activity party. It contains the following optional keys:id
: A string representing the party ID.size
: A list of up to two integer elements denoting (current_size, maximum_size).
-
start
¶ Optional[
datetime.datetime
] -- When the user started doing this activity in UTC, if applicable.
-
end
¶ Optional[
datetime.datetime
] -- When the user will stop doing this activity in UTC, if applicable.
-
large_image_url
¶ Optional[
str
] -- Returns a URL pointing to the large image asset of this activity if applicable.
-
small_image_url
¶ Optional[
str
] -- Returns a URL pointing to the small image asset of this activity if applicable.
-
Game¶
-
class
discord.
Game
(name, **extra)¶ A slimmed down version of
Activity
that represents a Discord game.This is typically displayed via Playing on the official Discord client.
-
x == y
Checks if two games are equal.
-
x != y
Checks if two games are not equal.
-
hash(x)
Returns the game's hash.
-
str(x)
Returns the game's name.
- パラメータ
name (
str
) -- The game's name.start (Optional[
datetime.datetime
]) -- A naive UTC timestamp representing when the game started. Keyword-only parameter. Ignored for bots.end (Optional[
datetime.datetime
]) -- A naive UTC timestamp representing when the game ends. Keyword-only parameter. Ignored for bots.
-
type
¶ Returns the game's type. This is for compatibility with
Activity
.It always returns
ActivityType.playing
.
-
start
¶ Optional[
datetime.datetime
] -- When the user started playing this game in UTC, if applicable.
-
end
¶ Optional[
datetime.datetime
] -- When the user will stop playing this game in UTC, if applicable.
-
Streaming¶
-
class
discord.
Streaming
(*, name, url, **extra)¶ A slimmed down version of
Activity
that represents a Discord streaming status.This is typically displayed via Streaming on the official Discord client.
-
x == y
Checks if two streams are equal.
-
x != y
Checks if two streams are not equal.
-
hash(x)
Returns the stream's hash.
-
str(x)
Returns the stream's name.
-
url
¶ str
-- The stream's URL. Currently only twitch.tv URLs are supported. Anything else is silently discarded.
-
assets
¶ dict
-- A dictionary comprising of similar keys than those inActivity.assets
.
-
type
¶ Returns the game's type. This is for compatibility with
Activity
.It always returns
ActivityType.streaming
.
-
twitch_name
¶ Optional[
str
] -- If provided, the twitch name of the user streaming.This corresponds to the
large_image
key of theStreaming.assets
dictionary if it starts withtwitch:
. Typically set by the Discord client.
-
Permissions¶
-
class
discord.
Permissions
(permissions=0)¶ Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
-
x == y
Checks if two permissions are equal.
-
x != y
Checks if two permissions are not equal.
-
x <= y
Checks if a permission is a subset of another permission.
-
x >= y
Checks if a permission is a superset of another permission.
-
x < y
Checks if a permission is a strict subset of another permission.
-
x > y
Checks if a permission is a strict superset of another permission.
-
hash(x)
Return the permission's hash.
-
iter(x)
Returns an iterator of
(perm, value)
pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
-
value
¶ The raw value. This value is a bit array field of a 53-bit integer representing the currently available permissions. You should query permissions via the properties rather than using this raw value.
-
is_subset
(other)¶ Returns True if self has the same or fewer permissions as other.
-
is_superset
(other)¶ Returns True if self has the same or more permissions as other.
-
is_strict_subset
(other)¶ Returns True if the permissions on other are a strict subset of those on self.
-
is_strict_superset
(other)¶ Returns True if the permissions on other are a strict superset of those on self.
-
classmethod
none
()¶ A factory method that creates a
Permissions
with all permissions set to False.
-
classmethod
all
()¶ A factory method that creates a
Permissions
with all permissions set to True.
-
classmethod
all_channel
()¶ A
Permissions
with all channel-specific permissions set to True and the guild-specific ones set to False. The guild-specific permissions are currently:manage_guild
kick_members
ban_members
administrator
change_nickname
manage_nicknames
-
classmethod
general
()¶ A factory method that creates a
Permissions
with all "General" permissions from the official Discord UI set to True.
-
classmethod
text
()¶ A factory method that creates a
Permissions
with all "Text" permissions from the official Discord UI set to True.
-
classmethod
voice
()¶ A factory method that creates a
Permissions
with all "Voice" permissions from the official Discord UI set to True.
-
update
(**kwargs)¶ Bulk updates this permission object.
Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.
- パラメータ
**kwargs -- A list of key/value pairs to bulk update permissions with.
-
create_instant_invite
¶ Returns True if the user can create instant invites.
-
kick_members
¶ Returns True if the user can kick users from the guild.
-
ban_members
¶ Returns True if a user can ban users from the guild.
-
administrator
¶ Returns True if a user is an administrator. This role overrides all other permissions.
This also bypasses all channel-specific overrides.
-
manage_channels
¶ Returns True if a user can edit, delete, or create channels in the guild.
This also corresponds to the "Manage Channel" channel-specific override.
-
manage_guild
¶ Returns True if a user can edit guild properties.
-
add_reactions
¶ Returns True if a user can add reactions to messages.
-
view_audit_log
¶ Returns True if a user can view the guild's audit log.
-
priority_speaker
¶ Returns True if a user can be more easily heard while talking.
-
read_messages
¶ Returns True if a user can read messages from all or specific text channels.
-
send_messages
¶ Returns True if a user can send messages from all or specific text channels.
-
send_tts_messages
¶ Returns True if a user can send TTS messages from all or specific text channels.
-
manage_messages
¶ Returns True if a user can delete or pin messages in a text channel. Note that there are currently no ways to edit other people's messages.
-
embed_links
¶ Returns True if a user's messages will automatically be embedded by Discord.
-
attach_files
¶ Returns True if a user can send files in their messages.
-
read_message_history
¶ Returns True if a user can read a text channel's previous messages.
-
mention_everyone
¶ Returns True if a user's @everyone or @here will mention everyone in the text channel.
-
external_emojis
¶ Returns True if a user can use emojis from other guilds.
-
connect
¶ Returns True if a user can connect to a voice channel.
-
speak
¶ Returns True if a user can speak in a voice channel.
-
mute_members
¶ Returns True if a user can mute other users.
-
deafen_members
¶ Returns True if a user can deafen other users.
-
move_members
¶ Returns True if a user can move users between other voice channels.
-
use_voice_activation
¶ Returns True if a user can use voice activation in voice channels.
-
change_nickname
¶ Returns True if a user can change their nickname in the guild.
-
manage_nicknames
¶ Returns True if a user can change other user's nickname in the guild.
-
manage_roles
¶ Returns True if a user can create or edit roles less than their role's position.
This also corresponds to the "Manage Permissions" channel-specific override.
-
manage_webhooks
¶ Returns True if a user can create, edit, or delete webhooks.
-
manage_emojis
¶ Returns True if a user can create, edit, or delete emojis.
-
PermissionOverwrite¶
-
class
discord.
PermissionOverwrite
(**kwargs)¶ A type that is used to represent a channel specific permission.
Unlike a regular
Permissions
, the default value of a permission is equivalent toNone
and notFalse
. Setting a value toFalse
is explicitly denying that permission, while setting a value toTrue
is explicitly allowing that permission.The values supported by this are the same as
Permissions
with the added possibility of it being set toNone
.サポートされている操作:
Operation
Description
x == y
Checks if two overwrites are equal.
x != y
Checks if two overwrites are not equal.
iter(x)
Returns an iterator of (perm, value) pairs. This allows this class to be used as an iterable in e.g. set/list/dict constructions.
- パラメータ
**kwargs -- Set the value of permissions by their name.
-
pair
()¶ Returns the (allow, deny) pair from this overwrite.
The value of these pairs is
Permissions
.
-
classmethod
from_pair
(allow, deny)¶ Creates an overwrite from an allow/deny pair of
Permissions
.
-
is_empty
()¶ Checks if the permission overwrite is currently empty.
An empty permission overwrite is one that has no overwrites set to True or False.
-
update
(**kwargs)¶ Bulk updates this permission overwrite object.
Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.
- パラメータ
**kwargs -- A list of key/value pairs to bulk update with.
例外¶
The following exceptions are thrown by the library.
-
exception
discord.
DiscordException
¶ Base exception class for discord.py
Ideally speaking, this could be caught to handle any exceptions thrown from this library.
-
exception
discord.
ClientException
¶ Exception that's thrown when an operation in the
Client
fails.These are usually for exceptions that happened due to user input.
-
exception
discord.
LoginFailure
¶ Exception that's thrown when the
Client.login()
function fails to log you in from improper credentials or some other misc. failure.
-
exception
discord.
NoMoreItems
¶ Exception that is thrown when an async iteration operation has no more items.
-
exception
discord.
HTTPException
(response, message)¶ Exception that's thrown when an HTTP request operation fails.
-
response
¶ aiohttp.ClientResponse -- The response of the failed HTTP request. This is an instance of aiohttp.ClientResponse. In some cases this could also be a
requests.Response
.
-
-
exception
discord.
Forbidden
(response, message)¶ Exception that's thrown for when status code 403 occurs.
HTTPException
のサブクラス
-
exception
discord.
NotFound
(response, message)¶ Exception that's thrown for when status code 404 occurs.
HTTPException
のサブクラス
-
exception
discord.
InvalidArgument
¶ Exception that's thrown when an argument to a function is invalid some way (e.g. wrong value or wrong type).
This could be considered the analogous of
ValueError
andTypeError
except inherited fromClientException
and thusDiscordException
.
-
exception
discord.
GatewayNotFound
¶ An exception that is usually thrown when the gateway hub for the
Client
websocket is not found.
-
exception
discord.
ConnectionClosed
(original, *, shard_id)¶ Exception that's thrown when the gateway connection is closed for reasons that could not be handled internally.
-
exception
discord.opus.
OpusError
(code)¶ An exception that is thrown for libopus related errors.
-
exception
discord.opus.
OpusNotLoaded
¶ An exception that is thrown for when libopus is not loaded.