API 레퍼런스¶
아래의 섹션은 discord.py API에 대해 설명하고 있습니다.
참고
This module uses the Python logging module to log diagnostic and errors in an output independent way. If the logging module is not configured, these logs will not be output anywhere. See 로깅 설정 for more information on how to set up and use the logging module with discord.py.
Clients¶
클라이언트¶
- asyncapplication_info
- asyncbefore_identify_hook
- asyncchange_presence
- defclear
- asyncclose
- asyncconnect
- asynccreate_guild
- asyncdelete_invite
- @event
- asyncfetch_channel
- asyncfetch_guild
- asyncfetch_guilds
- asyncfetch_invite
- asyncfetch_template
- asyncfetch_user
- asyncfetch_user_profile
- asyncfetch_webhook
- asyncfetch_widget
- defget_all_channels
- defget_all_members
- defget_channel
- defget_emoji
- defget_guild
- defget_user
- defis_closed
- defis_ready
- defis_ws_ratelimited
- asynclogin
- asynclogout
- asyncon_error
- asyncrequest_offline_members
- defrun
- asyncstart
- asyncwait_for
- asyncwait_until_ready
-
class
discord.Client(*, loop=None, **options)¶ Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
여러 가지 옵션을
Client에 전달할 수 있습니다.- 매개변수
max_messages (Optional[
int]) –The maximum number of messages to store in the internal message cache. This defaults to
1000. Passing inNonedisables the message cache.버전 1.3에서 변경: Allow disabling the message cache and change the default size to
1000.loop (Optional[
asyncio.AbstractEventLoop]) – Theasyncio.AbstractEventLoopto use for asynchronous operations. Defaults toNone, in which case the default event loop is used viaasyncio.get_event_loop().connector (
aiohttp.BaseConnector) – 연결 풀링에 사용할 커넥터.proxy (Optional[
str]) – 프록시 URL.proxy_auth (Optional[
aiohttp.BasicAuth]) – 프록시 HTTP Basic Authorization을 나타내는 오브젝트shard_id (Optional[
int]) – Integer starting at0and less thanshard_count.shard_count (Optional[
int]) – 샤드의 총 개수.intents (
Intents) –The intents that you want to enable for the session. This is a way of disabling and enabling certain gateway events from triggering and being sent. If not given, defaults to a regularly constructed
Intentsclass.버전 1.5에 추가.
member_cache_flags (
MemberCacheFlags) –Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible with the currently selected intents.
버전 1.5에 추가.
fetch_offline_members (
bool) – A deprecated alias ofchunk_guilds_at_startup.chunk_guilds_at_startup (
bool) –Indicates if
on_ready()should be delayed to chunk all guilds at start-up if necessary. This operation is incredibly slow for large amounts of guilds. The default isTrueifIntents.membersisTrue.버전 1.5에 추가.
status (Optional[
Status]) – 디스코드에 로그인할 때 나타나는 상태.activity (Optional[
BaseActivity]) – 디스코드에 로그인할 때 나타나는 활동.allowed_mentions (Optional[
AllowedMentions]) – 전송된 모든 멘션에 대해 클라이언트가 어떻게 다루는지 제어합니다. .. versionadded:: 1.4heartbeat_timeout (
float) – The maximum numbers of seconds before timing out and restarting the WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if processing the initial packets take too long to the point of disconnecting you. The default timeout is 60 seconds.guild_ready_timeout (
float) –The maximum number of seconds to wait for the GUILD_CREATE stream to end before preparing the member cache and firing READY. The default timeout is 2 seconds.
버전 1.4에 추가.
guild_subscriptions (
bool) –Whether to dispatch presence or typing events. Defaults to
True.버전 1.3에 추가.
경고
이것이
False로 설정되어 있을 경우, 아래의 기능이 비활성화됩니다:사용자 관련 이벤트 없음 (
on_user_update()는 처리되지 않습니다)- 모든 멤버 관련 이벤트가 비활성화됩니다.
타이핑 이벤트가 비활성화됩니다 (
on_typing()).If
fetch_offline_membersis set toFalsethen the user cache will not exist. This makes it difficult or impossible to do many things, for example:컴퓨팅 권한
Querying members in a voice channel via
VoiceChannel.memberswill be empty.Most forms of receiving
Memberwill be receivingUserinstead, except for message events.Guild.owner이None으로 반환됩니다.Guild.get_member()의 사용이 불가능해집니다.Member를 사용한 모든 것.users의 값이 그렇게 많지 않을 것입니다.등등.
In short, this makes it so the only member you can reliably query is the message author. Useful for bots that do not require any state.
assume_unsync_clock (
bool) –Whether to assume the system clock is unsynced. This applies to the ratelimit handling code. If this is set to
True, the default, then the library uses the time to reset a rate limit bucket given by Discord. If this isFalsethen your system clock is used to calculate how long to sleep for. If this is set toFalseit is recommended to sync your system clock to Google’s NTP server.버전 1.3에 추가.
-
ws¶ 클라이언트가 현재 연결되어있는 웹소켓 대역폭.
None일수도 있습니다.
-
loop¶ 클라이언트가 HTTP 요청과 웹소켓 작업에 사용하는 루프 이벤트.
-
latency¶ HEARTBEAT와 HEARTBEAT_ACK 사이의 지연 시간을 초 단위로 측정합니다.
Discord WebSocket 프로토콜 지연 시간이라고 불리기도 합니다.
- 타입
-
is_ws_ratelimited()¶ bool: Whether the websocket is currently rate limited.This can be useful to know when deciding whether you should query members using HTTP or via the gateway.
버전 1.6에 추가.
-
user¶ Represents the connected client.
Noneif not logged in.- 타입
Optional[
ClientUser]
-
private_channels¶ 연결된 클라이언트가 참여중인 비공개 채널.
참고
디스코드 자체의 비공개 채널을 다루는 방식 때문에 최근 128개의 비공개 채널만 반환합니다.
- 타입
List[
abc.PrivateChannel]
-
voice_clients¶ 음성 연결 목록을 나타냅니다.
These are usually
VoiceClientinstances.- 타입
List[
VoiceProtocol]
-
await
on_error(event_method, *args, **kwargs)¶ 이 함수는 코루틴 입니다.
클라이언트가 제공하는 기본적인 오류 처리기.
By default this prints to
sys.stderrhowever it could be overridden to have a different implementation. Checkon_error()for more details.
-
await
request_offline_members(*guilds)¶ 이 함수는 코루틴 입니다.
Requests previously offline members from the guild to be filled up into the
Guild.memberscache. This function is usually not called. It should only be used if you have thefetch_offline_membersparameter set toFalse.When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if
Guild.largeisTrue.경고
This method is deprecated. Use
Guild.chunk()instead.- 매개변수
*guilds (
Guild) – 오프라인 멤버들의 정보를 요청할 길드의 목록.- 예외
InvalidArgument – If any guild is unavailable in the collection.
-
await
before_identify_hook(shard_id, *, initial=False)¶ 이 함수는 코루틴 입니다.
A hook that is called before IDENTIFYing a session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients.
The default implementation sleeps for 5 seconds.
버전 1.4에 추가.
-
await
login(token, *, bot=True)¶ 이 함수는 코루틴 입니다.
지정된 인증서로 클라이언트에 로그인합니다.
이 함수는 두 가지의 다른 방법으로 사용될 수 있습니다.
경고
Logging on with a user token is against the Discord Terms of Service and doing so might potentially get your account banned. Use this at your own risk.
- 매개변수
- 예외
LoginFailure – The wrong credentials are passed.
HTTPException – An unknown HTTP related error occurred, usually when it isn’t 200 or the known incorrect credentials passing status code.
-
await
connect(*, reconnect=True)¶ 이 함수는 코루틴 입니다.
Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.
- 매개변수
reconnect (
bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).- 예외
GatewayNotFound – If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.
ConnectionClosed – The websocket connection has been terminated.
-
clear()¶ Clears the internal state of the bot.
After this, the bot can be considered 《re-opened》, i.e.
is_closed()andis_ready()both returnFalsealong with the bot’s internal cache cleared.
-
await
start(*args, **kwargs)¶ 이 함수는 코루틴 입니다.
A shorthand coroutine for
login()+connect().- 예외
TypeError – An unexpected keyword argument was received.
-
run(*args, **kwargs)¶ A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use
start()coroutine orconnect()+login().Roughly Equivalent to:
try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # cancel all tasks lingering finally: loop.close()
경고
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
-
activity¶ The activity being used upon logging in.
- 타입
Optional[
BaseActivity]
-
allowed_mentions¶ The allowed mention configuration.
버전 1.4에 추가.
- 타입
Optional[
AllowedMentions]
-
get_channel(id)¶ Returns a channel with the given ID.
- 매개변수
id (
int) – The ID to search for.- 반환값
The returned channel or
Noneif not found.- 반환 형식
Optional[Union[
abc.GuildChannel,abc.PrivateChannel]]
-
get_guild(id)¶ Returns a guild with the given ID.
-
get_user(id)¶ Returns a user with the given ID.
-
get_emoji(id)¶ Returns an emoji with the given ID.
-
for ... in
get_all_channels()¶ A generator that retrieves every
abc.GuildChannelthe client can 〈access〉.This is equivalent to:
for guild in client.guilds: for channel in guild.channels: yield channel
참고
Just because you receive a
abc.GuildChanneldoes not mean that you can communicate in said channel.abc.GuildChannel.permissions_for()should be used for that.- Yields
abc.GuildChannel– A channel the client can 〈access〉.
-
for ... in
get_all_members()¶ Returns a generator with every
Memberthe client can see.This is equivalent to:
for guild in client.guilds: for member in guild.members: yield member
- Yields
Member– A member the client can see.
-
wait_for(event, *, check=None, timeout=None)¶ 이 함수는 코루틴 입니다.
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The
timeoutparameter is passed ontoasyncio.wait_for(). By default, it does not timeout. Note that this does propagate theasyncio.TimeoutErrorfor you in case of timeout and is provided for ease of use.In case the event returns multiple arguments, a
tuplecontaining those arguments is returned instead. Please check the documentation for a list of events and their parameters.This function returns the first event that meets the requirements.
예제
Waiting for a user reply:
@client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send('Hello {.author}!'.format(msg))
Waiting for a thumbs up reaction from the message author:
@client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that 👍 reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '👍' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('👎') else: await channel.send('👍')
- 매개변수
event (
str) – The event name, similar to the event reference, but without theon_prefix, to wait for.check (Optional[Callable[…,
bool]]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.timeout (Optional[
float]) – The number of seconds to wait before timing out and raisingasyncio.TimeoutError.
- 예외
asyncio.TimeoutError – If a timeout is provided and it was reached.
- 반환값
Returns no arguments, a single argument, or a
tupleof multiple arguments that mirrors the parameters passed in the event reference.- 반환 형식
Any
-
event(coro)¶ A decorator that registers an event to listen to.
You can find more info about the events on the documentation below.
The events must be a coroutine, if not,
TypeErroris raised.예제
@client.event async def on_ready(): print('Ready!')
- 예외
TypeError – The coroutine passed is not actually a coroutine.
-
await
change_presence(*, activity=None, status=None, afk=False)¶ 이 함수는 코루틴 입니다.
Changes the client’s presence.
예제
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
- 매개변수
activity (Optional[
BaseActivity]) – The activity being done.Noneif no currently active activity is done.status (Optional[
Status]) – Indicates what status to change to. IfNone, thenStatus.onlineis used.afk (Optional[
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 – If the
activityparameter is not the proper type.
-
fetch_guilds(*, limit=100, before=None, after=None)¶ 이 함수는 코루틴 입니다.
Retrieves an
AsyncIteratorthat enables receiving your guilds.참고
Using this, you will only receive
Guild.owner,Guild.icon,Guild.id, andGuild.nameperGuild.참고
This method is an API call. For general usage, consider
guildsinstead.예제
사용법
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...
모든 매개 변수는 선택 사항입니다.
- 매개변수
limit (Optional[
int]) – The number of guilds to retrieve. IfNone, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to100.before (Union[
abc.Snowflake,datetime.datetime]) – Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Union[
abc.Snowflake,datetime.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.
-
await
fetch_template(code)¶ 이 함수는 코루틴 입니다.
Gets a
Templatefrom a discord.new URL or code.- 매개변수
code (Union[
Template,str]) – The Discord Template Code or URL (must be a discord.new URL).- 예외
NotFound – The template is invalid.
HTTPException – Getting the template failed.
- 반환값
The template from the URL/code.
- 반환 형식
-
await
fetch_guild(guild_id)¶ 이 함수는 코루틴 입니다.
Retrieves a
Guildfrom an ID.참고
Using this, you will not receive
Guild.channels,Guild.members,Member.activityandMember.voiceperMember.참고
This method is an API call. For general usage, consider
get_guild()instead.- 매개변수
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.
- 반환 형식
-
await
create_guild(name, region=None, icon=None, *, code=None)¶ 이 함수는 코루틴 입니다.
Creates a
Guild.Bot accounts in more than 10 guilds are not allowed to create guilds.
- 매개변수
name (
str) – The name of the guild.region (
VoiceRegion) – The region for the voice communication server. Defaults toVoiceRegion.us_west.icon (
bytes) – The bytes-like object representing the icon. SeeClientUser.edit()for more details on what is expected.code (Optional[
str]) –The code for a template to create the guild with.
버전 1.4에 추가.
- 예외
HTTPException – Guild creation failed.
InvalidArgument – Invalid icon image format given. Must be PNG or JPG.
- 반환값
The guild created. This is not the same guild that is added to cache.
- 반환 형식
-
await
fetch_invite(url, *, with_counts=True)¶ 이 함수는 코루틴 입니다.
Gets an
Invitefrom a discord.gg URL or ID.참고
If the invite is for a guild you have not joined, the guild and channel attributes of the returned
Invitewill bePartialInviteGuildandPartialInviteChannelrespectively.- 매개변수
url (Union[
Invite,str]) – The Discord invite ID or URL (must be a discord.gg URL).with_counts (
bool) – Whether to include count information in the invite. This fills theInvite.approximate_member_countandInvite.approximate_presence_countfields.
- 예외
NotFound – The invite has expired or is invalid.
HTTPException – Getting the invite failed.
- 반환값
The invite from the URL/ID.
- 반환 형식
-
await
delete_invite(invite)¶ 이 함수는 코루틴 입니다.
Revokes an
Invite, URL, or ID to an invite.You must have the
manage_channelspermission in the associated guild to do this.- 매개변수
- 예외
Forbidden – 초대를 삭제할 권한이 없습니다.
NotFound – 초대가 유효하지 않거나 만료되었습니다.
HTTPException – 초대 삭제에 실패했습니다.
-
await
fetch_widget(guild_id)¶ 이 함수는 코루틴 입니다.
Gets a
Widgetfrom 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.
- 반환 형식
-
await
application_info()¶ 이 함수는 코루틴 입니다.
Retrieves the bot’s application information.
- 예외
HTTPException – Retrieving the information failed somehow.
- 반환값
The bot’s application information.
- 반환 형식
-
await
fetch_user(user_id)¶ 이 함수는 코루틴 입니다.
Retrieves a
Userbased on their ID. This can only be used by bot accounts. You do not have to share any guilds with the user to get this information, however many operations do require that you do.참고
This method is an API call. For general usage, consider
get_user()instead.- 매개변수
user_id (
int) – The user’s ID to fetch from.- 예외
NotFound – A user with this ID does not exist.
HTTPException – Fetching the user failed.
- 반환값
The user you requested.
- 반환 형식
-
await
fetch_user_profile(user_id)¶ 이 함수는 코루틴 입니다.
Gets an arbitrary user’s profile.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 매개변수
user_id (
int) – The ID of the user to fetch their profile for.- 예외
Forbidden – Not allowed to fetch profiles.
HTTPException – Fetching the profile failed.
- 반환값
The profile of the user.
- 반환 형식
-
await
fetch_channel(channel_id)¶ 이 함수는 코루틴 입니다.
Retrieves a
abc.GuildChannelorabc.PrivateChannelwith the specified ID.참고
This method is an API call. For general usage, consider
get_channel()instead.버전 1.2에 추가.
- 예외
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channel failed.
NotFound – Invalid Channel ID.
Forbidden – You do not have permission to fetch this channel.
- 반환값
The channel from the ID.
- 반환 형식
Union[
abc.GuildChannel,abc.PrivateChannel]
AutoShardedClient¶
- asyncchange_presence
- asyncclose
- asyncconnect
- defget_shard
- defis_ws_ratelimited
- asyncrequest_offline_members
-
class
discord.AutoShardedClient(*args, loop=None, **kwargs)¶ A client similar to
Clientexcept it handles the complications of sharding for the user into a more manageable and transparent single process bot.When using this client, you will be able to use it as-if it was a regular
Clientwith a single shard when implementation wise internally it is split up into multiple shards. This allows you to not have to deal with IPC or other complicated infrastructure.It is recommended to use this client only if you have surpassed at least 1000 guilds.
If no
shard_countis provided, then the library will use the Bot Gateway endpoint call to figure out how many shards to use.If a
shard_idsparameter is given, then those shard IDs will be used to launch the internal shards. Note thatshard_countmust be provided if this is used. By default, when omitted, the client will launch shards from 0 toshard_count - 1.-
latency¶ HEARTBEAT와 HEARTBEAT_ACK 사이의 지연 시간을 초 단위로 측정합니다.
This operates similarly to
Client.latency()except it uses the average latency of every shard’s latency. To get a list of shard latency, check thelatenciesproperty. Returnsnanif there are no shards ready.- 타입
-
latencies¶ A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This returns a list of tuples with elements
(shard_id, latency).
-
get_shard(shard_id)¶ Optional[
ShardInfo]: Gets the shard information at a given shard ID orNoneif not found.
-
await
request_offline_members(*guilds)¶ 이 함수는 코루틴 입니다.
Requests previously offline members from the guild to be filled up into the
Guild.memberscache. This function is usually not called. It should only be used if you have thefetch_offline_membersparameter set toFalse.When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if
Guild.largeisTrue.경고
This method is deprecated. Use
Guild.chunk()instead.- 매개변수
*guilds (
Guild) – 오프라인 멤버들의 정보를 요청할 길드의 목록.- 예외
InvalidArgument – If any guild is unavailable in the collection.
-
await
connect(*, reconnect=True)¶ 이 함수는 코루틴 입니다.
Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.
- 매개변수
reconnect (
bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).- 예외
GatewayNotFound – If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.
ConnectionClosed – The websocket connection has been terminated.
-
await
change_presence(*, activity=None, status=None, afk=False, shard_id=None)¶ 이 함수는 코루틴 입니다.
Changes the client’s presence.
Example:
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
- 매개변수
activity (Optional[
BaseActivity]) – The activity being done.Noneif no currently active activity is done.status (Optional[
Status]) – Indicates what status to change to. IfNone, thenStatus.onlineis used.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]) – The shard_id to change the presence to. If not specified orNone, then it will change the presence of every shard the bot can see.
- 예외
InvalidArgument – If the
activityparameter is not of proper type.
-
is_ws_ratelimited()¶ bool: Whether the websocket is currently rate limited.This can be useful to know when deciding whether you should query members using HTTP or via the gateway.
This implementation checks if any of the shards are rate limited. For more granular control, consider
ShardInfo.is_ws_ratelimited().버전 1.6에 추가.
-
Application Info¶
AppInfo¶
-
class
discord.AppInfo¶ Represents the application info for the bot provided by Discord.
-
bot_public¶ Whether the bot can be invited by anyone or if it is locked to the application owner.
- 타입
-
bot_require_code_grant¶ Whether the bot requires the completion of the full oauth2 code grant flow to join.
- 타입
-
summary¶ If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU
버전 1.3에 추가.
- 타입
-
guild_id¶ If this application is a game sold on Discord, this field will be the guild to which it has been linked
버전 1.3에 추가.
- 타입
Optional[
int]
-
primary_sku_id¶ If this application is a game sold on Discord, this field will be the id of the 《Game SKU》 that is created, if exists
버전 1.3에 추가.
- 타입
Optional[
int]
-
slug¶ If this application is a game sold on Discord, this field will be the URL slug that links to the store page
버전 1.3에 추가.
- 타입
Optional[
str]
-
cover_image¶ If this application is a game sold on Discord, this field will be the hash of the image on store embeds
버전 1.3에 추가.
- 타입
Optional[
str]
-
icon_url¶ Retrieves the application’s icon asset.
This is equivalent to calling
icon_url_as()with the default parameters (〈webp〉 format and a size of 1024).버전 1.3에 추가.
- 타입
-
icon_url_as(*, format='webp', size=1024)¶ Returns an
Assetfor the icon the application has.The format must be one of 〈webp〉, 〈jpeg〉, 〈jpg〉 or 〈png〉. The size must be a power of 2 between 16 and 4096.
버전 1.6에 추가.
- 매개변수
- 예외
InvalidArgument – Bad image format passed to
formator invalidsize.- 반환값
The resulting CDN asset.
- 반환 형식
-
cover_image_url¶ Retrieves the cover image on a store embed.
This is equivalent to calling
cover_image_url_as()with the default parameters (〈webp〉 format and a size of 1024).버전 1.3에 추가.
- 타입
-
cover_image_url_as(*, format='webp', size=1024)¶ Returns an
Assetfor the image on store embeds if this application is a game sold on Discord.The format must be one of 〈webp〉, 〈jpeg〉, 〈jpg〉 or 〈png〉. The size must be a power of 2 between 16 and 4096.
버전 1.6에 추가.
- 매개변수
- 예외
InvalidArgument – Bad image format passed to
formator invalidsize.- 반환값
The resulting CDN asset.
- 반환 형식
-
Team¶
-
class
discord.Team¶ Represents an application team for a bot provided by Discord.
-
members¶ A list of the members in the team
버전 1.3에 추가.
- 타입
List[
TeamMember]
-
icon_url¶ Retrieves the team’s icon asset.
This is equivalent to calling
icon_url_as()with the default parameters (〈webp〉 format and a size of 1024).- 타입
-
icon_url_as(*, format='webp', size=1024)¶ Returns an
Assetfor the icon the team has.The format must be one of 〈webp〉, 〈jpeg〉, 〈jpg〉 or 〈png〉. The size must be a power of 2 between 16 and 4096.
버전 2.0에 추가.
- 매개변수
- 예외
InvalidArgument – Bad image format passed to
formator invalidsize.- 반환값
The resulting CDN asset.
- 반환 형식
-
owner¶ The team’s owner.
- 타입
Optional[
TeamMember]
-
TeamMember¶
-
class
discord.TeamMember¶ Represents a team member in a team.
-
x == y Checks if two team members are equal.
-
x != y Checks if two team members are not equal.
-
hash(x) Return the team member’s hash.
-
str(x) Returns the team member’s name with discriminator.
버전 1.3에 추가.
-
discriminator¶ The team member’s discriminator. This is given when the username has conflicts.
- 타입
-
membership_state¶ The membership state of the member (e.g. invited or accepted)
-
Event Reference¶
This section outlines the different types of events listened by Client.
There are two ways to register an event, the first way is through the use of
Client.event(). The second way is through subclassing Client and
overriding the specific events. For example:
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!')
If an event handler raises an exception, on_error() will be called
to handle it, which defaults to print a traceback and ignoring the exception.
경고
All the events must be a 코루틴. If they aren’t, then you might get unexpected
errors. In order to turn a function into a coroutine they must be async def
functions.
-
discord.on_connect()¶ Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see
on_ready()for that.The warnings on
on_ready()also apply.
-
discord.on_shard_connect(shard_id)¶ Similar to
on_connect()except used byAutoShardedClientto denote when a particular shard ID has connected to Discord.버전 1.4에 추가.
- 매개변수
shard_id (
int) – The shard ID that has connected.
-
discord.on_disconnect()¶ Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to logout, or Discord terminating the connection one way or the other.
This function can be called many times without a corresponding
on_connect()call.
-
discord.on_shard_disconnect(shard_id)¶ Similar to
on_disconnect()except used byAutoShardedClientto denote when a particular shard ID has disconnected from Discord.버전 1.4에 추가.
- 매개변수
shard_id (
int) – The shard ID that has disconnected.
-
discord.on_ready()¶ Called when the client is done preparing the data received from Discord. Usually after login is successful and the
Client.guildsand co. are filled up.경고
This function is not guaranteed to be the first event called. Likewise, this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
-
discord.on_shard_ready(shard_id)¶ Similar to
on_ready()except used byAutoShardedClientto denote when a particular shard ID has become ready.- 매개변수
shard_id (
int) – The shard ID that is ready.
-
discord.on_resumed()¶ Called when the client has resumed a session.
-
discord.on_shard_resumed(shard_id)¶ Similar to
on_resumed()except used byAutoShardedClientto denote when a particular shard ID has resumed a session.버전 1.4에 추가.
- 매개변수
shard_id (
int) – The shard ID that has resumed.
-
discord.on_error(event, *args, **kwargs)¶ 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
Clientclass you can define anon_errorhandler consisting of a single empty raise 문. Exceptions raised byon_errorwill not be handled in any way byClient.참고
on_errorwill only be dispatched toClient.event().It will not be received by
Client.wait_for(), or, if used, Bots listeners such aslisten()orlistener().- 매개변수
event (
str) – The name of the event that raised the exception.args – The positional arguments for the event that raised the exception.
kwargs – The keyword arguments for the event that raised the exception.
-
discord.on_socket_raw_receive(msg)¶ Called whenever a message is received from the WebSocket, before it’s processed. This event is always dispatched when a message is received and the passed data is not processed in any way.
This is only really useful for grabbing the WebSocket stream and debugging purposes.
참고
This is only for the messages received from the client WebSocket. The voice WebSocket will not trigger this event.
-
discord.on_socket_raw_send(payload)¶ Called whenever a send operation is done on the WebSocket before the message is sent. The passed parameter is the message that is being sent to the WebSocket.
This is only really useful for grabbing the WebSocket stream and debugging purposes.
참고
This is only for the messages sent from the client WebSocket. The voice WebSocket will not trigger this event.
-
discord.on_typing(channel, user, when)¶ 유저가 메세지 작성을 시작하면 작동합니다.
channel의 매개변수는abc.Messageable의 인스턴스입니다. 이것이TextChannel,GroupChannel, 혹은DMChannel가 될수도 있습니다..만약에
channel에 대한TextChannel유저라면user매게변수값이Member로 반환되고, 아닐경우User로 반환됩니다.This requires
Intents.typingto be enabled.- 매개변수
channel (
abc.Messageable) – 유저가 작성한 채널의 값을 불러옵니다.when (
datetime.datetime) – datetime형태로 작성을 시작한 시간을 UTC 기준으로 값을 불러옵니다.
-
discord.on_message(message)¶ Message가 보내졌을때, 작동합니다.This requires
Intents.messagesto be enabled.경고
봇의 메세지과 개인 이벤트는 이 이벤트를 통해 전송됩니다.봇이 프로그래밍된 방식에 따라, <재귀> 현상이 발생할 수 있습니다.따라서, 봇 자신에 응답하지 않게할려면, 사용자ID 확인을 해보시기 바랍니다.이 현상은
Bot에서 발생하지는 않습니다.- 매개변수
message (
Message) – 현재의 메세지
-
discord.on_message_delete(message)¶ 메시지가 삭제 될 때 호출됩니다. 내부 메시지 캐시에서 메시지를 찾을 수 없으면이 이벤트가 호출되지 않습니다.메시지가 너무 오래되었거나 클라이언트가 트래픽 길드에 참여하는 경우 메시지가 캐시에 없을 수 있습니다.
이럴 경우,
Client.max_messages의 값을 늘리거나 해당on_raw_message_delete()이벤트 사용을 해보시기 바랍니다.This requires
Intents.messagesto be enabled.- 매개변수
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_messagesattribute or use theon_raw_bulk_message_delete()event instead.This requires
Intents.messagesto be enabled.- 매개변수
messages (List[
Message]) – The messages that have been deleted.
-
discord.on_raw_message_delete(payload)¶ Called when a message is deleted. Unlike
on_message_delete(), this is called regardless of the message being in the internal message cache or not.If the message is found in the message cache, it can be accessed via
RawMessageDeleteEvent.cached_messageThis requires
Intents.messagesto be enabled.- 매개변수
payload (
RawMessageDeleteEvent) – The raw event payload data.
-
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_messagesThis requires
Intents.messagesto be enabled.- 매개변수
payload (
RawBulkMessageDeleteEvent) – The raw event payload data.
-
discord.on_message_edit(before, after)¶ Called when a
Messagereceives 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_messagesattribute or use theon_raw_message_edit()event instead.The following non-exhaustive cases trigger this event:
A message has been pinned or unpinned.
The message content has been changed.
The message has received an embed.
For performance reasons, the embed server does not do this in a 《consistent》 manner.
The message’s embeds were suppressed or unsuppressed.
A call message has received an update to its participants or ending time.
This requires
Intents.messagesto be enabled.
-
discord.on_raw_message_edit(payload)¶ Called when a message is edited. Unlike
on_message_edit(), this is called regardless of the state of the internal message cache.If the message is found in the message cache, it can be accessed via
RawMessageUpdateEvent.cached_message. The cached message represents the message before it has been edited. For example, if the content of a message is modified and triggers theon_raw_message_edit()coroutine, theRawMessageUpdateEvent.cached_messagewill return aMessageobject that represents the message before the content was modified.Due to the inherently raw nature of this event, the data parameter coincides with the raw data given by the gateway.
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.This requires
Intents.messagesto be enabled.- 매개변수
payload (
RawMessageUpdateEvent) – The raw event payload data.
-
discord.on_reaction_add(reaction, user)¶ Called when a message has a reaction added to it. Similar to
on_message_edit(), if the message is not found in the internal message cache, then this event will not be called. Consider usingon_raw_reaction_add()instead.참고
To get the
Messagebeing reacted, access it viaReaction.message.This requires
Intents.reactionsto be enabled.참고
This doesn’t require
Intents.memberswithin a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider usingon_raw_reaction_add()if you need this and do not otherwise want to enable the members intent.
-
discord.on_raw_reaction_add(payload)¶ Called when a message has a reaction added. Unlike
on_reaction_add(), this is called regardless of the state of the internal message cache.This requires
Intents.reactionsto be enabled.- 매개변수
payload (
RawReactionActionEvent) – The raw event payload data.
-
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.This requires
Intents.reactionsto be enabled.
-
discord.on_raw_reaction_remove(payload)¶ Called when a message has a reaction removed. Unlike
on_reaction_remove(), this is called regardless of the state of the internal message cache.This requires
Intents.reactionsto be enabled.- 매개변수
payload (
RawReactionActionEvent) – The raw event payload data.
-
discord.on_reaction_clear(message, reactions)¶ Called when a message has all its reactions removed from it. Similar to
on_message_edit(), if the message is not found in the internal message cache, then this event will not be called. Consider usingon_raw_reaction_clear()instead.This requires
Intents.reactionsto be enabled.
-
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.This requires
Intents.reactionsto be enabled.- 매개변수
payload (
RawReactionClearEvent) – The raw event payload data.
-
discord.on_reaction_clear_emoji(reaction)¶ Called when a message has a specific reaction removed from it. Similar to
on_message_edit(), if the message is not found in the internal message cache, then this event will not be called. Consider usingon_raw_reaction_clear_emoji()instead.This requires
Intents.reactionsto be enabled.버전 1.3에 추가.
- 매개변수
reaction (
Reaction) – The reaction that got cleared.
-
discord.on_raw_reaction_clear_emoji(payload)¶ Called when a message has a specific reaction removed from it. Unlike
on_reaction_clear_emoji()this is called regardless of the state of the internal message cache.This requires
Intents.reactionsto be enabled.버전 1.3에 추가.
- 매개변수
payload (
RawReactionClearEmojiEvent) – The raw event payload data.
-
discord.on_private_channel_delete(channel)¶ -
discord.on_private_channel_create(channel)¶ Called whenever a private channel is deleted or created.
This requires
Intents.messagesto be enabled.- 매개변수
channel (
abc.PrivateChannel) – The private channel 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.
This requires
Intents.messagesto be enabled.- 매개변수
before (
GroupChannel) – The updated group channel’s old info.after (
GroupChannel) – The updated group channel’s new info.
-
discord.on_private_channel_pins_update(channel, last_pin)¶ Called whenever a message is pinned or unpinned from a private channel.
- 매개변수
channel (
abc.PrivateChannel) – The private channel that had its pins updated.last_pin (Optional[
datetime.datetime]) – The latest message that was pinned as a naive datetime in UTC. Could beNone.
-
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.This requires
Intents.guildsto be enabled.- 매개변수
channel (
abc.GuildChannel) – The guild channel 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.
This requires
Intents.guildsto be enabled.- 매개변수
before (
abc.GuildChannel) – The updated guild channel’s old info.after (
abc.GuildChannel) – The updated guild channel’s new info.
-
discord.on_guild_channel_pins_update(channel, last_pin)¶ Called whenever a message is pinned or unpinned from a guild channel.
This requires
Intents.guildsto be enabled.- 매개변수
channel (
abc.GuildChannel) – The guild channel that had its pins updated.last_pin (Optional[
datetime.datetime]) – The latest message that was pinned as a naive datetime in UTC. Could beNone.
-
discord.on_guild_integrations_update(guild)¶ 버전 1.4에 추가.
Called whenever an integration is created, modified, or removed from a guild.
This requires
Intents.integrationsto be enabled.- 매개변수
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.
This requires
Intents.webhooksto be enabled.- 매개변수
channel (
abc.GuildChannel) – The channel that had its webhooks updated.
-
discord.on_member_join(member)¶ -
discord.on_member_remove(member)¶ Called when a
Memberleaves or joins aGuild.This requires
Intents.membersto be enabled.- 매개변수
member (
Member) – The member who joined or left.
-
discord.on_member_update(before, after)¶ Called when a
Memberupdates their profile.This is called when one or more of the following things change:
status
activity
nickname
roles
pending
This requires
Intents.membersto be enabled.
-
discord.on_user_update(before, after)¶ Called when a
Userupdates their profile.This is called when one or more of the following things change:
avatar
username
discriminator
This requires
Intents.membersto be enabled.
-
discord.on_guild_join(guild)¶ Called when a
Guildis either created by theClientor when theClientjoins a guild.This requires
Intents.guildsto be enabled.- 매개변수
guild (
Guild) – The guild that was joined.
-
discord.on_guild_remove(guild)¶ Called when a
Guildis removed from theClient.This happens through, but not limited to, these circumstances:
The client got banned.
The client got kicked.
The client left the guild.
The client or the guild owner deleted the guild.
In order for this event to be invoked then the
Clientmust have been part of the guild to begin with. (i.e. it is part ofClient.guilds)This requires
Intents.guildsto be enabled.- 매개변수
guild (
Guild) – The guild that got removed.
-
discord.on_guild_update(before, after)¶ Called when a
Guildupdates, for example:Changed name
Changed AFK channel
Changed AFK timeout
etc
This requires
Intents.guildsto be enabled.
-
discord.on_guild_role_create(role)¶ -
discord.on_guild_role_delete(role)¶ Called when a
Guildcreates or deletes a newRole.To get the guild it belongs to, use
Role.guild.This requires
Intents.guildsto be enabled.- 매개변수
role (
Role) – The role that was created or deleted.
-
discord.on_guild_role_update(before, after)¶ Called when a
Roleis changed guild-wide.This requires
Intents.guildsto be enabled.
-
discord.on_guild_emojis_update(guild, before, after)¶ Called when a
Guildadds or removesEmoji.This requires
Intents.emojisto be enabled.
-
discord.on_guild_available(guild)¶ Called when a guild becomes available or unavailable. The guild must have existed in the
Client.guildscache.This requires
Intents.guildsto be enabled.- 매개변수
guild – The
Guildthat has changed availability.
-
discord.on_voice_state_update(member, before, after)¶ Called when a
Memberchanges theirVoiceState.The following, but not limited to, examples illustrate when this event is called:
A member joins a voice channel.
A member leaves a voice channel.
A member is muted or deafened by their own accord.
A member is muted or deafened by a guild administrator.
This requires
Intents.voice_statesto be enabled.- 매개변수
member (
Member) – The member whose voice states changed.before (
VoiceState) – The voice state prior to the changes.after (
VoiceState) – The voice state after to the changes.
-
discord.on_member_ban(guild, user)¶ Called when user gets banned from a
Guild.This requires
Intents.bansto be enabled.
-
discord.on_member_unban(guild, user)¶ Called when a
Usergets unbanned from aGuild.This requires
Intents.bansto be enabled.
-
discord.on_invite_create(invite)¶ Called when an
Inviteis created. You must have themanage_channelspermission to receive this.버전 1.3에 추가.
참고
There is a rare possibility that the
Invite.guildandInvite.channelattributes will be ofObjectrather than the respective models.This requires
Intents.invitesto be enabled.- 매개변수
invite (
Invite) – 생성된 초대.
-
discord.on_invite_delete(invite)¶ Called when an
Inviteis deleted. You must have themanage_channelspermission to receive this.버전 1.3에 추가.
참고
There is a rare possibility that the
Invite.guildandInvite.channelattributes will be ofObjectrather than the respective models.Outside of those two attributes, the only other attribute guaranteed to be filled by the Discord gateway for this event is
Invite.code.This requires
Intents.invitesto be enabled.- 매개변수
invite (
Invite) – 삭제된 초대.
-
discord.on_group_join(channel, user)¶ -
discord.on_group_remove(channel, user)¶ Called when someone joins or leaves a
GroupChannel.- 매개변수
channel (
GroupChannel) – The group that the user joined or left.user (
User) – The user that joined or left.
-
discord.on_relationship_add(relationship)¶ -
discord.on_relationship_remove(relationship)¶ Called when a
Relationshipis added or removed from theClientUser.버전 1.7부터 폐지.
- 매개변수
relationship (
Relationship) – The relationship that was added or removed.
-
discord.on_relationship_update(before, after)¶ Called when a
Relationshipis updated, e.g. when you block a friend or a friendship is accepted.버전 1.7부터 폐지.
- 매개변수
before (
Relationship) – The previous relationship status.after (
Relationship) – The updated relationship status.
Utility Functions¶
-
discord.utils.find(predicate, seq)¶ A helper to return the first element found in the sequence that meets the predicate. For example:
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
would find the first
Memberwhose name is 〈Mighty〉 and return it. If an entry is not found, thenNoneis 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 forfind().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__yas the keyword argument.If nothing is found that matches the attributes passed, then
Noneis 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)¶ - 매개변수
id (
int) – The snowflake ID.- 반환값
The creation date in UTC of a Discord snowflake 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.
- 반환값
The OAuth2 URL for inviting the bot into guilds.
- 반환 형식
-
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.
- 반환 형식
-
discord.utils.escape_mentions(text)¶ A helper function that escapes everyone, here, role, and user mentions.
참고
This does not include channel mentions.
참고
For more granular control over what mentions should be escaped within messages, refer to the
AllowedMentionsclass.
-
discord.utils.resolve_template(code)¶ Resolves a template code from a
Template, URL or code.버전 1.4에 추가.
-
await
discord.utils.sleep_until(when, result=None)¶ 이 함수는 코루틴 입니다.
Sleep until a specified time.
If the time supplied is in the past this function will yield instantly.
버전 1.3에 추가.
- 매개변수
when (
datetime.datetime) – The timestamp in which to sleep until. If the datetime is naive then it is assumed to be in UTC.result (Any) – If provided is returned to the caller when the coroutine completes.
Profile¶
-
class
discord.Profile¶ A namedtuple representing a user’s Discord public profile.
버전 1.7부터 폐지.
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
Noneif not applicable.
-
hypesquad_houses¶ A list of
HypeSquadHousethat the user is in.- 타입
List[
HypeSquadHouse]
-
system¶ A boolean indicating if the user is officially part of the Discord urgent message system.
버전 1.3에 추가.
- 타입
-
mutual_guilds¶ A list of
Guildthat theClientUsershares with this user.- 타입
List[
Guild]
Enumerations¶
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.
All enumerations are subclasses of an internal class which mimics the behaviour
of enum.Enum.
-
class
discord.ChannelType¶ Specifies the type of channel.
-
text¶ A text channel.
-
voice¶ A voice channel.
-
private¶ A private text channel. Also called a direct message.
-
group¶ A private group text channel.
-
category¶ A category 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.-
x == y Checks if two messages are equal.
-
x != y Checks if two messages are not equal.
-
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.
The system message denoting that a member has 《nitro boosted》 a guild.
The system message denoting that a member has 《nitro boosted》 a guild and it achieved level 1.
The system message denoting that a member has 《nitro boosted》 a guild and it achieved level 2.
The system message denoting that a member has 《nitro boosted》 a guild and it achieved level 3.
-
channel_follow_add¶ The system message denoting that an announcement channel has been followed.
버전 1.3에 추가.
-
guild_stream¶ The system message denoting that a member is streaming in the guild.
버전 1.7에 추가.
-
guild_discovery_disqualified¶ The system message denoting that the guild is no longer eligible for Server Discovery.
버전 1.7에 추가.
-
guild_discovery_requalified¶ The system message denoting that the guild has become eligible again for Server Discovery.
버전 1.7에 추가.
-
guild_discovery_grace_period_initial_warning¶ The system message denoting that the guild has failed to meet the Server Discovery requirements for one week.
버전 1.7에 추가.
-
guild_discovery_grace_period_final_warning¶ The system message denoting that the guild has failed to meet the Server Discovery requirements for 3 weeks in a row.
버전 1.7에 추가.
-
-
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.
-
custom¶ A custom activity type.
-
competing¶ A competing activity type.
버전 1.5에 추가.
-
-
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.
-
dubai¶ The Dubai region.
버전 1.3에 추가.
-
eu_central¶ The EU Central region.
-
eu_west¶ The EU West region.
-
europe¶ The Europe region.
버전 1.3에 추가.
-
frankfurt¶ The Frankfurt region.
-
hongkong¶ The Hong Kong region.
-
india¶ The India region.
버전 1.2에 추가.
-
japan¶ The Japan region.
-
london¶ The London region.
-
russia¶ The Russia region.
-
singapore¶ The Singapore region.
-
southafrica¶ The South Africa region.
-
south_korea¶ The South Korea 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
Guildhas 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 beofflineinstead.
-
-
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
targetis theGuild.Possible attributes for
AuditLogDiff:
-
channel_create¶ A new channel was created.
When this is the action, the type of
targetis either aabc.GuildChannelorObjectwith an ID.A more filled out object in the
Objectcase 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
targetis theabc.GuildChannelorObjectwith an ID.A more filled out object in the
Objectcase can be found by usingafterorbefore.Possible attributes for
AuditLogDiff:
-
channel_delete¶ A channel was deleted.
When this is the action, the type of
targetis anObjectwith an ID.A more filled out object can be found by using the
beforeobject.Possible attributes for
AuditLogDiff:
-
overwrite_create¶ A channel permission overwrite was created.
When this is the action, the type of
targetis theabc.GuildChannelorObjectwith an ID.When this is the action, the type of
extrais either aRoleorMember. If the object is not found then it is aObjectwith an ID being filled, a name, and atypeattribute 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_createfor more information on how thetargetandextrafields are set.Possible attributes for
AuditLogDiff:
-
overwrite_delete¶ A channel permission overwrite was deleted.
See
overwrite_createfor more information on how thetargetandextrafields are set.Possible attributes for
AuditLogDiff:
-
kick¶ A member was kicked.
When this is the action, the type of
targetis theUserwho got kicked.When this is the action,
changesis empty.
-
member_prune¶ A member prune was triggered.
When this is the action, the type of
targetis set toNone.When this is the action, the type of
extrais 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,
changesis empty.
-
ban¶ A member was banned.
When this is the action, the type of
targetis theUserwho got banned.When this is the action,
changesis empty.
-
unban¶ A member was unbanned.
When this is the action, the type of
targetis theUserwho got unbanned.When this is the action,
changesis 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
targetis theMemberorUserwho 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
targetis theMemberorUserwho got the role.Possible attributes for
AuditLogDiff:
-
member_move¶ A member’s voice channel has been updated. This triggers when a member is moved to a different voice channel.
When this is the action, the type of
extrais set to an unspecified proxy object with two attributes:channel: ATextChannelorObjectwith the channel ID where the members were moved.count: An integer specifying how many members were moved.
버전 1.3에 추가.
-
member_disconnect¶ A member’s voice state has changed. This triggers when a member is force disconnected from voice.
When this is the action, the type of
extrais set to an unspecified proxy object with one attribute:count: An integer specifying how many members were disconnected.
버전 1.3에 추가.
-
bot_add¶ A bot was added to the guild.
When this is the action, the type of
targetis theMemberorUserwhich was added to the guild.버전 1.3에 추가.
-
role_create¶ A new role was created.
When this is the action, the type of
targetis theRoleor aObjectwith 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
targetis theRoleor aObjectwith the ID.Possible attributes for
AuditLogDiff:
-
role_delete¶ A role was deleted.
When this is the action, the type of
targetis theRoleor aObjectwith the ID.Possible attributes for
AuditLogDiff:
-
invite_create¶ An invite was created.
When this is the action, the type of
targetis theInvitethat was created.Possible attributes for
AuditLogDiff:
-
invite_update¶ An invite was updated.
When this is the action, the type of
targetis theInvitethat was updated.
-
invite_delete¶ An invite was deleted.
When this is the action, the type of
targetis theInvitethat was deleted.Possible attributes for
AuditLogDiff:
-
webhook_create¶ A webhook was created.
When this is the action, the type of
targetis theObjectwith 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
targetis theObjectwith the webhook ID.Possible attributes for
AuditLogDiff:
-
webhook_delete¶ A webhook was deleted.
When this is the action, the type of
targetis theObjectwith the webhook ID.Possible attributes for
AuditLogDiff:
-
emoji_create¶ An emoji was created.
When this is the action, the type of
targetis theEmojiorObjectwith 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
targetis theEmojiorObjectwith the emoji ID.Possible attributes for
AuditLogDiff:
-
emoji_delete¶ An emoji was deleted.
When this is the action, the type of
targetis theObjectwith the emoji ID.Possible attributes for
AuditLogDiff:
-
message_delete¶ A message was deleted by a moderator. Note that this only triggers if the message was deleted by someone other than the author.
When this is the action, the type of
targetis theMemberorUserwho had their message deleted.When this is the action, the type of
extrais set to an unspecified proxy object with two attributes:count: An integer specifying how many messages were deleted.channel: ATextChannelorObjectwith the channel ID where the message got deleted.
-
message_bulk_delete¶ Messages were bulk deleted by a moderator.
When this is the action, the type of
targetis theTextChannelorObjectwith the ID of the channel that was purged.When this is the action, the type of
extrais set to an unspecified proxy object with one attribute:count: An integer specifying how many messages were deleted.
버전 1.3에 추가.
-
message_pin¶ A message was pinned in a channel.
When this is the action, the type of
targetis theMemberorUserwho had their message pinned.When this is the action, the type of
extrais set to an unspecified proxy object with two attributes:channel: ATextChannelorObjectwith the channel ID where the message was pinned.message_id: the ID of the message which was pinned.
버전 1.3에 추가.
-
message_unpin¶ A message was unpinned in a channel.
When this is the action, the type of
targetis theMemberorUserwho had their message unpinned.When this is the action, the type of
extrais set to an unspecified proxy object with two attributes:channel: ATextChannelorObjectwith the channel ID where the message was unpinned.message_id: the ID of the message which was unpinned.
버전 1.3에 추가.
-
integration_create¶ A guild integration was created.
When this is the action, the type of
targetis theObjectwith the integration ID of the integration which was created.버전 1.3에 추가.
-
-
class
discord.AuditLogActionCategory¶ Represents the category that the
AuditLogActionbelongs to.This can be retrieved via
AuditLogEntry.category.-
create¶ The action is the creation of something.
-
delete¶ The action is the deletion of something.
-
update¶ The action is the update of something.
-
-
class
discord.RelationshipType¶ Specifies the type of
Relationship.버전 1.7부터 폐지.
참고
This only applies to users, not bots.
-
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.UserContentFilter¶ Represents the options found in
Settings > Privacy & Safety > Safe Direct Messagingin the Discord client.버전 1.7부터 폐지.
참고
This only applies to users, not bots.
-
all_messages¶ Scan all direct messages from everyone.
-
friends¶ Scan all direct messages that aren’t from friends.
-
disabled¶ Don’t scan any direct messages.
-
-
class
discord.FriendFlags¶ Represents the options found in
Settings > Privacy & Safety > Who Can Add You As A Friendin the Discord client.버전 1.7부터 폐지.
참고
This only applies to users, not bots.
-
noone¶ This allows no-one to add you as a friend.
-
mutual_guilds¶ This allows guild members to add you as a friend.
-
mutual_friends¶ This allows friends of friends to add you as a friend.
-
guild_and_friends¶ This is a superset of
mutual_guildsandmutual_friends.
-
everyone¶ This allows everyone to add you as a friend.
-
-
class
discord.PremiumType¶ Represents the user’s Discord Nitro subscription type.
버전 1.7부터 폐지.
참고
This only applies to users, not bots.
-
nitro¶ Represents the Discord Nitro with Nitro-exclusive games.
-
nitro_classic¶ Represents the Discord Nitro with no Nitro-exclusive games.
-
-
class
discord.Theme¶ Represents the theme synced across all Discord clients.
버전 1.7부터 폐지.
참고
This only applies to users, not bots.
-
light¶ Represents the Light theme on Discord.
-
dark¶ Represents the Dark theme on Discord.
-
-
class
discord.TeamMembershipState¶ Represents the membership state of a team member retrieved through
Bot.application_info().버전 1.3에 추가.
-
invited¶ Represents an invited member.
-
accepted¶ Represents a member currently in the team.
-
-
class
discord.WebhookType¶ Represents the type of webhook that can be received.
버전 1.3에 추가.
-
incoming¶ Represents a webhook that can post messages to channels with a token.
-
channel_follower¶ Represents a webhook that is internally managed by Discord, used for following channels.
-
-
class
discord.ExpireBehaviour¶ Represents the behaviour the
Integrationshould perform when a user’s subscription has finished.There is an alias for this called
ExpireBehavior.버전 1.4에 추가.
-
remove_role¶ This will remove the
Integration.rolefrom the user when their subscription is finished.
-
kick¶ This will kick the user when their subscription is finished.
-
-
class
discord.DefaultAvatar¶ Represents the default avatar of a Discord
User-
blurple¶ Represents the default avatar with the color blurple. See also
Colour.blurple
-
grey¶ Represents the default avatar with the color grey. See also
Colour.greyple
-
green¶ Represents the default avatar with the color green. See also
Colour.green
-
orange¶ Represents the default avatar with the color orange. See also
Colour.orange
-
red¶ Represents the default avatar with the color red. See also
Colour.red
-
Async Iterator¶
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.
-
await
next()¶ 이 함수는 코루틴 입니다.
Advances the iterator by one, if possible. If no more items are found then this raises
NoMoreItems.
-
await
get(**attrs)¶ 이 함수는 코루틴 입니다.
Similar to
utils.get()except run over the async iterator.Getting the last message by a user named 〈Dave〉 or
None:msg = await channel.history().get(author__name='Dave')
-
await
find(predicate)¶ 이 함수는 코루틴 입니다.
Similar to
utils.find()except run over the async iterator.Unlike
utils.find(), the predicate provided can be a 코루틴.Getting the last audit log with a reason or
None:def predicate(event): return event.reason is not None event = await guild.audit_logs().find(predicate)
- 매개변수
predicate – The predicate to use. Could be a 코루틴.
- 반환값
The first element that returns
Truefor the predicate orNone.
-
await
flatten()¶ 이 함수는 코루틴 입니다.
Flattens the async iterator into a
listwith all the elements.- 반환값
A list of every element in the async iterator.
- 반환 형식
-
chunk(max_size)¶ Collects items into chunks of up to a given maximum size. Another
AsyncIteratoris returned which collects items intolists of a given size. The maximum chunk size must be a positive integer.버전 1.6에 추가.
Collecting groups of users:
async for leader, *users in reaction.users().chunk(3): ...
경고
The last chunk collected may not be as large as
max_size.- 매개변수
max_size – The size of individual chunks.
- 반환 형식
-
map(func)¶ This is similar to the built-in
mapfunction. AnotherAsyncIteratoris returned that executes the function on every element it is iterating over. This function can either be a regular function or a 코루틴.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 코루틴.
- 반환 형식
-
filter(predicate)¶ This is similar to the built-in
filterfunction. AnotherAsyncIteratoris returned that filters over the original async iterator. This predicate can be a regular function or a 코루틴.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 코루틴.
- 반환 형식
-
Audit Log Data¶
Working with Guild.audit_logs() is a complicated process with a lot of machinery
involved. The library attempts to make it easy to use and friendly. In order to accomplish
this goal, it must make use of a couple of data classes that aid in this goal.
AuditLogEntry¶
-
class
discord.AuditLogEntry(*, users, data, guild)¶ Represents an Audit Log entry.
You retrieve these via
Guild.audit_logs().-
action¶ The action that was done.
-
target¶ The target that got changed. The exact type of this depends on the action being done.
- 타입
Any
-
extra¶ Extra information that this entry has that might be useful. For most actions, this is
None. However in some cases it contains extra information. SeeAuditLogActionfor which actions have this field filled out.- 타입
Any
-
created_at¶ Returns the entry’s creation time in UTC.
-
category¶ The category of the action, if applicable.
- 타입
Optional[
AuditLogActionCategory]
-
changes¶ The list of changes this entry has.
-
before¶ The target’s prior state.
- 타입
-
after¶ The target’s subsequent state.
- 타입
-
AuditLogChanges¶
-
class
discord.AuditLogChanges¶ An audit log change set.
-
before¶ The old value. The attribute has the type of
AuditLogDiff.Depending on the
AuditLogActionCategoryretrieved bycategory, the data retrieved by this attribute differs:
-
after¶ The new value. The attribute has the type of
AuditLogDiff.Depending on the
AuditLogActionCategoryretrieved bycategory, the data retrieved by this attribute differs:
-
AuditLogDiff¶
- afk_channel
- afk_timeout
- allow
- avatar
- bitrate
- channel
- code
- color
- colour
- deaf
- default_message_notifications
- default_notifications
- deny
- explicit_content_filter
- hoist
- icon
- id
- inviter
- max_age
- max_uses
- mentionable
- mfa_level
- mute
- name
- nick
- overwrites
- owner
- permissions
- position
- region
- roles
- slowmode_delay
- splash
- system_channel
- temporary
- topic
- type
- uses
- vanity_url_code
- verification_level
- widget_channel
- widget_enabled
-
class
discord.AuditLogDiff¶ Represents an audit log 《change》 object. A change object has dynamic attributes that depend on the type of action being done. Certain actions map to certain attributes being set.
Note that accessing an attribute that does not match the specified action will lead to an attribute error.
To get a list of attributes that have been set, you can iterate over them. To see a list of all possible attributes that could be set based on the action being done, check the documentation for
AuditLogAction, otherwise check the documentation below for all attributes that are possible.-
iter(diff) Returns an iterator over (attribute, value) tuple of this diff.
-
icon¶ A guild’s icon hash. See also
Guild.icon.- 타입
-
splash¶ The guild’s invite splash hash. See also
Guild.splash.- 타입
-
owner¶ The guild’s owner. See also
Guild.owner
-
region¶ The guild’s voice region. See also
Guild.region.- 타입
-
afk_channel¶ The guild’s AFK channel.
If this could not be found, then it falls back to a
Objectwith the ID being set.See
Guild.afk_channel.- 타입
Union[
VoiceChannel,Object]
-
system_channel¶ The guild’s system channel.
If this could not be found, then it falls back to a
Objectwith the ID being set.See
Guild.system_channel.- 타입
Union[
TextChannel,Object]
-
afk_timeout¶ The guild’s AFK timeout. See
Guild.afk_timeout.- 타입
-
mfa_level¶ The guild’s MFA level. See
Guild.mfa_level.- 타입
-
widget_channel¶ The widget’s channel.
If this could not be found then it falls back to a
Objectwith the ID being set.- 타입
Union[
TextChannel,Object]
-
verification_level¶ The guild’s verification level.
See also
Guild.verification_level.
-
default_notifications¶ The guild’s default notification level.
See also
Guild.default_notifications.
-
explicit_content_filter¶ The guild’s content filter.
See also
Guild.explicit_content_filter.
-
vanity_url_code¶ The guild’s vanity URL.
See also
Guild.vanity_invite()andGuild.edit().- 타입
-
position¶ The position of a
Roleorabc.GuildChannel.- 타입
-
type¶ The type of channel or channel permission overwrite.
If the type is an
int, then it is a type of channel which can be either0to indicate a text channel or1to indicate a voice channel.If the type is a
str, then it is a type of permission overwrite which can be either'role'or'member'.
-
topic¶ The topic of a
TextChannel.See also
TextChannel.topic.- 타입
-
bitrate¶ The bitrate of a
VoiceChannel.See also
VoiceChannel.bitrate.- 타입
-
overwrites¶ A list of permission overwrite tuples that represents a target and a
PermissionOverwritefor said target.The first element is the object being targeted, which can either be a
MemberorUserorRole. If this object is not found then it is aObjectwith an ID being filled and atypeattribute set to either'role'or'member'to help decide what type of ID it is.- 타입
List[Tuple[target,
PermissionOverwrite]]
-
roles¶ A list of roles being added or removed from a member.
If a role is not found then it is a
Objectwith the ID and name being filled in.
-
nick¶ The nickname of a member.
See also
Member.nick- 타입
Optional[
str]
-
deaf¶ Whether the member is being server deafened.
See also
VoiceState.deaf.- 타입
-
mute¶ Whether the member is being server muted.
See also
VoiceState.mute.- 타입
-
permissions¶ The permissions of a role.
See also
Role.permissions.- 타입
-
colour¶ -
color¶ The colour of a role.
See also
Role.colour- 타입
-
hoist¶ Whether the role is being hoisted or not.
See also
Role.hoist- 타입
-
mentionable¶ Whether the role is mentionable or not.
See also
Role.mentionable- 타입
-
code¶ The invite’s code.
See also
Invite.code- 타입
-
channel¶ A guild channel.
If the channel is not found then it is a
Objectwith the ID being set. In some cases the channel name is also set.- 타입
Union[
abc.GuildChannel,Object]
-
inviter¶ 초대를 만든 사용자.
See also
Invite.inviter.- 타입
-
max_uses¶ The invite’s max uses.
See also
Invite.max_uses.- 타입
-
uses¶ The invite’s current uses.
See also
Invite.uses.- 타입
-
max_age¶ The invite’s max age in seconds.
See also
Invite.max_age.- 타입
-
temporary¶ If the invite is a temporary invite.
See also
Invite.temporary.- 타입
-
avatar¶ The avatar hash of a member.
See also
User.avatar.- 타입
-
slowmode_delay¶ The number of seconds members have to wait before sending another message in the channel.
See also
TextChannel.slowmode_delay.- 타입
-
Webhook Support¶
discord.py offers support for creating, editing, and executing webhooks through the Webhook class.
Webhook¶
- clsWebhook.from_url
- clsWebhook.partial
- defavatar_url_as
- defdelete
- defdelete_message
- defedit
- defedit_message
- defexecute
- defsend
-
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 either aiohttp or requests.For example, creating a webhook from a URL and using aiohttp:
from discord import Webhook, AsyncWebhookAdapter import aiohttp async def foo(): async with aiohttp.ClientSession() as session: webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session)) await webhook.send('Hello World', username='Foo')
Or creating a webhook from an ID and token and using requests:
import requests from discord import Webhook, RequestsWebhookAdapter webhook = Webhook.partial(123456, 'abcdefg', adapter=RequestsWebhookAdapter()) webhook.send('Hello World', username='Foo')
-
x == y Checks if two webhooks are equal.
-
x != y Checks if two webhooks are not equal.
-
hash(x) Returns the webhooks’s hash.
버전 1.4에서 변경: Webhooks are now comparable and hashable.
-
type¶ The type of the webhook.
버전 1.3에 추가.
- 타입
-
token¶ The authentication token of the webhook. If this is
Nonethen the webhook cannot be used to make requests.- 타입
Optional[
str]
-
user¶ The user this webhook was created by. If the webhook was received without authentication then this will be
None.- 타입
Optional[
abc.User]
-
classmethod
partial(id, token, *, adapter)¶ Creates a partial
Webhook.- 매개변수
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 typicallyAsyncWebhookAdapterfor aiohttp orRequestsWebhookAdapterfor requests.
- 반환값
A partial
Webhook. A partial webhook is just a webhook object with an ID and a token.- 반환 형식
-
classmethod
from_url(url, *, adapter)¶ Creates a partial
Webhookfrom a webhook URL.- 매개변수
url (
str) – The URL of the webhook.adapter (
WebhookAdapter) – The webhook adapter to use when sending requests. This is typicallyAsyncWebhookAdapterfor aiohttp orRequestsWebhookAdapterfor requests.
- 예외
InvalidArgument – The URL is invalid.
- 반환값
A partial
Webhook. A partial webhook is just a webhook object with an ID and a token.- 반환 형식
-
guild¶ The guild this webhook belongs to.
If this is a partial webhook, then this will always return
None.- 타입
Optional[
Guild]
-
channel¶ The text channel this webhook belongs to.
If this is a partial webhook, then this will always return
None.- 타입
Optional[
TextChannel]
-
created_at¶ Returns the webhook’s creation time in UTC.
-
avatar_url¶ Returns an
Assetfor the avatar the webhook has.If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead.
This is equivalent to calling
avatar_url_as()with the default parameters.- 타입
-
avatar_url_as(*, format=None, size=1024)¶ Returns an
Assetfor the avatar the webhook has.If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead.
The format must be one of 〈jpeg〉, 〈jpg〉, or 〈png〉. The size must be a power of 2 between 16 and 1024.
- 매개변수
- 예외
InvalidArgument – Bad image format passed to
formator invalidsize.- 반환값
The resulting CDN asset.
- 반환 형식
-
delete(*, reason=None)¶ 이 함수는 코루틴 일 수 있습니다.
Deletes this Webhook.
If the webhook is constructed with a
RequestsWebhookAdapterthen this is not a coroutine.- 매개변수
reason (Optional[
str]) –The reason for deleting this webhook. Shows up on the audit log.
버전 1.4에 추가.
- 예외
HTTPException – Deleting the webhook failed.
NotFound – This webhook does not exist.
Forbidden – You do not have permissions to delete this webhook.
InvalidArgument – This webhook does not have a token associated with it.
-
edit(*, reason=None, **kwargs)¶ 이 함수는 코루틴 일 수 있습니다.
Edits this Webhook.
If the webhook is constructed with a
RequestsWebhookAdapterthen 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.reason (Optional[
str]) –The reason for editing this webhook. Shows up on the audit log.
버전 1.4에 추가.
- 예외
HTTPException – Editing the webhook failed.
NotFound – This webhook does not exist.
InvalidArgument – This webhook does not have a token associated with it.
-
send(content=None, *, wait=False, username=None, avatar_url=None, tts=False, file=None, files=None, embed=None, embeds=None, allowed_mentions=None)¶ 이 함수는 코루틴 일 수 있습니다.
Sends a message using the webhook.
If the webhook is constructed with a
RequestsWebhookAdapterthen 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
fileparameter should be used with a singleFileobject.If the
embedparameter is provided, it must be of typeEmbedand it must be a rich embed type. You cannot mix theembedparameter with theembedsparameter, which must be alistofEmbedobjects to send.- 매개변수
content (
str) – 보낼 메시지의 내용(컨텐츠).wait (
bool) – Whether the server should wait before sending a response. This essentially means that the return type of this function changes fromNoneto aWebhookMessageif 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) – 텍스트 음성 변환을 사용하여 메시지를 보내야 하는지 여부를 나타냅니다.file (
File) – The file to upload. This cannot be mixed withfilesparameter.files (List[
File]) – A list of files to send with the content. This cannot be mixed with thefileparameter.embed (
Embed) – The rich embed for the content to send. This cannot be mixed withembedsparameter.embeds (List[
Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembedparameter.allowed_mentions (
AllowedMentions) – 이 메시지에서 처리되는 멘션을 제어합니다.
- 예외
HTTPException – 메시지 전송에 실패했습니다.
NotFound – This webhook was not found.
Forbidden – The authorization token for the webhook is incorrect.
InvalidArgument – You specified both
embedandembedsor the length ofembedswas invalid or there was no token associated with this webhook.
- 반환값
전송한 메시지.
- 반환 형식
Optional[
WebhookMessage]
-
edit_message(message_id, **fields)¶ 이 함수는 코루틴 일 수 있습니다.
Edits a message owned by this webhook.
This is a lower level interface to
WebhookMessage.edit()in case you only have an ID.버전 1.6에 추가.
- 매개변수
message_id (
int) – The message ID to edit.content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.
- 예외
HTTPException – 메시지 편집에 실패했습니다.
Forbidden – Edited a message that is not yours.
InvalidArgument – You specified both
embedandembedsor the length ofembedswas invalid or there was no token associated with this webhook.
-
delete_message(message_id)¶ 이 함수는 코루틴 일 수 있습니다.
Deletes a message owned by this webhook.
This is a lower level interface to
WebhookMessage.delete()in case you only have an ID.버전 1.6에 추가.
- 매개변수
message_id (
int) – The message ID to delete.- 예외
HTTPException – 메시지 삭제에 실패했습니다.
Forbidden – Deleted a message that is not yours.
-
WebhookMessage¶
-
class
discord.WebhookMessage(*, state, channel, data)¶ Represents a message sent from your webhook.
This allows you to edit or delete a message sent by your webhook.
This inherits from
discord.Messagewith changes toedit()anddelete()to work.버전 1.6에 추가.
-
edit(**fields)¶ 이 함수는 코루틴 일 수 있습니다.
메시지를 편집합니다.
내용은
str(내용)을 통해 문자열로 변환할 수 있어야 합니다.버전 1.6에 추가.
- 매개변수
content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.
- 예외
HTTPException – 메시지 편집에 실패했습니다.
Forbidden – Edited a message that is not yours.
InvalidArgument – You specified both
embedandembedsor the length ofembedswas invalid or there was no token associated with this webhook.
-
delete(*, delay=None)¶ 이 함수는 코루틴 입니다.
메시지를 삭제합니다.
- 매개변수
delay (Optional[
float]) – If provided, the number of seconds to wait before deleting the message. If this is a coroutine, the waiting is done in the background and deletion failures are ignored. If this is not a coroutine then the delay blocks the thread.- 예외
Forbidden – 메시지를 삭제할 수 있는 권한이 없습니다.
NotFound – The message was deleted already.
HTTPException – 메시지 삭제에 실패했습니다.
-
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.
Subclasses must implement this.
- 매개변수
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 afilekey which will have a 3-elementtupledenoting(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
Messageif necessary.Subclasses must implement this.
- 매개변수
data – The data that was returned from the request.
wait (
bool) – Whether the webhook execution was asked to wait or not.
-
-
class
discord.AsyncWebhookAdapter(session)¶ A webhook adapter suited for use with aiohttp.
참고
You are responsible for cleaning up the client session.
- 매개변수
session (
aiohttp.ClientSession) – The session to use to send requests.
-
await
request(verb, url, payload=None, multipart=None, *, files=None, reason=None)¶ Actually does the request.
Subclasses must implement this.
- 매개변수
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 afilekey which will have a 3-elementtupledenoting(filename, file, content_type).payload (Optional[
dict]) – The JSON to send with the request, if any.
-
await
handle_execution_response(response, *, wait)¶ Transforms the webhook execution response into something more meaningful.
This is mainly used to convert the data into a
Messageif necessary.Subclasses must implement this.
- 매개변수
data – The data that was returned from the request.
wait (
bool) – Whether the webhook execution was asked to wait or not.
-
class
discord.RequestsWebhookAdapter(session=None, *, sleep=True)¶ A webhook adapter suited for use with
requests.Only versions of requests higher than 2.13.0 are supported.
- 매개변수
session (Optional[requests.Session]) – The requests session to use for sending requests. If not given then each request will create a new session. Note if a session is given, the webhook adapter will not clean it up for you. You must close the session yourself.
sleep (
bool) – Whether to sleep the thread when encountering a 429 or pre-emptive rate limit or a 5xx status code. Defaults toTrue. If set toFalsethen this will raise anHTTPExceptioninstead.
-
request(verb, url, payload=None, multipart=None, *, files=None, reason=None)¶ Actually does the request.
Subclasses must implement this.
- 매개변수
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 afilekey which will have a 3-elementtupledenoting(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
Messageif necessary.Subclasses must implement this.
- 매개변수
data – The data that was returned from the request.
wait (
bool) – Whether the webhook execution was asked to wait or not.
Abstract Base Classes¶
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.
Snowflake¶
-
class
discord.abc.Snowflake¶ An ABC that details the common operations on a Discord model.
Almost all Discord models meet this abstract base class.
If you want to create a snowflake on your own, consider using
Object.-
abstractmethod
created_at¶ Returns the model’s creation time as a naive datetime in UTC.
-
abstractmethod
유저¶
PrivateChannel¶
GuildChannel¶
- asyncclone
- asynccreate_invite
- asyncdelete
- asyncinvites
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
-
class
discord.abc.GuildChannel¶ An ABC that details the common operations on a Discord guild channel.
The following implement this ABC:
This ABC must also implement
Snowflake.-
created_at¶ 채널의 생성 시간을 UTC 시간으로 리턴합니다.
-
overwrites_for(obj)¶ 멤버 또는 역할에 대한 채널별 덮어쓰기를 리턴합니다.
- 매개변수
- 반환값
이 객체에 대한 권한 덮어쓰기.
- 반환 형식
-
overwrites¶ 채널의 모든 덮어쓰기를 리턴합니다.
이것은
Role또는Member가 될 수 있는 대상이 키에 포함되고, 값은PermissionOverwrite인딕셔너리로 리턴됩니다.- 반환값
채널의 권한 덮어쓰기.
- 반환 형식
Mapping[Union[
Role,Member],PermissionOverwrite]
-
category¶ 이 채널이 속해 있는 카테고리.
없을 경우
None입니다.- 타입
Optional[
CategoryChannel]
-
permissions_synced¶ 이 채널의 권한이 이 채널에 속한 카테고리와 동기화되는지 여부입니다.
만약 카테고리가 없다면
False입니다.버전 1.3에 추가.
- 타입
-
permissions_for(member)¶ 현재 멤버의 권한 확인을 처리합니다.
이 기능은 다음과 같은 경우를 고려합니다:
길드 소유자
길드 역할들
채널 덮어쓰기
멤버 덮어쓰기
- 매개변수
member (
Member) – 권한을 확인할 멤버.- 반환값
멤버에 대해 확인된 권한
- 반환 형식
-
await
delete(*, reason=None)¶ 이 함수는 코루틴 입니다.
채널을 삭제합니다.
이것을 사용하려면
manage_channels권한이 있어야 합니다.- 매개변수
reason (Optional[
str]) – 채널 삭제의 사유입니다. 감사 로그에 뜨게 됩니다.- 예외
Forbidden – 채널을 삭제할 권한이 없습니다.
NotFound – 채널을 찾을 수 없거나 이미 삭제되었습니다.
HTTPException – 채널 삭제에 실패했습니다.
-
await
set_permissions(target, *, overwrite=see - below, reason=None, **permissions)¶ 이 함수는 코루틴 입니다.
채널에 대한 특정 권한 덮어쓰기를 설정합니다.
target매개 변수는 길드에 속한Member또는Role이어야 합니다.overwrite매개 변수는, 제공된 경우None또는PermissionOverwrite이어야 합니다. 편의를 위해Permissions속성을 나타내는 키워드 인수를 전달할 수 있습니다. 이 작업을 수행하면 키워드 인수를overwrite매개 변수와 함께 쓸 수 없습니다.overwrite매개 변수가None이면, 권한 덮어쓰기가 삭제됩니다.이것을 사용하려면
manage_roles권한이 있어야 합니다.예제
허용 및 거부 설정하기:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
덮어쓰기 삭제하기
await channel.set_permissions(member, overwrite=None)
PermissionOverwrite사용하기overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- 매개변수
overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – 사용하기 쉽도록 설정하는 권한들의 키워드 인수.
overwrite와 함께 사용할 수 없습니다.reason (Optional[
str]) – 이 작업을 수행하는 사유. 감사 로그에 뜨게 됩니다.
- 예외
Forbidden – 채널별 권한을 편집할 권한이 없습니다.
HTTPException – 채널별 권한을 편집하는 데 실패했습니다.
NotFound – 편집하려는 역할 또는 멤버가 이 길드에 속해 있지 않습니다.
InvalidArgument – overwrite 매개 변수가 유효하지 않거나 target 의 타입이
Role또는Member가 아닙니다.
-
await
clone(*, name=None, reason=None)¶ 이 함수는 코루틴 입니다.
이 채널을 복제합니다. 이 채널과 동일한 속성을 가진 채널을 만듭니다.
You must have the
manage_channelspermission to do this.버전 1.1에 추가.
- 매개변수
- 예외
Forbidden – 이 채널을 생성할 권한이 없습니다.
HTTPException – 채널 생성에 실패했습니다.
- 반환값
The channel that was created.
- 반환 형식
-
await
create_invite(*, reason=None, **fields)¶ 이 함수는 코루틴 입니다.
Creates an instant invite from a text or voice channel.
이것을 사용하려면
create_instant_invite권한이 있어야 합니다.- 매개변수
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – 초대에 임시 회원 자격이 부여되는지를 나타냅니다. (즉, 연결이 끊어지면 추방됨.)기본값은False입니다.unique (
bool) – 고유한 초대 URL을 생성해야 하는지 나타냅니다. 기본값은True입니다.reason (Optional[
str]) – 이 초대 생성의 사유입니다. 감사 로그에 뜨게 됩니다.
- 예외
HTTPException – 초대 생성에 실패했습니다.
NotFound – The channel that was passed is a category or an invalid channel.
- 반환값
생성된 초대.
- 반환 형식
-
await
invites()¶ 이 함수는 코루틴 입니다.
이 채널의 모든 활성 인스턴트 초대 목록을 리턴합니다.
You must have
manage_channelsto get this information.- 예외
Forbidden – 이 정보를 얻기 위한 권한이 없습니다.
HTTPException – 이 정보를 가져오는 중에 오류가 발생했습니다.
- 반환값
현재 활성화된 초대 목록.
- 반환 형식
List[
Invite]
-
Messageable¶
- asyncfetch_message
- defhistory
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
-
class
discord.abc.Messageable¶ An ABC that details the common operations on a model that can send messages.
The following implement this ABC:
-
async for ... in
history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ 대상의 메시지 기록을 받을 수 있는
AsyncIterator를 반환합니다.이것을 사용하려면
read_message_history권한이 있어야 합니다.예제
사용법
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
리스트로 병합하기:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
모든 매개 변수는 선택 사항입니다.
- 매개변수
limit (Optional[
int]) – 받아올 메시지 수입니다.None일 경우, 채널에 있는 모든 메시지를 받아옵니다. 하지만 참고로, 이렇게 하면 작동이 느려질 수 있습니다.before (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이전의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.after (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이후의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.around (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 주변의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다. 이 매개변수를 사용할 때, 최대 제한은 101입니다. 제한이 짝수이면 최대 + 1 메시지를 리턴합니다.oldest_first (Optional[
bool]) –True로 설정되면 메시지를 가장 오래된 순서부터 리턴합니다.after가 지정되면 기본값은True이고, 그렇지 않으면False입니다.
- 예외
Forbidden – 메시지 기록을 볼 권한이 없습니다.
HTTPException – 메시지 기록 가져오기에 실패했습니다.
- Yields
Message– 매시지 데이터가 파싱된 메시지를 리턴합니다.
-
async with
typing()¶ 무기한으로 타이핑할 수 있는 컨텍스트 관리자를 리턴합니다.
이는 봇에서 긴 계산을 하고 있음을 나타내는 데 유용합니다.
참고
이것은 일반적인 컨텍스트 관리자이면서도 비동기 컨텍스트 관리자입니다. 이는
with와async with둘 다 작동한다는 것을 의미합니다.사용법 예제:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
-
await
send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)¶ 이 함수는 코루틴 입니다.
주어진 내용(컨텐츠)으로 대상에 메시지를 보냅니다.
컨텐츠는
str(content)을 통해 문자열로 변환할 수 있는 타입이여야 합니다. 내용이None(기본값)으로 설정되면embed매개 변수를 제공해야 합니다.단일 파일을 업로드하려면,
file매개 변수에 단일File객체를 사용해야 합니다. 여러 파일을 업로드하려면files매개 변수에File객체가 담긴list를 사용해야 합니다. 두 매개 변수를 모두 지정하면 예외가 발생합니다.embed매개 변수가 제공될 경우,Embed타입이여야 하며 이것은 rich embed 타입이여야 합니다.- 매개변수
content (
str) – 보낼 메시지의 내용(컨텐츠).tts (
bool) – 텍스트 음성 변환을 사용하여 메시지를 보내야 하는지 여부를 나타냅니다.embed (
Embed) – 콘텐츠의 리치 임베드.file (
File) – 업로드할 파일.files (List[
File]) – 업로드할 파일들의 리스트. 최대 10개여야 합니다.nonce (
int) – 이 메시지를 전송할 때 사용할 논스입니다. 메시지가 성공적으로 보내졌다면, 그 메시지에 이 값을 가진 논스가 있습니다.delete_after (
float) – 제공된 경우 방금 보낸 메시지를 삭제할 때 까지 백그라운드에서 대기하는 시간(초) 입니다. 삭제가 실패하면 자동으로 무시됩니다.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.버전 1.4에 추가.
reference (Union[
Message,MessageReference]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.버전 1.6에 추가.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.버전 1.6에 추가.
- 예외
HTTPException – 메시지 전송에 실패했습니다.
Forbidden – 메시지를 보낼 권한이 없습니다.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or thereferenceobject is not aMessageorMessageReference.
- 반환값
전송한 메시지.
- 반환 형식
-
await
trigger_typing()¶ 이 함수는 코루틴 입니다.
대상에 입력 중 표시기를 트리거합니다.
입력 중 표시기는 10초 후에 또는 메시지가 전송 된 후에 사라집니다.
-
await
fetch_message(id)¶ 이 함수는 코루틴 입니다.
대상에서 단일
Message를 검색합니다.오직 봇 계정에서만 사용할 수 있습니다.
- 매개변수
id (
int) – 찾을 메시지 ID.- 예외
NotFound – 지정된 메시지를 찾을 수 없습니다.
Forbidden – 메시지를 가져올 권한이 없습니다.
HTTPException – 메시지 가져오기에 실패했습니다.
- 반환값
요청한 메시지.
- 반환 형식
-
await
pins()¶ 이 함수는 코루틴 입니다.
채널에 현재 고정되어 있는 모든 메시지를 검색합니다.
참고
Discord API 제한으로 인해 이 메소드가 리턴한
Message객체는 완전한Message.reactions데이터를 포함하지 않습니다.- 예외
HTTPException – 고정된 메시지를 가져오는 데 실패했습니다.
- 반환값
현재 고정되어 있는 메시지들.
- 반환 형식
List[
Message]
-
async for ... in
Connectable¶
-
class
discord.abc.Connectable¶ An ABC that details the common operations on a channel that can connect to a voice server.
The following implement this ABC:
디스코드 모델¶
모델은 디스코드에서 수신되는 클래스로., 라이브러리 사용자에 의해 생성되지 않습니다
위험
The classes listed below are not intended to be created by users and are also read-only.
예를 들어, User 인스턴스를 직접 만들거나 User 인스턴스를 직접 수정해서는 안됩니다.
이런 모델 클래스 인스턴스 중 하나를 얻기 위해서는 캐시를 거치는 것이며, 그 중 가장 일반적인 방법은 Event Reference에 명시되어 있는 이벤트로부터 얻게 되는 모델 클래스의 utils.find() 함수 또는 속성을 거치는 것입니다.
참고
여기의 거의 모든 클래스에는 __slots__ 이 정의되어 있으므로 데이터 클래스에 동적 속성을 가질 수 없습니다.
클라이언트 사용자¶
- defavatar_url_as
- asynccreate_group
- asyncedit
- asyncedit_settings
- defget_relationship
- defis_avatar_animated
- defmentioned_in
- defpermissions_in
-
class
discord.ClientUser¶ 디스코드 사용자를 나타냅니다.
-
x == y 두 사용자가 같은지 확인합니다.
-
x != y 두 명의 사용자가 다른지 확인합니다.
-
hash(x) 사용자의 해시를 리턴합니다.
-
str(x) 태그와 함께 사용자 이름을 리턴합니다.
사용자가 프리미엄 사용자인지 여부를 지정(예 : Discord Nitro 사용)
버전 1.7부터 폐지.
- 타입
사용자가 가진 프리미엄 유형을 지정 (예 : Nitro 또는 Nitro Classic) 사용자가 프리미엄이 아닌 경우 None 일 수 있습니다.
버전 1.7부터 폐지.
- 타입
선택 사항 [
PremiumType]
-
get_relationship(user_id)¶ Relationship이 적용 가능한 경우를 검색버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 매개변수
user_id (
int) – 관련성이 있는지 확인할 사용자 ID- 반환값
가능한 경우 관련성 또는
None- 반환 형식
선택 사항[
Relationship]
-
relationships¶ 사용자가 가진 모든 관련성를 리턴
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 타입
리스트 [
User]
-
friends¶ 사용자와 친구인 모든 사용자를 리턴
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 타입
리스트 [
User]
-
blocked¶ 사용자가 차단한 모든 사용자를 리턴
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 타입
리스트 [
User]
-
await
edit(**fields)¶ 이 함수는 코루틴 입니다.
클라이언트의 프로필을 편집
봇 계정을 사용하는 경우 비밀번호 필드는 선택 사항이며 그렇지 않은 경우는 비밀번호 필드가 필요합니다.
경고
The user account-only fields are deprecated.
참고
아바타를 업로드 하려면 bytes-like object 형식의 이미지로 전달해야 합니다.
open('파일이름', 'rb')로 파일을 열어야 하며,fp.read()로 전달해야 합니다.업로드는 JPEG 또는 PNG형식으로만 해야합니다.
- 매개변수
password (
str) – 클라이언트 계정의 현재 비밀번호 입니다. 유저 계정에만 적용됩니다.new_password (
str) – 변경하려는 새 비밀번호입니다. 유저 계정에만 적용됩니다.email (
str) – 변경하려는 새 이메일입니다. 유저 계정에만 적용됩니다.house (Optional[
HypeSquadHouse]) – The hypesquad house you wish to change to. Could beNoneto leave the current house. Only applicable to user accounts.username (
str) – 변경하려는 새 사용자 이름입니다.avatar (
bytes) – 업로드 할 이미지를 가진 bytes-like object 입니다.None로 아바타 없음을 표시 할 수 있습니다.
- 예외
HTTPException – 프로필 편집에 실패했습니다.
InvalidArgument –
avatar에 잘못된 이미지 형식이 전달되었습니다.ClientException – 봇이 아닌 계정에는 암호가 필요합니다. house 필드는 HypeSquadHouse가 아닙니다.
-
await
create_group(*recipients)¶ 이 함수는 코루틴 입니다.
제공된 유저와 그룹 채팅을 합니다. 이런 유저는
RelationshipType.friend유형이여야 합니다.버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 매개변수
- 예외
HTTPException – 그룹 채팅을 작성하지 못했습니다.
ClientException – 유저가 한 명인 그룹을 만드려고 했습니다. 여기에는 자신이 포함되지 않습니다.
- 반환값
새로운 그룹 채팅
- 반환 형식
-
await
edit_settings(**kwargs)¶ 이 함수는 코루틴 입니다.
클라이언트의 설정을 편집합니다.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 매개변수
afk_timeout (
int) – 디스코드에서 모바일 기기로 푸시 알림을 보낼 때까지 사용자가 잠수 상태여야 하는 시간(초)입니다.animate_emojis (
bool) – 채팅에서 이모티콘을 자동으로 재생할지 여부입니다.convert_emoticons (
bool) – 채팅 이모티콘을 이모티콘으로 자동 변환할지 여부입니다. 예) :-) -> 😃default_guilds_restricted (
bool) – 가입한 새로운 서버에서 클라이언트와 구성원 사이에서 DM을 자동으로 비활성화할지 여부입니다.detect_platform_accounts (
bool) – 디스코드를 켤 때 스팀 및 블리자드와 같은 서비스에서 계정을 자동으로 감지할지 여부입니다.developer_mode (
bool) – 개발자 모드를 사용할지 여부입니다.disable_games_tab (
bool) – 게임 탭 표시를 비활성화할지 여부입니다.enable_tts_command (
bool) – tts 메시지의 재생 / 전송 허용 여부입니다.explicit_content_filter (
UserContentFilter) – 모든 메시지의 내용에 대한 필터입니다.friend_source_flags (
FriendFlags) – 친구로 나를 추가 할 수있는 사람입니다.gif_auto_play (
bool) – 채팅중에 GIF를 자동으로 재생할지 여부입니다.guild_positions (List[
abc.Snowflake]) – UI 왼쪽에있는 길드 / 길드 아이콘 순서대로 길드 목록입니다.inline_attachment_media (
bool) – 첨부 파일을 채팅에 업로드 할 때 첨부 파일을 표시할지 여부입니다.inline_embed_media (
bool) – 채팅에 올라온 링크의 비디오 및 이미지를 표시할지 여부입니다.message_display_compact (
bool) – 메시지 컴팩트 모드 사용 여부입니다.render_embeds (
bool) – 채팅에서 전송된 임베드를 렌더링할지 여부입니다.render_reactions (
bool) – 메시지에 추가된 반응을 렌더링할지 여부입니다.restricted_guilds (List[
abc.Snowflake]) – DM을 받지 않을 길드 목록입니다.show_current_game (
bool) – 현재 플레이중인 게임을 표시할지 여부입니다.status (
Status) – 다른 사람에게 표시되는 상태입니다.theme (
Theme) – 디스코드 UI의 테마입니다.timezone_offset (
int) – 사용할 시간대 입니다.
- 예외
HTTPException – 설정 편집에 실패했습니다.
Forbidden – 클라이언트는 봇 사용자이며 사용자 계정이 아닙니다.
- 반환값
클라이언트 사용자의 업데이트 된 설정.
- 반환 형식
-
avatar_url¶ 사용자의
Asset에서 아바타를 리턴합니다.만약 사용자에게 기존 아바타가 없는 경우 기본 아바타의 자산을 대신 리턴합니다.
이는
avatar_url_as()의 기본인 (webp / gif , 크기: 1024) 를 사용하여 호출 하는 것과 같습니다.- 타입
-
avatar_url_as(*, format=None, static_format='webp', size=1024)¶ 사용자의
Asset에서 아바타를 리턴합니다.만약 사용자에게 기존 아바타가 없는 경우 기본 아바타의 자산을 대신 리턴합니다.
형식은 〈webp〉, 〈jpeg〉, 〈jpg〉, 〈png〉, 〈gif〉 중 하나여야 하며, 〈gif〉 은 애미메이션 아바타에만 유효합니다. 크기는 16에서 4096사이의 2의 거듭 제곱 이여야합니다.
- 매개변수
- 예외
InvalidArgument – 잘못된 형식이
format또는static_format에 전달되었거나,size가 유효하지 않습니다.- 반환값
The resulting CDN asset.
- 반환 형식
-
color¶ 사용자의 렌더링 된 색상을 나타내는 색상을 리턴하는 속성입니다. 이것은 항상
Colour.default()를 리턴합니다.There is an alias for this named
colour.- 타입
-
colour¶ 사용자의 렌더링 된 색상을 나타내는 색상을 리턴하는 속성입니다. 이것은 항상
Colour.default()를 리턴합니다.There is an alias for this named
color.- 타입
-
created_at¶ 사용자 계정의 생성시간을 UTC로 리턴합니다.
사용자의 디스코드 계정이 생성 된 시점입니다.
-
default_avatar¶ 지정된 사용자의 기본 아바타를 리턴합니다. 이것은 사용자의 태그에 의해 계산됩니다.
-
display_name¶ Returns the user’s display name.
일반 사용자의 경우에는 사용자 이름이지만 길드별 닉네임이 있는 경우 해당 닉네임을 리턴합니다.
- 타입
-
mentioned_in(message)¶ 지정된 메시지에서 사용자가 언급되었는지 확인합니다.
-
permissions_in(channel)¶ abc.GuildChannel.permissions_for()의 별칭입니다.기본적으로 다음과 같습니다.
channel.permissions_for(self)
- 매개변수
channel (
abc.GuildChannel) – 권한을 확인할 채널입니다.
-
public_flags¶ The publicly available flags the user has.
-
관련성¶
-
class
discord.Relationship¶ 디스코드에서 관련성을 나타냄
관련성은 친구, 차단 된 유저와 같습니다. 봇이 아닌 계정만 관련성이 있습니다.
버전 1.7부터 폐지.
-
type¶ 관련성의 타입
-
await
delete()¶ 이 함수는 코루틴 입니다.
관련성을 삭제
버전 1.7부터 폐지.
- 예외
HTTPException – 관련성 삭제에 실패했습니다.
-
await
accept()¶ 이 함수는 코루틴 입니다.
친구 요청을 수락
버전 1.7부터 폐지.
- 예외
HTTPException – 친구 요청 수락에 실패했습니다.
-
유저¶
- defavatar_url_as
- asyncblock
- asynccreate_dm
- asyncfetch_message
- defhistory
- defis_avatar_animated
- defis_blocked
- defis_friend
- defmentioned_in
- asyncmutual_friends
- defpermissions_in
- asyncpins
- asyncprofile
- asyncremove_friend
- asyncsend
- asyncsend_friend_request
- asynctrigger_typing
- deftyping
- asyncunblock
-
class
discord.User¶ 디스코드 사용자를 나타냅니다.
-
x == y 두 사용자가 같은지 확인합니다.
-
x != y 두 명의 사용자가 다른지 확인합니다.
-
hash(x) 사용자의 해시를 리턴합니다.
-
str(x) 태그와 함께 사용자 이름을 리턴합니다.
-
async for ... in
history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ 대상의 메시지 기록을 받을 수 있는
AsyncIterator를 반환합니다.이것을 사용하려면
read_message_history권한이 있어야 합니다.예제
사용법
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
리스트로 병합하기:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
모든 매개 변수는 선택 사항입니다.
- 매개변수
limit (Optional[
int]) – 받아올 메시지 수입니다.None일 경우, 채널에 있는 모든 메시지를 받아옵니다. 하지만 참고로, 이렇게 하면 작동이 느려질 수 있습니다.before (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이전의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.after (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이후의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.around (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 주변의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다. 이 매개변수를 사용할 때, 최대 제한은 101입니다. 제한이 짝수이면 최대 + 1 메시지를 리턴합니다.oldest_first (Optional[
bool]) –True로 설정되면 메시지를 가장 오래된 순서부터 리턴합니다.after가 지정되면 기본값은True이고, 그렇지 않으면False입니다.
- 예외
Forbidden – 메시지 기록을 볼 권한이 없습니다.
HTTPException – 메시지 기록 가져오기에 실패했습니다.
- Yields
Message– 매시지 데이터가 파싱된 메시지를 리턴합니다.
-
async with
typing()¶ 무기한으로 타이핑할 수 있는 컨텍스트 관리자를 리턴합니다.
이는 봇에서 긴 계산을 하고 있음을 나타내는 데 유용합니다.
참고
이것은 일반적인 컨텍스트 관리자이면서도 비동기 컨텍스트 관리자입니다. 이는
with와async with둘 다 작동한다는 것을 의미합니다.사용법 예제:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
-
dm_channel¶ 사용자와 연관된 DM 채널이 있으면 이를 리턴합니다
만약
None이 리턴된다면,create_dm()코루틴 함수를 사용해서 DM 채널을 만들 수 있습니다.- 타입
선택 [
DMChannel]
-
mutual_guilds¶ The guilds that the user shares with the client.
참고
This will only return mutual guilds within the client’s internal cache.
버전 1.7에 추가.
- 타입
List[
Guild]
-
await
create_dm()¶ 사용자와의
DMChannel을 만듭니다.이것은 대부분의 사람들에게 투명하게 이루어지기 때문에 거의 호출되지 않아야합니다.
- 반환값
The channel that was created.
- 반환 형식
-
relationship¶ 해당되는 경우
Relationship를 리턴하고 해당되지 않다면None를 리턴합니다.참고
This can only be used by non-bot accounts.
- 타입
선택 사항[
Relationship]
-
await
mutual_friends()¶ 이 함수는 코루틴 입니다.
사용자의 모든 친구를 얻습니다.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – 이 사용자의 친구를 얻을 수 없음
HTTPException – 친구를 얻지 못함
- 반환값
친구인 사용자들
- 반환 형식
리스트 [
User]
-
is_friend()¶ bool: Checks if the user is your friend.버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
-
is_blocked()¶ bool: Checks if the user is blocked.버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
-
await
block()¶ 이 함수는 코루틴 입니다.
사용자를 차단합니다.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – 사용자를 차단할 수 없습니다
HTTPException – 사용자 차단에 실패했습니다.
-
await
unblock()¶ 이 함수는 코루틴 입니다.
사용자를 차단 해제합니다.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – 이 사용자를 차단 헤제 할 수 없습니다.
HTTPException – 사용자 차단 해제에 실패했습니다.
-
await
remove_friend()¶ 이 함수는 코루틴 입니다.
사용자를 친구 삭제합니다
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – 이 사용자를 친구 삭제할 수 없습니다.
HTTPException – 친구 삭제에 실패했습니다.
-
await
send_friend_request()¶ 이 함수는 코루틴 입니다.
사용자에게 친구 요청을 보냅니다.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – 사용자에게 친구 요청을 보낼 수 없습니다.
HTTPException – 친구 요청을 보내지 못했습니다.
-
await
profile()¶ 이 함수는 코루틴 입니다.
사용자의 프로필을 가져옵니다.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – Not allowed to fetch profiles.
HTTPException – Fetching the profile failed.
- 반환값
The profile of the user.
- 반환 형식
-
avatar_url¶ 사용자의
Asset에서 아바타를 리턴합니다.만약 사용자에게 기존 아바타가 없는 경우 기본 아바타의 자산을 대신 리턴합니다.
이는
avatar_url_as()의 기본인 (webp / gif , 크기: 1024) 를 사용하여 호출 하는 것과 같습니다.- 타입
-
avatar_url_as(*, format=None, static_format='webp', size=1024)¶ 사용자의
Asset에서 아바타를 리턴합니다.만약 사용자에게 기존 아바타가 없는 경우 기본 아바타의 자산을 대신 리턴합니다.
형식은 〈webp〉, 〈jpeg〉, 〈jpg〉, 〈png〉, 〈gif〉 중 하나여야 하며, 〈gif〉 은 애미메이션 아바타에만 유효합니다. 크기는 16에서 4096사이의 2의 거듭 제곱 이여야합니다.
- 매개변수
- 예외
InvalidArgument – 잘못된 형식이
format또는static_format에 전달되었거나,size가 유효하지 않습니다.- 반환값
The resulting CDN asset.
- 반환 형식
-
color¶ 사용자의 렌더링 된 색상을 나타내는 색상을 리턴하는 속성입니다. 이것은 항상
Colour.default()를 리턴합니다.There is an alias for this named
colour.- 타입
-
colour¶ 사용자의 렌더링 된 색상을 나타내는 색상을 리턴하는 속성입니다. 이것은 항상
Colour.default()를 리턴합니다.There is an alias for this named
color.- 타입
-
created_at¶ 사용자 계정의 생성시간을 UTC로 리턴합니다.
사용자의 디스코드 계정이 생성 된 시점입니다.
-
default_avatar¶ 지정된 사용자의 기본 아바타를 리턴합니다. 이것은 사용자의 태그에 의해 계산됩니다.
-
display_name¶ Returns the user’s display name.
일반 사용자의 경우에는 사용자 이름이지만 길드별 닉네임이 있는 경우 해당 닉네임을 리턴합니다.
- 타입
-
await
fetch_message(id)¶ 이 함수는 코루틴 입니다.
대상에서 단일
Message를 검색합니다.오직 봇 계정에서만 사용할 수 있습니다.
- 매개변수
id (
int) – 찾을 메시지 ID.- 예외
NotFound – 지정된 메시지를 찾을 수 없습니다.
Forbidden – 메시지를 가져올 권한이 없습니다.
HTTPException – 메시지 가져오기에 실패했습니다.
- 반환값
요청한 메시지.
- 반환 형식
-
mentioned_in(message)¶ 지정된 메시지에서 사용자가 언급되었는지 확인합니다.
-
permissions_in(channel)¶ abc.GuildChannel.permissions_for()의 별칭입니다.기본적으로 다음과 같습니다.
channel.permissions_for(self)
- 매개변수
channel (
abc.GuildChannel) – 권한을 확인할 채널입니다.
-
await
pins()¶ 이 함수는 코루틴 입니다.
채널에 현재 고정되어 있는 모든 메시지를 검색합니다.
참고
Discord API 제한으로 인해 이 메소드가 리턴한
Message객체는 완전한Message.reactions데이터를 포함하지 않습니다.- 예외
HTTPException – 고정된 메시지를 가져오는 데 실패했습니다.
- 반환값
현재 고정되어 있는 메시지들.
- 반환 형식
List[
Message]
-
public_flags¶ The publicly available flags the user has.
-
await
send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)¶ 이 함수는 코루틴 입니다.
주어진 내용(컨텐츠)으로 대상에 메시지를 보냅니다.
컨텐츠는
str(content)을 통해 문자열로 변환할 수 있는 타입이여야 합니다. 내용이None(기본값)으로 설정되면embed매개 변수를 제공해야 합니다.단일 파일을 업로드하려면,
file매개 변수에 단일File객체를 사용해야 합니다. 여러 파일을 업로드하려면files매개 변수에File객체가 담긴list를 사용해야 합니다. 두 매개 변수를 모두 지정하면 예외가 발생합니다.embed매개 변수가 제공될 경우,Embed타입이여야 하며 이것은 rich embed 타입이여야 합니다.- 매개변수
content (
str) – 보낼 메시지의 내용(컨텐츠).tts (
bool) – 텍스트 음성 변환을 사용하여 메시지를 보내야 하는지 여부를 나타냅니다.embed (
Embed) – 콘텐츠의 리치 임베드.file (
File) – 업로드할 파일.files (List[
File]) – 업로드할 파일들의 리스트. 최대 10개여야 합니다.nonce (
int) – 이 메시지를 전송할 때 사용할 논스입니다. 메시지가 성공적으로 보내졌다면, 그 메시지에 이 값을 가진 논스가 있습니다.delete_after (
float) – 제공된 경우 방금 보낸 메시지를 삭제할 때 까지 백그라운드에서 대기하는 시간(초) 입니다. 삭제가 실패하면 자동으로 무시됩니다.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.버전 1.4에 추가.
reference (Union[
Message,MessageReference]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.버전 1.6에 추가.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.버전 1.6에 추가.
- 예외
HTTPException – 메시지 전송에 실패했습니다.
Forbidden – 메시지를 보낼 권한이 없습니다.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or thereferenceobject is not aMessageorMessageReference.
- 반환값
전송한 메시지.
- 반환 형식
-
첨부 파일¶
- defis_spoiler
- asyncread
- asyncsave
- asyncto_file
-
class
discord.Attachment¶ 디스코드의 첨부 파일을 나타냅니다.
-
await
save(fp, *, seek_begin=True, use_cached=False)¶ 이 함수는 코루틴 입니다.
첨부 파일을 파일 객체에 저장
- 매개변수
fp (Union[
io.BufferedIOBase,os.PathLike]) – 이 첨부 파일을 저장할 곳과 사용할 파일 이름입니다. 파일 이름이 전달되면 해당 파일 이름으로 파일이 생성되어 대신 사용됩니다.seek_begin (
bool) – 저장 후 파일의 시작 부분을 탐색할지 여부입니다.use_cached (
bool) – 첨부 파일을 다운로드할 때url이 아닌proxy_url을 사용할지 여부입니다. 일반적으로 메시지가 삭제된 직후 삭제되는 일반 URL에 비해, 삭제 후 첨부 파일을 더 자주 저장할 수 있습니다. 시간이 너무 많이 경과하여 일부 첨부 파일 형식에서는 작동하지 않는 경우에도 삭제된 첨부 파일을 다운로드하지 못할 수 있습니다.
- 예외
HTTPException – 첨부 파일을 저장하지 못했습니다.
NotFound – 첨부 파일이 삭제되었습니다.
- 반환값
쓴 바이트의 수입니다.
- 반환 형식
-
await
read(*, use_cached=False)¶ 이 함수는 코루틴 입니다.
첨부 파일의 내용을
bytes객체로 가져옵니다.버전 1.1에 추가.
- 매개변수
use_cached (
bool) – 첨부 파일을 다운로드할 때url이 아닌proxy_url을 사용할지 여부입니다. 일반적으로 메시지가 삭제된 직후 삭제되는 일반 URL에 비해, 삭제 후 첨부 파일을 더 자주 저장할 수 있습니다. 시간이 너무 많이 경과하여 일부 첨부 파일 형식에서는 작동하지 않는 경우에도 삭제된 첨부 파일을 다운로드하지 못할 수 있습니다.- 예외
HTTPException – 첨부 파일를 다운로드 하지 못했습니다.
Forbidden – 이 첨부 파일에 액세스 할 수있는 권한이 없습니다.
NotFound – 첨부 파일이 삭제되었습니다.
- 반환값
첨부 파일의 내용
- 반환 형식
-
await
to_file(*, use_cached=False, spoiler=False)¶ 이 함수는 코루틴 입니다.
File을abc.Messageable.send()하기 적합한 파일로 변환합니다.버전 1.3에 추가.
- 매개변수
- 예외
HTTPException – 첨부 파일를 다운로드 하지 못했습니다.
Forbidden – 이 첨부 파일에 액세스 할 수있는 권한이 없습니다.
NotFound – 첨부 파일이 삭제되었습니다.
- 반환값
파일을 보내기에 적합한 첨부파일입니다.
- 반환 형식
-
await
에셋¶
-
class
discord.Asset¶ 디스코드의 CDN 에셋을 나타냅니다.
-
str(x) CDN 에셋의 URL을 리턴합니다.
-
len(x) CDN 에셋의 URL 길이를 리턴합니다.
-
bool(x) 에셋에 URL이 있는지 확인합니다.
-
x == y 에셋이 다른 에셋과 같은지 확인합니다.
-
x != y 에셋이 다른 에셋과 다른지 확인합니다.
-
hash(x) 에셋의 해시를 반환합니다.
-
await
read()¶ 이 함수는 코루틴 입니다.
에셋의 내용을
bytes객체로 가져옵니다.경고
사용자가 만든
PartialEmoji는 연결 상태가 되지 않으며, 사용자 지정 이미지가 에셋과 연결되지 않은 경우 (예 : 사용자 지정 아이콘이 없는 길드) URL이 표시되지 않습니다.버전 1.1에 추가.
- 예외
DiscordException – 유효한 URL 또는 내부 연결 상태가 없습니다.
HTTPException – 에셋 다운로드에 실패했습니다.
NotFound – 에셋이 삭제되었습니다.
- 반환값
에셋의 내용
- 반환 형식
-
await
save(fp, *, seek_begin=True)¶ 이 함수는 코루틴 입니다.
에셋을 파일 객체에 저장합니다.
- 매개변수
fp (Union[BinaryIO,
os.PathLike]) –Attachment.save()와 동일합니다,seek_begin (
bool) –Attachment.save()와 동일합니다,
- 예외
DiscordException – 유효한 URL 또는 내부 연결 상태가 없습니다.
HTTPException – 에셋 다운로드에 실패했습니다.
NotFound – 에셋이 삭제되었습니다.
- 반환값
쓴 바이트의 수입니다.
- 반환 형식
-
메시지¶
- activity
- application
- attachments
- author
- call
- channel
- channel_mentions
- clean_content
- content
- created_at
- edited_at
- embeds
- flags
- guild
- id
- jump_url
- mention_everyone
- mentions
- nonce
- pinned
- raw_channel_mentions
- raw_mentions
- raw_role_mentions
- reactions
- reference
- role_mentions
- stickers
- system_content
- tts
- type
- webhook_id
- asyncack
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asyncdelete
- asyncedit
- defis_system
- asyncpin
- asyncpublish
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
-
class
discord.Message¶ 디스코드의 메시지를 나타냅니다.
-
x == y Checks if two messages are equal.
-
x != y Checks if two messages are not equal.
-
hash(x) Returns the message’s hash.
-
tts¶ 메시지가 tts로 왔는지 여부를 지정합니다. 이는 디스코드의 제한으로 인해
on_message()에서만 정확하게 확인 할 수 있습니다.- 타입
-
type¶ 메시지의 타입입니다. 보통은 필요 없지만
system_content메시지일때 유용합니다.- 타입
-
nonce¶ The value used by the discord guild and the client to verify that the message is successfully sent. This is not stored long term within Discord’s servers and is only used ephemerally.
-
channel¶ 메시지가 전송된
TextChannel입니다. 개인 메시지일 경우에는DMChannel또는GroupChannel일 수 있습니다.- 타입
Union[
abc.Messageable]
-
call¶ 그룹 통화 메시지.
MessageType.call유형의 메시지에만 적용됩니다.버전 1.7부터 폐지.
- 타입
선택 사항[
CallMessage]
-
reference¶ The message that this message references. This is only applicable to messages of type
MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.버전 1.5에 추가.
- 타입
Optional[
MessageReference]
-
mention_everyone¶ 메시지가 모든 사람을 멘션하는지 여부를 지정합니다.
참고
메시지 자체에
@everyone또는@here텍스트가 있는지 확인하지 않습니다. 이 부울은@everyone또는@here텍스트 중 하나가 메시지에 있고 결국 언급한건지를 나타냅니다.- 타입
-
mentions¶ 언급된
Member의 목록입니다. 메시지가 개인 메시지일 경우 리스트가User가 됩니다.MessageType.default유형이 아닌 메시지의 경우 이 배열을 사용하여 시스템 메시지를 지원할 수 있습니다. 자세한 내용은system_content를 참조하시기 바랍니다.경고
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
- 타입
List[
abc.User]
-
channel_mentions¶ 언급된
abc.GuildChannel의 리스트입니다. 메시지가 개인 메시지일 경우 리스트는 항상 비어있습니다.- 타입
List[
abc.GuildChannel]
-
attachments¶ 메시지에 있는 첨부파일 리스트
- 타입
List[
Attachment]
-
flags¶ 메시지의 추가 기능
버전 1.3에 추가.
- 타입
-
activity¶ 이 메시지와 관련된 활동입니다. Rich-Presence 관련 메시지 입니다. (예 : 다른 회원의 참여, 관람 또는 청취(스포티파이) 요청)
이 딕셔너리에는 다음과 같은 선택적 키가 있습니다.
type: 요청중인 메시지 활동의 유형을 나타내는 정수.party_id: 파티와 연결된 파티 ID
- 타입
Optional[
dict]
-
application¶ 이 메시지와 연관된 rich presence 애플리케이션
다음 키들이 있는 딕셔너리입니다.
id: 애플리케이션 ID를 나타내는 문자열입니다.name: 애플리케이션 이름을 나타내는 문자열입니다.description: 애플리케이션 설명을 나타내는 문자열입니다.icon: 애플리케이션의 아이콘 ID를 나타내는 문자열입니다.cover_image: 임베드의 커버 이미지 ID를 나타내는 문자열입니다.
- 타입
Optional[
dict]
-
raw_mentions¶ 메시지 내용의
<@user_id>구문과 일치하는 사용자 ID 배열을 반환하는 속성입니다.이렇게 하면 개인 메시지 컨텍스트에서도 언급된 사용자의 사용자 ID를 수신할 수 있습니다.
- 타입
List[
int]
-
clean_content¶ 《정리》 방식으로 내용을 반환하는 속성입니다. 이는 기본적으로 언급이 클라이언트가 표시하는 방식으로 변환됨을 의미합니다. 예를 들어,
<#id>는#name으로 변환됩니다.또한 @everyone 및 @here 언급을 멘션이 아닌것으로 변환합니다.
참고
이것은 마크다운을 피하지 않습니다. 마크다운을 피하려면
utils.escape_markdown()기능과 함께 사용하세요.- 타입
-
created_at¶ 메시지 작성 시간(UTC) 입니다.
-
edited_at¶ 메시지의 편집된 시간을 포함하는 UTC datetime 객체입니다.
- 타입
Optional[
datetime.datetime]
-
system_content¶ Message.type에 관계없이 렌더링되는 내용을 반환하는 속성입니다.:attr:MessageType.default의 경우 일반 :attr:`Message.content`만 반환합니다. 그렇지 않으면 시스템 메시지의 내용을 나타내는 영어 메시지가 리턴됩니다.
- 타입
-
await
delete(*, delay=None)¶ 이 함수는 코루틴 입니다.
메시지를 삭제합니다.
권한없이 자신의 메시지를 삭제할 수 있습니다. 그러나 다른 사람의 메시지를 삭제하려면
manage_messages권한 이 필요합니다 .버전 1.1에서 변경: 새
delay키워드 전용 매개 변수를 추가했습니다.- 매개변수
delay (Optional[
float]) – 제공한 경우 메시지를 삭제하기 전에 백그라운드에서 대기하는 시간 (초)입니다. 삭제가 실패하면 자동으로 무시됩니다.- 예외
Forbidden – 메시지를 삭제할 수 있는 권한이 없습니다.
NotFound – 메시지가 이미 삭제되었습니다
HTTPException – 메시지 삭제에 실패했습니다.
-
await
edit(**fields)¶ 이 함수는 코루틴 입니다.
메시지를 편집합니다.
내용은
str(내용)을 통해 문자열로 변환할 수 있어야 합니다.버전 1.3에서 변경: 새
suppress키워드 전용 매개 변수를 추가했습니다.- 매개변수
content (Optional[
str]) – 메시지를 대체 할 새 컨텐츠입니다.None으로 내용을 제거 할 수 있습니다.embed (Optional[
Embed]) – 임베드를 대체 할 새 임베드입니다.None으로 임베드를 제거 할 수 있습니다.suppress (
bool) – 메시지에 대한 임베드를 억제할지 여부입니다.True로 설정하면 모든 임베드가 제거됩니다.False으로 설정된 경우 억제된 경우 임베드를 다시 가져옵니다. 이 매개 변수를 사용하려면manage_messages가 필요합니다.delete_after (Optional[
float]) – 제공한 경우 방금 편집 한 메시지를 삭제하기 전에 백그라운드에서 대기하는 시간 (초)입니다. 삭제가 실패하면 자동으로 무시됩니다.allowed_mentions (Optional[
AllowedMentions]) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.버전 1.4에 추가.
- 예외
HTTPException – 메시지 편집에 실패했습니다.
Forbidden – 권한이 없는 메시지를 편집하거나 자신의 것이 아닌 메시지의 내용 또는 임베드를 편집하려고 했습니다.
-
await
publish()¶ 이 함수는 코루틴 입니다.
이 메시지를 공지 사항 채널에 게시합니다.
메시지가 자신의 것이 아닌 경우
manage_messages권한이 필요합니다.- 예외
Forbidden – 이 메시지를 게시 할 수 있는 적절한 권한이 없습니다.
HTTPException – 메시지 게시에 실패했습니다.
-
await
pin(*, reason=None)¶ 이 함수는 코루틴 입니다.
메시지를 고정합니다.
DM이 아닌 채널에서는
manage_messages권한이 필요합니다.- 매개변수
reason (Optional[
str]) –The reason for pinning the message. Shows up on the audit log.
버전 1.4에 추가.
- 예외
Forbidden – 메시지를 고정 할 권한이 없습니다.
NotFound – 메시지 또는 채널을 찾지 못했거나 삭제했습니다.
HTTPException – 채널에 50 개 이상의 고정 된 메시지가 있기 때문에 메시지 고정에 실패했습니다.
-
await
unpin(*, reason=None)¶ 이 함수는 코루틴 입니다.
메시지를 고정 해제합니다.
DM이 아닌 채널에서는
manage_messages권한이 필요합니다.- 매개변수
reason (Optional[
str]) –The reason for unpinning the message. Shows up on the audit log.
버전 1.4에 추가.
- 예외
Forbidden – 메시지를 고정 해제 할 수 있는 권한이 없습니다.
NotFound – 메시지 또는 채널을 찾지 못했거나 삭제했습니다.
HTTPException – 메시지 고정 해제에 실패했습니다.
-
await
add_reaction(emoji)¶ 이 함수는 코루틴 입니다.
메시지에 반응 추가
이모지는 유니코드 이모지 또는 사용자 지정 길드
Emoji일 수 있습니다.이 기능을 사용하려면
read_message_history권한이 있어야 합니다. 이 이모지를 사용하여 메시지에 응답한 사람이 없는 경우add_reactions권한이 필요합니다.- 매개변수
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – 반응할 이모티콘입니다.- 예외
HTTPException – Adding the reaction failed.
Forbidden – 메시지에 응답 할 수 있는 적절한 권한이 없습니다.
NotFound – 지정한 이모티콘을 찾을 수 없습니다.
InvalidArgument – emoji 매개 변수가 유효하지 않습니다.
-
await
remove_reaction(emoji, member)¶ 이 함수는 코루틴 입니다.
메시지에서 멤버의 반응 제거
이모지는 유니코드 이모지 또는 사용자 지정 길드
Emoji일 수 있습니다.반응이 사용자 자신의 것이 아닌 경우(즉,
member매개변수가 내가 아닌 경우)manage_messages권한이 필요합니다.멤버 파라미터는 멤버를 나타내야 하며
abc.Snowflakeabc를 충족해야 합니다.- 매개변수
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – 이모티콘을 제거합니다.member (
abc.Snowflake) – 반응을 제거 할 멤버입니다.
- 예외
HTTPException – 반응 제거에 실패했습니다.
Forbidden – 반응을 제거 할 수 있는 권한이 없습니다.
NotFound – 지정한 멤버 또는 이모티콘을 찾을 수 없습니다.
InvalidArgument – emoji 매개 변수가 유효하지 않습니다.
-
await
clear_reaction(emoji)¶ 이 함수는 코루틴 입니다.
메시지에서 특정 반응을 지웁니다.
이모지는 유니코드 이모지 또는 사용자 지정 길드
Emoji일 수 있습니다.이것을 사용하려면
manage_messages권한이 필요합니다.버전 1.3에 추가.
- 매개변수
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – 이모티콘을 삭제합니다.- 예외
HTTPException – 반응 지우기에 실패했습니다.
Forbidden – 반응을 지울 수 있는 적절한 권한이 없습니다.
NotFound – 지정한 이모티콘을 찾을 수 없습니다.
InvalidArgument – emoji 매개 변수가 유효하지 않습니다.
-
await
clear_reactions()¶ 이 함수는 코루틴 입니다.
메시지에서 모든 반응을 제거합니다.
이것을 사용하려면
manage_messages권한이 필요합니다.- 예외
HTTPException – 반응 제거에 실패했습니다.
Forbidden – 모든 반응을 제거 할 수 있는 권한이 없습니다.
-
await
ack()¶ 이 함수는 코루틴 입니다.
메시지를 읽은 것 으로 표시합니다.
사용자는 봇이 아니여야 합니다.
버전 1.7부터 폐지.
- 예외
HTTPException – Ack에 실패했습니다.
ClientException – 봇이 아니어야합니다.
-
await
reply(content=None, **kwargs)¶ 이 함수는 코루틴 입니다.
A shortcut method to
abc.Messageable.send()to reply to theMessage.버전 1.6에 추가.
- 예외
HTTPException – 메시지 전송에 실패했습니다.
Forbidden – 메시지를 보낼 권한이 없습니다.
InvalidArgument –
files리스트의 길이가 적당하지 않거나file과files를 모두 지정했습니다.
- 반환값
전송한 메시지.
- 반환 형식
-
to_reference()¶ Creates a
MessageReferencefrom the current message.버전 1.6에 추가.
- 반환값
The reference to this message.
- 반환 형식
-
DeletedReferencedMessage¶
-
class
discord.DeletedReferencedMessage¶ A special sentinel type that denotes whether the resolved message referenced message had since been deleted.
The purpose of this class is to separate referenced messages that could not be fetched and those that were previously fetched but have since been deleted.
버전 1.6에 추가.
Reaction¶
-
class
discord.Reaction¶ Represents a reaction to a message.
이 객체가 작성된 방식에 따라 일부 속성의 값은
None일 수 있습니다.-
x == y Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered 《equal》.
-
x != y Checks if two reactions are not equal.
-
hash(x) Returns the reaction’s hash.
-
str(x) Returns the string form of the reaction’s emoji.
-
emoji¶ The reaction emoji. May be a custom emoji, or a unicode emoji.
- 타입
Union[
Emoji,PartialEmoji,str]
-
async for ... in
users(limit=None, after=None)¶ Returns an
AsyncIteratorrepresenting the users that have reacted to the message.The
afterparameter must represent a member and meet theabc.Snowflakeabc.예제
사용법
# 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))
리스트로 병합하기:
users = await reaction.users().flatten() # users is now a list of User... winner = random.choice(users) await channel.send('{} has won the raffle.'.format(winner))
- 매개변수
limit (
int) – The maximum number of results to return. If not provided, returns all the users who reacted to the message.after (
abc.Snowflake) – For pagination, reactions are sorted by member.
- 예외
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 aMemberis in a guild message context. Sometimes it can be aUserif the member has left the guild.
-
await
remove(user)¶ 이 함수는 코루틴 입니다.
Remove the reaction by the provided
Userfrom the message.If the reaction is not your own (i.e.
userparameter is not you) then themanage_messagespermission is needed.The
userparameter must represent a user or member and meet theabc.Snowflakeabc.- 매개변수
user (
abc.Snowflake) – The user or member from which to remove the reaction.- 예외
HTTPException – 반응 제거에 실패했습니다.
Forbidden – 반응을 제거 할 수 있는 권한이 없습니다.
NotFound – The user you specified, or the reaction’s message was not found.
-
await
clear()¶ 이 함수는 코루틴 입니다.
Clears this reaction from the message.
이것을 사용하려면
manage_messages권한이 필요합니다.버전 1.3에 추가.
- 예외
HTTPException – 반응 지우기에 실패했습니다.
Forbidden – 반응을 지울 수 있는 적절한 권한이 없습니다.
NotFound – 지정한 이모티콘을 찾을 수 없습니다.
InvalidArgument – emoji 매개 변수가 유효하지 않습니다.
-
CallMessage¶
-
class
discord.CallMessage¶ Represents a group call message from Discord.
This is only received in cases where the message type is equivalent to
MessageType.call.버전 1.7부터 폐지.
-
ended_timestamp¶ A naive UTC datetime object that represents the time that the call has ended.
- 타입
Optional[
datetime.datetime]
-
channel¶ The private channel associated with this message.
버전 1.7부터 폐지.
- 타입
-
duration¶ Queries the duration of the call.
If the call has not ended then the current duration will be returned.
버전 1.7부터 폐지.
- 반환값
The timedelta object representing the duration.
- 반환 형식
-
GroupCall¶
-
class
discord.GroupCall¶ Represents the actual group call from Discord.
This is accompanied with a
CallMessagedenoting the information.버전 1.7부터 폐지.
-
call¶ The call message associated with this group call.
- 타입
Denotes if this group call is unavailable.
- 타입
-
region¶ The guild region the group call is being hosted on.
- 타입
-
connected¶ A property that returns all users that are currently in this call.
버전 1.7부터 폐지.
- 타입
리스트 [
User]
-
channel¶ Returns the channel the group call is in.
버전 1.7부터 폐지.
- 타입
-
voice_state_for(user)¶ Retrieves the
VoiceStatefor a specifiedUser.If the
Userhas no voice state then this function returnsNone.버전 1.7부터 폐지.
- 매개변수
user (
User) – The user to retrieve the voice state for.- 반환값
The voice state associated with this user.
- 반환 형식
Optional[
VoiceState]
-
Guild¶
- afk_channel
- afk_timeout
- banner
- banner_url
- bitrate_limit
- categories
- channels
- chunked
- created_at
- default_notifications
- default_role
- description
- discovery_splash
- discovery_splash_url
- emoji_limit
- emojis
- explicit_content_filter
- features
- filesize_limit
- icon
- icon_url
- id
- large
- max_members
- max_presences
- max_video_channel_users
- me
- member_count
- members
- mfa_level
- name
- owner
- owner_id
- preferred_locale
- premium_subscriber_role
- premium_subscribers
- premium_subscription_count
- premium_tier
- public_updates_channel
- region
- roles
- rules_channel
- self_role
- shard_id
- splash
- splash_url
- system_channel
- system_channel_flags
- text_channels
- unavailable
- verification_level
- voice_channels
- voice_client
- asyncack
- defaudit_logs
- asyncban
- defbanner_url_as
- asyncbans
- defby_category
- asyncchange_voice_state
- asyncchunk
- asynccreate_category
- asynccreate_category_channel
- asynccreate_custom_emoji
- asynccreate_integration
- asynccreate_role
- asynccreate_template
- asynccreate_text_channel
- asynccreate_voice_channel
- asyncdelete
- defdiscovery_splash_url_as
- asyncedit
- asyncedit_role_positions
- asyncestimate_pruned_members
- asyncfetch_ban
- asyncfetch_channels
- asyncfetch_emoji
- asyncfetch_emojis
- asyncfetch_member
- asyncfetch_members
- asyncfetch_roles
- defget_channel
- defget_member
- defget_member_named
- defget_role
- deficon_url_as
- asyncintegrations
- asyncinvites
- defis_icon_animated
- asynckick
- asyncleave
- asyncprune_members
- asyncquery_members
- defsplash_url_as
- asynctemplates
- asyncunban
- asyncvanity_invite
- asyncwebhooks
- asyncwidget
-
class
discord.Guild¶ Represents a Discord guild.
This is referred to as a 《server》 in the official Discord UI.
-
x == y Checks if two guilds are equal.
-
x != y Checks if two guilds are not equal.
-
hash(x) Returns the guild’s hash.
-
str(x) Returns the guild’s name.
-
region¶ The region the guild belongs on. There is a chance that the region will be a
strif the value is not recognised by the enumerator.- 타입
-
afk_channel¶ The channel that denotes the AFK channel.
Noneif it doesn’t exist.- 타입
Optional[
VoiceChannel]
-
owner_id¶ The guild owner’s ID. Use
Guild.ownerinstead.- 타입
Indicates if the guild is unavailable. If this is
Truethen the reliability of other attributes outside ofGuild.id()is slim and they might all beNone. It is best to not do anything with the guild if it is unavailable.Check the
on_guild_unavailable()andon_guild_available()events.- 타입
-
max_members¶ The maximum amount of members for the guild.
참고
This attribute is only available via
Client.fetch_guild().- 타입
Optional[
int]
-
max_video_channel_users¶ The maximum amount of users in a video channel.
버전 1.4에 추가.
- 타입
Optional[
int]
The guild’s banner.
- 타입
Optional[
str]
-
mfa_level¶ Indicates the guild’s two factor authorisation level. If this value is 0 then the guild does not require 2FA for their administrative members. If the value is 1 then they do.
- 타입
-
verification_level¶ The guild’s verification level.
-
explicit_content_filter¶ The guild’s explicit content filter.
-
default_notifications¶ The guild’s notification settings.
-
features¶ A list of features that the guild has. They are currently as follows:
VIP_REGIONS: Guild has VIP voice regionsVANITY_URL: Guild can have a vanity invite URL (e.g. discord.gg/discord-api)INVITE_SPLASH: Guild’s invite page can have a special splash.VERIFIED: Guild is a verified server.PARTNERED: Guild is a partnered server.MORE_EMOJI: Guild is allowed to have more than 50 custom emoji.DISCOVERABLE: Guild shows up in Server Discovery.FEATURABLE: Guild is able to be featured in Server Discovery.COMMUNITY: Guild is a community server.COMMERCE: Guild can sell things using store channels.PUBLIC: Guild is a public guild.NEWS: Guild can create news channels.BANNER: Guild can upload and use a banner (i.e.banner_url()).ANIMATED_ICON: Guild can upload an animated icon.PUBLIC_DISABLED: Guild cannot be public.WELCOME_SCREEN_ENABLED: Guild has enabled the welcome screenMEMBER_VERIFICATION_GATE_ENABLED: Guild has Membership Screening enabled.PREVIEW_ENABLED: Guild can be viewed before being accepted via Membership Screening.
- 타입
List[
str]
The premium tier for this guild. Corresponds to 《Nitro Server》 in the official UI. The number goes from 0 to 3 inclusive.
- 타입
The number of 《boosts》 this guild currently has.
- 타입
-
preferred_locale¶ The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.
- 타입
Optional[
str]
-
async for ... in
audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)¶ Returns an
AsyncIteratorthat enables receiving the guild’s audit logs.You must have the
view_audit_logpermission 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. IfNoneretrieve all entries.before (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries before this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries after this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time.oldest_first (
bool) – If set toTrue, return entries in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.user (
abc.Snowflake) – The moderator to filter entries from.action (
AuditLogAction) – The action to filter with.
- 예외
Forbidden – You are not allowed to fetch audit logs
HTTPException – An error occurred while fetching the audit logs.
- Yields
AuditLogEntry– The audit log entry.
-
channels¶ A list of channels that belongs to this guild.
- 타입
List[
abc.GuildChannel]
-
large¶ Indicates if the guild is a 〈large〉 guild.
A large guild is defined as having more than
large_thresholdcount members, which for this library is set to the maximum of 250.- 타입
-
voice_channels¶ A list of voice channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
- 타입
List[
VoiceChannel]
-
me¶ Similar to
Client.userexcept an instance ofMember. This is essentially used to get the member version of yourself.- 타입
-
voice_client¶ Returns the
VoiceProtocolassociated with this guild, if any.- 타입
Optional[
VoiceProtocol]
-
text_channels¶ A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
- 타입
List[
TextChannel]
-
categories¶ A list of categories that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
- 타입
List[
CategoryChannel]
-
by_category()¶ Returns every
CategoryChanneland their associated channels.These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
None.- 반환값
The categories and their associated channels.
- 반환 형식
List[Tuple[Optional[
CategoryChannel], List[abc.GuildChannel]]]
-
get_channel(channel_id)¶ Returns a channel with the given ID.
- 매개변수
channel_id (
int) – The ID to search for.- 반환값
The returned channel or
Noneif not found.- 반환 형식
Optional[
abc.GuildChannel]
-
system_channel¶ Returns the guild’s channel used for system messages.
If no channel is set, then this returns
None.- 타입
Optional[
TextChannel]
-
system_channel_flags¶ Returns the guild’s system channel settings.
-
rules_channel¶ Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns
None.버전 1.3에 추가.
- 타입
Optional[
TextChannel]
-
public_updates_channel¶ Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.
If no channel is set, then this returns
None.버전 1.4에 추가.
- 타입
Optional[
TextChannel]
-
get_member(user_id)¶ Returns a member with the given ID.
A list of members who have 《boosted》 this guild.
- 타입
List[
Member]
-
roles¶ Returns a
listof the guild’s roles in hierarchy order.The first element of this list will be the lowest role in the hierarchy.
- 타입
List[
Role]
-
get_role(role_id)¶ Returns a role with the given ID.
Gets the premium subscriber role, AKA 《boost》 role, in this guild.
버전 1.6에 추가.
- 타입
Optional[
Role]
-
icon_url_as(*, format=None, static_format='webp', size=1024)¶ Returns an
Assetfor the guild’s icon.형식은 〈webp〉, 〈jpeg〉, 〈jpg〉, 〈png〉, 〈gif〉 중 하나여야 하며, 〈gif〉 은 애미메이션 아바타에만 유효합니다. 크기는 16에서 4096사이의 2의 거듭 제곱 이여야합니다.
- 매개변수
format (Optional[
str]) – The format to attempt to convert the icon to. If the format isNone, then it is automatically detected into either 〈gif〉 or static_format depending on the icon being animated or not.static_format (Optional[
str]) – Format to attempt to convert only non-animated icons to.size (
int) – The size of the image to display.
- 예외
InvalidArgument – Bad image format passed to
formator invalidsize.- 반환값
The resulting CDN asset.
- 반환 형식
Returns the guild’s banner asset.
- 타입
Returns an
Assetfor the guild’s banner.The format must be one of 〈webp〉, 〈jpeg〉, or 〈png〉. The size must be a power of 2 between 16 and 4096.
- 매개변수
- 예외
InvalidArgument – Bad image format passed to
formator invalidsize.- 반환값
The resulting CDN asset.
- 반환 형식
-
splash_url_as(*, format='webp', size=2048)¶ Returns an
Assetfor the guild’s invite splash.The format must be one of 〈webp〉, 〈jpeg〉, 〈jpg〉, or 〈png〉. The size must be a power of 2 between 16 and 4096.
- 매개변수
- 예외
InvalidArgument – Bad image format passed to
formator invalidsize.- 반환값
The resulting CDN asset.
- 반환 형식
-
discovery_splash_url_as(*, format='webp', size=2048)¶ Returns an
Assetfor the guild’s discovery splash.The format must be one of 〈webp〉, 〈jpeg〉, 〈jpg〉, or 〈png〉. The size must be a power of 2 between 16 and 4096.
버전 1.3에 추가.
- 매개변수
- 예외
InvalidArgument – Bad image format passed to
formator invalidsize.- 반환값
The resulting CDN asset.
- 반환 형식
-
member_count¶ Returns the true member count regardless of it being loaded fully or not.
경고
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.membersto be specified.- 타입
-
chunked¶ Returns a boolean indicating if the guild is 《chunked》.
A chunked guild means that
member_countis equal to the number of members stored in the internalmemberscache.If this value returns
False, then you should request for offline members.- 타입
-
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,
Noneis returned.
-
await
create_text_channel(name, *, overwrites=None, category=None, reason=None, **options)¶ 이 함수는 코루틴 입니다.
Creates a
TextChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a 〈secret〉 channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas 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
dictof target (either a role or a member) toPermissionOverwriteto 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) – 채널 목록에서의 위치. 이는 0부터 시작하는 숫자입니다. 예를 들어, 맨 위의 채널의 위치는 0입니다.topic (Optional[
str]) – 채널의 새 주제.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is 21600.nsfw (
bool) – 채널을 NSFW로 표시 여부reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.
- 예외
Forbidden – 이 채널을 생성할 권한이 없습니다.
HTTPException – 채널 생성에 실패했습니다.
InvalidArgument – The permission overwrite information is not in proper form.
- 반환값
The channel that was just created.
- 반환 형식
-
await
create_voice_channel(name, *, overwrites=None, category=None, reason=None, **options)¶ 이 함수는 코루틴 입니다.
This is similar to
create_text_channel()except makes aVoiceChannelinstead, in addition to having the following new parameters.- 매개변수
- 예외
Forbidden – 이 채널을 생성할 권한이 없습니다.
HTTPException – 채널 생성에 실패했습니다.
InvalidArgument – The permission overwrite information is not in proper form.
- 반환값
The channel that was just created.
- 반환 형식
-
await
create_category(name, *, overwrites=None, reason=None, position=None)¶ 이 함수는 코루틴 입니다.
Same as
create_text_channel()except makes aCategoryChannelinstead.참고
The
categoryparameter is not supported in this function since categories cannot have categories.- 예외
Forbidden – 이 채널을 생성할 권한이 없습니다.
HTTPException – 채널 생성에 실패했습니다.
InvalidArgument – The permission overwrite information is not in proper form.
- 반환값
The channel that was just created.
- 반환 형식
-
await
create_category_channel(name, *, overwrites=None, reason=None, position=None)¶ 이 함수는 코루틴 입니다.
Same as
create_text_channel()except makes aCategoryChannelinstead.참고
The
categoryparameter is not supported in this function since categories cannot have categories.- 예외
Forbidden – 이 채널을 생성할 권한이 없습니다.
HTTPException – 채널 생성에 실패했습니다.
InvalidArgument – The permission overwrite information is not in proper form.
- 반환값
The channel that was just created.
- 반환 형식
-
await
leave()¶ 이 함수는 코루틴 입니다.
Leaves the guild.
참고
You cannot leave the guild that you own, you must delete it instead via
delete().- 예외
HTTPException – Leaving the guild failed.
-
await
delete()¶ 이 함수는 코루틴 입니다.
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.
-
await
edit(*, reason=None, **fields)¶ 이 함수는 코루틴 입니다.
Edits the guild.
You must have the
manage_guildpermission to edit the guild.버전 1.4에서 변경: The rules_channel and public_updates_channel keyword-only parameters were added.
- 매개변수
name (
str) – The new name of the guild.description (
str) – The new description of the guild. This is only available to guilds that containPUBLICinGuild.features.icon (
bytes) – A bytes-like object representing the icon. Only PNG/JPEG supported and GIF This is only available to guilds that containANIMATED_ICONinGuild.features. Could beNoneto denote removal of the icon.banner (
bytes) – A bytes-like object representing the banner. Could beNoneto denote removal of the banner.splash (
bytes) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containINVITE_SPLASHinGuild.features.region (
VoiceRegion) – The new region for the guild’s voice communication.afk_channel (Optional[
VoiceChannel]) – The new channel that is the AFK channel. Could beNonefor 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 beNonefor no system channel.system_channel_flags (
SystemChannelFlags) – The new system channel settings to use with the new system channel.preferred_locale (
str) – The new preferred locale for the guild. Used as the primary language in the guild. If set, this must be an ISO 639 code, e.g.en-USorjaorzh-CN.rules_channel (Optional[
TextChannel]) – The new channel that is used for rules. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no rules channel.public_updates_channel (Optional[
TextChannel]) – The new channel that is used for public updates from Discord. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no public updates channel.reason (Optional[
str]) – The reason for editing this guild. Shows up on the audit log.
- 예외
Forbidden – You do not have permissions to edit the guild.
HTTPException – Editing the guild failed.
InvalidArgument – The image format passed in to
iconis invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.
-
await
fetch_channels()¶ 이 함수는 코루틴 입니다.
Retrieves all
abc.GuildChannelthat the guild has.참고
This method is an API call. For general usage, consider
channelsinstead.버전 1.2에 추가.
- 예외
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channels failed.
- 반환값
All channels in the guild.
- 반환 형식
List[
abc.GuildChannel]
-
fetch_members(*, limit=1000, after=None)¶ 이 함수는 코루틴 입니다.
Retrieves an
AsyncIteratorthat enables receiving the guild’s members. In order to use this,Intents.members()must be enabled.참고
This method is an API call. For general usage, consider
membersinstead.버전 1.3에 추가.
모든 매개 변수는 선택 사항입니다.
- 매개변수
limit (Optional[
int]) – The number of members to retrieve. Defaults to 1000. PassNoneto fetch all members. Note that this is potentially slow.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve members after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.
- 예외
ClientException – The members intent is not enabled.
HTTPException – Getting the members failed.
- Yields
Member– The member with the member data parsed.
예제
사용법
async for member in guild.fetch_members(limit=150): print(member.name)
Flattening into a list
members = await guild.fetch_members(limit=150).flatten() # members is now a list of Member...
-
await
fetch_member(member_id)¶ 이 함수는 코루틴 입니다.
Retrieves a
Memberfrom a guild ID, and a member ID.참고
This method is an API call. For general usage, consider
get_member()instead.- 매개변수
member_id (
int) – The member’s ID to fetch from.- 예외
Forbidden – You do not have access to the guild.
HTTPException – Fetching the member failed.
- 반환값
The member from the member ID.
- 반환 형식
-
await
fetch_ban(user)¶ 이 함수는 코루틴 입니다.
Retrieves the
BanEntryfor a user.You must have the
ban_memberspermission to get this information.- 매개변수
user (
abc.Snowflake) – The user to get ban information from.- 예외
Forbidden – 이 정보를 얻기 위한 권한이 없습니다.
NotFound – This user is not banned.
HTTPException – 이 정보를 가져오는 중에 오류가 발생했습니다.
- 반환값
The
BanEntryobject for the specified user.- 반환 형식
-
await
bans()¶ 이 함수는 코루틴 입니다.
Retrieves all the users that are banned from the guild as a
listofBanEntry.You must have the
ban_memberspermission to get this information.- 예외
Forbidden – 이 정보를 얻기 위한 권한이 없습니다.
HTTPException – 이 정보를 가져오는 중에 오류가 발생했습니다.
- 반환값
A list of
BanEntryobjects.- 반환 형식
List[
BanEntry]
-
await
prune_members(*, days, compute_prune_count=True, roles=None, reason=None)¶ 이 함수는 코루틴 입니다.
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
daysnumber of days and they have no roles.You must have the
kick_memberspermission to use this.To check how many members you would prune without actually pruning, see the
estimate_pruned_members()function.To prune members that have specific roles see the
rolesparameter.버전 1.4에서 변경: The
roleskeyword-only parameter was added.- 매개변수
days (
int) – The number of days before counting as inactive.reason (Optional[
str]) – 이 작업을 수행하는 사유. 감사 로그에 뜨게 됩니다.compute_prune_count (
bool) – Whether to compute the prune count. This defaults toTruewhich makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this toFalse. If this is set toFalse, then this function will always returnNone.roles (Optional[List[
abc.Snowflake]]) – A list ofabc.Snowflakethat represent roles to include in the pruning process. If a member has a role that is not specified, they’ll be excluded.
- 예외
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while pruning members.
InvalidArgument – An integer was not passed for
days.
- 반환값
The number of members pruned. If
compute_prune_countisFalsethen this returnsNone.- 반환 형식
Optional[
int]
-
await
templates()¶ 이 함수는 코루틴 입니다.
Gets the list of templates from this guild.
Requires
manage_guildpermissions.버전 1.7에 추가.
-
await
webhooks()¶ 이 함수는 코루틴 입니다.
Gets the list of webhooks from this guild.
manage_webhooks권한이 필요합니다.
-
await
estimate_pruned_members(*, days)¶ 이 함수는 코루틴 입니다.
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 for
days.
- 반환값
The number of members estimated to be pruned.
- 반환 형식
-
await
invites()¶ 이 함수는 코루틴 입니다.
Returns a list of all active instant invites from the guild.
You must have the
manage_guildpermission to get this information.- 예외
Forbidden – 이 정보를 얻기 위한 권한이 없습니다.
HTTPException – 이 정보를 가져오는 중에 오류가 발생했습니다.
- 반환값
현재 활성화된 초대 목록.
- 반환 형식
List[
Invite]
-
await
create_template(*, name, description=None)¶ 이 함수는 코루틴 입니다.
Creates a template for the guild.
You must have the
manage_guildpermission to do this.버전 1.7에 추가.
-
await
create_integration(*, type, id)¶ 이 함수는 코루틴 입니다.
Attaches an integration to the guild.
You must have the
manage_guildpermission to do this.버전 1.4에 추가.
- 매개변수
- 예외
Forbidden – You do not have permission to create the integration.
HTTPException – The account could not be found.
-
await
integrations()¶ 이 함수는 코루틴 입니다.
Returns a list of all integrations attached to the guild.
You must have the
manage_guildpermission to do this.버전 1.4에 추가.
- 예외
Forbidden – You do not have permission to create the integration.
HTTPException – Fetching the integrations failed.
- 반환값
The list of integrations that are attached to the guild.
- 반환 형식
List[
Integration]
-
await
fetch_emojis()¶ 이 함수는 코루틴 입니다.
Retrieves all custom
Emojis from the guild.참고
This method is an API call. For general usage, consider
emojisinstead.- 예외
HTTPException – An error occurred fetching the emojis.
- 반환값
The retrieved emojis.
- 반환 형식
List[
Emoji]
-
await
fetch_emoji(emoji_id)¶ 이 함수는 코루틴 입니다.
Retrieves a custom
Emojifrom the guild.참고
This method is an API call. For general usage, consider iterating over
emojisinstead.- 매개변수
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.
- 반환 형식
-
await
create_custom_emoji(*, name, image, roles=None, reason=None)¶ 이 함수는 코루틴 입니다.
Creates a custom
Emojifor the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJIfeature which extends the limit to 200.You must have the
manage_emojispermission 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]]) – AlistofRoles 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.
- 반환 형식
-
await
fetch_roles()¶ 이 함수는 코루틴 입니다.
Retrieves all
Rolethat the guild has.참고
This method is an API call. For general usage, consider
rolesinstead.버전 1.3에 추가.
- 예외
HTTPException – Retrieving the roles failed.
- 반환값
All roles in the guild.
- 반환 형식
List[
Role]
-
await
create_role(*, reason=None, **fields)¶ 이 함수는 코루틴 입니다.
Creates a
Rolefor the guild.All fields are optional.
You must have the
manage_rolespermission to do this.버전 1.6에서 변경: Can now pass
inttocolourkeyword-only parameter.- 매개변수
name (
str) – The role name. Defaults to 〈new role〉.permissions (
Permissions) – The permissions to have. Defaults to no permissions.colour (Union[
Colour,int]) – The colour for the role. Defaults toColour.default(). This is aliased tocoloras well.hoist (
bool) – Indicates if the role should be shown separately in the member list. Defaults toFalse.mentionable (
bool) – Indicates if the role should be mentionable by others. Defaults toFalse.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.
- 반환 형식
-
await
edit_role_positions(positions, *, reason=None)¶ 이 함수는 코루틴 입니다.
Bulk edits a list of
Rolein the guild.You must have the
manage_rolespermission to do this.버전 1.4에 추가.
Example:
positions = { bots_role: 1, # penultimate role tester_role: 2, admin_role: 6 } await guild.edit_role_positions(positions=positions)
- 매개변수
- 예외
Forbidden – You do not have permissions to move the roles.
HTTPException – Moving the roles failed.
InvalidArgument – An invalid keyword argument was given.
- 반환값
A list of all the roles in the guild.
- 반환 형식
List[
Role]
-
await
kick(user, *, reason=None)¶ 이 함수는 코루틴 입니다.
Kicks a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
kick_memberspermission 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.
-
await
ban(user, *, reason=None, delete_message_days=1)¶ 이 함수는 코루틴 입니다.
Bans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission 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.
-
await
unban(user, *, reason=None)¶ 이 함수는 코루틴 입니다.
Unbans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- 매개변수
user (
abc.Snowflake) – The user to unban.reason (Optional[
str]) – 이 작업을 수행하는 사유. 감사 로그에 뜨게 됩니다.
- 예외
Forbidden – You do not have the proper permissions to unban.
HTTPException – Unbanning failed.
-
await
vanity_invite()¶ 이 함수는 코루틴 입니다.
Returns the guild’s special vanity invite.
The guild must have
VANITY_URLinfeatures.You must have the
manage_guildpermission 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.
- 반환 형식
-
ack()¶ 이 함수는 코루틴 입니다.
Marks every message in this guild as read.
사용자는 봇이 아니여야 합니다.
버전 1.7부터 폐지.
- 예외
HTTPException – Ack에 실패했습니다.
ClientException – 봇이 아니어야합니다.
-
await
widget()¶ 이 함수는 코루틴 입니다.
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.
- 반환 형식
-
await
chunk(*, cache=True)¶ 이 함수는 코루틴 입니다.
Requests all members that belong to this guild. In order to use this,
Intents.members()must be enabled.This is a websocket operation and can be slow.
버전 1.5에 추가.
- 매개변수
cache (
bool) – Whether to cache the members as well.- 예외
ClientException – The members intent is not enabled.
-
await
query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)¶ 이 함수는 코루틴 입니다.
Request members that belong to this guild whose username starts with the query given.
This is a websocket operation and can be slow.
버전 1.3에 추가.
- 매개변수
query (Optional[
str]) – The string that the username’s start with.limit (
int) – The maximum number of members to send back. This must be a number between 5 and 100.presences (
bool) –Whether to request for presences to be provided. This defaults to
False.버전 1.6에 추가.
cache (
bool) – Whether to cache the members internally. This makes operations such asget_member()work for those that matched.user_ids (Optional[List[
int]]) –List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.
버전 1.4에 추가.
- 예외
asyncio.TimeoutError – The query timed out waiting for the members.
ValueError – Invalid parameters were passed to the function
ClientException – The presences intent is not enabled.
- 반환값
The list of members that have matched the query.
- 반환 형식
List[
Member]
-
await
change_voice_state(*, channel, self_mute=False, self_deaf=False)¶ 이 함수는 코루틴 입니다.
Changes client’s voice state in the guild.
버전 1.4에 추가.
- 매개변수
channel (Optional[
VoiceChannel]) – Channel the client wants to join. UseNoneto disconnect.self_mute (
bool) – Indicates if the client should be self-muted.self_deaf (
bool) – Indicates if the client should be self-deafened.
-
Integration¶
-
class
discord.Integration¶ Represents a guild integration.
버전 1.4에 추가.
-
enable_emoticons¶ Whether emoticons should be synced for this integration (currently twitch only).
- 타입
Optional[
bool]
-
expire_behaviour¶ The behaviour of expiring subscribers. Aliased to
expire_behavioras well.
-
account¶ The integration account information.
-
synced_at¶ When the integration was last synced.
-
await
edit(**fields)¶ 이 함수는 코루틴 입니다.
Edits the integration.
You must have the
manage_guildpermission to do this.- 매개변수
expire_behaviour (
ExpireBehaviour) – The behaviour when an integration subscription lapses. Aliased toexpire_behavioras well.expire_grace_period (
int) – The period (in days) where the integration will ignore lapsed subscriptions.enable_emoticons (
bool) – Where emoticons should be synced for this integration (currently twitch only).
- 예외
Forbidden – You do not have permission to edit the integration.
HTTPException – Editing the guild failed.
InvalidArgument –
expire_behaviourdid not receive aExpireBehaviour.
-
await
sync()¶ 이 함수는 코루틴 입니다.
Syncs the integration.
You must have the
manage_guildpermission to do this.- 예외
Forbidden – You do not have permission to sync the integration.
HTTPException – Syncing the integration failed.
-
await
delete()¶ 이 함수는 코루틴 입니다.
Deletes the integration.
You must have the
manage_guildpermission to do this.- 예외
Forbidden – You do not have permission to delete the integration.
HTTPException – Deleting the integration failed.
-
Member¶
- activities
- activity
- avatar
- avatar_url
- bot
- color
- colour
- created_at
- default_avatar
- default_avatar_url
- desktop_status
- discriminator
- display_name
- dm_channel
- guild
- guild_permissions
- id
- joined_at
- mention
- mobile_status
- mutual_guilds
- name
- nick
- pending
- premium_since
- public_flags
- raw_status
- relationship
- roles
- status
- system
- top_role
- voice
- web_status
- asyncadd_roles
- defavatar_url_as
- asyncban
- asyncblock
- defcreate_dm
- asyncedit
- asyncfetch_message
- defhistory
- defis_avatar_animated
- defis_blocked
- defis_friend
- defis_on_mobile
- asynckick
- defmentioned_in
- asyncmove_to
- asyncmutual_friends
- defpermissions_in
- asyncpins
- asyncprofile
- asyncremove_friend
- asyncremove_roles
- asyncsend
- asyncsend_friend_request
- asynctrigger_typing
- deftyping
- asyncunban
- asyncunblock
-
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
Userinstances too.
-
x != y Checks if two members are not equal. Note that this works with
Userinstances too.
-
hash(x) Returns the member’s hash.
-
str(x) Returns the member’s name with the discriminator.
-
joined_at¶ A datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be
None.- 타입
Optional[
datetime.datetime]
-
activities¶ The activities that the user is currently doing.
- 타입
Tuple[Union[
BaseActivity,Spotify]]
A datetime object that specifies the date and time in UTC when the member used their Nitro boost on the guild, if available. This could be
None.- 타입
Optional[
datetime.datetime]
-
async for ... in
history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ 대상의 메시지 기록을 받을 수 있는
AsyncIterator를 반환합니다.이것을 사용하려면
read_message_history권한이 있어야 합니다.예제
사용법
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
리스트로 병합하기:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
모든 매개 변수는 선택 사항입니다.
- 매개변수
limit (Optional[
int]) – 받아올 메시지 수입니다.None일 경우, 채널에 있는 모든 메시지를 받아옵니다. 하지만 참고로, 이렇게 하면 작동이 느려질 수 있습니다.before (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이전의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.after (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이후의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.around (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 주변의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다. 이 매개변수를 사용할 때, 최대 제한은 101입니다. 제한이 짝수이면 최대 + 1 메시지를 리턴합니다.oldest_first (Optional[
bool]) –True로 설정되면 메시지를 가장 오래된 순서부터 리턴합니다.after가 지정되면 기본값은True이고, 그렇지 않으면False입니다.
- 예외
Forbidden – 메시지 기록을 볼 권한이 없습니다.
HTTPException – 메시지 기록 가져오기에 실패했습니다.
- Yields
Message– 매시지 데이터가 파싱된 메시지를 리턴합니다.
-
async with
typing()¶ 무기한으로 타이핑할 수 있는 컨텍스트 관리자를 리턴합니다.
이는 봇에서 긴 계산을 하고 있음을 나타내는 데 유용합니다.
참고
이것은 일반적인 컨텍스트 관리자이면서도 비동기 컨텍스트 관리자입니다. 이는
with와async with둘 다 작동한다는 것을 의미합니다.사용법 예제:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
-
colour¶ A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
color.- 타입
-
color¶ A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
colour.- 타입
-
roles¶ A
listofRolethat 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.
- 타입
List[
Role]
-
display_name¶ Returns the user’s display name.
일반 사용자의 경우에는 사용자 이름이지만 길드별 닉네임이 있는 경우 해당 닉네임을 리턴합니다.
- 타입
-
activity¶ Returns the primary activity the user is currently doing. Could be
Noneif no activity is being done.참고
A user may have multiple activities, these can be accessed under
activities.- 타입
Union[
BaseActivity,Spotify]
-
mentioned_in(message)¶ Checks if the member is mentioned in the specified message.
-
permissions_in(channel)¶ abc.GuildChannel.permissions_for()의 별칭입니다.기본적으로 다음과 같습니다.
channel.permissions_for(self)
- 매개변수
channel (
abc.GuildChannel) – 권한을 확인할 채널입니다.- 반환값
멤버에 대해 확인된 권한
- 반환 형식
-
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¶ Returns the member’s current voice state.
- 타입
Optional[
VoiceState]
-
await
ban(**kwargs)¶ 이 함수는 코루틴 입니다.
Bans this member. Equivalent to
Guild.ban().
-
await
unban(*, reason=None)¶ 이 함수는 코루틴 입니다.
Unbans this member. Equivalent to
Guild.unban().
-
await
kick(*, reason=None)¶ 이 함수는 코루틴 입니다.
Kicks this member. Equivalent to
Guild.kick().
-
await
edit(*, reason=None, **fields)¶ 이 함수는 코루틴 입니다.
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below:
Parameter
Permission
nick
mute
deafen
roles
voice_channel
모든 매개 변수는 선택 사항입니다.
버전 1.1에서 변경: Can now pass
Nonetovoice_channelto kick a member from voice.- 매개변수
nick (Optional[
str]) – The member’s new nickname. UseNoneto remove the nickname.mute (
bool) – Indicates if the member should be guild muted or un-muted.deafen (
bool) – Indicates if the member should be guild deafened or un-deafened.roles (Optional[List[
Role]]) – The member’s new list of roles. This replaces the roles.voice_channel (Optional[
VoiceChannel]) – The voice channel to move the member to. PassNoneto kick them from voice.reason (Optional[
str]) – The reason for editing this member. Shows up on the audit log.
- 예외
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
-
await
move_to(channel, *, reason=None)¶ 이 함수는 코루틴 입니다.
Moves a member to a new voice channel (they must be connected first).
You must have the
move_memberspermission to use this.This raises the same exceptions as
edit().버전 1.1에서 변경: Can now pass
Noneto kick a member from voice.- 매개변수
channel (Optional[
VoiceChannel]) – The new voice channel to move the member to. PassNoneto kick them from voice.reason (Optional[
str]) – 이 작업을 수행하는 사유. 감사 로그에 뜨게 됩니다.
-
await
add_roles(*roles, reason=None, atomic=True)¶ 이 함수는 코루틴 입니다.
Gives the member a number of
Roles.You must have the
manage_rolespermission to use this, and the addedRoles must appear lower in the list of roles than the highest role of the member.- 매개변수
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto 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)¶ 사용자의
Asset에서 아바타를 리턴합니다.만약 사용자에게 기존 아바타가 없는 경우 기본 아바타의 자산을 대신 리턴합니다.
형식은 〈webp〉, 〈jpeg〉, 〈jpg〉, 〈png〉, 〈gif〉 중 하나여야 하며, 〈gif〉 은 애미메이션 아바타에만 유효합니다. 크기는 16에서 4096사이의 2의 거듭 제곱 이여야합니다.
- 매개변수
- 예외
InvalidArgument – 잘못된 형식이
format또는static_format에 전달되었거나,size가 유효하지 않습니다.- 반환값
The resulting CDN asset.
- 반환 형식
-
block(*args, **kwargs)¶ 이 함수는 코루틴 입니다.
사용자를 차단합니다.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – 사용자를 차단할 수 없습니다
HTTPException – 사용자 차단에 실패했습니다.
-
create_dm(*args, **kwargs)¶ 사용자와의
DMChannel을 만듭니다.이것은 대부분의 사람들에게 투명하게 이루어지기 때문에 거의 호출되지 않아야합니다.
- 반환값
The channel that was created.
- 반환 형식
-
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
-
await
fetch_message(id)¶ 이 함수는 코루틴 입니다.
대상에서 단일
Message를 검색합니다.오직 봇 계정에서만 사용할 수 있습니다.
- 매개변수
id (
int) – 찾을 메시지 ID.- 예외
NotFound – 지정된 메시지를 찾을 수 없습니다.
Forbidden – 메시지를 가져올 권한이 없습니다.
HTTPException – 메시지 가져오기에 실패했습니다.
- 반환값
요청한 메시지.
- 반환 형식
-
is_blocked(*args, **kwargs)¶ bool: Checks if the user is blocked.버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
-
is_friend(*args, **kwargs)¶ bool: Checks if the user is your friend.버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
-
mutual_friends(*args, **kwargs)¶ 이 함수는 코루틴 입니다.
사용자의 모든 친구를 얻습니다.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – 이 사용자의 친구를 얻을 수 없음
HTTPException – 친구를 얻지 못함
- 반환값
친구인 사용자들
- 반환 형식
리스트 [
User]
-
mutual_guilds¶ Equivalent to
User.mutual_guilds
-
await
pins()¶ 이 함수는 코루틴 입니다.
채널에 현재 고정되어 있는 모든 메시지를 검색합니다.
참고
Discord API 제한으로 인해 이 메소드가 리턴한
Message객체는 완전한Message.reactions데이터를 포함하지 않습니다.- 예외
HTTPException – 고정된 메시지를 가져오는 데 실패했습니다.
- 반환값
현재 고정되어 있는 메시지들.
- 반환 형식
List[
Message]
-
profile(*args, **kwargs)¶ 이 함수는 코루틴 입니다.
사용자의 프로필을 가져옵니다.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – Not allowed to fetch profiles.
HTTPException – Fetching the profile failed.
- 반환값
The profile of the user.
- 반환 형식
-
public_flags¶ Equivalent to
User.public_flags
-
relationship¶ Equivalent to
User.relationship
-
remove_friend(*args, **kwargs)¶ 이 함수는 코루틴 입니다.
사용자를 친구 삭제합니다
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – 이 사용자를 친구 삭제할 수 없습니다.
HTTPException – 친구 삭제에 실패했습니다.
-
await
remove_roles(*roles, reason=None, atomic=True)¶ 이 함수는 코루틴 입니다.
Removes
Roles from this member.You must have the
manage_rolespermission to use this, and the removedRoles must appear lower in the list of roles than the highest role of the member.- 매개변수
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto 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.
-
await
send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)¶ 이 함수는 코루틴 입니다.
주어진 내용(컨텐츠)으로 대상에 메시지를 보냅니다.
컨텐츠는
str(content)을 통해 문자열로 변환할 수 있는 타입이여야 합니다. 내용이None(기본값)으로 설정되면embed매개 변수를 제공해야 합니다.단일 파일을 업로드하려면,
file매개 변수에 단일File객체를 사용해야 합니다. 여러 파일을 업로드하려면files매개 변수에File객체가 담긴list를 사용해야 합니다. 두 매개 변수를 모두 지정하면 예외가 발생합니다.embed매개 변수가 제공될 경우,Embed타입이여야 하며 이것은 rich embed 타입이여야 합니다.- 매개변수
content (
str) – 보낼 메시지의 내용(컨텐츠).tts (
bool) – 텍스트 음성 변환을 사용하여 메시지를 보내야 하는지 여부를 나타냅니다.embed (
Embed) – 콘텐츠의 리치 임베드.file (
File) – 업로드할 파일.files (List[
File]) – 업로드할 파일들의 리스트. 최대 10개여야 합니다.nonce (
int) – 이 메시지를 전송할 때 사용할 논스입니다. 메시지가 성공적으로 보내졌다면, 그 메시지에 이 값을 가진 논스가 있습니다.delete_after (
float) – 제공된 경우 방금 보낸 메시지를 삭제할 때 까지 백그라운드에서 대기하는 시간(초) 입니다. 삭제가 실패하면 자동으로 무시됩니다.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.버전 1.4에 추가.
reference (Union[
Message,MessageReference]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.버전 1.6에 추가.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.버전 1.6에 추가.
- 예외
HTTPException – 메시지 전송에 실패했습니다.
Forbidden – 메시지를 보낼 권한이 없습니다.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or thereferenceobject is not aMessageorMessageReference.
- 반환값
전송한 메시지.
- 반환 형식
-
send_friend_request(*args, **kwargs)¶ 이 함수는 코루틴 입니다.
사용자에게 친구 요청을 보냅니다.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – 사용자에게 친구 요청을 보낼 수 없습니다.
HTTPException – 친구 요청을 보내지 못했습니다.
-
system¶ Equivalent to
User.system
-
await
trigger_typing()¶ 이 함수는 코루틴 입니다.
대상에 입력 중 표시기를 트리거합니다.
입력 중 표시기는 10초 후에 또는 메시지가 전송 된 후에 사라집니다.
-
unblock(*args, **kwargs)¶ 이 함수는 코루틴 입니다.
사용자를 차단 해제합니다.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 예외
Forbidden – 이 사용자를 차단 헤제 할 수 없습니다.
HTTPException – 사용자 차단 해제에 실패했습니다.
-
Spotify¶
-
class
discord.Spotify¶ Represents a Spotify listening activity from Discord. This is a special case of
Activitythat makes it easier to work with the Spotify integration.-
x == y Checks if two activities are equal.
-
x != y Checks if two activities are not equal.
-
hash(x) Returns the activity’s hash.
-
str(x) Returns the string 〈Spotify〉.
-
type¶ Returns the activity’s type. This is for compatibility with
Activity.It always returns
ActivityType.listening.- 타입
-
created_at¶ When the user started listening in UTC.
버전 1.3에 추가.
- 타입
Optional[
datetime.datetime]
-
colour¶ Returns the Spotify integration colour, as a
Colour.There is an alias for this named
color- 타입
-
color¶ Returns the Spotify integration colour, as a
Colour.There is an alias for this named
colour- 타입
-
artist¶ The artist of the song being played.
This does not attempt to split the artist information into multiple artists. Useful if there’s only a single artist.
- 타입
-
start¶ When the user started playing this song in UTC.
-
end¶ When the user will stop playing this song in UTC.
-
duration¶ The duration of the song being played.
-
VoiceState¶
-
class
discord.VoiceState¶ Represents a Discord user’s voice state.
-
self_stream¶ Indicates if the user is currently streaming via 〈Go Live〉 feature.
버전 1.3에 추가.
- 타입
-
channel¶ The voice channel that the user is currently connected to.
Noneif the user is not currently in a voice channel.- 타입
Optional[
VoiceChannel]
-
Emoji¶
-
class
discord.Emoji¶ Represents a custom emoji.
이 객체가 작성된 방식에 따라 일부 속성의 값은
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¶ If colons are required to use this emoji in the client (:PJSalt: vs PJSalt).
- 타입
-
user¶ The user that created the emoji. This can only be retrieved using
Guild.fetch_emoji()and having themanage_emojispermission.- 타입
Optional[
User]
-
created_at¶ Returns the emoji’s creation time in UTC.
-
url¶ Returns the asset of the emoji.
This is equivalent to calling
url_as()with the default parameters (i.e. png/gif detection).- 타입
-
roles¶ A
listof roles that is allowed to use this emoji.If roles is empty, the emoji is unrestricted.
- 타입
List[
Role]
-
url_as(*, format=None, static_format='png')¶ Returns an
Assetfor the emoji’s url.The format must be one of 〈webp〉, 〈jpeg〉, 〈jpg〉, 〈png〉 or 〈gif〉. 〈gif〉 is only valid for animated emojis.
버전 1.6에 추가.
- 매개변수
format (Optional[
str]) – The format to attempt to convert the emojis to. If the format isNone, then it is automatically detected as either 〈gif〉 or static_format, depending on whether the emoji is animated or not.static_format (Optional[
str]) – Format to attempt to convert only non-animated emoji’s to. Defaults to 〈png〉
- 예외
InvalidArgument – Bad image format passed to
formatorstatic_format.- 반환값
The resulting CDN asset.
- 반환 형식
-
await
delete(*, reason=None)¶ 이 함수는 코루틴 입니다.
Deletes the custom emoji.
You must have
manage_emojispermission 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.
-
await
edit(*, name=None, roles=None, reason=None)¶ 이 함수는 코루틴 입니다.
Edits the custom emoji.
You must have
manage_emojispermission to do this.- 매개변수
- 예외
Forbidden – You are not allowed to edit emojis.
HTTPException – An error occurred editing the emoji.
-
PartialEmoji¶
- defis_custom_emoji
- defis_unicode_emoji
- defurl_as
-
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¶ The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji. This can be
Noneif the emoji got deleted (e.g. removing a reaction with a deleted emoji).- 타입
Optional[
str]
-
created_at¶ Returns the emoji’s creation time in UTC, or None if Unicode emoji.
버전 1.6에 추가.
- 타입
Optional[
datetime.datetime]
-
url¶ Returns the asset of the emoji, if it is custom.
This is equivalent to calling
url_as()with the default parameters (i.e. png/gif detection).- 타입
-
url_as(*, format=None, static_format='png')¶ Returns an
Assetfor the emoji’s url, if it is custom.The format must be one of 〈webp〉, 〈jpeg〉, 〈jpg〉, 〈png〉 or 〈gif〉. 〈gif〉 is only valid for animated emojis.
버전 1.7에 추가.
- 매개변수
format (Optional[
str]) – The format to attempt to convert the emojis to. If the format isNone, then it is automatically detected as either 〈gif〉 or static_format, depending on whether the emoji is animated or not.static_format (Optional[
str]) – Format to attempt to convert only non-animated emoji’s to. Defaults to 〈png〉
- 예외
InvalidArgument – Bad image format passed to
formatorstatic_format.- 반환값
The resulting CDN asset.
- 반환 형식
Role¶
- asyncdelete
- asyncedit
- defis_bot_managed
- defis_default
- defis_integration
- defis_premium_subscriber
-
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) Return the role’s hash.
-
str(x) Returns the role’s name.
-
position¶ The position of the role. This number is usually positive. The bottom role has a position of 0.
- 타입
-
managed¶ Indicates if the role is managed by the guild through some form of integrations such as Twitch.
- 타입
The role tags associated with this role.
- 타입
Optional[
RoleTags]
bool: Whether the role is the premium subscriber, AKA 《boost》, role for the guild.버전 1.6에 추가.
-
permissions¶ Returns the role’s permissions.
- 타입
-
created_at¶ Returns the role’s creation time in UTC.
-
await
edit(*, reason=None, **fields)¶ 이 함수는 코루틴 입니다.
Edits the role.
이것을 사용하려면
manage_roles권한이 있어야 합니다.All fields are optional.
버전 1.4에서 변경: Can now pass
inttocolourkeyword-only parameter.- 매개변수
name (
str) – The new role name to change to.permissions (
Permissions) – The new permissions to change to.colour (Union[
Colour,int]) – The new colour to change to. (aliased to color as well)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.
-
await
delete(*, reason=None)¶ 이 함수는 코루틴 입니다.
Deletes the role.
이것을 사용하려면
manage_roles권한이 있어야 합니다.- 매개변수
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.
-
텍스트 채널¶
- asyncclone
- asynccreate_invite
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_message
- asyncfollow
- defget_partial_message
- defhistory
- asyncinvites
- defis_news
- defis_nsfw
- defoverwrites_for
- defpermissions_for
- asyncpins
- asyncpurge
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
-
class
discord.TextChannel¶ 디스코드 길드 텍스트 채널을 나타냅니다.
-
x == y 두 채널이 같은지 확인합니다.
-
x != y 두 채널이 다른지 확인합니다.
-
hash(x) 채널의 해시값을 리턴합니다.
-
str(x) 채널의 이름을 리턴합니다.
-
slowmode_delay¶ 멤버가 메시지를 보낼 때까지 기다려야 하는 시간(초) 입니다. 0 일 경우 이것이 비활성화 되어 있음을 나타냅니다.
manage_channels또는manage_messages가 있는 봇 및 사용자는 슬로우 모드를 무시합니다.- 타입
-
async for ... in
history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ 대상의 메시지 기록을 받을 수 있는
AsyncIterator를 반환합니다.이것을 사용하려면
read_message_history권한이 있어야 합니다.예제
사용법
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
리스트로 병합하기:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
모든 매개 변수는 선택 사항입니다.
- 매개변수
limit (Optional[
int]) – 받아올 메시지 수입니다.None일 경우, 채널에 있는 모든 메시지를 받아옵니다. 하지만 참고로, 이렇게 하면 작동이 느려질 수 있습니다.before (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이전의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.after (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이후의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.around (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 주변의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다. 이 매개변수를 사용할 때, 최대 제한은 101입니다. 제한이 짝수이면 최대 + 1 메시지를 리턴합니다.oldest_first (Optional[
bool]) –True로 설정되면 메시지를 가장 오래된 순서부터 리턴합니다.after가 지정되면 기본값은True이고, 그렇지 않으면False입니다.
- 예외
Forbidden – 메시지 기록을 볼 권한이 없습니다.
HTTPException – 메시지 기록 가져오기에 실패했습니다.
- Yields
Message– 매시지 데이터가 파싱된 메시지를 리턴합니다.
-
async with
typing()¶ 무기한으로 타이핑할 수 있는 컨텍스트 관리자를 리턴합니다.
이는 봇에서 긴 계산을 하고 있음을 나타내는 데 유용합니다.
참고
이것은 일반적인 컨텍스트 관리자이면서도 비동기 컨텍스트 관리자입니다. 이는
with와async with둘 다 작동한다는 것을 의미합니다.사용법 예제:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
-
type¶ 채널의 디스코드 타입.
- 타입
-
permissions_for(member)¶ 현재 멤버의 권한 확인을 처리합니다.
이 기능은 다음과 같은 경우를 고려합니다:
길드 소유자
길드 역할들
채널 덮어쓰기
멤버 덮어쓰기
- 매개변수
member (
Member) – 권한을 확인할 멤버.- 반환값
멤버에 대해 확인된 권한
- 반환 형식
-
last_message¶ 캐시에서 이 채널의 마지막 메시지를 가져옵니다.
메시지는 유효하지 않거나 존재하지 않는 메시지를 가리킬 수도 있습니다.
안정적으로 가져오기
약간 더 안정적인 방법으로 마지막 메시지를 가져오려면,
last_message_id속성과 함께history()또는fetch_message()를 사용하는 것을 고려하십시오.- 반환값
이 채널의 마지막 메시지. 존재하지 않을 경우
None입니다.- 반환 형식
Optional[
Message]
-
await
edit(*, reason=None, **options)¶ 이 함수는 코루틴 입니다.
채널을 편집합니다.
이것을 사용하려면
manage_channels권한이 있어야 합니다.버전 1.3에서 변경:
overwrites키워드 전용 매개변수가 추가되었습니다.버전 1.4에서 변경: The
typekeyword-only parameter was added.- 매개변수
name (
str) – 채널의 새 이름.topic (
str) – 채널의 새 주제.position (
int) – 채널의 새 위치.nsfw (
bool) – 채널을 NSFW로 표시 여부sync_permissions (
bool) – 채널의 새 카테고리 또는 기존 카테고리와 권한을 동기화할지 여부입니다. 기본값은False입니다.category (Optional[
CategoryChannel]) – 이 채널의 새 카테고리입니다. 카테고리를 제거하려면None을 쓸 수 있습니다.slowmode_delay (
int) – 이 채널의 사용자에 대한 슬로우 모드 속도 제한을 초 단위로 지정합니다. 0 일 경우 슬로우 모드를 비활성화합니다. 가능한 최댓값은 21600 입니다.type (
ChannelType) – 이 채널의 종류를 변경합니다. 현재ChannelType.text와ChannelType.news간의 변환만 지원됩니다.reason (Optional[
str]) – 이 채널을 편집하는 사유입니다. 감사 로그에 뜨게 됩니다.overwrites (
dict) – 채널에 적용할PermissionOverwrite에 대한 대상 (역할 또는 멤버) 의dict입니다.
- 예외
InvalidArgument – 채널 위치가 0보다 작거나 전체 채널 수보다 클 경우, 또는 권한 덮어쓰기 정보가 올바른 형식이 아닙니다.
Forbidden – 이 채널을 수정할 수 있는 권한이 없습니다.
HTTPException – 채널 수정에 실패했습니다.
-
await
clone(*, name=None, reason=None)¶ 이 함수는 코루틴 입니다.
이 채널을 복제합니다. 이 채널과 동일한 속성을 가진 채널을 만듭니다.
You must have the
manage_channelspermission to do this.버전 1.1에 추가.
- 매개변수
- 예외
Forbidden – 이 채널을 생성할 권한이 없습니다.
HTTPException – 채널 생성에 실패했습니다.
- 반환값
The channel that was created.
- 반환 형식
-
await
delete_messages(messages)¶ 이 함수는 코루틴 입니다.
메시지 목록을 삭제합니다. 여러 메시지를 대량으로 삭제한다는 점을 제외하면
Message.delete()와 비슷합니다.특별한 경우로, 메시지 수가 0이면 아무것도 수행되지 않습니다. 메시지 수가 1이면 단일 메시지 삭제가 수행됩니다. 둘 이상인 경우 대량 삭제가 사용됩니다.
100개가 넘는 메시지 또는 14일이 지난 메시지는 대량으로 삭제할 수 없습니다.
이것을 사용하려면
manage_messages권한이 있어야 합니다.봇 계정에서만 사용할 수 있습니다.
- 매개변수
messages (Iterable[
abc.Snowflake]) – 대량 삭제할 메시지를 나타내는 이터레이터블.- 예외
ClientException – 삭제할 메시지 수가 100개를 넘습니다.
Forbidden – 메시지를 삭제할 수 있는 권한이 없거나 봇 계정을 사용하고 있지 않습니다.
NotFound – 단일 삭제일 경우, 메시지가 이미 지워졌습니다.
HTTPException – 메시지 삭제에 실패했습니다.
-
await
purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)¶ 이 함수는 코루틴 입니다.
프리디케이트
check에 의해 주어진 기준을 만족하는 메시지 목록을 제거합니다.check가 제공되지 않으면 모든 메시지가 차별없이 제거됩니다.자신이 쓴 경우에도 (사용자 계정이 아닌 경우) 메시지를 삭제하려면
manage_messages권한이 있어야 합니다.메시지 히스토리를 받아오려면read_message_history권한도 필요합니다.내부적으로는, 대량 삭제가 가능한지 또는 계정이 사용자 봇인지 여부와 같은 조건에 따라 다른 수의 전략을 사용합니다.
예제
봇의 메시지 삭제하기
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]) – 검색할 메시지 수입니다. 삭제될 메시지 수는 아니지만, 그럴 수도 있습니다.check (Callable[[
Message],bool]) – 메시지가 삭제되어야 할지를 확인하는 데 사용되는 함수입니다. 이 함수는Message를 유일한 매개 변수로 사용해야 합니다.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) –history()에서의before와 동일합니다.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) –history()에서의after와 동일합니다.around (Optional[Union[
abc.Snowflake,datetime.datetime]]) –history()에서의around와 동일합니다.oldest_first (Optional[
bool]) –history()에서의oldest_first와 동일합니다.bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.
- 예외
Forbidden – 필요한 작업을 수행할 수 있는 적절한 권한이 없습니다.
HTTPException – 메시지 제거에 실패했습니다.
- 반환값
삭제된 메시지들의 리스트.
- 반환 형식
List[
Message]
-
await
webhooks()¶ 이 함수는 코루틴 입니다.
이 채널의 웹후크 리스트를 가져옵니다.
manage_webhooks권한이 필요합니다.
-
await
create_webhook(*, name, avatar=None, reason=None)¶ 이 함수는 코루틴 입니다.
이 채널의 웹후크를 생성합니다.
manage_webhooks권한이 필요합니다.버전 1.1에서 변경:
reason키워드 전용 매개변수를 추가했습니다.- 매개변수
name (
str) – 웹후크의 이름.avatar (Optional[
bytes]) – 웹후크의 기본 아바타를 나타내는 bytes-like object 입니다. 이는edit()과 유사하게 작동합니다.reason (Optional[
str]) – 웹후크를 생성하는 사유입니다. 감사 로그에 뜨게 됩니다.
- 예외
HTTPException – 웹후크 생성에 실패했습니다.
Forbidden – 웹후크를 생성할 권한이 없습니다.
- 반환값
생성된 웹후크.
- 반환 형식
-
await
follow(*, destination, reason=None)¶ 웹후크를 사용해 채널을 팔로우합니다.
뉴스 채널만을 팔로우할 수 있습니다.
참고
리턴된 웹후크는 디스코드가 제공하지 않으므로, 웹후크 작업을 수행하기 위한 토큰을 제공하지 않습니다.
버전 1.3에 추가.
- 매개변수
destination (
TextChannel) – 팔로우하려는 채널입니다.reason (Optional[
str]) –The reason for following the channel. Shows up on the destination guild’s audit log.
버전 1.4에 추가.
- 예외
HTTPException – 채널 팔로우에 실패했습니다.
Forbidden – 웹후크를 생성할 권한이 없습니다.
- 반환값
생성된 웹후크.
- 반환 형식
-
get_partial_message(message_id)¶ Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
버전 1.6에 추가.
- 매개변수
message_id (
int) – The message ID to create a partial message for.- 반환값
The partial message.
- 반환 형식
-
category¶ 이 채널이 속해 있는 카테고리.
없을 경우
None입니다.- 타입
Optional[
CategoryChannel]
-
await
create_invite(*, reason=None, **fields)¶ 이 함수는 코루틴 입니다.
Creates an instant invite from a text or voice channel.
이것을 사용하려면
create_instant_invite권한이 있어야 합니다.- 매개변수
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – 초대에 임시 회원 자격이 부여되는지를 나타냅니다. (즉, 연결이 끊어지면 추방됨.)기본값은False입니다.unique (
bool) – 고유한 초대 URL을 생성해야 하는지 나타냅니다. 기본값은True입니다.reason (Optional[
str]) – 이 초대 생성의 사유입니다. 감사 로그에 뜨게 됩니다.
- 예외
HTTPException – 초대 생성에 실패했습니다.
NotFound – The channel that was passed is a category or an invalid channel.
- 반환값
생성된 초대.
- 반환 형식
-
created_at¶ 채널의 생성 시간을 UTC 시간으로 리턴합니다.
-
await
delete(*, reason=None)¶ 이 함수는 코루틴 입니다.
채널을 삭제합니다.
이것을 사용하려면
manage_channels권한이 있어야 합니다.- 매개변수
reason (Optional[
str]) – 채널 삭제의 사유입니다. 감사 로그에 뜨게 됩니다.- 예외
Forbidden – 채널을 삭제할 권한이 없습니다.
NotFound – 채널을 찾을 수 없거나 이미 삭제되었습니다.
HTTPException – 채널 삭제에 실패했습니다.
-
await
fetch_message(id)¶ 이 함수는 코루틴 입니다.
대상에서 단일
Message를 검색합니다.오직 봇 계정에서만 사용할 수 있습니다.
- 매개변수
id (
int) – 찾을 메시지 ID.- 예외
NotFound – 지정된 메시지를 찾을 수 없습니다.
Forbidden – 메시지를 가져올 권한이 없습니다.
HTTPException – 메시지 가져오기에 실패했습니다.
- 반환값
요청한 메시지.
- 반환 형식
-
await
invites()¶ 이 함수는 코루틴 입니다.
이 채널의 모든 활성 인스턴트 초대 목록을 리턴합니다.
You must have
manage_channelsto get this information.- 예외
Forbidden – 이 정보를 얻기 위한 권한이 없습니다.
HTTPException – 이 정보를 가져오는 중에 오류가 발생했습니다.
- 반환값
현재 활성화된 초대 목록.
- 반환 형식
List[
Invite]
-
overwrites¶ 채널의 모든 덮어쓰기를 리턴합니다.
이것은
Role또는Member가 될 수 있는 대상이 키에 포함되고, 값은PermissionOverwrite인딕셔너리로 리턴됩니다.- 반환값
채널의 권한 덮어쓰기.
- 반환 형식
Mapping[Union[
Role,Member],PermissionOverwrite]
-
overwrites_for(obj)¶ 멤버 또는 역할에 대한 채널별 덮어쓰기를 리턴합니다.
- 매개변수
- 반환값
이 객체에 대한 권한 덮어쓰기.
- 반환 형식
-
permissions_synced¶ 이 채널의 권한이 이 채널에 속한 카테고리와 동기화되는지 여부입니다.
만약 카테고리가 없다면
False입니다.버전 1.3에 추가.
- 타입
-
await
pins()¶ 이 함수는 코루틴 입니다.
채널에 현재 고정되어 있는 모든 메시지를 검색합니다.
참고
Discord API 제한으로 인해 이 메소드가 리턴한
Message객체는 완전한Message.reactions데이터를 포함하지 않습니다.- 예외
HTTPException – 고정된 메시지를 가져오는 데 실패했습니다.
- 반환값
현재 고정되어 있는 메시지들.
- 반환 형식
List[
Message]
-
await
send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)¶ 이 함수는 코루틴 입니다.
주어진 내용(컨텐츠)으로 대상에 메시지를 보냅니다.
컨텐츠는
str(content)을 통해 문자열로 변환할 수 있는 타입이여야 합니다. 내용이None(기본값)으로 설정되면embed매개 변수를 제공해야 합니다.단일 파일을 업로드하려면,
file매개 변수에 단일File객체를 사용해야 합니다. 여러 파일을 업로드하려면files매개 변수에File객체가 담긴list를 사용해야 합니다. 두 매개 변수를 모두 지정하면 예외가 발생합니다.embed매개 변수가 제공될 경우,Embed타입이여야 하며 이것은 rich embed 타입이여야 합니다.- 매개변수
content (
str) – 보낼 메시지의 내용(컨텐츠).tts (
bool) – 텍스트 음성 변환을 사용하여 메시지를 보내야 하는지 여부를 나타냅니다.embed (
Embed) – 콘텐츠의 리치 임베드.file (
File) – 업로드할 파일.files (List[
File]) – 업로드할 파일들의 리스트. 최대 10개여야 합니다.nonce (
int) – 이 메시지를 전송할 때 사용할 논스입니다. 메시지가 성공적으로 보내졌다면, 그 메시지에 이 값을 가진 논스가 있습니다.delete_after (
float) – 제공된 경우 방금 보낸 메시지를 삭제할 때 까지 백그라운드에서 대기하는 시간(초) 입니다. 삭제가 실패하면 자동으로 무시됩니다.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.버전 1.4에 추가.
reference (Union[
Message,MessageReference]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.버전 1.6에 추가.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.버전 1.6에 추가.
- 예외
HTTPException – 메시지 전송에 실패했습니다.
Forbidden – 메시지를 보낼 권한이 없습니다.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or thereferenceobject is not aMessageorMessageReference.
- 반환값
전송한 메시지.
- 반환 형식
-
await
set_permissions(target, *, overwrite=see - below, reason=None, **permissions)¶ 이 함수는 코루틴 입니다.
채널에 대한 특정 권한 덮어쓰기를 설정합니다.
target매개 변수는 길드에 속한Member또는Role이어야 합니다.overwrite매개 변수는, 제공된 경우None또는PermissionOverwrite이어야 합니다. 편의를 위해Permissions속성을 나타내는 키워드 인수를 전달할 수 있습니다. 이 작업을 수행하면 키워드 인수를overwrite매개 변수와 함께 쓸 수 없습니다.overwrite매개 변수가None이면, 권한 덮어쓰기가 삭제됩니다.이것을 사용하려면
manage_roles권한이 있어야 합니다.예제
허용 및 거부 설정하기:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
덮어쓰기 삭제하기
await channel.set_permissions(member, overwrite=None)
PermissionOverwrite사용하기overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- 매개변수
overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – 사용하기 쉽도록 설정하는 권한들의 키워드 인수.
overwrite와 함께 사용할 수 없습니다.reason (Optional[
str]) – 이 작업을 수행하는 사유. 감사 로그에 뜨게 됩니다.
- 예외
Forbidden – 채널별 권한을 편집할 권한이 없습니다.
HTTPException – 채널별 권한을 편집하는 데 실패했습니다.
NotFound – 편집하려는 역할 또는 멤버가 이 길드에 속해 있지 않습니다.
InvalidArgument – overwrite 매개 변수가 유효하지 않거나 target 의 타입이
Role또는Member가 아닙니다.
-
음성 채널¶
- asyncclone
- asyncconnect
- asynccreate_invite
- asyncdelete
- asyncedit
- asyncinvites
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
-
class
discord.VoiceChannel¶ 디스코드 길드 음성 채널을 나타냅니다.
-
x == y 두 채널이 같은지 확인합니다.
-
x != y 두 채널이 다른지 확인합니다.
-
hash(x) 채널의 해시값을 리턴합니다.
-
str(x) 채널의 이름을 리턴합니다.
-
type¶ 채널의 디스코드 타입.
- 타입
-
voice_states¶ 이 채널에 음성 상태가 있는 멤버 ID의 매핑을 반환합니다.
버전 1.3에 추가.
참고
이 기능은 의도적으로 낮은 레벨로, 멤버 캐시를 사용할 수 없을 때
members를 교체합니다.- 반환값
멤버 ID와 음성 상태의 매핑.
- 반환 형식
Mapping[
int,VoiceState]
-
permissions_for(member)¶ 현재 멤버의 권한 확인을 처리합니다.
이 기능은 다음과 같은 경우를 고려합니다:
길드 소유자
길드 역할들
채널 덮어쓰기
멤버 덮어쓰기
- 매개변수
member (
Member) – 권한을 확인할 멤버.- 반환값
멤버에 대해 확인된 권한
- 반환 형식
-
await
clone(*, name=None, reason=None)¶ 이 함수는 코루틴 입니다.
이 채널을 복제합니다. 이 채널과 동일한 속성을 가진 채널을 만듭니다.
You must have the
manage_channelspermission to do this.버전 1.1에 추가.
- 매개변수
- 예외
Forbidden – 이 채널을 생성할 권한이 없습니다.
HTTPException – 채널 생성에 실패했습니다.
- 반환값
The channel that was created.
- 반환 형식
-
await
edit(*, reason=None, **options)¶ 이 함수는 코루틴 입니다.
채널을 편집합니다.
이것을 사용하려면
manage_channels권한이 있어야 합니다.버전 1.3에서 변경:
overwrites키워드 전용 매개변수가 추가되었습니다.- 매개변수
name (
str) – 채널의 새 이름.bitrate (
int) – 채널의 새 비트레이트.user_limit (
int) – 채널의 새 최대 사용자 수.position (
int) – 채널의 새 위치.sync_permissions (
bool) – 채널의 새 카테고리 또는 기존 카테고리와 권한을 동기화할지 여부입니다. 기본값은False입니다.category (Optional[
CategoryChannel]) – 이 채널의 새 카테고리입니다. 카테고리를 제거하려면None을 쓸 수 있습니다.reason (Optional[
str]) – 이 채널을 편집하는 사유입니다. 감사 로그에 뜨게 됩니다.overwrites (
dict) – 채널에 적용할PermissionOverwrite에 대한 대상 (역할 또는 멤버) 의dict입니다.
- 예외
InvalidArgument – 권한 덮어쓰기 정보가 올바른 형식이 아닌 경우.
Forbidden – 이 채널을 수정할 수 있는 권한이 없습니다.
HTTPException – 채널 수정에 실패했습니다.
-
category¶ 이 채널이 속해 있는 카테고리.
없을 경우
None입니다.- 타입
Optional[
CategoryChannel]
-
await
connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)¶ 이 함수는 코루틴 입니다.
음성을 연결하고 :class:`VoiceClient 를 만들어 음성 서버에 연결합니다.
- 매개변수
timeout (
float) – 음성 엔드포인트를 기다리는 시간(초)입니다.reconnect (
bool) – 핸드셰이크의 일부가 실패하거나 게이트웨이가 다운되는 경우 봇이 자동으로 다시 연결을 시도해야 하는지 여부입니다.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.
- 예외
asyncio.TimeoutError – 시간 내에 음성 채널에 연결할 수 없었습니다.
ClientException – 이미 음성 채널에 연결되어 있습니다.
OpusNotLoaded – Opus 라이브러리가 로드되지 않았습니다.
- 반환값
음성 서버에 완전히 연결된 음성 클라이언트.
- 반환 형식
-
await
create_invite(*, reason=None, **fields)¶ 이 함수는 코루틴 입니다.
Creates an instant invite from a text or voice channel.
이것을 사용하려면
create_instant_invite권한이 있어야 합니다.- 매개변수
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – 초대에 임시 회원 자격이 부여되는지를 나타냅니다. (즉, 연결이 끊어지면 추방됨.)기본값은False입니다.unique (
bool) – 고유한 초대 URL을 생성해야 하는지 나타냅니다. 기본값은True입니다.reason (Optional[
str]) – 이 초대 생성의 사유입니다. 감사 로그에 뜨게 됩니다.
- 예외
HTTPException – 초대 생성에 실패했습니다.
NotFound – The channel that was passed is a category or an invalid channel.
- 반환값
생성된 초대.
- 반환 형식
-
created_at¶ 채널의 생성 시간을 UTC 시간으로 리턴합니다.
-
await
delete(*, reason=None)¶ 이 함수는 코루틴 입니다.
채널을 삭제합니다.
이것을 사용하려면
manage_channels권한이 있어야 합니다.- 매개변수
reason (Optional[
str]) – 채널 삭제의 사유입니다. 감사 로그에 뜨게 됩니다.- 예외
Forbidden – 채널을 삭제할 권한이 없습니다.
NotFound – 채널을 찾을 수 없거나 이미 삭제되었습니다.
HTTPException – 채널 삭제에 실패했습니다.
-
await
invites()¶ 이 함수는 코루틴 입니다.
이 채널의 모든 활성 인스턴트 초대 목록을 리턴합니다.
You must have
manage_channelsto get this information.- 예외
Forbidden – 이 정보를 얻기 위한 권한이 없습니다.
HTTPException – 이 정보를 가져오는 중에 오류가 발생했습니다.
- 반환값
현재 활성화된 초대 목록.
- 반환 형식
List[
Invite]
-
overwrites¶ 채널의 모든 덮어쓰기를 리턴합니다.
이것은
Role또는Member가 될 수 있는 대상이 키에 포함되고, 값은PermissionOverwrite인딕셔너리로 리턴됩니다.- 반환값
채널의 권한 덮어쓰기.
- 반환 형식
Mapping[Union[
Role,Member],PermissionOverwrite]
-
overwrites_for(obj)¶ 멤버 또는 역할에 대한 채널별 덮어쓰기를 리턴합니다.
- 매개변수
- 반환값
이 객체에 대한 권한 덮어쓰기.
- 반환 형식
-
permissions_synced¶ 이 채널의 권한이 이 채널에 속한 카테고리와 동기화되는지 여부입니다.
만약 카테고리가 없다면
False입니다.버전 1.3에 추가.
- 타입
-
await
set_permissions(target, *, overwrite=see - below, reason=None, **permissions)¶ 이 함수는 코루틴 입니다.
채널에 대한 특정 권한 덮어쓰기를 설정합니다.
target매개 변수는 길드에 속한Member또는Role이어야 합니다.overwrite매개 변수는, 제공된 경우None또는PermissionOverwrite이어야 합니다. 편의를 위해Permissions속성을 나타내는 키워드 인수를 전달할 수 있습니다. 이 작업을 수행하면 키워드 인수를overwrite매개 변수와 함께 쓸 수 없습니다.overwrite매개 변수가None이면, 권한 덮어쓰기가 삭제됩니다.이것을 사용하려면
manage_roles권한이 있어야 합니다.예제
허용 및 거부 설정하기:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
덮어쓰기 삭제하기
await channel.set_permissions(member, overwrite=None)
PermissionOverwrite사용하기overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- 매개변수
overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – 사용하기 쉽도록 설정하는 권한들의 키워드 인수.
overwrite와 함께 사용할 수 없습니다.reason (Optional[
str]) – 이 작업을 수행하는 사유. 감사 로그에 뜨게 됩니다.
- 예외
Forbidden – 채널별 권한을 편집할 권한이 없습니다.
HTTPException – 채널별 권한을 편집하는 데 실패했습니다.
NotFound – 편집하려는 역할 또는 멤버가 이 길드에 속해 있지 않습니다.
InvalidArgument – overwrite 매개 변수가 유효하지 않거나 target 의 타입이
Role또는Member가 아닙니다.
-
카테고리 채널¶
- asyncclone
- asynccreate_invite
- asynccreate_text_channel
- asynccreate_voice_channel
- asyncdelete
- asyncedit
- asyncinvites
- defis_nsfw
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
-
class
discord.CategoryChannel¶ 디스코드 채널 카테고리를 나타냅니다.
채널을 논리 구획으로 그룹화하는 데 유용합니다.
-
x == y 두 채널이 같은지 확인합니다.
-
x != y 두 채널이 다른지 확인합니다.
-
hash(x) 카테고리의 해시를 리턴합니다.
-
str(x) 카테고리의 이름을 리턴합니다.
-
type¶ 채널의 디스코드 타입.
- 타입
-
await
clone(*, name=None, reason=None)¶ 이 함수는 코루틴 입니다.
이 채널을 복제합니다. 이 채널과 동일한 속성을 가진 채널을 만듭니다.
You must have the
manage_channelspermission to do this.버전 1.1에 추가.
- 매개변수
- 예외
Forbidden – 이 채널을 생성할 권한이 없습니다.
HTTPException – 채널 생성에 실패했습니다.
- 반환값
The channel that was created.
- 반환 형식
-
await
edit(*, reason=None, **options)¶ 이 함수는 코루틴 입니다.
채널을 편집합니다.
이것을 사용하려면
manage_channels권한이 있어야 합니다.버전 1.3에서 변경:
overwrites키워드 전용 매개변수가 추가되었습니다.- 매개변수
- 예외
InvalidArgument – 카테고리 위치가 0보다 작거나 전체 카테고리 수보다 클 경우.
Forbidden – 카테고리를 편집할 권한이 없습니다.
HTTPException – 카테고리 편집에 실패했습니다.
-
channels¶ 이 카테고리에 속한 채널들을 리턴합니다.
텍스트 채널 아래에 음성 채널을 배치하는 공식 Discord UI로 정렬됩니다.
- 타입
List[
abc.GuildChannel]
-
text_channels¶ 이 카테고리에 속한 텍스트 채널들을 리턴합니다.
- 타입
List[
TextChannel]
-
voice_channels¶ 이 카테고리에 속한 음성 채널들을 리턴합니다.
- 타입
List[
VoiceChannel]
-
await
create_text_channel(name, *, overwrites=None, reason=None, **options)¶ 이 함수는 코루틴 입니다.
카테고리에서
TextChannel을 만들기 위한Guild.create_text_channel()의 바로가기 메소드입니다.- 반환값
The channel that was just created.
- 반환 형식
-
await
create_voice_channel(name, *, overwrites=None, reason=None, **options)¶ 이 함수는 코루틴 입니다.
카테고리에서
VoiceChannel을 만들기 위한Guild.create_voice_channel()의 바로가기 메소드입니다.- 반환값
The channel that was just created.
- 반환 형식
-
category¶ 이 채널이 속해 있는 카테고리.
없을 경우
None입니다.- 타입
Optional[
CategoryChannel]
-
await
create_invite(*, reason=None, **fields)¶ 이 함수는 코루틴 입니다.
Creates an instant invite from a text or voice channel.
이것을 사용하려면
create_instant_invite권한이 있어야 합니다.- 매개변수
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – 초대에 임시 회원 자격이 부여되는지를 나타냅니다. (즉, 연결이 끊어지면 추방됨.)기본값은False입니다.unique (
bool) – 고유한 초대 URL을 생성해야 하는지 나타냅니다. 기본값은True입니다.reason (Optional[
str]) – 이 초대 생성의 사유입니다. 감사 로그에 뜨게 됩니다.
- 예외
HTTPException – 초대 생성에 실패했습니다.
NotFound – The channel that was passed is a category or an invalid channel.
- 반환값
생성된 초대.
- 반환 형식
-
created_at¶ 채널의 생성 시간을 UTC 시간으로 리턴합니다.
-
await
delete(*, reason=None)¶ 이 함수는 코루틴 입니다.
채널을 삭제합니다.
이것을 사용하려면
manage_channels권한이 있어야 합니다.- 매개변수
reason (Optional[
str]) – 채널 삭제의 사유입니다. 감사 로그에 뜨게 됩니다.- 예외
Forbidden – 채널을 삭제할 권한이 없습니다.
NotFound – 채널을 찾을 수 없거나 이미 삭제되었습니다.
HTTPException – 채널 삭제에 실패했습니다.
-
await
invites()¶ 이 함수는 코루틴 입니다.
이 채널의 모든 활성 인스턴트 초대 목록을 리턴합니다.
You must have
manage_channelsto get this information.- 예외
Forbidden – 이 정보를 얻기 위한 권한이 없습니다.
HTTPException – 이 정보를 가져오는 중에 오류가 발생했습니다.
- 반환값
현재 활성화된 초대 목록.
- 반환 형식
List[
Invite]
-
overwrites¶ 채널의 모든 덮어쓰기를 리턴합니다.
이것은
Role또는Member가 될 수 있는 대상이 키에 포함되고, 값은PermissionOverwrite인딕셔너리로 리턴됩니다.- 반환값
채널의 권한 덮어쓰기.
- 반환 형식
Mapping[Union[
Role,Member],PermissionOverwrite]
-
overwrites_for(obj)¶ 멤버 또는 역할에 대한 채널별 덮어쓰기를 리턴합니다.
- 매개변수
- 반환값
이 객체에 대한 권한 덮어쓰기.
- 반환 형식
-
permissions_for(member)¶ 현재 멤버의 권한 확인을 처리합니다.
이 기능은 다음과 같은 경우를 고려합니다:
길드 소유자
길드 역할들
채널 덮어쓰기
멤버 덮어쓰기
- 매개변수
member (
Member) – 권한을 확인할 멤버.- 반환값
멤버에 대해 확인된 권한
- 반환 형식
-
permissions_synced¶ 이 채널의 권한이 이 채널에 속한 카테고리와 동기화되는지 여부입니다.
만약 카테고리가 없다면
False입니다.버전 1.3에 추가.
- 타입
-
await
set_permissions(target, *, overwrite=see - below, reason=None, **permissions)¶ 이 함수는 코루틴 입니다.
채널에 대한 특정 권한 덮어쓰기를 설정합니다.
target매개 변수는 길드에 속한Member또는Role이어야 합니다.overwrite매개 변수는, 제공된 경우None또는PermissionOverwrite이어야 합니다. 편의를 위해Permissions속성을 나타내는 키워드 인수를 전달할 수 있습니다. 이 작업을 수행하면 키워드 인수를overwrite매개 변수와 함께 쓸 수 없습니다.overwrite매개 변수가None이면, 권한 덮어쓰기가 삭제됩니다.이것을 사용하려면
manage_roles권한이 있어야 합니다.예제
허용 및 거부 설정하기:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
덮어쓰기 삭제하기
await channel.set_permissions(member, overwrite=None)
PermissionOverwrite사용하기overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- 매개변수
overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – 사용하기 쉽도록 설정하는 권한들의 키워드 인수.
overwrite와 함께 사용할 수 없습니다.reason (Optional[
str]) – 이 작업을 수행하는 사유. 감사 로그에 뜨게 됩니다.
- 예외
Forbidden – 채널별 권한을 편집할 권한이 없습니다.
HTTPException – 채널별 권한을 편집하는 데 실패했습니다.
NotFound – 편집하려는 역할 또는 멤버가 이 길드에 속해 있지 않습니다.
InvalidArgument – overwrite 매개 변수가 유효하지 않거나 target 의 타입이
Role또는Member가 아닙니다.
-
DM 채널¶
- asyncfetch_message
- defget_partial_message
- defhistory
- defpermissions_for
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
-
class
discord.DMChannel¶ 디스코드 개인 메시지를 나타냅니다.
-
x == y 두 채널이 같은지 확인합니다.
-
x != y 두 채널이 다른지 확인합니다.
-
hash(x) 채널의 해시값을 리턴합니다.
-
str(x) 채널의 문자열 표현을 리턴합니다.
-
me¶ 자기 자신을 나타내는 사용자입니다.
- 타입
-
async for ... in
history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ 대상의 메시지 기록을 받을 수 있는
AsyncIterator를 반환합니다.이것을 사용하려면
read_message_history권한이 있어야 합니다.예제
사용법
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
리스트로 병합하기:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
모든 매개 변수는 선택 사항입니다.
- 매개변수
limit (Optional[
int]) – 받아올 메시지 수입니다.None일 경우, 채널에 있는 모든 메시지를 받아옵니다. 하지만 참고로, 이렇게 하면 작동이 느려질 수 있습니다.before (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이전의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.after (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이후의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.around (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 주변의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다. 이 매개변수를 사용할 때, 최대 제한은 101입니다. 제한이 짝수이면 최대 + 1 메시지를 리턴합니다.oldest_first (Optional[
bool]) –True로 설정되면 메시지를 가장 오래된 순서부터 리턴합니다.after가 지정되면 기본값은True이고, 그렇지 않으면False입니다.
- 예외
Forbidden – 메시지 기록을 볼 권한이 없습니다.
HTTPException – 메시지 기록 가져오기에 실패했습니다.
- Yields
Message– 매시지 데이터가 파싱된 메시지를 리턴합니다.
-
async with
typing()¶ 무기한으로 타이핑할 수 있는 컨텍스트 관리자를 리턴합니다.
이는 봇에서 긴 계산을 하고 있음을 나타내는 데 유용합니다.
참고
이것은 일반적인 컨텍스트 관리자이면서도 비동기 컨텍스트 관리자입니다. 이는
with와async with둘 다 작동한다는 것을 의미합니다.사용법 예제:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
-
type¶ 채널의 디스코드 타입.
- 타입
-
created_at¶ 개인 메시지 채널의 생성 시간을 UTC로 리턴합니다.
-
permissions_for(user=None)¶ User에 대한 권한 확인을 처리합니다.이 기능은 다른 채널 유형과의 호환성을 위해 존재합니다.
실제 개인 메시지에는 권한 개념이 없습니다.
다음을 제외한 모든 텍스트 관련 권한이
True로 설정됩니다.send_tts_messages: 개인 메시지에서는 TTS 메시지를 보낼 수 없습니다.manage_messages: 개인 메시지에서는 다른 메시지를 삭제할 수 없습니다.
- 매개변수
user (
User) – 권한을 확인할 사용자입니다. 이 매개 변수는 무시되지만 호환성을 위해 유지됩니다.- 반환값
확인된 권한.
- 반환 형식
-
get_partial_message(message_id)¶ Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
버전 1.6에 추가.
- 매개변수
message_id (
int) – The message ID to create a partial message for.- 반환값
The partial message.
- 반환 형식
-
await
fetch_message(id)¶ 이 함수는 코루틴 입니다.
대상에서 단일
Message를 검색합니다.오직 봇 계정에서만 사용할 수 있습니다.
- 매개변수
id (
int) – 찾을 메시지 ID.- 예외
NotFound – 지정된 메시지를 찾을 수 없습니다.
Forbidden – 메시지를 가져올 권한이 없습니다.
HTTPException – 메시지 가져오기에 실패했습니다.
- 반환값
요청한 메시지.
- 반환 형식
-
await
pins()¶ 이 함수는 코루틴 입니다.
채널에 현재 고정되어 있는 모든 메시지를 검색합니다.
참고
Discord API 제한으로 인해 이 메소드가 리턴한
Message객체는 완전한Message.reactions데이터를 포함하지 않습니다.- 예외
HTTPException – 고정된 메시지를 가져오는 데 실패했습니다.
- 반환값
현재 고정되어 있는 메시지들.
- 반환 형식
List[
Message]
-
await
send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)¶ 이 함수는 코루틴 입니다.
주어진 내용(컨텐츠)으로 대상에 메시지를 보냅니다.
컨텐츠는
str(content)을 통해 문자열로 변환할 수 있는 타입이여야 합니다. 내용이None(기본값)으로 설정되면embed매개 변수를 제공해야 합니다.단일 파일을 업로드하려면,
file매개 변수에 단일File객체를 사용해야 합니다. 여러 파일을 업로드하려면files매개 변수에File객체가 담긴list를 사용해야 합니다. 두 매개 변수를 모두 지정하면 예외가 발생합니다.embed매개 변수가 제공될 경우,Embed타입이여야 하며 이것은 rich embed 타입이여야 합니다.- 매개변수
content (
str) – 보낼 메시지의 내용(컨텐츠).tts (
bool) – 텍스트 음성 변환을 사용하여 메시지를 보내야 하는지 여부를 나타냅니다.embed (
Embed) – 콘텐츠의 리치 임베드.file (
File) – 업로드할 파일.files (List[
File]) – 업로드할 파일들의 리스트. 최대 10개여야 합니다.nonce (
int) – 이 메시지를 전송할 때 사용할 논스입니다. 메시지가 성공적으로 보내졌다면, 그 메시지에 이 값을 가진 논스가 있습니다.delete_after (
float) – 제공된 경우 방금 보낸 메시지를 삭제할 때 까지 백그라운드에서 대기하는 시간(초) 입니다. 삭제가 실패하면 자동으로 무시됩니다.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.버전 1.4에 추가.
reference (Union[
Message,MessageReference]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.버전 1.6에 추가.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.버전 1.6에 추가.
- 예외
HTTPException – 메시지 전송에 실패했습니다.
Forbidden – 메시지를 보낼 권한이 없습니다.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or thereferenceobject is not aMessageorMessageReference.
- 반환값
전송한 메시지.
- 반환 형식
-
그룹 채널¶
- asyncadd_recipients
- asyncedit
- asyncfetch_message
- defhistory
- deficon_url_as
- asyncleave
- defpermissions_for
- asyncpins
- asyncremove_recipients
- asyncsend
- asynctrigger_typing
- deftyping
-
class
discord.GroupChannel¶ 디스코드 그룹 채널을 나타냅니다.
-
x == y 두 채널이 같은지 확인합니다.
-
x != y 두 채널이 다른지 확인합니다.
-
hash(x) 채널의 해시값을 리턴합니다.
-
str(x) 채널의 문자열 표현을 리턴합니다.
-
me¶ 자기 자신을 나타내는 사용자입니다.
- 타입
-
async for ... in
history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ 대상의 메시지 기록을 받을 수 있는
AsyncIterator를 반환합니다.이것을 사용하려면
read_message_history권한이 있어야 합니다.예제
사용법
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
리스트로 병합하기:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
모든 매개 변수는 선택 사항입니다.
- 매개변수
limit (Optional[
int]) – 받아올 메시지 수입니다.None일 경우, 채널에 있는 모든 메시지를 받아옵니다. 하지만 참고로, 이렇게 하면 작동이 느려질 수 있습니다.before (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이전의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.after (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 이후의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다.around (Optional[Union[
Snowflake,datetime.datetime]]) – 이 날짜 또는 이 메시지 주변의 메시지를 검색합니다. 날짜가 제공되면 UTC 시간을 나타내는 시간대 없는 날짜, 시간이여야 합니다. 이 매개변수를 사용할 때, 최대 제한은 101입니다. 제한이 짝수이면 최대 + 1 메시지를 리턴합니다.oldest_first (Optional[
bool]) –True로 설정되면 메시지를 가장 오래된 순서부터 리턴합니다.after가 지정되면 기본값은True이고, 그렇지 않으면False입니다.
- 예외
Forbidden – 메시지 기록을 볼 권한이 없습니다.
HTTPException – 메시지 기록 가져오기에 실패했습니다.
- Yields
Message– 매시지 데이터가 파싱된 메시지를 리턴합니다.
-
async with
typing()¶ 무기한으로 타이핑할 수 있는 컨텍스트 관리자를 리턴합니다.
이는 봇에서 긴 계산을 하고 있음을 나타내는 데 유용합니다.
참고
이것은 일반적인 컨텍스트 관리자이면서도 비동기 컨텍스트 관리자입니다. 이는
with와async with둘 다 작동한다는 것을 의미합니다.사용법 예제:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
-
type¶ 채널의 디스코드 타입.
- 타입
-
icon_url¶ 가능한 경우 채널의 아이콘 에셋을 리턴합니다.
This is equivalent to calling
icon_url_as()with the default parameters (〈webp〉 format and a size of 1024).- 타입
-
icon_url_as(*, format='webp', size=1024)¶ Returns an
Assetfor the icon the channel has.The format must be one of 〈webp〉, 〈jpeg〉, 〈jpg〉 or 〈png〉. The size must be a power of 2 between 16 and 4096.
버전 2.0에 추가.
- 매개변수
- 예외
InvalidArgument – Bad image format passed to
formator invalidsize.- 반환값
The resulting CDN asset.
- 반환 형식
-
created_at¶ 채널의 생성 시간을 UTC 시간으로 리턴합니다.
-
permissions_for(user)¶ User에 대한 권한 확인을 처리합니다.이 기능은 다른 채널 유형과의 호환성을 위해 존재합니다.
실제 개인 메시지에는 권한 개념이 없습니다.
다음을 제외한 모든 텍스트 관련 권한이
True로 설정됩니다.send_tts_messages: 개인 메시지에서는 TTS 메시지를 보낼 수 없습니다.manage_messages: 개인 메시지에서는 다른 메시지를 삭제할 수 없습니다.
사용자가 소유자인 경우 kick_members 권한도 확인합니다.
- 매개변수
user (
User) – 권한을 확인할 사용자.- 반환값
유저에 대해 확인환 권한.
- 반환 형식
-
await
add_recipients(*recipients)¶ 이 함수는 코루틴 입니다.
이 그룹에 사용자를 추가합니다.
한 그룹은 최대 10명의 멤버만 가질 수 있습니다. 더 추가하려고 하면 예외가 발생합니다.사용자를 그룹에 추가하려면
RelationshipType.friend유형의 사용자와 관련성을 가져야 합니다.버전 1.7부터 폐지.
- 매개변수
*recipients (
User) – 이 그룹에 추가할 사용자의 인수 목록.- 예외
HTTPException – 이 그룹에 사용자를 추가하는 데 실패했습니다.
-
await
remove_recipients(*recipients)¶ 이 함수는 코루틴 입니다.
이 그룹에서 사용자를 제거합니다.
버전 1.7부터 폐지.
- 매개변수
*recipients (
User) – 이 그룹에서 제거할 사용자의 인수 목록.- 예외
HTTPException – 이 그룹에서 사용자를 제거하는 데 실패했습니다.
-
await
edit(**fields)¶ 이 함수는 코루틴 입니다.
그룹을 편집합니다.
버전 1.7부터 폐지.
- 매개변수
- 예외
HTTPException – 그룹 편집에 실패했습니다.
-
await
leave()¶ 이 함수는 코루틴 입니다.
그룹에서 나갑니다.
그룹에 혼자 남아 있는 경우, 그롭도 삭제됩니다.
- 예외
HTTPException – 그룹에서 나가는 데 실패했습니다.
-
await
fetch_message(id)¶ 이 함수는 코루틴 입니다.
대상에서 단일
Message를 검색합니다.오직 봇 계정에서만 사용할 수 있습니다.
- 매개변수
id (
int) – 찾을 메시지 ID.- 예외
NotFound – 지정된 메시지를 찾을 수 없습니다.
Forbidden – 메시지를 가져올 권한이 없습니다.
HTTPException – 메시지 가져오기에 실패했습니다.
- 반환값
요청한 메시지.
- 반환 형식
-
await
pins()¶ 이 함수는 코루틴 입니다.
채널에 현재 고정되어 있는 모든 메시지를 검색합니다.
참고
Discord API 제한으로 인해 이 메소드가 리턴한
Message객체는 완전한Message.reactions데이터를 포함하지 않습니다.- 예외
HTTPException – 고정된 메시지를 가져오는 데 실패했습니다.
- 반환값
현재 고정되어 있는 메시지들.
- 반환 형식
List[
Message]
-
await
send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)¶ 이 함수는 코루틴 입니다.
주어진 내용(컨텐츠)으로 대상에 메시지를 보냅니다.
컨텐츠는
str(content)을 통해 문자열로 변환할 수 있는 타입이여야 합니다. 내용이None(기본값)으로 설정되면embed매개 변수를 제공해야 합니다.단일 파일을 업로드하려면,
file매개 변수에 단일File객체를 사용해야 합니다. 여러 파일을 업로드하려면files매개 변수에File객체가 담긴list를 사용해야 합니다. 두 매개 변수를 모두 지정하면 예외가 발생합니다.embed매개 변수가 제공될 경우,Embed타입이여야 하며 이것은 rich embed 타입이여야 합니다.- 매개변수
content (
str) – 보낼 메시지의 내용(컨텐츠).tts (
bool) – 텍스트 음성 변환을 사용하여 메시지를 보내야 하는지 여부를 나타냅니다.embed (
Embed) – 콘텐츠의 리치 임베드.file (
File) – 업로드할 파일.files (List[
File]) – 업로드할 파일들의 리스트. 최대 10개여야 합니다.nonce (
int) – 이 메시지를 전송할 때 사용할 논스입니다. 메시지가 성공적으로 보내졌다면, 그 메시지에 이 값을 가진 논스가 있습니다.delete_after (
float) – 제공된 경우 방금 보낸 메시지를 삭제할 때 까지 백그라운드에서 대기하는 시간(초) 입니다. 삭제가 실패하면 자동으로 무시됩니다.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.버전 1.4에 추가.
reference (Union[
Message,MessageReference]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.버전 1.6에 추가.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.버전 1.6에 추가.
- 예외
HTTPException – 메시지 전송에 실패했습니다.
Forbidden – 메시지를 보낼 권한이 없습니다.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or thereferenceobject is not aMessageorMessageReference.
- 반환값
전송한 메시지.
- 반환 형식
-
PartialInviteGuild¶
- defbanner_url_as
- deficon_url_as
- defis_icon_animated
- defsplash_url_as
-
class
discord.PartialInviteGuild¶ Represents a 《partial》 invite guild.
This model will be given when the user is not part of the guild the
Inviteresolves 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¶ The partial guild’s verification level.
-
features¶ A list of features the guild has. See
Guild.featuresfor more information.- 타입
List[
str]
The partial guild’s banner.
- 타입
Optional[
str]
-
created_at¶ Returns the guild’s creation time in UTC.
-
icon_url_as(*, format=None, static_format='webp', size=1024)¶ The same operation as
Guild.icon_url_as().- 반환값
The resulting CDN asset.
- 반환 형식
Returns the guild’s banner asset.
- 타입
The same operation as
Guild.banner_url_as().- 반환값
The resulting CDN asset.
- 반환 형식
-
splash_url_as(*, format='webp', size=2048)¶ The same operation as
Guild.splash_url_as().- 반환값
The resulting CDN asset.
- 반환 형식
-
PartialInviteChannel¶
-
class
discord.PartialInviteChannel¶ Represents a 《partial》 invite channel.
This model will be given when the user is not part of the guild the
Inviteresolves 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¶ The partial channel’s type.
- 타입
-
created_at¶ 채널의 생성 시간을 UTC 시간으로 리턴합니다.
-
초대¶
- asyncdelete
-
class
discord.Invite¶ 디스코드
Guild또는abc.GuildChannel의 초대를 나타냅니다.이 객체가 작성된 방식에 따라 일부 속성의 값은
None일 수 있습니다.-
x == y 두 초대가 같은지 확인합니다.
-
x != y 두 초대가 다른지 확인합니다.
-
hash(x) 초대의 해시를 리턴합니다.
-
str(x) 초대의 URL을 리턴합니다.
다음 표는 속성을 얻는 메소드를 보여줍니다:
속성
메소드
위 표에 없으면 모든 메소드에서 사용할 수 있습니다.
-
guild¶ 초대의 길드입니다. 그룹 개인 메시지일 경우
None이 될 수 있습니다.- 타입
Optional[Union[
Guild,Object,PartialInviteGuild]]
-
created_at¶ 초대가 생성된 시간을 나타내는 datetime 객체입니다.
-
approximate_presence_count¶ 현재 길드에서 활동중인 회원의 대략적인 수. 여기에는 자리 비움, 방해 금지, 온라인, 보이지 않는 멤버가 포함됩니다. 오프라인 멤버는 제외됩니다.
- 타입
Optional[
int]
-
channel¶ 초대의 채널입니다.
- 타입
Union[
abc.GuildChannel,Object,PartialInviteChannel]
-
await
delete(*, reason=None)¶ 이 함수는 코루틴 입니다.
인스턴트 초대를 삭제합니다.
사용하려면
manage_channels권한이 필요합니다.- 매개변수
reason (Optional[
str]) – 이 초대를 삭제하는 사유입니다. 감사 로그에 뜨게 됩니다.- 예외
Forbidden – 초대를 삭제할 권한이 없습니다.
NotFound – 초대가 유효하지 않거나 만료되었습니다.
HTTPException – 초대 삭제에 실패했습니다.
-
Template¶
- asynccreate_guild
- asyncdelete
- asyncedit
- asyncsync
-
class
discord.Template¶ Represents a Discord template.
버전 1.4에 추가.
-
created_at¶ When the template was created.
-
updated_at¶ When the template was last updated (referred to as 《last synced》 in the client).
-
await
create_guild(name, region=None, icon=None)¶ 이 함수는 코루틴 입니다.
Creates a
Guildusing the template.Bot accounts in more than 10 guilds are not allowed to create guilds.
- 매개변수
name (
str) – The name of the guild.region (
VoiceRegion) – The region for the voice communication server. Defaults toVoiceRegion.us_west.icon (
bytes) – The bytes-like object representing the icon. SeeClientUser.edit()for more details on what is expected.
- 예외
HTTPException – Guild creation failed.
InvalidArgument – Invalid icon image format given. Must be PNG or JPG.
- 반환값
The guild created. This is not the same guild that is added to cache.
- 반환 형식
-
await
sync()¶ 이 함수는 코루틴 입니다.
Sync the template to the guild’s current state.
You must have the
manage_guildpermission in the source guild to do this.버전 1.7에 추가.
- 예외
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
-
await
edit(**kwargs)¶ 이 함수는 코루틴 입니다.
Edit the template metadata.
You must have the
manage_guildpermission in the source guild to do this.버전 1.7에 추가.
- 매개변수
- 예외
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
-
await
delete()¶ 이 함수는 코루틴 입니다.
Delete the template.
You must have the
manage_guildpermission in the source guild to do this.버전 1.7에 추가.
- 예외
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
-
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¶ 채널의 생성 시간을 UTC 시간으로 리턴합니다.
-
WidgetMember¶
- defavatar_url_as
- defis_avatar_animated
- defmentioned_in
- defpermissions_in
-
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.
-
activity¶ The member’s activity.
- 타입
Optional[Union[
BaseActivity,Spotify]]
-
connected_channel¶ Which channel the member is connected to.
- 타입
Optional[
VoiceChannel]
-
avatar_url¶ 사용자의
Asset에서 아바타를 리턴합니다.만약 사용자에게 기존 아바타가 없는 경우 기본 아바타의 자산을 대신 리턴합니다.
이는
avatar_url_as()의 기본인 (webp / gif , 크기: 1024) 를 사용하여 호출 하는 것과 같습니다.- 타입
-
avatar_url_as(*, format=None, static_format='webp', size=1024)¶ 사용자의
Asset에서 아바타를 리턴합니다.만약 사용자에게 기존 아바타가 없는 경우 기본 아바타의 자산을 대신 리턴합니다.
형식은 〈webp〉, 〈jpeg〉, 〈jpg〉, 〈png〉, 〈gif〉 중 하나여야 하며, 〈gif〉 은 애미메이션 아바타에만 유효합니다. 크기는 16에서 4096사이의 2의 거듭 제곱 이여야합니다.
- 매개변수
- 예외
InvalidArgument – 잘못된 형식이
format또는static_format에 전달되었거나,size가 유효하지 않습니다.- 반환값
The resulting CDN asset.
- 반환 형식
-
color¶ 사용자의 렌더링 된 색상을 나타내는 색상을 리턴하는 속성입니다. 이것은 항상
Colour.default()를 리턴합니다.There is an alias for this named
colour.- 타입
-
colour¶ 사용자의 렌더링 된 색상을 나타내는 색상을 리턴하는 속성입니다. 이것은 항상
Colour.default()를 리턴합니다.There is an alias for this named
color.- 타입
-
created_at¶ 사용자 계정의 생성시간을 UTC로 리턴합니다.
사용자의 디스코드 계정이 생성 된 시점입니다.
-
default_avatar¶ 지정된 사용자의 기본 아바타를 리턴합니다. 이것은 사용자의 태그에 의해 계산됩니다.
-
mentioned_in(message)¶ 지정된 메시지에서 사용자가 언급되었는지 확인합니다.
-
permissions_in(channel)¶ abc.GuildChannel.permissions_for()의 별칭입니다.기본적으로 다음과 같습니다.
channel.permissions_for(self)
- 매개변수
channel (
abc.GuildChannel) – 권한을 확인할 채널입니다.
-
public_flags¶ The publicly available flags the user has.
-
Widget¶
- asyncfetch_invite
-
class
discord.Widget¶ Represents a
Guildwidget.-
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¶ The accessible voice channels in the guild.
- 타입
Optional[List[
WidgetChannel]]
-
members¶ The online members in the server. Offline members do not appear in the widget.
참고
Due to a Discord limitation, if this data is available the users will be 《anonymized》 with linear IDs and discriminator information being incorrect. Likewise, the number of members retrieved is capped.
- 타입
Optional[List[
Member]]
-
created_at¶ Returns the member’s creation time in UTC.
-
await
fetch_invite(*, with_counts=True)¶ 이 함수는 코루틴 입니다.
Retrieves an
Invitefrom a invite URL or ID. This is the same asClient.fetch_invite(); the invite code is abstracted away.- 매개변수
with_counts (
bool) – Whether to include count information in the invite. This fills theInvite.approximate_member_countandInvite.approximate_presence_countfields.- 반환값
The invite from the URL/ID.
- 반환 형식
-
Sticker¶
- defimage_url_as
-
class
discord.Sticker¶ Represents a sticker
버전 1.6에 추가.
-
str(x) Returns the name of the sticker
-
x == y Checks if the sticker is equal to another sticker
-
x != y Checks if the sticker is not equal to another sticker
-
format¶ The format for the sticker’s image
- 타입
A list of tags for the sticker
- 타입
List[
str]
-
created_at¶ Returns the sticker’s creation time in UTC as a naive datetime.
-
image_url¶ Returns an
Assetfor the sticker’s image.참고
This will return
Noneif the format isStickerType.lottie- 반환값
The resulting CDN asset.
- 반환 형식
Optional[
Asset]
-
image_url_as(*, size=1024)¶ Optionally returns an
Assetfor the sticker’s image.The size must be a power of 2 between 16 and 4096.
참고
This will return
Noneif the format isStickerType.lottie.- 매개변수
size (
int) – The size of the image to display.- 예외
InvalidArgument – Invalid
size.- 반환값
The resulting CDN asset or
None.- 반환 형식
Optional[
Asset]
-
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¶
-
class
discord.RawMessageUpdateEvent¶ Represents the payload for a
on_raw_message_edit()event.-
cached_message¶ The cached message, if found in the internal message cache. Represents the message before it is modified by the data in
RawMessageUpdateEvent.data.- 타입
Optional[
Message]
-
RawReactionActionEvent¶
-
class
discord.RawReactionActionEvent¶ Represents the payload for a
on_raw_reaction_add()oron_raw_reaction_remove()event.-
emoji¶ The custom or unicode emoji being used.
- 타입
-
RawReactionClearEvent¶
-
class
discord.RawReactionClearEvent¶ Represents the payload for a
on_raw_reaction_clear()event.
RawReactionClearEmojiEvent¶
-
class
discord.RawReactionClearEmojiEvent¶ Represents the payload for a
on_raw_reaction_clear_emoji()event.버전 1.3에 추가.
-
emoji¶ The custom or unicode emoji being removed.
- 타입
-
Data Classes¶
Some classes are just there to be data containers, this lists them.
Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes.
여기의 거의 모든 클래스에는 __slots__ 이 정의되어 있으므로 데이터 클래스에 동적 속성을 가질 수 없습니다.
The only exception to this rule is abc.Snowflake, which is made with
dynamic attributes in mind.
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 Checks if two objects are equal.
-
x != y Checks if two objects are not equal.
-
hash(x) Returns the object’s hash.
-
created_at¶ Returns the snowflake’s creation time in UTC.
-
Embed¶
- clsEmbed.from_dict
- defadd_field
- defclear_fields
- defcopy
- definsert_field_at
- defremove_author
- defremove_field
- defset_author
- defset_field_at
- defset_footer
- defset_image
- defset_thumbnail
- defto_dict
-
class
discord.Embed(**kwargs)¶ Represents a Discord embed.
-
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
Certain properties return an
EmbedProxy, a type that acts similar to a regulardictexcept using dotted access, e.g.embed.author.icon_url. If the attribute is invalid or empty, then a special sentinel value is returned,Embed.Empty.For ease of use, all parameters that expect a
strare implicitly casted tostrfor you.-
timestamp¶ The timestamp of the embed content. This could be a naive or aware datetime.
-
colour¶ The colour code of the embed. Aliased to
coloras well. This can be set during initialisation.
-
Empty¶ A special sentinel value used by
EmbedProxyand this class to denote that the value or attribute is empty.
-
classmethod
from_dict(data)¶ Converts a
dictto aEmbedprovided 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
EmbedProxydenoting the footer contents.See
set_footer()for possible values you can access.If the attribute has no value then
Emptyis returned.- 타입
Union[
EmbedProxy,Empty]
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
-
image¶ Returns an
EmbedProxydenoting the image contents.Possible attributes you can access are:
urlproxy_urlwidthheight
If the attribute has no value then
Emptyis returned.- 타입
Union[
EmbedProxy,Empty]
-
set_image(*, url)¶ Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
버전 1.4에서 변경: Passing
Emptyremoves the image.- 매개변수
url (
str) – The source URL for the image. Only HTTP(S) is supported.
-
thumbnail¶ Returns an
EmbedProxydenoting the thumbnail contents.Possible attributes you can access are:
urlproxy_urlwidthheight
If the attribute has no value then
Emptyis returned.- 타입
Union[
EmbedProxy,Empty]
-
set_thumbnail(*, url)¶ Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
버전 1.4에서 변경: Passing
Emptyremoves the thumbnail.- 매개변수
url (
str) – The source URL for the thumbnail. Only HTTP(S) is supported.
-
video¶ Returns an
EmbedProxydenoting the video contents.Possible attributes include:
urlfor the video URL.heightfor the video height.widthfor the video width.
If the attribute has no value then
Emptyis returned.- 타입
Union[
EmbedProxy,Empty]
-
provider¶ Returns an
EmbedProxydenoting the provider contents.The only attributes that might be accessed are
nameandurl.If the attribute has no value then
Emptyis returned.- 타입
Union[
EmbedProxy,Empty]
Returns an
EmbedProxydenoting the author contents.See
set_author()for possible values you can access.If the attribute has no value then
Emptyis returned.- 타입
Union[
EmbedProxy,Empty]
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Clears embed’s author information.
This function returns the class instance to allow for fluent-style chaining.
버전 1.4에 추가.
-
fields¶ Returns a
listofEmbedProxydenoting the field contents.See
add_field()for possible values you can access.If the attribute has no value then
Emptyis returned.- 타입
Union[List[
EmbedProxy],Empty]
-
add_field(*, name, value, inline=True)¶ Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
-
insert_field_at(index, *, name, value, inline=True)¶ Inserts a field before a specified index to the embed.
This function returns the class instance to allow for fluent-style chaining.
버전 1.2에 추가.
-
clear_fields()¶ Removes all fields from this embed.
-
remove_field(index)¶ Removes a field at a specified 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 – An invalid index was provided.
-
to_dict()¶ Converts this embed object into a dict.
-
AllowedMentions¶
-
class
discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)¶ A class that represents what mentions are allowed in a message.
This class can be set during
Clientinitialisation to apply to every message sent. It can also be applied on a per message basis viaabc.Messageable.send()for more fine-grained control.-
users¶ Controls the users being mentioned. If
True(the default) then users are mentioned based on the message content. IfFalsethen users are not mentioned at all. If a list ofabc.Snowflakeis given then only the users provided will be mentioned, provided those users are in the message content.- 타입
Union[
bool, List[abc.Snowflake]]
-
roles¶ Controls the roles being mentioned. If
True(the default) then roles are mentioned based on the message content. IfFalsethen roles are not mentioned at all. If a list ofabc.Snowflakeis given then only the roles provided will be mentioned, provided those roles are in the message content.- 타입
Union[
bool, List[abc.Snowflake]]
-
replied_user¶ Whether to mention the author of the message being replied to. Defaults to
True.버전 1.6에 추가.
- 타입
-
classmethod
all()¶ A factory method that returns a
AllowedMentionswith all fields explicitly set toTrue버전 1.5에 추가.
-
classmethod
none()¶ A factory method that returns a
AllowedMentionswith all fields set toFalse버전 1.5에 추가.
-
MessageReference¶
-
class
discord.MessageReference(*, message_id, channel_id, guild_id=None)¶ Represents a reference to a
Message.버전 1.5에 추가.
버전 1.6에서 변경: This class can now be constructed by users.
-
resolved¶ The message that this reference resolved to. If this is
Nonethen the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of typeDeletedReferencedMessage.Currently, this is mainly the replied to message when a user replies to a message.
버전 1.6에 추가.
- 타입
Optional[Union[
Message,DeletedReferencedMessage]]
-
classmethod
from_message(message)¶ Creates a
MessageReferencefrom an existingMessage.버전 1.6에 추가.
- 매개변수
message (
Message) – The message to be converted into a reference.- 반환값
A reference to the message.
- 반환 형식
-
PartialMessage¶
-
class
discord.PartialMessage(*, channel, id)¶ Represents a partial message to aid with working messages when only a message and channel ID are present.
There are two ways to construct this class. The first one is through the constructor itself, and the second is via
TextChannel.get_partial_message()orDMChannel.get_partial_message().Note that this class is trimmed down and has no rich attributes.
버전 1.6에 추가.
-
x == y Checks if two partial messages are equal.
-
x != y Checks if two partial messages are not equal.
-
hash(x) Returns the partial message’s hash.
-
channel¶ The channel associated with this partial message.
- 타입
Union[
TextChannel,DMChannel]
-
created_at¶ The partial message’s creation time in UTC.
-
await
fetch()¶ 이 함수는 코루틴 입니다.
Fetches the partial message to a full
Message.- 예외
NotFound – The message was not found.
Forbidden – 메시지를 가져올 권한이 없습니다.
HTTPException – 메시지 가져오기에 실패했습니다.
- 반환값
The full message.
- 반환 형식
-
await
edit(**fields)¶ 이 함수는 코루틴 입니다.
메시지를 편집합니다.
내용은
str(내용)을 통해 문자열로 변환할 수 있어야 합니다.버전 1.7에서 변경:
discord.Messageis returned instead ofNoneif an edit took place.- 매개변수
content (Optional[
str]) – 메시지를 대체 할 새 컨텐츠입니다.None으로 내용을 제거 할 수 있습니다.embed (Optional[
Embed]) – 임베드를 대체 할 새 임베드입니다.None으로 임베드를 제거 할 수 있습니다.suppress (
bool) – 메시지에 대한 임베드를 억제할지 여부입니다.True로 설정하면 모든 임베드가 제거됩니다.False으로 설정된 경우 억제된 경우 임베드를 다시 가져옵니다. 이 매개 변수를 사용하려면manage_messages가 필요합니다.delete_after (Optional[
float]) – 제공한 경우 방금 편집 한 메시지를 삭제하기 전에 백그라운드에서 대기하는 시간 (초)입니다. 삭제가 실패하면 자동으로 무시됩니다.allowed_mentions (Optional[
AllowedMentions]) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.
- 예외
NotFound – The message was not found.
HTTPException – 메시지 편집에 실패했습니다.
Forbidden – 권한이 없는 메시지를 편집하거나 자신의 것이 아닌 메시지의 내용 또는 임베드를 편집하려고 했습니다.
- 반환값
The message that was edited.
- 반환 형식
Optional[
Message]
-
await
add_reaction(emoji)¶ 이 함수는 코루틴 입니다.
메시지에 반응 추가
이모지는 유니코드 이모지 또는 사용자 지정 길드
Emoji일 수 있습니다.이 기능을 사용하려면
read_message_history권한이 있어야 합니다. 이 이모지를 사용하여 메시지에 응답한 사람이 없는 경우add_reactions권한이 필요합니다.- 매개변수
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – 반응할 이모티콘입니다.- 예외
HTTPException – Adding the reaction failed.
Forbidden – 메시지에 응답 할 수 있는 적절한 권한이 없습니다.
NotFound – 지정한 이모티콘을 찾을 수 없습니다.
InvalidArgument – emoji 매개 변수가 유효하지 않습니다.
-
await
clear_reaction(emoji)¶ 이 함수는 코루틴 입니다.
메시지에서 특정 반응을 지웁니다.
이모지는 유니코드 이모지 또는 사용자 지정 길드
Emoji일 수 있습니다.이것을 사용하려면
manage_messages권한이 필요합니다.버전 1.3에 추가.
- 매개변수
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – 이모티콘을 삭제합니다.- 예외
HTTPException – 반응 지우기에 실패했습니다.
Forbidden – 반응을 지울 수 있는 적절한 권한이 없습니다.
NotFound – 지정한 이모티콘을 찾을 수 없습니다.
InvalidArgument – emoji 매개 변수가 유효하지 않습니다.
-
await
clear_reactions()¶ 이 함수는 코루틴 입니다.
메시지에서 모든 반응을 제거합니다.
이것을 사용하려면
manage_messages권한이 필요합니다.- 예외
HTTPException – 반응 제거에 실패했습니다.
Forbidden – 모든 반응을 제거 할 수 있는 권한이 없습니다.
-
await
delete(*, delay=None)¶ 이 함수는 코루틴 입니다.
메시지를 삭제합니다.
권한없이 자신의 메시지를 삭제할 수 있습니다. 그러나 다른 사람의 메시지를 삭제하려면
manage_messages권한 이 필요합니다 .버전 1.1에서 변경: 새
delay키워드 전용 매개 변수를 추가했습니다.- 매개변수
delay (Optional[
float]) – 제공한 경우 메시지를 삭제하기 전에 백그라운드에서 대기하는 시간 (초)입니다. 삭제가 실패하면 자동으로 무시됩니다.- 예외
Forbidden – 메시지를 삭제할 수 있는 권한이 없습니다.
NotFound – 메시지가 이미 삭제되었습니다
HTTPException – 메시지 삭제에 실패했습니다.
-
await
pin(*, reason=None)¶ 이 함수는 코루틴 입니다.
메시지를 고정합니다.
DM이 아닌 채널에서는
manage_messages권한이 필요합니다.- 매개변수
reason (Optional[
str]) –The reason for pinning the message. Shows up on the audit log.
버전 1.4에 추가.
- 예외
Forbidden – 메시지를 고정 할 권한이 없습니다.
NotFound – 메시지 또는 채널을 찾지 못했거나 삭제했습니다.
HTTPException – 채널에 50 개 이상의 고정 된 메시지가 있기 때문에 메시지 고정에 실패했습니다.
-
await
publish()¶ 이 함수는 코루틴 입니다.
이 메시지를 공지 사항 채널에 게시합니다.
메시지가 자신의 것이 아닌 경우
manage_messages권한이 필요합니다.- 예외
Forbidden – 이 메시지를 게시 할 수 있는 적절한 권한이 없습니다.
HTTPException – 메시지 게시에 실패했습니다.
-
await
remove_reaction(emoji, member)¶ 이 함수는 코루틴 입니다.
메시지에서 멤버의 반응 제거
이모지는 유니코드 이모지 또는 사용자 지정 길드
Emoji일 수 있습니다.반응이 사용자 자신의 것이 아닌 경우(즉,
member매개변수가 내가 아닌 경우)manage_messages권한이 필요합니다.멤버 파라미터는 멤버를 나타내야 하며
abc.Snowflakeabc를 충족해야 합니다.- 매개변수
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – 이모티콘을 제거합니다.member (
abc.Snowflake) – 반응을 제거 할 멤버입니다.
- 예외
HTTPException – 반응 제거에 실패했습니다.
Forbidden – 반응을 제거 할 수 있는 권한이 없습니다.
NotFound – 지정한 멤버 또는 이모티콘을 찾을 수 없습니다.
InvalidArgument – emoji 매개 변수가 유효하지 않습니다.
-
await
reply(content=None, **kwargs)¶ 이 함수는 코루틴 입니다.
A shortcut method to
abc.Messageable.send()to reply to theMessage.버전 1.6에 추가.
- 예외
HTTPException – 메시지 전송에 실패했습니다.
Forbidden – 메시지를 보낼 권한이 없습니다.
InvalidArgument –
files리스트의 길이가 적당하지 않거나file과files를 모두 지정했습니다.
- 반환값
전송한 메시지.
- 반환 형식
-
to_reference()¶ Creates a
MessageReferencefrom the current message.버전 1.6에 추가.
- 반환값
The reference to this message.
- 반환 형식
-
await
unpin(*, reason=None)¶ 이 함수는 코루틴 입니다.
메시지를 고정 해제합니다.
DM이 아닌 채널에서는
manage_messages권한이 필요합니다.- 매개변수
reason (Optional[
str]) –The reason for unpinning the message. Shows up on the audit log.
버전 1.4에 추가.
- 예외
Forbidden – 메시지를 고정 해제 할 수 있는 권한이 없습니다.
NotFound – 메시지 또는 채널을 찾지 못했거나 삭제했습니다.
HTTPException – 메시지 고정 해제에 실패했습니다.
-
Intents¶
-
class
discord.Intents(**kwargs)¶ Wraps up a Discord gateway intent flag.
Similar to
Permissions, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the
intentskeyword argument ofClient.버전 1.5에 추가.
-
x == y Checks if two flags are equal.
-
x != y Checks if two flags are not equal.
-
hash(x) Return the flag’s hash.
-
iter(x) Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
-
value¶ The raw value. You should query flags via the properties rather than using this raw value.
- 타입
-
classmethod
default()¶ A factory method that creates a
Intentswith everything enabled exceptpresencesandmembers.
-
guilds¶ Whether guild related events are enabled.
This corresponds to the following events:
This also corresponds to the following attributes and classes in terms of cache:
Guildand all its attributes.
It is highly advisable to leave this intent enabled for your bot to function.
- 타입
-
members¶ Whether guild member related events are enabled.
This corresponds to the following events:
on_member_update()(nickname, roles)
This also corresponds to the following attributes and classes in terms of cache:
For more information go to the member intent documentation.
참고
Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.
- 타입
-
bans¶ Whether guild ban related events are enabled.
This corresponds to the following events:
This does not correspond to any attributes or classes in the library in terms of cache.
- 타입
-
emojis¶ Whether guild emoji related events are enabled.
This corresponds to the following events:
This also corresponds to the following attributes and classes in terms of cache:
- 타입
-
integrations¶ Whether guild integration related events are enabled.
This corresponds to the following events:
This does not correspond to any attributes or classes in the library in terms of cache.
- 타입
-
webhooks¶ Whether guild webhook related events are enabled.
This corresponds to the following events:
This does not correspond to any attributes or classes in the library in terms of cache.
- 타입
-
invites¶ Whether guild invite related events are enabled.
This corresponds to the following events:
This does not correspond to any attributes or classes in the library in terms of cache.
- 타입
-
voice_states¶ Whether guild voice state related events are enabled.
This corresponds to the following events:
This also corresponds to the following attributes and classes in terms of cache:
- 타입
-
presences¶ Whether guild presence related events are enabled.
This corresponds to the following events:
on_member_update()(activities, status)
This also corresponds to the following attributes and classes in terms of cache:
For more information go to the presence intent documentation.
참고
Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.
- 타입
-
messages¶ Whether guild and direct message related events are enabled.
This is a shortcut to set or get both
guild_messagesanddm_messages.This corresponds to the following events:
on_message()(both guilds and DMs)on_message_edit()(both guilds and DMs)on_message_delete()(both guilds and DMs)on_raw_message_delete()(both guilds and DMs)on_raw_message_edit()(both guilds and DMs)
This also corresponds to the following attributes and classes in terms of cache:
Note that due to an implicit relationship this also corresponds to the following events:
on_reaction_add()(both guilds and DMs)on_reaction_remove()(both guilds and DMs)on_reaction_clear()(both guilds and DMs)
- 타입
-
guild_messages¶ Whether guild message related events are enabled.
See also
dm_messagesfor DMs ormessagesfor both.This corresponds to the following events:
on_message()(only for guilds)on_message_edit()(only for guilds)on_message_delete()(only for guilds)on_raw_message_delete()(only for guilds)on_raw_message_edit()(only for guilds)
This also corresponds to the following attributes and classes in terms of cache:
Client.cached_messages(only for guilds)
Note that due to an implicit relationship this also corresponds to the following events:
on_reaction_add()(only for guilds)on_reaction_remove()(only for guilds)on_reaction_clear()(only for guilds)
- 타입
-
dm_messages¶ Whether direct message related events are enabled.
See also
guild_messagesfor guilds ormessagesfor both.This corresponds to the following events:
on_message()(only for DMs)on_message_edit()(only for DMs)on_message_delete()(only for DMs)on_raw_message_delete()(only for DMs)on_raw_message_edit()(only for DMs)
This also corresponds to the following attributes and classes in terms of cache:
Client.cached_messages(only for DMs)
Note that due to an implicit relationship this also corresponds to the following events:
on_reaction_add()(only for DMs)on_reaction_remove()(only for DMs)on_reaction_clear()(only for DMs)
- 타입
-
reactions¶ Whether guild and direct message reaction related events are enabled.
This is a shortcut to set or get both
guild_reactionsanddm_reactions.This corresponds to the following events:
on_reaction_add()(both guilds and DMs)on_reaction_remove()(both guilds and DMs)on_reaction_clear()(both guilds and DMs)on_raw_reaction_add()(both guilds and DMs)on_raw_reaction_remove()(both guilds and DMs)on_raw_reaction_clear()(both guilds and DMs)
This also corresponds to the following attributes and classes in terms of cache:
Message.reactions(both guild and DM messages)
- 타입
-
guild_reactions¶ Whether guild message reaction related events are enabled.
See also
dm_reactionsfor DMs orreactionsfor both.This corresponds to the following events:
on_reaction_add()(only for guilds)on_reaction_remove()(only for guilds)on_reaction_clear()(only for guilds)on_raw_reaction_add()(only for guilds)on_raw_reaction_remove()(only for guilds)on_raw_reaction_clear()(only for guilds)
This also corresponds to the following attributes and classes in terms of cache:
Message.reactions(only for guild messages)
- 타입
-
dm_reactions¶ Whether direct message reaction related events are enabled.
See also
guild_reactionsfor guilds orreactionsfor both.This corresponds to the following events:
on_reaction_add()(only for DMs)on_reaction_remove()(only for DMs)on_reaction_clear()(only for DMs)on_raw_reaction_add()(only for DMs)on_raw_reaction_remove()(only for DMs)on_raw_reaction_clear()(only for DMs)
This also corresponds to the following attributes and classes in terms of cache:
Message.reactions(only for DM messages)
- 타입
-
typing¶ Whether guild and direct message typing related events are enabled.
This is a shortcut to set or get both
guild_typinganddm_typing.This corresponds to the following events:
on_typing()(both guilds and DMs)
This does not correspond to any attributes or classes in the library in terms of cache.
- 타입
-
guild_typing¶ Whether guild and direct message typing related events are enabled.
See also
dm_typingfor DMs ortypingfor both.This corresponds to the following events:
on_typing()(only for guilds)
This does not correspond to any attributes or classes in the library in terms of cache.
- 타입
-
dm_typing¶ Whether guild and direct message typing related events are enabled.
See also
guild_typingfor guilds ortypingfor both.This corresponds to the following events:
on_typing()(only for DMs)
This does not correspond to any attributes or classes in the library in terms of cache.
- 타입
-
MemberCacheFlags¶
-
class
discord.MemberCacheFlags(**kwargs)¶ Controls the library’s cache policy when it comes to members.
This allows for finer grained control over what members are cached. Note that the bot’s own member is always cached. This class is passed to the
member_cache_flagsparameter inClient.Due to a quirk in how Discord works, in order to ensure proper cleanup of cache resources it is recommended to have
Intents.membersenabled. Otherwise the library cannot know when a member leaves a guild and is thus unable to cleanup after itself.To construct an object you can pass keyword arguments denoting the flags to enable or disable.
The default value is all flags enabled.
버전 1.5에 추가.
-
x == y Checks if two flags are equal.
-
x != y Checks if two flags are not equal.
-
hash(x) Return the flag’s hash.
-
iter(x) Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
-
value¶ The raw value. You should query flags via the properties rather than using this raw value.
- 타입
-
classmethod
all()¶ A factory method that creates a
MemberCacheFlagswith everything enabled.
-
classmethod
none()¶ A factory method that creates a
MemberCacheFlagswith everything disabled.
-
online¶ Whether to cache members with a status.
For example, members that are part of the initial
GUILD_CREATEor become online at a later point. This requiresIntents.presences.Members that go offline are no longer cached.
- 타입
-
voice¶ Whether to cache members that are in voice.
This requires
Intents.voice_states.Members that leave voice are no longer cached.
- 타입
-
joined¶ Whether to cache members that joined the guild or are chunked as part of the initial log in flow.
This requires
Intents.members.Members that leave the guild are no longer cached.
- 타입
-
classmethod
from_intents(intents)¶ A factory method that creates a
MemberCacheFlagsbased on the currently selectedIntents.- 매개변수
intents (
Intents) – The intents to select from.- 반환값
The resulting member cache flags.
- 반환 형식
-
File¶
-
class
discord.File(fp, filename=None, *, spoiler=False)¶ A parameter object used for
abc.Messageable.send()for sending file objects.참고
File objects are single use and are not meant to be reused in multiple
abc.Messageable.send()s.-
fp¶ A file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open.
참고
If the file-like object passed is opened via
openthen the modes 〈rb〉 should be used.To pass binary data, consider usage of
io.BytesIO.- 타입
Union[
str,io.BufferedIOBase]
-
Colour¶
- clsColour.blue
- clsColour.blurple
- clsColour.dark_blue
- clsColour.dark_gold
- clsColour.dark_gray
- clsColour.dark_green
- clsColour.dark_grey
- clsColour.dark_magenta
- clsColour.dark_orange
- clsColour.dark_purple
- clsColour.dark_red
- clsColour.dark_teal
- clsColour.dark_theme
- clsColour.darker_gray
- clsColour.darker_grey
- clsColour.default
- clsColour.from_hsv
- clsColour.from_rgb
- clsColour.gold
- clsColour.green
- clsColour.greyple
- clsColour.light_gray
- clsColour.light_grey
- clsColour.lighter_gray
- clsColour.lighter_grey
- clsColour.magenta
- clsColour.orange
- clsColour.purple
- clsColour.random
- clsColour.red
- clsColour.teal
- defto_rgb
-
class
discord.Colour(value)¶ Represents a Discord role colour. This class is similar to a (red, green, blue)
tuple.There is an alias for this called Color.
-
x == y Checks if two colours are equal.
-
x != y Checks if two colours are not equal.
-
hash(x) Return the colour’s hash.
-
str(x) Returns the hex format for the colour.
-
BaseActivity¶
-
class
discord.BaseActivity(**kwargs)¶ The base activity that all user-settable activities inherit from. A user-settable activity is one that can be used in
Client.change_presence().The following types currently count as user-settable:
Note that although these types are considered user-settable by the library, Discord typically ignores certain combinations of activity depending on what is currently set. This behaviour may change in the future so there are no guarantees on whether Discord will actually let you set these types.
버전 1.3에 추가.
-
created_at¶ When the user started doing this activity in UTC.
버전 1.3에 추가.
- 타입
Optional[
datetime.datetime]
-
Activity¶
-
class
discord.Activity(**kwargs)¶ Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
-
type¶ The type of activity currently being done.
- 타입
-
timestamps¶ A dictionary of timestamps. It contains the following optional keys:
start: Corresponds to when the user started doing the activity in milliseconds since Unix epoch.end: Corresponds to when the user will finish doing the activity in milliseconds since Unix epoch.
- 타입
-
assets¶ A dictionary representing the images and their hover text of an activity. It contains the following optional keys:
large_image: A string representing the ID for the large image asset.large_text: A string representing the text when hovering over the large image asset.small_image: A string representing the ID for the small image asset.small_text: A string representing the text when hovering over the small image asset.
- 타입
-
party¶ A dictionary representing the activity party. It contains the following optional keys:
id: A string representing the party ID.size: A list of up to two integer elements denoting (current_size, maximum_size).
- 타입
-
emoji¶ The emoji that belongs to this activity.
- 타입
Optional[
PartialEmoji]
-
start¶ When the user started doing this activity in UTC, if applicable.
- 타입
Optional[
datetime.datetime]
-
end¶ When the user will stop doing this activity in UTC, if applicable.
- 타입
Optional[
datetime.datetime]
-
large_image_url¶ Returns a URL pointing to the large image asset of this activity if applicable.
- 타입
Optional[
str]
-
small_image_url¶ Returns a URL pointing to the small image asset of this activity if applicable.
- 타입
Optional[
str]
-
Game¶
-
class
discord.Game(name, **extra)¶ A slimmed down version of
Activitythat 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¶ When the user started playing this game in UTC, if applicable.
- 타입
Optional[
datetime.datetime]
-
end¶ When the user will stop playing this game in UTC, if applicable.
- 타입
Optional[
datetime.datetime]
-
Streaming¶
-
class
discord.Streaming(*, name, url, **extra)¶ A slimmed down version of
Activitythat 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.
-
assets¶ A dictionary comprising of similar keys than those in
Activity.assets.- 타입
-
type¶ Returns the game’s type. This is for compatibility with
Activity.It always returns
ActivityType.streaming.- 타입
-
twitch_name¶ If provided, the twitch name of the user streaming.
This corresponds to the
large_imagekey of theStreaming.assetsdictionary if it starts withtwitch:. Typically set by the Discord client.- 타입
Optional[
str]
-
CustomActivity¶
-
class
discord.CustomActivity(name, *, emoji=None, **extra)¶ Represents a Custom activity from Discord.
-
x == y Checks if two activities are equal.
-
x != y Checks if two activities are not equal.
-
hash(x) Returns the activity’s hash.
-
str(x) Returns the custom status text.
버전 1.3에 추가.
-
emoji¶ The emoji to pass to the activity, if any.
- 타입
Optional[
PartialEmoji]
-
type¶ Returns the activity’s type. This is for compatibility with
Activity.It always returns
ActivityType.custom.- 타입
-
Permissions¶
- add_reactions
- administrator
- attach_files
- ban_members
- change_nickname
- connect
- create_instant_invite
- deafen_members
- embed_links
- external_emojis
- kick_members
- manage_channels
- manage_emojis
- manage_guild
- manage_messages
- manage_nicknames
- manage_permissions
- manage_roles
- manage_webhooks
- mention_everyone
- move_members
- mute_members
- priority_speaker
- read_message_history
- read_messages
- send_messages
- send_tts_messages
- speak
- stream
- use_external_emojis
- use_slash_commands
- use_voice_activation
- value
- view_audit_log
- view_channel
- view_guild_insights
- clsPermissions.all
- clsPermissions.all_channel
- clsPermissions.general
- clsPermissions.none
- clsPermissions.text
- clsPermissions.voice
- defis_strict_subset
- defis_strict_superset
- defis_subset
- defis_superset
- defupdate
-
class
discord.Permissions(permissions=0, **kwargs)¶ Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
버전 1.3에서 변경: You can now use keyword arguments to initialize
Permissionssimilar toupdate().-
x == y Checks if two permissions are equal.
-
x != y Checks if two permissions are not equal.
-
x <= y Checks if a permission is a subset of another permission.
-
x >= y Checks if a permission is a superset of another permission.
-
x < y Checks if a permission is a strict subset of another permission.
-
x > y Checks if a permission is a strict superset of another permission.
-
hash(x) Return the permission’s hash.
-
iter(x) Returns an iterator of
(perm, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
-
value¶ The raw value. This value is a bit array field of a 53-bit integer representing the currently available permissions. You should query permissions via the properties rather than using this raw value.
- 타입
-
is_subset(other)¶ Returns
Trueif self has the same or fewer permissions as other.
-
is_superset(other)¶ Returns
Trueif self has the same or more permissions as other.
-
is_strict_subset(other)¶ Returns
Trueif the permissions on other are a strict subset of those on self.
-
is_strict_superset(other)¶ Returns
Trueif the permissions on other are a strict superset of those on self.
-
classmethod
none()¶ A factory method that creates a
Permissionswith all permissions set toFalse.
-
classmethod
all()¶ A factory method that creates a
Permissionswith all permissions set toTrue.
-
classmethod
all_channel()¶ A
Permissionswith all channel-specific permissions set toTrueand the guild-specific ones set toFalse. 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
Permissionswith all 《General》 permissions from the official Discord UI set toTrue.
-
classmethod
text()¶ A factory method that creates a
Permissionswith all 《Text》 permissions from the official Discord UI set toTrue.
-
classmethod
voice()¶ A factory method that creates a
Permissionswith all 《Voice》 permissions from the official Discord UI set toTrue.
-
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.
-
administrator¶ Returns
Trueif a user is an administrator. This role overrides all other permissions.This also bypasses all channel-specific overrides.
- 타입
-
manage_channels¶ Returns
Trueif a user can edit, delete, or create channels in the guild.This also corresponds to the 《Manage Channel》 channel-specific override.
- 타입
-
view_channel¶ An alias for
read_messages.버전 1.3에 추가.
- 타입
-
send_tts_messages¶ Returns
Trueif a user can send TTS messages from all or specific text channels.- 타입
-
manage_messages¶ Returns
Trueif a user can delete or pin messages in a text channel.참고
Note that there are currently no ways to edit other people’s messages.
- 타입
-
mention_everyone¶ Returns
Trueif a user’s @everyone or @here will mention everyone in the text channel.- 타입
-
use_external_emojis¶ An alias for
external_emojis.버전 1.3에 추가.
- 타입
-
manage_roles¶ Returns
Trueif a user can create or edit roles less than their role’s position.This also corresponds to the 《Manage Permissions》 channel-specific override.
- 타입
-
manage_permissions¶ An alias for
manage_roles.버전 1.3에 추가.
- 타입
-
PermissionOverwrite¶
- clsPermissionOverwrite.from_pair
- defis_empty
- defpair
- defupdate
-
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 toNoneand notFalse. Setting a value toFalseis explicitly denying that permission, while setting a value toTrueis explicitly allowing that permission.The values supported by this are the same as
Permissionswith the added possibility of it being set toNone.-
x == y Checks if two overwrites are equal.
-
x != y Checks if two overwrites are not equal.
-
iter(x) Returns an iterator of
(perm, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
- 매개변수
**kwargs – Set the value of permissions by their name.
-
pair()¶ Tuple[
Permissions,Permissions]: Returns the (allow, deny) pair from this overwrite.
-
classmethod
from_pair(allow, deny)¶ Creates an overwrite from an allow/deny pair of
Permissions.
-
is_empty()¶ Checks if the permission overwrite is currently empty.
An empty permission overwrite is one that has no overwrites set to
TrueorFalse.- 반환값
Indicates if the overwrite is empty.
- 반환 형식
-
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.
-
SystemChannelFlags¶
-
class
discord.SystemChannelFlags¶ Wraps up a Discord system channel flag value.
Similar to
Permissions, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit the system flags easily.To construct an object you can pass keyword arguments denoting the flags to enable or disable.
-
x == y Checks if two flags are equal.
-
x != y Checks if two flags are not equal.
-
hash(x) Return the flag’s hash.
-
iter(x) Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
-
value¶ The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- 타입
-
join_notifications¶ Returns
Trueif the system channel is used for member join notifications.- 타입
Returns
Trueif the system channel is used for Nitro boosting notifications.- 타입
-
MessageFlags¶
-
class
discord.MessageFlags¶ Wraps up a Discord Message flag value.
See
SystemChannelFlags.-
x == y Checks if two flags are equal.
-
x != y Checks if two flags are not equal.
-
hash(x) Return the flag’s hash.
-
iter(x) Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
버전 1.3에 추가.
-
value¶ The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- 타입
-
source_message_deleted¶ Returns
Trueif the source message for this crosspost has been deleted.- 타입
-
PublicUserFlags¶
-
class
discord.PublicUserFlags¶ Wraps up the Discord User Public flags.
-
x == y Checks if two PublicUserFlags are equal.
-
x != y Checks if two PublicUserFlags are not equal.
-
hash(x) Return the flag’s hash.
-
iter(x) Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
버전 1.4에 추가.
-
value¶ The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- 타입
-
early_verified_bot_developer¶ An alias for
verified_bot_developer.버전 1.5에 추가.
- 타입
-
all()¶ List[
UserFlags]: Returns all public flags the user has.
-
Exceptions¶
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
Clientfails.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¶ The response of the failed HTTP request. This is an instance of
aiohttp.ClientResponse. In some cases this could also be arequests.Response.
-
-
exception
discord.Forbidden(response, message)¶ Exception that’s thrown for when status code 403 occurs.
Subclass of
HTTPException
-
exception
discord.NotFound(response, message)¶ Exception that’s thrown for when status code 404 occurs.
Subclass of
HTTPException
-
exception
discord.DiscordServerError(response, message)¶ Exception that’s thrown for when a 500 range status code occurs.
Subclass of
HTTPException.버전 1.5에 추가.
-
exception
discord.InvalidData¶ Exception that’s raised when the library encounters unknown or invalid data from Discord.
-
exception
discord.InvalidArgument¶ Exception that’s 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
ValueErrorandTypeErrorexcept inherited fromClientExceptionand thusDiscordException.
-
exception
discord.GatewayNotFound¶ An exception that is usually thrown when the gateway hub for the
Clientwebsocket is not found.
-
exception
discord.ConnectionClosed(socket, *, shard_id, code=None)¶ Exception that’s thrown when the gateway connection is closed for reasons that could not be handled internally.
-
exception
discord.PrivilegedIntentsRequired(shard_id)¶ Exception that’s thrown when the gateway is requesting privileged intents but they’re not ticked in the developer page yet.
Go to https://discord.com/developers/applications/ and enable the intents that are required. Currently these are as follows:
-
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.