partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
Client.delete_invite
|coro| Revokes an :class:`.Invite`, URL, or ID to an invite. You must have the :attr:`~.Permissions.manage_channels` permission in the associated guild to do this. Parameters ---------- invite: Union[:class:`.Invite`, :class:`str`] The invite to revoke. Raises ------- Forbidden You do not have permissions to revoke invites. NotFound The invite is invalid or expired. HTTPException Revoking the invite failed.
discord/client.py
async def delete_invite(self, invite): """|coro| Revokes an :class:`.Invite`, URL, or ID to an invite. You must have the :attr:`~.Permissions.manage_channels` permission in the associated guild to do this. Parameters ---------- invite: Union[:class:`.Invite`, :class:`str`] The invite to revoke. Raises ------- Forbidden You do not have permissions to revoke invites. NotFound The invite is invalid or expired. HTTPException Revoking the invite failed. """ invite_id = utils.resolve_invite(invite) await self.http.delete_invite(invite_id)
async def delete_invite(self, invite): """|coro| Revokes an :class:`.Invite`, URL, or ID to an invite. You must have the :attr:`~.Permissions.manage_channels` permission in the associated guild to do this. Parameters ---------- invite: Union[:class:`.Invite`, :class:`str`] The invite to revoke. Raises ------- Forbidden You do not have permissions to revoke invites. NotFound The invite is invalid or expired. HTTPException Revoking the invite failed. """ invite_id = utils.resolve_invite(invite) await self.http.delete_invite(invite_id)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L996-L1020
[ "async", "def", "delete_invite", "(", "self", ",", "invite", ")", ":", "invite_id", "=", "utils", ".", "resolve_invite", "(", "invite", ")", "await", "self", ".", "http", ".", "delete_invite", "(", "invite_id", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.fetch_widget
|coro| Gets a :class:`.Widget` from a guild ID. .. note:: The guild must have the widget enabled to get this information. Parameters ----------- guild_id: :class:`int` The ID of the guild. Raises ------- Forbidden The widget for this guild is disabled. HTTPException Retrieving the widget failed. Returns -------- :class:`.Widget` The guild's widget.
discord/client.py
async def fetch_widget(self, guild_id): """|coro| Gets a :class:`.Widget` from a guild ID. .. note:: The guild must have the widget enabled to get this information. Parameters ----------- guild_id: :class:`int` The ID of the guild. Raises ------- Forbidden The widget for this guild is disabled. HTTPException Retrieving the widget failed. Returns -------- :class:`.Widget` The guild's widget. """ data = await self.http.get_widget(guild_id) return Widget(state=self._connection, data=data)
async def fetch_widget(self, guild_id): """|coro| Gets a :class:`.Widget` from a guild ID. .. note:: The guild must have the widget enabled to get this information. Parameters ----------- guild_id: :class:`int` The ID of the guild. Raises ------- Forbidden The widget for this guild is disabled. HTTPException Retrieving the widget failed. Returns -------- :class:`.Widget` The guild's widget. """ data = await self.http.get_widget(guild_id) return Widget(state=self._connection, data=data)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L1024-L1052
[ "async", "def", "fetch_widget", "(", "self", ",", "guild_id", ")", ":", "data", "=", "await", "self", ".", "http", ".", "get_widget", "(", "guild_id", ")", "return", "Widget", "(", "state", "=", "self", ".", "_connection", ",", "data", "=", "data", ")"...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.application_info
|coro| Retrieve's the bot's application information. Raises ------- HTTPException Retrieving the information failed somehow. Returns -------- :class:`.AppInfo` A namedtuple representing the application info.
discord/client.py
async def application_info(self): """|coro| Retrieve's the bot's application information. Raises ------- HTTPException Retrieving the information failed somehow. Returns -------- :class:`.AppInfo` A namedtuple representing the application info. """ data = await self.http.application_info() if 'rpc_origins' not in data: data['rpc_origins'] = None return AppInfo(self._connection, data)
async def application_info(self): """|coro| Retrieve's the bot's application information. Raises ------- HTTPException Retrieving the information failed somehow. Returns -------- :class:`.AppInfo` A namedtuple representing the application info. """ data = await self.http.application_info() if 'rpc_origins' not in data: data['rpc_origins'] = None return AppInfo(self._connection, data)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L1054-L1072
[ "async", "def", "application_info", "(", "self", ")", ":", "data", "=", "await", "self", ".", "http", ".", "application_info", "(", ")", "if", "'rpc_origins'", "not", "in", "data", ":", "data", "[", "'rpc_origins'", "]", "=", "None", "return", "AppInfo", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.fetch_user
|coro| Retrieves a :class:`~discord.User` based 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. .. note:: This method is an API call. For general usage, consider :meth:`get_user` instead. Parameters ----------- user_id: :class:`int` The user's ID to fetch from. Raises ------- NotFound A user with this ID does not exist. HTTPException Fetching the user failed. Returns -------- :class:`~discord.User` The user you requested.
discord/client.py
async def fetch_user(self, user_id): """|coro| Retrieves a :class:`~discord.User` based 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. .. note:: This method is an API call. For general usage, consider :meth:`get_user` instead. Parameters ----------- user_id: :class:`int` The user's ID to fetch from. Raises ------- NotFound A user with this ID does not exist. HTTPException Fetching the user failed. Returns -------- :class:`~discord.User` The user you requested. """ data = await self.http.get_user(user_id) return User(state=self._connection, data=data)
async def fetch_user(self, user_id): """|coro| Retrieves a :class:`~discord.User` based 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. .. note:: This method is an API call. For general usage, consider :meth:`get_user` instead. Parameters ----------- user_id: :class:`int` The user's ID to fetch from. Raises ------- NotFound A user with this ID does not exist. HTTPException Fetching the user failed. Returns -------- :class:`~discord.User` The user you requested. """ data = await self.http.get_user(user_id) return User(state=self._connection, data=data)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L1074-L1104
[ "async", "def", "fetch_user", "(", "self", ",", "user_id", ")", ":", "data", "=", "await", "self", ".", "http", ".", "get_user", "(", "user_id", ")", "return", "User", "(", "state", "=", "self", ".", "_connection", ",", "data", "=", "data", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.fetch_user_profile
|coro| Gets an arbitrary user's profile. This can only be used by non-bot accounts. Parameters ------------ user_id: :class:`int` The ID of the user to fetch their profile for. Raises ------- Forbidden Not allowed to fetch profiles. HTTPException Fetching the profile failed. Returns -------- :class:`.Profile` The profile of the user.
discord/client.py
async def fetch_user_profile(self, user_id): """|coro| Gets an arbitrary user's profile. This can only be used by non-bot accounts. Parameters ------------ user_id: :class:`int` The ID of the user to fetch their profile for. Raises ------- Forbidden Not allowed to fetch profiles. HTTPException Fetching the profile failed. Returns -------- :class:`.Profile` The profile of the user. """ state = self._connection data = await self.http.get_user_profile(user_id) def transform(d): return state._get_guild(int(d['id'])) since = data.get('premium_since') mutual_guilds = list(filter(None, map(transform, data.get('mutual_guilds', [])))) user = data['user'] return Profile(flags=user.get('flags', 0), premium_since=utils.parse_time(since), mutual_guilds=mutual_guilds, user=User(data=user, state=state), connected_accounts=data['connected_accounts'])
async def fetch_user_profile(self, user_id): """|coro| Gets an arbitrary user's profile. This can only be used by non-bot accounts. Parameters ------------ user_id: :class:`int` The ID of the user to fetch their profile for. Raises ------- Forbidden Not allowed to fetch profiles. HTTPException Fetching the profile failed. Returns -------- :class:`.Profile` The profile of the user. """ state = self._connection data = await self.http.get_user_profile(user_id) def transform(d): return state._get_guild(int(d['id'])) since = data.get('premium_since') mutual_guilds = list(filter(None, map(transform, data.get('mutual_guilds', [])))) user = data['user'] return Profile(flags=user.get('flags', 0), premium_since=utils.parse_time(since), mutual_guilds=mutual_guilds, user=User(data=user, state=state), connected_accounts=data['connected_accounts'])
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L1106-L1142
[ "async", "def", "fetch_user_profile", "(", "self", ",", "user_id", ")", ":", "state", "=", "self", ".", "_connection", "data", "=", "await", "self", ".", "http", ".", "get_user_profile", "(", "user_id", ")", "def", "transform", "(", "d", ")", ":", "retur...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.fetch_webhook
|coro| Retrieves a :class:`.Webhook` with the specified ID. Raises -------- HTTPException Retrieving the webhook failed. NotFound Invalid webhook ID. Forbidden You do not have permission to fetch this webhook. Returns --------- :class:`.Webhook` The webhook you requested.
discord/client.py
async def fetch_webhook(self, webhook_id): """|coro| Retrieves a :class:`.Webhook` with the specified ID. Raises -------- HTTPException Retrieving the webhook failed. NotFound Invalid webhook ID. Forbidden You do not have permission to fetch this webhook. Returns --------- :class:`.Webhook` The webhook you requested. """ data = await self.http.get_webhook(webhook_id) return Webhook.from_state(data, state=self._connection)
async def fetch_webhook(self, webhook_id): """|coro| Retrieves a :class:`.Webhook` with the specified ID. Raises -------- HTTPException Retrieving the webhook failed. NotFound Invalid webhook ID. Forbidden You do not have permission to fetch this webhook. Returns --------- :class:`.Webhook` The webhook you requested. """ data = await self.http.get_webhook(webhook_id) return Webhook.from_state(data, state=self._connection)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L1144-L1164
[ "async", "def", "fetch_webhook", "(", "self", ",", "webhook_id", ")", ":", "data", "=", "await", "self", ".", "http", ".", "get_webhook", "(", "webhook_id", ")", "return", "Webhook", ".", "from_state", "(", "data", ",", "state", "=", "self", ".", "_conne...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
PartialInviteGuild.icon_url_as
:class:`Asset`: The same operation as :meth:`Guild.icon_url_as`.
discord/invite.py
def icon_url_as(self, *, format='webp', size=1024): """:class:`Asset`: The same operation as :meth:`Guild.icon_url_as`.""" return Asset._from_guild_image(self._state, self.id, self.icon, 'icons', format=format, size=size)
def icon_url_as(self, *, format='webp', size=1024): """:class:`Asset`: The same operation as :meth:`Guild.icon_url_as`.""" return Asset._from_guild_image(self._state, self.id, self.icon, 'icons', format=format, size=size)
[ ":", "class", ":", "Asset", ":", "The", "same", "operation", "as", ":", "meth", ":", "Guild", ".", "icon_url_as", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/invite.py#L153-L155
[ "def", "icon_url_as", "(", "self", ",", "*", ",", "format", "=", "'webp'", ",", "size", "=", "1024", ")", ":", "return", "Asset", ".", "_from_guild_image", "(", "self", ".", "_state", ",", "self", ".", "id", ",", "self", ".", "icon", ",", "'icons'", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
PartialInviteGuild.banner_url_as
:class:`Asset`: The same operation as :meth:`Guild.banner_url_as`.
discord/invite.py
def banner_url_as(self, *, format='webp', size=2048): """:class:`Asset`: The same operation as :meth:`Guild.banner_url_as`.""" return Asset._from_guild_image(self._state, self.id, self.banner, 'banners', format=format, size=size)
def banner_url_as(self, *, format='webp', size=2048): """:class:`Asset`: The same operation as :meth:`Guild.banner_url_as`.""" return Asset._from_guild_image(self._state, self.id, self.banner, 'banners', format=format, size=size)
[ ":", "class", ":", "Asset", ":", "The", "same", "operation", "as", ":", "meth", ":", "Guild", ".", "banner_url_as", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/invite.py#L162-L164
[ "def", "banner_url_as", "(", "self", ",", "*", ",", "format", "=", "'webp'", ",", "size", "=", "2048", ")", ":", "return", "Asset", ".", "_from_guild_image", "(", "self", ".", "_state", ",", "self", ".", "id", ",", "self", ".", "banner", ",", "'banne...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
PartialInviteGuild.splash_url_as
:class:`Asset`: The same operation as :meth:`Guild.splash_url_as`.
discord/invite.py
def splash_url_as(self, *, format='webp', size=2048): """:class:`Asset`: The same operation as :meth:`Guild.splash_url_as`.""" return Asset._from_guild_image(self._state, self.id, self.splash, 'splashes', format=format, size=size)
def splash_url_as(self, *, format='webp', size=2048): """:class:`Asset`: The same operation as :meth:`Guild.splash_url_as`.""" return Asset._from_guild_image(self._state, self.id, self.splash, 'splashes', format=format, size=size)
[ ":", "class", ":", "Asset", ":", "The", "same", "operation", "as", ":", "meth", ":", "Guild", ".", "splash_url_as", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/invite.py#L171-L173
[ "def", "splash_url_as", "(", "self", ",", "*", ",", "format", "=", "'webp'", ",", "size", "=", "2048", ")", ":", "return", "Asset", ".", "_from_guild_image", "(", "self", ".", "_state", ",", "self", ".", "id", ",", "self", ".", "splash", ",", "'splas...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Invite.delete
|coro| Revokes the instant invite. You must have the :attr:`~Permissions.manage_channels` permission to do this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this invite. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to revoke invites. NotFound The invite is invalid or expired. HTTPException Revoking the invite failed.
discord/invite.py
async def delete(self, *, reason=None): """|coro| Revokes the instant invite. You must have the :attr:`~Permissions.manage_channels` permission to do this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this invite. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to revoke invites. NotFound The invite is invalid or expired. HTTPException Revoking the invite failed. """ await self._state.http.delete_invite(self.code, reason=reason)
async def delete(self, *, reason=None): """|coro| Revokes the instant invite. You must have the :attr:`~Permissions.manage_channels` permission to do this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this invite. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to revoke invites. NotFound The invite is invalid or expired. HTTPException Revoking the invite failed. """ await self._state.http.delete_invite(self.code, reason=reason)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/invite.py#L286-L308
[ "async", "def", "delete", "(", "self", ",", "*", ",", "reason", "=", "None", ")", ":", "await", "self", ".", "_state", ".", "http", ".", "delete_invite", "(", "self", ".", "code", ",", "reason", "=", "reason", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Attachment.save
|coro| Saves this attachment into a file-like object. Parameters ----------- fp: Union[BinaryIO, :class:`os.PathLike`] The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead. seek_begin: :class:`bool` Whether to seek to the beginning of the file after saving is successfully done. use_cached: :class:`bool` Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some type of attachments. Raises -------- HTTPException Saving the attachment failed. NotFound The attachment was deleted. Returns -------- :class:`int` The number of bytes written.
discord/message.py
async def save(self, fp, *, seek_begin=True, use_cached=False): """|coro| Saves this attachment into a file-like object. Parameters ----------- fp: Union[BinaryIO, :class:`os.PathLike`] The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead. seek_begin: :class:`bool` Whether to seek to the beginning of the file after saving is successfully done. use_cached: :class:`bool` Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some type of attachments. Raises -------- HTTPException Saving the attachment failed. NotFound The attachment was deleted. Returns -------- :class:`int` The number of bytes written. """ url = self.proxy_url if use_cached else self.url data = await self._http.get_from_cdn(url) if isinstance(fp, io.IOBase) and fp.writable(): written = fp.write(data) if seek_begin: fp.seek(0) return written else: with open(fp, 'wb') as f: return f.write(data)
async def save(self, fp, *, seek_begin=True, use_cached=False): """|coro| Saves this attachment into a file-like object. Parameters ----------- fp: Union[BinaryIO, :class:`os.PathLike`] The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead. seek_begin: :class:`bool` Whether to seek to the beginning of the file after saving is successfully done. use_cached: :class:`bool` Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some type of attachments. Raises -------- HTTPException Saving the attachment failed. NotFound The attachment was deleted. Returns -------- :class:`int` The number of bytes written. """ url = self.proxy_url if use_cached else self.url data = await self._http.get_from_cdn(url) if isinstance(fp, io.IOBase) and fp.writable(): written = fp.write(data) if seek_begin: fp.seek(0) return written else: with open(fp, 'wb') as f: return f.write(data)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L81-L124
[ "async", "def", "save", "(", "self", ",", "fp", ",", "*", ",", "seek_begin", "=", "True", ",", "use_cached", "=", "False", ")", ":", "url", "=", "self", ".", "proxy_url", "if", "use_cached", "else", "self", ".", "url", "data", "=", "await", "self", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.raw_mentions
A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content. This allows you to receive the user IDs of mentioned users even in a private message context.
discord/message.py
def raw_mentions(self): """A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content. This allows you to receive the user IDs of mentioned users even in a private message context. """ return [int(x) for x in re.findall(r'<@!?([0-9]+)>', self.content)]
def raw_mentions(self): """A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content. This allows you to receive the user IDs of mentioned users even in a private message context. """ return [int(x) for x in re.findall(r'<@!?([0-9]+)>', self.content)]
[ "A", "property", "that", "returns", "an", "array", "of", "user", "IDs", "matched", "with", "the", "syntax", "of", "<@user_id", ">", "in", "the", "message", "content", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L370-L377
[ "def", "raw_mentions", "(", "self", ")", ":", "return", "[", "int", "(", "x", ")", "for", "x", "in", "re", ".", "findall", "(", "r'<@!?([0-9]+)>'", ",", "self", ".", "content", ")", "]" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.raw_channel_mentions
A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content.
discord/message.py
def raw_channel_mentions(self): """A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content. """ return [int(x) for x in re.findall(r'<#([0-9]+)>', self.content)]
def raw_channel_mentions(self): """A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content. """ return [int(x) for x in re.findall(r'<#([0-9]+)>', self.content)]
[ "A", "property", "that", "returns", "an", "array", "of", "channel", "IDs", "matched", "with", "the", "syntax", "of", "<#channel_id", ">", "in", "the", "message", "content", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L380-L384
[ "def", "raw_channel_mentions", "(", "self", ")", ":", "return", "[", "int", "(", "x", ")", "for", "x", "in", "re", ".", "findall", "(", "r'<#([0-9]+)>'", ",", "self", ".", "content", ")", "]" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.raw_role_mentions
A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content.
discord/message.py
def raw_role_mentions(self): """A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content. """ return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)]
def raw_role_mentions(self): """A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content. """ return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)]
[ "A", "property", "that", "returns", "an", "array", "of", "role", "IDs", "matched", "with", "the", "syntax", "of", "<" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L387-L391
[ "def", "raw_role_mentions", "(", "self", ")", ":", "return", "[", "int", "(", "x", ")", "for", "x", "in", "re", ".", "findall", "(", "r'<@&([0-9]+)>'", ",", "self", ".", "content", ")", "]" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.clean_content
A property that returns the content in a "cleaned up" manner. This basically means that mentions are transformed into the way the client shows it. e.g. ``<#id>`` will transform into ``#name``. This will also transform @everyone and @here mentions into non-mentions. .. note:: This *does not* escape markdown. If you want to escape markdown then use :func:`utils.escape_markdown` along with this function.
discord/message.py
def clean_content(self): """A property that returns the content in a "cleaned up" manner. This basically means that mentions are transformed into the way the client shows it. e.g. ``<#id>`` will transform into ``#name``. This will also transform @everyone and @here mentions into non-mentions. .. note:: This *does not* escape markdown. If you want to escape markdown then use :func:`utils.escape_markdown` along with this function. """ transformations = { re.escape('<#%s>' % channel.id): '#' + channel.name for channel in self.channel_mentions } mention_transforms = { re.escape('<@%s>' % member.id): '@' + member.display_name for member in self.mentions } # add the <@!user_id> cases as well.. second_mention_transforms = { re.escape('<@!%s>' % member.id): '@' + member.display_name for member in self.mentions } transformations.update(mention_transforms) transformations.update(second_mention_transforms) if self.guild is not None: role_transforms = { re.escape('<@&%s>' % role.id): '@' + role.name for role in self.role_mentions } transformations.update(role_transforms) def repl(obj): return transformations.get(re.escape(obj.group(0)), '') pattern = re.compile('|'.join(transformations.keys())) result = pattern.sub(repl, self.content) transformations = { '@everyone': '@\u200beveryone', '@here': '@\u200bhere' } def repl2(obj): return transformations.get(obj.group(0), '') pattern = re.compile('|'.join(transformations.keys())) return pattern.sub(repl2, result)
def clean_content(self): """A property that returns the content in a "cleaned up" manner. This basically means that mentions are transformed into the way the client shows it. e.g. ``<#id>`` will transform into ``#name``. This will also transform @everyone and @here mentions into non-mentions. .. note:: This *does not* escape markdown. If you want to escape markdown then use :func:`utils.escape_markdown` along with this function. """ transformations = { re.escape('<#%s>' % channel.id): '#' + channel.name for channel in self.channel_mentions } mention_transforms = { re.escape('<@%s>' % member.id): '@' + member.display_name for member in self.mentions } # add the <@!user_id> cases as well.. second_mention_transforms = { re.escape('<@!%s>' % member.id): '@' + member.display_name for member in self.mentions } transformations.update(mention_transforms) transformations.update(second_mention_transforms) if self.guild is not None: role_transforms = { re.escape('<@&%s>' % role.id): '@' + role.name for role in self.role_mentions } transformations.update(role_transforms) def repl(obj): return transformations.get(re.escape(obj.group(0)), '') pattern = re.compile('|'.join(transformations.keys())) result = pattern.sub(repl, self.content) transformations = { '@everyone': '@\u200beveryone', '@here': '@\u200bhere' } def repl2(obj): return transformations.get(obj.group(0), '') pattern = re.compile('|'.join(transformations.keys())) return pattern.sub(repl2, result)
[ "A", "property", "that", "returns", "the", "content", "in", "a", "cleaned", "up", "manner", ".", "This", "basically", "means", "that", "mentions", "are", "transformed", "into", "the", "way", "the", "client", "shows", "it", ".", "e", ".", "g", ".", "<#id"...
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L401-L458
[ "def", "clean_content", "(", "self", ")", ":", "transformations", "=", "{", "re", ".", "escape", "(", "'<#%s>'", "%", "channel", ".", "id", ")", ":", "'#'", "+", "channel", ".", "name", "for", "channel", "in", "self", ".", "channel_mentions", "}", "men...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.system_content
r"""A property that returns the content that is rendered regardless of the :attr:`Message.type`. In the case of :attr:`MessageType.default`\, this just returns the regular :attr:`Message.content`. Otherwise this returns an English message denoting the contents of the system message.
discord/message.py
def system_content(self): r"""A property that returns the content that is rendered regardless of the :attr:`Message.type`. In the case of :attr:`MessageType.default`\, this just returns the regular :attr:`Message.content`. Otherwise this returns an English message denoting the contents of the system message. """ if self.type is MessageType.default: return self.content if self.type is MessageType.pins_add: return '{0.name} pinned a message to this channel.'.format(self.author) if self.type is MessageType.recipient_add: return '{0.name} added {1.name} to the group.'.format(self.author, self.mentions[0]) if self.type is MessageType.recipient_remove: return '{0.name} removed {1.name} from the group.'.format(self.author, self.mentions[0]) if self.type is MessageType.channel_name_change: return '{0.author.name} changed the channel name: {0.content}'.format(self) if self.type is MessageType.channel_icon_change: return '{0.author.name} changed the channel icon.'.format(self) if self.type is MessageType.new_member: formats = [ "{0} just joined the server - glhf!", "{0} just joined. Everyone, look busy!", "{0} just joined. Can I get a heal?", "{0} joined your party.", "{0} joined. You must construct additional pylons.", "Ermagherd. {0} is here.", "Welcome, {0}. Stay awhile and listen.", "Welcome, {0}. We were expecting you ( ͡° ͜ʖ ͡°)", "Welcome, {0}. We hope you brought pizza.", "Welcome {0}. Leave your weapons by the door.", "A wild {0} appeared.", "Swoooosh. {0} just landed.", "Brace yourselves. {0} just joined the server.", "{0} just joined... or did they?", "{0} just arrived. Seems OP - please nerf.", "{0} just slid into the server.", "A {0} has spawned in the server.", "Big {0} showed up!", "Where’s {0}? In the server!", "{0} hopped into the server. Kangaroo!!", "{0} just showed up. Hold my beer.", "Challenger approaching - {0} has appeared!", "It's a bird! It's a plane! Nevermind, it's just {0}.", "It's {0}! Praise the sun! \\[T]/", "Never gonna give {0} up. Never gonna let {0} down.", "{0} has joined the battle bus.", "Cheers, love! {0}'s here!", "Hey! Listen! {0} has joined!", "We've been expecting you {0}", "It's dangerous to go alone, take {0}!", "{0} has joined the server! It's super effective!", "Cheers, love! {0} is here!", "{0} is here, as the prophecy foretold.", "{0} has arrived. Party's over.", "Ready player {0}", "{0} is here to kick butt and chew bubblegum. And {0} is all out of gum.", "Hello. Is it {0} you're looking for?", "{0} has joined. Stay a while and listen!", "Roses are red, violets are blue, {0} joined this server with you", ] # manually reconstruct the epoch with millisecond precision, because # datetime.datetime.timestamp() doesn't return the exact posix # timestamp with the precision that we need created_at_ms = int((self.created_at - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) return formats[created_at_ms % len(formats)].format(self.author.name) if self.type is MessageType.call: # we're at the call message type now, which is a bit more complicated. # we can make the assumption that Message.channel is a PrivateChannel # with the type ChannelType.group or ChannelType.private call_ended = self.call.ended_timestamp is not None if self.channel.me in self.call.participants: return '{0.author.name} started a call.'.format(self) elif call_ended: return 'You missed a call from {0.author.name}'.format(self) else: return '{0.author.name} started a call \N{EM DASH} Join the call.'.format(self)
def system_content(self): r"""A property that returns the content that is rendered regardless of the :attr:`Message.type`. In the case of :attr:`MessageType.default`\, this just returns the regular :attr:`Message.content`. Otherwise this returns an English message denoting the contents of the system message. """ if self.type is MessageType.default: return self.content if self.type is MessageType.pins_add: return '{0.name} pinned a message to this channel.'.format(self.author) if self.type is MessageType.recipient_add: return '{0.name} added {1.name} to the group.'.format(self.author, self.mentions[0]) if self.type is MessageType.recipient_remove: return '{0.name} removed {1.name} from the group.'.format(self.author, self.mentions[0]) if self.type is MessageType.channel_name_change: return '{0.author.name} changed the channel name: {0.content}'.format(self) if self.type is MessageType.channel_icon_change: return '{0.author.name} changed the channel icon.'.format(self) if self.type is MessageType.new_member: formats = [ "{0} just joined the server - glhf!", "{0} just joined. Everyone, look busy!", "{0} just joined. Can I get a heal?", "{0} joined your party.", "{0} joined. You must construct additional pylons.", "Ermagherd. {0} is here.", "Welcome, {0}. Stay awhile and listen.", "Welcome, {0}. We were expecting you ( ͡° ͜ʖ ͡°)", "Welcome, {0}. We hope you brought pizza.", "Welcome {0}. Leave your weapons by the door.", "A wild {0} appeared.", "Swoooosh. {0} just landed.", "Brace yourselves. {0} just joined the server.", "{0} just joined... or did they?", "{0} just arrived. Seems OP - please nerf.", "{0} just slid into the server.", "A {0} has spawned in the server.", "Big {0} showed up!", "Where’s {0}? In the server!", "{0} hopped into the server. Kangaroo!!", "{0} just showed up. Hold my beer.", "Challenger approaching - {0} has appeared!", "It's a bird! It's a plane! Nevermind, it's just {0}.", "It's {0}! Praise the sun! \\[T]/", "Never gonna give {0} up. Never gonna let {0} down.", "{0} has joined the battle bus.", "Cheers, love! {0}'s here!", "Hey! Listen! {0} has joined!", "We've been expecting you {0}", "It's dangerous to go alone, take {0}!", "{0} has joined the server! It's super effective!", "Cheers, love! {0} is here!", "{0} is here, as the prophecy foretold.", "{0} has arrived. Party's over.", "Ready player {0}", "{0} is here to kick butt and chew bubblegum. And {0} is all out of gum.", "Hello. Is it {0} you're looking for?", "{0} has joined. Stay a while and listen!", "Roses are red, violets are blue, {0} joined this server with you", ] # manually reconstruct the epoch with millisecond precision, because # datetime.datetime.timestamp() doesn't return the exact posix # timestamp with the precision that we need created_at_ms = int((self.created_at - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) return formats[created_at_ms % len(formats)].format(self.author.name) if self.type is MessageType.call: # we're at the call message type now, which is a bit more complicated. # we can make the assumption that Message.channel is a PrivateChannel # with the type ChannelType.group or ChannelType.private call_ended = self.call.ended_timestamp is not None if self.channel.me in self.call.participants: return '{0.author.name} started a call.'.format(self) elif call_ended: return 'You missed a call from {0.author.name}'.format(self) else: return '{0.author.name} started a call \N{EM DASH} Join the call.'.format(self)
[ "r", "A", "property", "that", "returns", "the", "content", "that", "is", "rendered", "regardless", "of", "the", ":", "attr", ":", "Message", ".", "type", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L477-L564
[ "def", "system_content", "(", "self", ")", ":", "if", "self", ".", "type", "is", "MessageType", ".", "default", ":", "return", "self", ".", "content", "if", "self", ".", "type", "is", "MessageType", ".", "pins_add", ":", "return", "'{0.name} pinned a message...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.delete
|coro| Deletes the message. Your own messages could be deleted without any proper permissions. However to delete other people's messages, you need the :attr:`~Permissions.manage_messages` permission. .. versionchanged:: 1.1.0 Added the new ``delay`` keyword-only parameter. Parameters ----------- delay: Optional[:class:`float`] If provided, the number of seconds to wait in the background before deleting the message. Raises ------ Forbidden You do not have proper permissions to delete the message. HTTPException Deleting the message failed.
discord/message.py
async def delete(self, *, delay=None): """|coro| Deletes the message. Your own messages could be deleted without any proper permissions. However to delete other people's messages, you need the :attr:`~Permissions.manage_messages` permission. .. versionchanged:: 1.1.0 Added the new ``delay`` keyword-only parameter. Parameters ----------- delay: Optional[:class:`float`] If provided, the number of seconds to wait in the background before deleting the message. Raises ------ Forbidden You do not have proper permissions to delete the message. HTTPException Deleting the message failed. """ if delay is not None: async def delete(): await asyncio.sleep(delay, loop=self._state.loop) try: await self._state.http.delete_message(self.channel.id, self.id) except HTTPException: pass asyncio.ensure_future(delete(), loop=self._state.loop) else: await self._state.http.delete_message(self.channel.id, self.id)
async def delete(self, *, delay=None): """|coro| Deletes the message. Your own messages could be deleted without any proper permissions. However to delete other people's messages, you need the :attr:`~Permissions.manage_messages` permission. .. versionchanged:: 1.1.0 Added the new ``delay`` keyword-only parameter. Parameters ----------- delay: Optional[:class:`float`] If provided, the number of seconds to wait in the background before deleting the message. Raises ------ Forbidden You do not have proper permissions to delete the message. HTTPException Deleting the message failed. """ if delay is not None: async def delete(): await asyncio.sleep(delay, loop=self._state.loop) try: await self._state.http.delete_message(self.channel.id, self.id) except HTTPException: pass asyncio.ensure_future(delete(), loop=self._state.loop) else: await self._state.http.delete_message(self.channel.id, self.id)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L566-L601
[ "async", "def", "delete", "(", "self", ",", "*", ",", "delay", "=", "None", ")", ":", "if", "delay", "is", "not", "None", ":", "async", "def", "delete", "(", ")", ":", "await", "asyncio", ".", "sleep", "(", "delay", ",", "loop", "=", "self", ".",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.edit
|coro| Edits the message. The content must be able to be transformed into a string via ``str(content)``. Parameters ----------- content: Optional[:class:`str`] The new content to replace the message with. Could be ``None`` to remove the content. embed: Optional[:class:`Embed`] The new embed to replace the original with. Could be ``None`` to remove the embed. delete_after: Optional[:class:`float`] If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored. Raises ------- HTTPException Editing the message failed.
discord/message.py
async def edit(self, **fields): """|coro| Edits the message. The content must be able to be transformed into a string via ``str(content)``. Parameters ----------- content: Optional[:class:`str`] The new content to replace the message with. Could be ``None`` to remove the content. embed: Optional[:class:`Embed`] The new embed to replace the original with. Could be ``None`` to remove the embed. delete_after: Optional[:class:`float`] If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored. Raises ------- HTTPException Editing the message failed. """ try: content = fields['content'] except KeyError: pass else: if content is not None: fields['content'] = str(content) try: embed = fields['embed'] except KeyError: pass else: if embed is not None: fields['embed'] = embed.to_dict() data = await self._state.http.edit_message(self.channel.id, self.id, **fields) self._update(channel=self.channel, data=data) try: delete_after = fields['delete_after'] except KeyError: pass else: if delete_after is not None: await self.delete(delay=delete_after)
async def edit(self, **fields): """|coro| Edits the message. The content must be able to be transformed into a string via ``str(content)``. Parameters ----------- content: Optional[:class:`str`] The new content to replace the message with. Could be ``None`` to remove the content. embed: Optional[:class:`Embed`] The new embed to replace the original with. Could be ``None`` to remove the embed. delete_after: Optional[:class:`float`] If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored. Raises ------- HTTPException Editing the message failed. """ try: content = fields['content'] except KeyError: pass else: if content is not None: fields['content'] = str(content) try: embed = fields['embed'] except KeyError: pass else: if embed is not None: fields['embed'] = embed.to_dict() data = await self._state.http.edit_message(self.channel.id, self.id, **fields) self._update(channel=self.channel, data=data) try: delete_after = fields['delete_after'] except KeyError: pass else: if delete_after is not None: await self.delete(delay=delete_after)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L603-L654
[ "async", "def", "edit", "(", "self", ",", "*", "*", "fields", ")", ":", "try", ":", "content", "=", "fields", "[", "'content'", "]", "except", "KeyError", ":", "pass", "else", ":", "if", "content", "is", "not", "None", ":", "fields", "[", "'content'"...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.pin
|coro| Pins the message. You must have the :attr:`~Permissions.manage_messages` permission to do this in a non-private channel context. Raises ------- Forbidden You do not have permissions to pin the message. NotFound The message or channel was not found or deleted. HTTPException Pinning the message failed, probably due to the channel having more than 50 pinned messages.
discord/message.py
async def pin(self): """|coro| Pins the message. You must have the :attr:`~Permissions.manage_messages` permission to do this in a non-private channel context. Raises ------- Forbidden You do not have permissions to pin the message. NotFound The message or channel was not found or deleted. HTTPException Pinning the message failed, probably due to the channel having more than 50 pinned messages. """ await self._state.http.pin_message(self.channel.id, self.id) self.pinned = True
async def pin(self): """|coro| Pins the message. You must have the :attr:`~Permissions.manage_messages` permission to do this in a non-private channel context. Raises ------- Forbidden You do not have permissions to pin the message. NotFound The message or channel was not found or deleted. HTTPException Pinning the message failed, probably due to the channel having more than 50 pinned messages. """ await self._state.http.pin_message(self.channel.id, self.id) self.pinned = True
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L656-L676
[ "async", "def", "pin", "(", "self", ")", ":", "await", "self", ".", "_state", ".", "http", ".", "pin_message", "(", "self", ".", "channel", ".", "id", ",", "self", ".", "id", ")", "self", ".", "pinned", "=", "True" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.unpin
|coro| Unpins the message. You must have the :attr:`~Permissions.manage_messages` permission to do this in a non-private channel context. Raises ------- Forbidden You do not have permissions to unpin the message. NotFound The message or channel was not found or deleted. HTTPException Unpinning the message failed.
discord/message.py
async def unpin(self): """|coro| Unpins the message. You must have the :attr:`~Permissions.manage_messages` permission to do this in a non-private channel context. Raises ------- Forbidden You do not have permissions to unpin the message. NotFound The message or channel was not found or deleted. HTTPException Unpinning the message failed. """ await self._state.http.unpin_message(self.channel.id, self.id) self.pinned = False
async def unpin(self): """|coro| Unpins the message. You must have the :attr:`~Permissions.manage_messages` permission to do this in a non-private channel context. Raises ------- Forbidden You do not have permissions to unpin the message. NotFound The message or channel was not found or deleted. HTTPException Unpinning the message failed. """ await self._state.http.unpin_message(self.channel.id, self.id) self.pinned = False
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L678-L697
[ "async", "def", "unpin", "(", "self", ")", ":", "await", "self", ".", "_state", ".", "http", ".", "unpin_message", "(", "self", ".", "channel", ".", "id", ",", "self", ".", "id", ")", "self", ".", "pinned", "=", "False" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.add_reaction
|coro| Add a reaction to the message. The emoji may be a unicode emoji or a custom guild :class:`Emoji`. You must have the :attr:`~Permissions.read_message_history` permission to use this. If nobody else has reacted to the message using this emoji, the :attr:`~Permissions.add_reactions` permission is required. Parameters ------------ emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] The emoji to react with. Raises -------- HTTPException Adding the reaction failed. Forbidden You do not have the proper permissions to react to the message. NotFound The emoji you specified was not found. InvalidArgument The emoji parameter is invalid.
discord/message.py
async def add_reaction(self, emoji): """|coro| Add a reaction to the message. The emoji may be a unicode emoji or a custom guild :class:`Emoji`. You must have the :attr:`~Permissions.read_message_history` permission to use this. If nobody else has reacted to the message using this emoji, the :attr:`~Permissions.add_reactions` permission is required. Parameters ------------ emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] The emoji to react with. Raises -------- HTTPException Adding the reaction failed. Forbidden You do not have the proper permissions to react to the message. NotFound The emoji you specified was not found. InvalidArgument The emoji parameter is invalid. """ emoji = self._emoji_reaction(emoji) await self._state.http.add_reaction(self.channel.id, self.id, emoji)
async def add_reaction(self, emoji): """|coro| Add a reaction to the message. The emoji may be a unicode emoji or a custom guild :class:`Emoji`. You must have the :attr:`~Permissions.read_message_history` permission to use this. If nobody else has reacted to the message using this emoji, the :attr:`~Permissions.add_reactions` permission is required. Parameters ------------ emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] The emoji to react with. Raises -------- HTTPException Adding the reaction failed. Forbidden You do not have the proper permissions to react to the message. NotFound The emoji you specified was not found. InvalidArgument The emoji parameter is invalid. """ emoji = self._emoji_reaction(emoji) await self._state.http.add_reaction(self.channel.id, self.id, emoji)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L699-L728
[ "async", "def", "add_reaction", "(", "self", ",", "emoji", ")", ":", "emoji", "=", "self", ".", "_emoji_reaction", "(", "emoji", ")", "await", "self", ".", "_state", ".", "http", ".", "add_reaction", "(", "self", ".", "channel", ".", "id", ",", "self",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.remove_reaction
|coro| Remove a reaction by the member from the message. The emoji may be a unicode emoji or a custom guild :class:`Emoji`. If the reaction is not your own (i.e. ``member`` parameter is not you) then the :attr:`~Permissions.manage_messages` permission is needed. The ``member`` parameter must represent a member and meet the :class:`abc.Snowflake` abc. Parameters ------------ emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] The emoji to remove. member: :class:`abc.Snowflake` The member for which to remove the reaction. Raises -------- HTTPException Removing the reaction failed. Forbidden You do not have the proper permissions to remove the reaction. NotFound The member or emoji you specified was not found. InvalidArgument The emoji parameter is invalid.
discord/message.py
async def remove_reaction(self, emoji, member): """|coro| Remove a reaction by the member from the message. The emoji may be a unicode emoji or a custom guild :class:`Emoji`. If the reaction is not your own (i.e. ``member`` parameter is not you) then the :attr:`~Permissions.manage_messages` permission is needed. The ``member`` parameter must represent a member and meet the :class:`abc.Snowflake` abc. Parameters ------------ emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] The emoji to remove. member: :class:`abc.Snowflake` The member for which to remove the reaction. Raises -------- HTTPException Removing the reaction failed. Forbidden You do not have the proper permissions to remove the reaction. NotFound The member or emoji you specified was not found. InvalidArgument The emoji parameter is invalid. """ emoji = self._emoji_reaction(emoji) if member.id == self._state.self_id: await self._state.http.remove_own_reaction(self.channel.id, self.id, emoji) else: await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)
async def remove_reaction(self, emoji, member): """|coro| Remove a reaction by the member from the message. The emoji may be a unicode emoji or a custom guild :class:`Emoji`. If the reaction is not your own (i.e. ``member`` parameter is not you) then the :attr:`~Permissions.manage_messages` permission is needed. The ``member`` parameter must represent a member and meet the :class:`abc.Snowflake` abc. Parameters ------------ emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] The emoji to remove. member: :class:`abc.Snowflake` The member for which to remove the reaction. Raises -------- HTTPException Removing the reaction failed. Forbidden You do not have the proper permissions to remove the reaction. NotFound The member or emoji you specified was not found. InvalidArgument The emoji parameter is invalid. """ emoji = self._emoji_reaction(emoji) if member.id == self._state.self_id: await self._state.http.remove_own_reaction(self.channel.id, self.id, emoji) else: await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L730-L767
[ "async", "def", "remove_reaction", "(", "self", ",", "emoji", ",", "member", ")", ":", "emoji", "=", "self", ".", "_emoji_reaction", "(", "emoji", ")", "if", "member", ".", "id", "==", "self", ".", "_state", ".", "self_id", ":", "await", "self", ".", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.clear_reactions
|coro| Removes all the reactions from the message. You need the :attr:`~Permissions.manage_messages` permission to use this. Raises -------- HTTPException Removing the reactions failed. Forbidden You do not have the proper permissions to remove all the reactions.
discord/message.py
async def clear_reactions(self): """|coro| Removes all the reactions from the message. You need the :attr:`~Permissions.manage_messages` permission to use this. Raises -------- HTTPException Removing the reactions failed. Forbidden You do not have the proper permissions to remove all the reactions. """ await self._state.http.clear_reactions(self.channel.id, self.id)
async def clear_reactions(self): """|coro| Removes all the reactions from the message. You need the :attr:`~Permissions.manage_messages` permission to use this. Raises -------- HTTPException Removing the reactions failed. Forbidden You do not have the proper permissions to remove all the reactions. """ await self._state.http.clear_reactions(self.channel.id, self.id)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L785-L799
[ "async", "def", "clear_reactions", "(", "self", ")", ":", "await", "self", ".", "_state", ".", "http", ".", "clear_reactions", "(", "self", ".", "channel", ".", "id", ",", "self", ".", "id", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Message.ack
|coro| Marks this message as read. The user must not be a bot user. Raises ------- HTTPException Acking failed. ClientException You must not be a bot user.
discord/message.py
async def ack(self): """|coro| Marks this message as read. The user must not be a bot user. Raises ------- HTTPException Acking failed. ClientException You must not be a bot user. """ state = self._state if state.is_bot: raise ClientException('Must not be a bot account to ack messages.') return await state.http.ack_message(self.channel.id, self.id)
async def ack(self): """|coro| Marks this message as read. The user must not be a bot user. Raises ------- HTTPException Acking failed. ClientException You must not be a bot user. """ state = self._state if state.is_bot: raise ClientException('Must not be a bot account to ack messages.') return await state.http.ack_message(self.channel.id, self.id)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L801-L819
[ "async", "def", "ack", "(", "self", ")", ":", "state", "=", "self", ".", "_state", "if", "state", ".", "is_bot", ":", "raise", "ClientException", "(", "'Must not be a bot account to ack messages.'", ")", "return", "await", "state", ".", "http", ".", "ack_messa...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Activity.large_image_url
Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity if applicable.
discord/activity.py
def large_image_url(self): """Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity if applicable.""" if self.application_id is None: return None try: large_image = self.assets['large_image'] except KeyError: return None else: return 'https://cdn.discordapp.com/app-assets/{0}/{1}.png'.format(self.application_id, large_image)
def large_image_url(self): """Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity if applicable.""" if self.application_id is None: return None try: large_image = self.assets['large_image'] except KeyError: return None else: return 'https://cdn.discordapp.com/app-assets/{0}/{1}.png'.format(self.application_id, large_image)
[ "Optional", "[", ":", "class", ":", "str", "]", ":", "Returns", "a", "URL", "pointing", "to", "the", "large", "image", "asset", "of", "this", "activity", "if", "applicable", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/activity.py#L186-L196
[ "def", "large_image_url", "(", "self", ")", ":", "if", "self", ".", "application_id", "is", "None", ":", "return", "None", "try", ":", "large_image", "=", "self", ".", "assets", "[", "'large_image'", "]", "except", "KeyError", ":", "return", "None", "else"...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Activity.small_image_url
Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable.
discord/activity.py
def small_image_url(self): """Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable.""" if self.application_id is None: return None try: small_image = self.assets['small_image'] except KeyError: return None else: return 'https://cdn.discordapp.com/app-assets/{0}/{1}.png'.format(self.application_id, small_image)
def small_image_url(self): """Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable.""" if self.application_id is None: return None try: small_image = self.assets['small_image'] except KeyError: return None else: return 'https://cdn.discordapp.com/app-assets/{0}/{1}.png'.format(self.application_id, small_image)
[ "Optional", "[", ":", "class", ":", "str", "]", ":", "Returns", "a", "URL", "pointing", "to", "the", "small", "image", "asset", "of", "this", "activity", "if", "applicable", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/activity.py#L199-L209
[ "def", "small_image_url", "(", "self", ")", ":", "if", "self", ".", "application_id", "is", "None", ":", "return", "None", "try", ":", "small_image", "=", "self", ".", "assets", "[", "'small_image'", "]", "except", "KeyError", ":", "return", "None", "else"...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Spotify.album_cover_url
:class:`str`: The album cover image URL from Spotify's CDN.
discord/activity.py
def album_cover_url(self): """:class:`str`: The album cover image URL from Spotify's CDN.""" large_image = self._assets.get('large_image', '') if large_image[:8] != 'spotify:': return '' album_image_id = large_image[8:] return 'https://i.scdn.co/image/' + album_image_id
def album_cover_url(self): """:class:`str`: The album cover image URL from Spotify's CDN.""" large_image = self._assets.get('large_image', '') if large_image[:8] != 'spotify:': return '' album_image_id = large_image[8:] return 'https://i.scdn.co/image/' + album_image_id
[ ":", "class", ":", "str", ":", "The", "album", "cover", "image", "URL", "from", "Spotify", "s", "CDN", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/activity.py#L539-L545
[ "def", "album_cover_url", "(", "self", ")", ":", "large_image", "=", "self", ".", "_assets", ".", "get", "(", "'large_image'", ",", "''", ")", "if", "large_image", "[", ":", "8", "]", "!=", "'spotify:'", ":", "return", "''", "album_image_id", "=", "large...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
when_mentioned_or
A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. Example -------- .. code-block:: python3 bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) .. note:: This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example: .. code-block:: python3 async def get_prefix(bot, message): extras = await prefixes_for(message.guild) # returns a list return commands.when_mentioned_or(*extras)(bot, message) See Also ---------- :func:`.when_mentioned`
discord/ext/commands/bot.py
def when_mentioned_or(*prefixes): """A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. Example -------- .. code-block:: python3 bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) .. note:: This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example: .. code-block:: python3 async def get_prefix(bot, message): extras = await prefixes_for(message.guild) # returns a list return commands.when_mentioned_or(*extras)(bot, message) See Also ---------- :func:`.when_mentioned` """ def inner(bot, msg): r = list(prefixes) r = when_mentioned(bot, msg) + r return r return inner
def when_mentioned_or(*prefixes): """A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. Example -------- .. code-block:: python3 bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) .. note:: This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example: .. code-block:: python3 async def get_prefix(bot, message): extras = await prefixes_for(message.guild) # returns a list return commands.when_mentioned_or(*extras)(bot, message) See Also ---------- :func:`.when_mentioned` """ def inner(bot, msg): r = list(prefixes) r = when_mentioned(bot, msg) + r return r return inner
[ "A", "callable", "that", "implements", "when", "mentioned", "or", "other", "prefixes", "provided", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L52-L86
[ "def", "when_mentioned_or", "(", "*", "prefixes", ")", ":", "def", "inner", "(", "bot", ",", "msg", ")", ":", "r", "=", "list", "(", "prefixes", ")", "r", "=", "when_mentioned", "(", "bot", ",", "msg", ")", "+", "r", "return", "r", "return", "inner...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.on_command_error
|coro| The default command error handler provided by the bot. By default this prints to ``sys.stderr`` however it could be overridden to have a different implementation. This only fires if you do not specify any listeners for command error.
discord/ext/commands/bot.py
async def on_command_error(self, context, exception): """|coro| The default command error handler provided by the bot. By default this prints to ``sys.stderr`` however it could be overridden to have a different implementation. This only fires if you do not specify any listeners for command error. """ if self.extra_events.get('on_command_error', None): return if hasattr(context.command, 'on_error'): return cog = context.cog if cog: if Cog._get_overridden_method(cog.cog_command_error) is not None: return print('Ignoring exception in command {}:'.format(context.command), file=sys.stderr) traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)
async def on_command_error(self, context, exception): """|coro| The default command error handler provided by the bot. By default this prints to ``sys.stderr`` however it could be overridden to have a different implementation. This only fires if you do not specify any listeners for command error. """ if self.extra_events.get('on_command_error', None): return if hasattr(context.command, 'on_error'): return cog = context.cog if cog: if Cog._get_overridden_method(cog.cog_command_error) is not None: return print('Ignoring exception in command {}:'.format(context.command), file=sys.stderr) traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L146-L168
[ "async", "def", "on_command_error", "(", "self", ",", "context", ",", "exception", ")", ":", "if", "self", ".", "extra_events", ".", "get", "(", "'on_command_error'", ",", "None", ")", ":", "return", "if", "hasattr", "(", "context", ".", "command", ",", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.add_check
Adds a global check to the bot. This is the non-decorator interface to :meth:`.check` and :meth:`.check_once`. Parameters ----------- func The function that was used as a global check. call_once: :class:`bool` If the function should only be called once per :meth:`.Command.invoke` call.
discord/ext/commands/bot.py
def add_check(self, func, *, call_once=False): """Adds a global check to the bot. This is the non-decorator interface to :meth:`.check` and :meth:`.check_once`. Parameters ----------- func The function that was used as a global check. call_once: :class:`bool` If the function should only be called once per :meth:`.Command.invoke` call. """ if call_once: self._check_once.append(func) else: self._checks.append(func)
def add_check(self, func, *, call_once=False): """Adds a global check to the bot. This is the non-decorator interface to :meth:`.check` and :meth:`.check_once`. Parameters ----------- func The function that was used as a global check. call_once: :class:`bool` If the function should only be called once per :meth:`.Command.invoke` call. """ if call_once: self._check_once.append(func) else: self._checks.append(func)
[ "Adds", "a", "global", "check", "to", "the", "bot", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L200-L218
[ "def", "add_check", "(", "self", ",", "func", ",", "*", ",", "call_once", "=", "False", ")", ":", "if", "call_once", ":", "self", ".", "_check_once", ".", "append", "(", "func", ")", "else", ":", "self", ".", "_checks", ".", "append", "(", "func", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.remove_check
Removes a global check from the bot. This function is idempotent and will not raise an exception if the function is not in the global checks. Parameters ----------- func The function to remove from the global checks. call_once: :class:`bool` If the function was added with ``call_once=True`` in the :meth:`.Bot.add_check` call or using :meth:`.check_once`.
discord/ext/commands/bot.py
def remove_check(self, func, *, call_once=False): """Removes a global check from the bot. This function is idempotent and will not raise an exception if the function is not in the global checks. Parameters ----------- func The function to remove from the global checks. call_once: :class:`bool` If the function was added with ``call_once=True`` in the :meth:`.Bot.add_check` call or using :meth:`.check_once`. """ l = self._check_once if call_once else self._checks try: l.remove(func) except ValueError: pass
def remove_check(self, func, *, call_once=False): """Removes a global check from the bot. This function is idempotent and will not raise an exception if the function is not in the global checks. Parameters ----------- func The function to remove from the global checks. call_once: :class:`bool` If the function was added with ``call_once=True`` in the :meth:`.Bot.add_check` call or using :meth:`.check_once`. """ l = self._check_once if call_once else self._checks try: l.remove(func) except ValueError: pass
[ "Removes", "a", "global", "check", "from", "the", "bot", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L220-L239
[ "def", "remove_check", "(", "self", ",", "func", ",", "*", ",", "call_once", "=", "False", ")", ":", "l", "=", "self", ".", "_check_once", "if", "call_once", "else", "self", ".", "_checks", "try", ":", "l", ".", "remove", "(", "func", ")", "except", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.is_owner
Checks if a :class:`~discord.User` or :class:`~discord.Member` is the owner of this bot. If an :attr:`owner_id` is not set, it is fetched automatically through the use of :meth:`~.Bot.application_info`. Parameters ----------- user: :class:`.abc.User` The user to check for.
discord/ext/commands/bot.py
async def is_owner(self, user): """Checks if a :class:`~discord.User` or :class:`~discord.Member` is the owner of this bot. If an :attr:`owner_id` is not set, it is fetched automatically through the use of :meth:`~.Bot.application_info`. Parameters ----------- user: :class:`.abc.User` The user to check for. """ if self.owner_id is None: app = await self.application_info() self.owner_id = owner_id = app.owner.id return user.id == owner_id return user.id == self.owner_id
async def is_owner(self, user): """Checks if a :class:`~discord.User` or :class:`~discord.Member` is the owner of this bot. If an :attr:`owner_id` is not set, it is fetched automatically through the use of :meth:`~.Bot.application_info`. Parameters ----------- user: :class:`.abc.User` The user to check for. """ if self.owner_id is None: app = await self.application_info() self.owner_id = owner_id = app.owner.id return user.id == owner_id return user.id == self.owner_id
[ "Checks", "if", "a", ":", "class", ":", "~discord", ".", "User", "or", ":", "class", ":", "~discord", ".", "Member", "is", "the", "owner", "of", "this", "bot", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L281-L298
[ "async", "def", "is_owner", "(", "self", ",", "user", ")", ":", "if", "self", ".", "owner_id", "is", "None", ":", "app", "=", "await", "self", ".", "application_info", "(", ")", "self", ".", "owner_id", "=", "owner_id", "=", "app", ".", "owner", ".",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.add_listener
The non decorator alternative to :meth:`.listen`. Parameters ----------- func: :ref:`coroutine <coroutine>` The function to call. name: Optional[:class:`str`] The name of the event to listen for. Defaults to ``func.__name__``. Example -------- .. code-block:: python3 async def on_ready(): pass async def my_message(message): pass bot.add_listener(on_ready) bot.add_listener(my_message, 'on_message')
discord/ext/commands/bot.py
def add_listener(self, func, name=None): """The non decorator alternative to :meth:`.listen`. Parameters ----------- func: :ref:`coroutine <coroutine>` The function to call. name: Optional[:class:`str`] The name of the event to listen for. Defaults to ``func.__name__``. Example -------- .. code-block:: python3 async def on_ready(): pass async def my_message(message): pass bot.add_listener(on_ready) bot.add_listener(my_message, 'on_message') """ name = func.__name__ if name is None else name if not asyncio.iscoroutinefunction(func): raise TypeError('Listeners must be coroutines') if name in self.extra_events: self.extra_events[name].append(func) else: self.extra_events[name] = [func]
def add_listener(self, func, name=None): """The non decorator alternative to :meth:`.listen`. Parameters ----------- func: :ref:`coroutine <coroutine>` The function to call. name: Optional[:class:`str`] The name of the event to listen for. Defaults to ``func.__name__``. Example -------- .. code-block:: python3 async def on_ready(): pass async def my_message(message): pass bot.add_listener(on_ready) bot.add_listener(my_message, 'on_message') """ name = func.__name__ if name is None else name if not asyncio.iscoroutinefunction(func): raise TypeError('Listeners must be coroutines') if name in self.extra_events: self.extra_events[name].append(func) else: self.extra_events[name] = [func]
[ "The", "non", "decorator", "alternative", "to", ":", "meth", ":", ".", "listen", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L367-L397
[ "def", "add_listener", "(", "self", ",", "func", ",", "name", "=", "None", ")", ":", "name", "=", "func", ".", "__name__", "if", "name", "is", "None", "else", "name", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "func", ")", ":", "raise", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.remove_listener
Removes a listener from the pool of listeners. Parameters ----------- func The function that was used as a listener to remove. name: :class:`str` The name of the event we want to remove. Defaults to ``func.__name__``.
discord/ext/commands/bot.py
def remove_listener(self, func, name=None): """Removes a listener from the pool of listeners. Parameters ----------- func The function that was used as a listener to remove. name: :class:`str` The name of the event we want to remove. Defaults to ``func.__name__``. """ name = func.__name__ if name is None else name if name in self.extra_events: try: self.extra_events[name].remove(func) except ValueError: pass
def remove_listener(self, func, name=None): """Removes a listener from the pool of listeners. Parameters ----------- func The function that was used as a listener to remove. name: :class:`str` The name of the event we want to remove. Defaults to ``func.__name__``. """ name = func.__name__ if name is None else name if name in self.extra_events: try: self.extra_events[name].remove(func) except ValueError: pass
[ "Removes", "a", "listener", "from", "the", "pool", "of", "listeners", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L399-L417
[ "def", "remove_listener", "(", "self", ",", "func", ",", "name", "=", "None", ")", ":", "name", "=", "func", ".", "__name__", "if", "name", "is", "None", "else", "name", "if", "name", "in", "self", ".", "extra_events", ":", "try", ":", "self", ".", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.listen
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as :func:`.on_ready` The functions being listened to must be a coroutine. Example -------- .. code-block:: python3 @bot.listen() async def on_message(message): print('one') # in some other file... @bot.listen('on_message') async def my_message(message): print('two') Would print one and two in an unspecified order. Raises ------- TypeError The function being listened to is not a coroutine.
discord/ext/commands/bot.py
def listen(self, name=None): """A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as :func:`.on_ready` The functions being listened to must be a coroutine. Example -------- .. code-block:: python3 @bot.listen() async def on_message(message): print('one') # in some other file... @bot.listen('on_message') async def my_message(message): print('two') Would print one and two in an unspecified order. Raises ------- TypeError The function being listened to is not a coroutine. """ def decorator(func): self.add_listener(func, name) return func return decorator
def listen(self, name=None): """A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as :func:`.on_ready` The functions being listened to must be a coroutine. Example -------- .. code-block:: python3 @bot.listen() async def on_message(message): print('one') # in some other file... @bot.listen('on_message') async def my_message(message): print('two') Would print one and two in an unspecified order. Raises ------- TypeError The function being listened to is not a coroutine. """ def decorator(func): self.add_listener(func, name) return func return decorator
[ "A", "decorator", "that", "registers", "another", "function", "as", "an", "external", "event", "listener", ".", "Basically", "this", "allows", "you", "to", "listen", "to", "multiple", "events", "from", "different", "places", "e", ".", "g", ".", "such", "as",...
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L419-L453
[ "def", "listen", "(", "self", ",", "name", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "self", ".", "add_listener", "(", "func", ",", "name", ")", "return", "func", "return", "decorator" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.add_cog
Adds a "cog" to the bot. A cog is a class that has its own event listeners and commands. Parameters ----------- cog: :class:`.Cog` The cog to register to the bot. Raises ------- TypeError The cog does not inherit from :class:`.Cog`. CommandError An error happened during loading.
discord/ext/commands/bot.py
def add_cog(self, cog): """Adds a "cog" to the bot. A cog is a class that has its own event listeners and commands. Parameters ----------- cog: :class:`.Cog` The cog to register to the bot. Raises ------- TypeError The cog does not inherit from :class:`.Cog`. CommandError An error happened during loading. """ if not isinstance(cog, Cog): raise TypeError('cogs must derive from Cog') cog = cog._inject(self) self.__cogs[cog.__cog_name__] = cog
def add_cog(self, cog): """Adds a "cog" to the bot. A cog is a class that has its own event listeners and commands. Parameters ----------- cog: :class:`.Cog` The cog to register to the bot. Raises ------- TypeError The cog does not inherit from :class:`.Cog`. CommandError An error happened during loading. """ if not isinstance(cog, Cog): raise TypeError('cogs must derive from Cog') cog = cog._inject(self) self.__cogs[cog.__cog_name__] = cog
[ "Adds", "a", "cog", "to", "the", "bot", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L457-L479
[ "def", "add_cog", "(", "self", ",", "cog", ")", ":", "if", "not", "isinstance", "(", "cog", ",", "Cog", ")", ":", "raise", "TypeError", "(", "'cogs must derive from Cog'", ")", "cog", "=", "cog", ".", "_inject", "(", "self", ")", "self", ".", "__cogs",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.remove_cog
Removes a cog from the bot. All registered commands and event listeners that the cog has registered will be removed as well. If no cog is found then this method has no effect. Parameters ----------- name: :class:`str` The name of the cog to remove.
discord/ext/commands/bot.py
def remove_cog(self, name): """Removes a cog from the bot. All registered commands and event listeners that the cog has registered will be removed as well. If no cog is found then this method has no effect. Parameters ----------- name: :class:`str` The name of the cog to remove. """ cog = self.__cogs.pop(name, None) if cog is None: return help_command = self._help_command if help_command and help_command.cog is cog: help_command.cog = None cog._eject(self)
def remove_cog(self, name): """Removes a cog from the bot. All registered commands and event listeners that the cog has registered will be removed as well. If no cog is found then this method has no effect. Parameters ----------- name: :class:`str` The name of the cog to remove. """ cog = self.__cogs.pop(name, None) if cog is None: return help_command = self._help_command if help_command and help_command.cog is cog: help_command.cog = None cog._eject(self)
[ "Removes", "a", "cog", "from", "the", "bot", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L495-L516
[ "def", "remove_cog", "(", "self", ",", "name", ")", ":", "cog", "=", "self", ".", "__cogs", ".", "pop", "(", "name", ",", "None", ")", "if", "cog", "is", "None", ":", "return", "help_command", "=", "self", ".", "_help_command", "if", "help_command", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.load_extension
Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, ``setup`` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the ``bot``. Parameters ------------ name: :class:`str` The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises -------- ExtensionNotFound The extension could not be imported. ExtensionAlreadyLoaded The extension is already loaded. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error.
discord/ext/commands/bot.py
def load_extension(self, name): """Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, ``setup`` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the ``bot``. Parameters ------------ name: :class:`str` The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises -------- ExtensionNotFound The extension could not be imported. ExtensionAlreadyLoaded The extension is already loaded. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error. """ if name in self.__extensions: raise errors.ExtensionAlreadyLoaded(name) try: lib = importlib.import_module(name) except ImportError as e: raise errors.ExtensionNotFound(name, e) from e else: self._load_from_module_spec(lib, name)
def load_extension(self, name): """Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, ``setup`` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the ``bot``. Parameters ------------ name: :class:`str` The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises -------- ExtensionNotFound The extension could not be imported. ExtensionAlreadyLoaded The extension is already loaded. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error. """ if name in self.__extensions: raise errors.ExtensionAlreadyLoaded(name) try: lib = importlib.import_module(name) except ImportError as e: raise errors.ExtensionNotFound(name, e) from e else: self._load_from_module_spec(lib, name)
[ "Loads", "an", "extension", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L584-L621
[ "def", "load_extension", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "__extensions", ":", "raise", "errors", ".", "ExtensionAlreadyLoaded", "(", "name", ")", "try", ":", "lib", "=", "importlib", ".", "import_module", "(", "name", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.unload_extension
Unloads an extension. When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported. The extension can provide an optional global function, ``teardown``, to do miscellaneous clean-up if necessary. This function takes a single parameter, the ``bot``, similar to ``setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded.
discord/ext/commands/bot.py
def unload_extension(self, name): """Unloads an extension. When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported. The extension can provide an optional global function, ``teardown``, to do miscellaneous clean-up if necessary. This function takes a single parameter, the ``bot``, similar to ``setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. """ lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name)
def unload_extension(self, name): """Unloads an extension. When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported. The extension can provide an optional global function, ``teardown``, to do miscellaneous clean-up if necessary. This function takes a single parameter, the ``bot``, similar to ``setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. """ lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name)
[ "Unloads", "an", "extension", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L623-L652
[ "def", "unload_extension", "(", "self", ",", "name", ")", ":", "lib", "=", "self", ".", "__extensions", ".", "get", "(", "name", ")", "if", "lib", "is", "None", ":", "raise", "errors", ".", "ExtensionNotLoaded", "(", "name", ")", "self", ".", "_remove_...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.reload_extension
Atomically reloads an extension. This replaces the extension with the same extension, only refreshed. This is equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension` except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state. Parameters ------------ name: :class:`str` The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. ExtensionNotFound The extension could not be imported. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error.
discord/ext/commands/bot.py
def reload_extension(self, name): """Atomically reloads an extension. This replaces the extension with the same extension, only refreshed. This is equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension` except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state. Parameters ------------ name: :class:`str` The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. ExtensionNotFound The extension could not be imported. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error. """ lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) # get the previous module states from sys modules modules = { name: module for name, module in sys.modules.items() if _is_submodule(lib.__name__, name) } try: # Unload and then load the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name) except Exception as e: # if the load failed, the remnants should have been # cleaned from the load_extension function call # so let's load it from our old compiled library. self._load_from_module_spec(lib, name) # revert sys.modules back to normal and raise back to caller sys.modules.update(modules) raise
def reload_extension(self, name): """Atomically reloads an extension. This replaces the extension with the same extension, only refreshed. This is equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension` except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state. Parameters ------------ name: :class:`str` The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. ExtensionNotFound The extension could not be imported. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error. """ lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) # get the previous module states from sys modules modules = { name: module for name, module in sys.modules.items() if _is_submodule(lib.__name__, name) } try: # Unload and then load the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name) except Exception as e: # if the load failed, the remnants should have been # cleaned from the load_extension function call # so let's load it from our old compiled library. self._load_from_module_spec(lib, name) # revert sys.modules back to normal and raise back to caller sys.modules.update(modules) raise
[ "Atomically", "reloads", "an", "extension", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L654-L705
[ "def", "reload_extension", "(", "self", ",", "name", ")", ":", "lib", "=", "self", ".", "__extensions", ".", "get", "(", "name", ")", "if", "lib", "is", "None", ":", "raise", "errors", ".", "ExtensionNotLoaded", "(", "name", ")", "# get the previous module...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.get_prefix
|coro| Retrieves the prefix the bot is listening to with the message as a context. Parameters ----------- message: :class:`discord.Message` The message context to get the prefix of. Returns -------- Union[List[:class:`str`], :class:`str`] A list of prefixes or a single prefix that the bot is listening for.
discord/ext/commands/bot.py
async def get_prefix(self, message): """|coro| Retrieves the prefix the bot is listening to with the message as a context. Parameters ----------- message: :class:`discord.Message` The message context to get the prefix of. Returns -------- Union[List[:class:`str`], :class:`str`] A list of prefixes or a single prefix that the bot is listening for. """ prefix = ret = self.command_prefix if callable(prefix): ret = await discord.utils.maybe_coroutine(prefix, self, message) if not isinstance(ret, str): try: ret = list(ret) except TypeError: # It's possible that a generator raised this exception. Don't # replace it with our own error if that's the case. if isinstance(ret, collections.Iterable): raise raise TypeError("command_prefix must be plain string, iterable of strings, or callable " "returning either of these, not {}".format(ret.__class__.__name__)) if not ret: raise ValueError("Iterable command_prefix must contain at least one prefix") return ret
async def get_prefix(self, message): """|coro| Retrieves the prefix the bot is listening to with the message as a context. Parameters ----------- message: :class:`discord.Message` The message context to get the prefix of. Returns -------- Union[List[:class:`str`], :class:`str`] A list of prefixes or a single prefix that the bot is listening for. """ prefix = ret = self.command_prefix if callable(prefix): ret = await discord.utils.maybe_coroutine(prefix, self, message) if not isinstance(ret, str): try: ret = list(ret) except TypeError: # It's possible that a generator raised this exception. Don't # replace it with our own error if that's the case. if isinstance(ret, collections.Iterable): raise raise TypeError("command_prefix must be plain string, iterable of strings, or callable " "returning either of these, not {}".format(ret.__class__.__name__)) if not ret: raise ValueError("Iterable command_prefix must contain at least one prefix") return ret
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L735-L771
[ "async", "def", "get_prefix", "(", "self", ",", "message", ")", ":", "prefix", "=", "ret", "=", "self", ".", "command_prefix", "if", "callable", "(", "prefix", ")", ":", "ret", "=", "await", "discord", ".", "utils", ".", "maybe_coroutine", "(", "prefix",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.get_context
r"""|coro| Returns the invocation context from the message. This is a more low-level counter-part for :meth:`.process_commands` to allow users more fine grained control over the processing. The returned context is not guaranteed to be a valid invocation context, :attr:`.Context.valid` must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under :meth:`~.Bot.invoke`. Parameters ----------- message: :class:`discord.Message` The message to get the invocation context from. cls The factory class that will be used to create the context. By default, this is :class:`.Context`. Should a custom class be provided, it must be similar enough to :class:`.Context`\'s interface. Returns -------- :class:`.Context` The invocation context. The type of this can change via the ``cls`` parameter.
discord/ext/commands/bot.py
async def get_context(self, message, *, cls=Context): r"""|coro| Returns the invocation context from the message. This is a more low-level counter-part for :meth:`.process_commands` to allow users more fine grained control over the processing. The returned context is not guaranteed to be a valid invocation context, :attr:`.Context.valid` must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under :meth:`~.Bot.invoke`. Parameters ----------- message: :class:`discord.Message` The message to get the invocation context from. cls The factory class that will be used to create the context. By default, this is :class:`.Context`. Should a custom class be provided, it must be similar enough to :class:`.Context`\'s interface. Returns -------- :class:`.Context` The invocation context. The type of this can change via the ``cls`` parameter. """ view = StringView(message.content) ctx = cls(prefix=None, view=view, bot=self, message=message) if self._skip_check(message.author.id, self.user.id): return ctx prefix = await self.get_prefix(message) invoked_prefix = prefix if isinstance(prefix, str): if not view.skip_string(prefix): return ctx else: try: # if the context class' __init__ consumes something from the view this # will be wrong. That seems unreasonable though. if message.content.startswith(tuple(prefix)): invoked_prefix = discord.utils.find(view.skip_string, prefix) else: return ctx except TypeError: if not isinstance(prefix, list): raise TypeError("get_prefix must return either a string or a list of string, " "not {}".format(prefix.__class__.__name__)) # It's possible a bad command_prefix got us here. for value in prefix: if not isinstance(value, str): raise TypeError("Iterable command_prefix or list returned from get_prefix must " "contain only strings, not {}".format(value.__class__.__name__)) # Getting here shouldn't happen raise invoker = view.get_word() ctx.invoked_with = invoker ctx.prefix = invoked_prefix ctx.command = self.all_commands.get(invoker) return ctx
async def get_context(self, message, *, cls=Context): r"""|coro| Returns the invocation context from the message. This is a more low-level counter-part for :meth:`.process_commands` to allow users more fine grained control over the processing. The returned context is not guaranteed to be a valid invocation context, :attr:`.Context.valid` must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under :meth:`~.Bot.invoke`. Parameters ----------- message: :class:`discord.Message` The message to get the invocation context from. cls The factory class that will be used to create the context. By default, this is :class:`.Context`. Should a custom class be provided, it must be similar enough to :class:`.Context`\'s interface. Returns -------- :class:`.Context` The invocation context. The type of this can change via the ``cls`` parameter. """ view = StringView(message.content) ctx = cls(prefix=None, view=view, bot=self, message=message) if self._skip_check(message.author.id, self.user.id): return ctx prefix = await self.get_prefix(message) invoked_prefix = prefix if isinstance(prefix, str): if not view.skip_string(prefix): return ctx else: try: # if the context class' __init__ consumes something from the view this # will be wrong. That seems unreasonable though. if message.content.startswith(tuple(prefix)): invoked_prefix = discord.utils.find(view.skip_string, prefix) else: return ctx except TypeError: if not isinstance(prefix, list): raise TypeError("get_prefix must return either a string or a list of string, " "not {}".format(prefix.__class__.__name__)) # It's possible a bad command_prefix got us here. for value in prefix: if not isinstance(value, str): raise TypeError("Iterable command_prefix or list returned from get_prefix must " "contain only strings, not {}".format(value.__class__.__name__)) # Getting here shouldn't happen raise invoker = view.get_word() ctx.invoked_with = invoker ctx.prefix = invoked_prefix ctx.command = self.all_commands.get(invoker) return ctx
[ "r", "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L773-L842
[ "async", "def", "get_context", "(", "self", ",", "message", ",", "*", ",", "cls", "=", "Context", ")", ":", "view", "=", "StringView", "(", "message", ".", "content", ")", "ctx", "=", "cls", "(", "prefix", "=", "None", ",", "view", "=", "view", ","...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.invoke
|coro| Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms. Parameters ----------- ctx: :class:`.Context` The invocation context to invoke.
discord/ext/commands/bot.py
async def invoke(self, ctx): """|coro| Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms. Parameters ----------- ctx: :class:`.Context` The invocation context to invoke. """ if ctx.command is not None: self.dispatch('command', ctx) try: if await self.can_run(ctx, call_once=True): await ctx.command.invoke(ctx) except errors.CommandError as exc: await ctx.command.dispatch_error(ctx, exc) else: self.dispatch('command_completion', ctx) elif ctx.invoked_with: exc = errors.CommandNotFound('Command "{}" is not found'.format(ctx.invoked_with)) self.dispatch('command_error', ctx, exc)
async def invoke(self, ctx): """|coro| Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms. Parameters ----------- ctx: :class:`.Context` The invocation context to invoke. """ if ctx.command is not None: self.dispatch('command', ctx) try: if await self.can_run(ctx, call_once=True): await ctx.command.invoke(ctx) except errors.CommandError as exc: await ctx.command.dispatch_error(ctx, exc) else: self.dispatch('command_completion', ctx) elif ctx.invoked_with: exc = errors.CommandNotFound('Command "{}" is not found'.format(ctx.invoked_with)) self.dispatch('command_error', ctx, exc)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L844-L866
[ "async", "def", "invoke", "(", "self", ",", "ctx", ")", ":", "if", "ctx", ".", "command", "is", "not", "None", ":", "self", ".", "dispatch", "(", "'command'", ",", "ctx", ")", "try", ":", "if", "await", "self", ".", "can_run", "(", "ctx", ",", "c...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
BotBase.process_commands
|coro| This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered. By default, this coroutine is called inside the :func:`.on_message` event. If you choose to override the :func:`.on_message` event, then you should invoke this coroutine as well. This is built using other low level tools, and is equivalent to a call to :meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`. This also checks if the message's author is a bot and doesn't call :meth:`~.Bot.get_context` or :meth:`~.Bot.invoke` if so. Parameters ----------- message: :class:`discord.Message` The message to process commands for.
discord/ext/commands/bot.py
async def process_commands(self, message): """|coro| This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered. By default, this coroutine is called inside the :func:`.on_message` event. If you choose to override the :func:`.on_message` event, then you should invoke this coroutine as well. This is built using other low level tools, and is equivalent to a call to :meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`. This also checks if the message's author is a bot and doesn't call :meth:`~.Bot.get_context` or :meth:`~.Bot.invoke` if so. Parameters ----------- message: :class:`discord.Message` The message to process commands for. """ if message.author.bot: return ctx = await self.get_context(message) await self.invoke(ctx)
async def process_commands(self, message): """|coro| This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered. By default, this coroutine is called inside the :func:`.on_message` event. If you choose to override the :func:`.on_message` event, then you should invoke this coroutine as well. This is built using other low level tools, and is equivalent to a call to :meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`. This also checks if the message's author is a bot and doesn't call :meth:`~.Bot.get_context` or :meth:`~.Bot.invoke` if so. Parameters ----------- message: :class:`discord.Message` The message to process commands for. """ if message.author.bot: return ctx = await self.get_context(message) await self.invoke(ctx)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L868-L894
[ "async", "def", "process_commands", "(", "self", ",", "message", ")", ":", "if", "message", ".", "author", ".", "bot", ":", "return", "ctx", "=", "await", "self", ".", "get_context", "(", "message", ")", "await", "self", ".", "invoke", "(", "ctx", ")" ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.large
:class:`bool`: Indicates if the guild is a 'large' guild. A large guild is defined as having more than ``large_threshold`` count members, which for this library is set to the maximum of 250.
discord/guild.py
def large(self): """:class:`bool`: Indicates if the guild is a 'large' guild. A large guild is defined as having more than ``large_threshold`` count members, which for this library is set to the maximum of 250. """ if self._large is None: try: return self._member_count >= 250 except AttributeError: return len(self._members) >= 250 return self._large
def large(self): """:class:`bool`: Indicates if the guild is a 'large' guild. A large guild is defined as having more than ``large_threshold`` count members, which for this library is set to the maximum of 250. """ if self._large is None: try: return self._member_count >= 250 except AttributeError: return len(self._members) >= 250 return self._large
[ ":", "class", ":", "bool", ":", "Indicates", "if", "the", "guild", "is", "a", "large", "guild", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L287-L298
[ "def", "large", "(", "self", ")", ":", "if", "self", ".", "_large", "is", "None", ":", "try", ":", "return", "self", ".", "_member_count", ">=", "250", "except", "AttributeError", ":", "return", "len", "(", "self", ".", "_members", ")", ">=", "250", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.voice_channels
List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom.
discord/guild.py
def voice_channels(self): """List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, VoiceChannel)] r.sort(key=lambda c: (c.position, c.id)) return r
def voice_channels(self): """List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, VoiceChannel)] r.sort(key=lambda c: (c.position, c.id)) return r
[ "List", "[", ":", "class", ":", "VoiceChannel", "]", ":", "A", "list", "of", "voice", "channels", "that", "belongs", "to", "this", "guild", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L301-L308
[ "def", "voice_channels", "(", "self", ")", ":", "r", "=", "[", "ch", "for", "ch", "in", "self", ".", "_channels", ".", "values", "(", ")", "if", "isinstance", "(", "ch", ",", "VoiceChannel", ")", "]", "r", ".", "sort", "(", "key", "=", "lambda", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.me
Similar to :attr:`Client.user` except an instance of :class:`Member`. This is essentially used to get the member version of yourself.
discord/guild.py
def me(self): """Similar to :attr:`Client.user` except an instance of :class:`Member`. This is essentially used to get the member version of yourself. """ self_id = self._state.user.id return self.get_member(self_id)
def me(self): """Similar to :attr:`Client.user` except an instance of :class:`Member`. This is essentially used to get the member version of yourself. """ self_id = self._state.user.id return self.get_member(self_id)
[ "Similar", "to", ":", "attr", ":", "Client", ".", "user", "except", "an", "instance", "of", ":", "class", ":", "Member", ".", "This", "is", "essentially", "used", "to", "get", "the", "member", "version", "of", "yourself", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L311-L316
[ "def", "me", "(", "self", ")", ":", "self_id", "=", "self", ".", "_state", ".", "user", ".", "id", "return", "self", ".", "get_member", "(", "self_id", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.text_channels
List[:class:`TextChannel`]: A list of text channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom.
discord/guild.py
def text_channels(self): """List[:class:`TextChannel`]: A list of text channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, TextChannel)] r.sort(key=lambda c: (c.position, c.id)) return r
def text_channels(self): """List[:class:`TextChannel`]: A list of text channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, TextChannel)] r.sort(key=lambda c: (c.position, c.id)) return r
[ "List", "[", ":", "class", ":", "TextChannel", "]", ":", "A", "list", "of", "text", "channels", "that", "belongs", "to", "this", "guild", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L324-L331
[ "def", "text_channels", "(", "self", ")", ":", "r", "=", "[", "ch", "for", "ch", "in", "self", ".", "_channels", ".", "values", "(", ")", "if", "isinstance", "(", "ch", ",", "TextChannel", ")", "]", "r", ".", "sort", "(", "key", "=", "lambda", "c...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.categories
List[:class:`CategoryChannel`]: A list of categories that belongs to this guild. This is sorted by the position and are in UI order from top to bottom.
discord/guild.py
def categories(self): """List[:class:`CategoryChannel`]: A list of categories that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, CategoryChannel)] r.sort(key=lambda c: (c.position, c.id)) return r
def categories(self): """List[:class:`CategoryChannel`]: A list of categories that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, CategoryChannel)] r.sort(key=lambda c: (c.position, c.id)) return r
[ "List", "[", ":", "class", ":", "CategoryChannel", "]", ":", "A", "list", "of", "categories", "that", "belongs", "to", "this", "guild", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L334-L341
[ "def", "categories", "(", "self", ")", ":", "r", "=", "[", "ch", "for", "ch", "in", "self", ".", "_channels", ".", "values", "(", ")", "if", "isinstance", "(", "ch", ",", "CategoryChannel", ")", "]", "r", ".", "sort", "(", "key", "=", "lambda", "...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.by_category
Returns every :class:`CategoryChannel` and their associated channels. These channels and categories are sorted in the official Discord UI order. If the channels do not have a category, then the first element of the tuple is ``None``. Returns -------- List[Tuple[Optional[:class:`CategoryChannel`], List[:class:`abc.GuildChannel`]]]: The categories and their associated channels.
discord/guild.py
def by_category(self): """Returns every :class:`CategoryChannel` and their associated channels. These channels and categories are sorted in the official Discord UI order. If the channels do not have a category, then the first element of the tuple is ``None``. Returns -------- List[Tuple[Optional[:class:`CategoryChannel`], List[:class:`abc.GuildChannel`]]]: The categories and their associated channels. """ grouped = defaultdict(list) for channel in self._channels.values(): if isinstance(channel, CategoryChannel): continue grouped[channel.category_id].append(channel) def key(t): k, v = t return ((k.position, k.id) if k else (-1, -1), v) _get = self._channels.get as_list = [(_get(k), v) for k, v in grouped.items()] as_list.sort(key=key) for _, channels in as_list: channels.sort(key=lambda c: (c._sorting_bucket, c.position, c.id)) return as_list
def by_category(self): """Returns every :class:`CategoryChannel` and their associated channels. These channels and categories are sorted in the official Discord UI order. If the channels do not have a category, then the first element of the tuple is ``None``. Returns -------- List[Tuple[Optional[:class:`CategoryChannel`], List[:class:`abc.GuildChannel`]]]: The categories and their associated channels. """ grouped = defaultdict(list) for channel in self._channels.values(): if isinstance(channel, CategoryChannel): continue grouped[channel.category_id].append(channel) def key(t): k, v = t return ((k.position, k.id) if k else (-1, -1), v) _get = self._channels.get as_list = [(_get(k), v) for k, v in grouped.items()] as_list.sort(key=key) for _, channels in as_list: channels.sort(key=lambda c: (c._sorting_bucket, c.position, c.id)) return as_list
[ "Returns", "every", ":", "class", ":", "CategoryChannel", "and", "their", "associated", "channels", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L343-L372
[ "def", "by_category", "(", "self", ")", ":", "grouped", "=", "defaultdict", "(", "list", ")", "for", "channel", "in", "self", ".", "_channels", ".", "values", "(", ")", ":", "if", "isinstance", "(", "channel", ",", "CategoryChannel", ")", ":", "continue"...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.system_channel
Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages. Currently this is only for new member joins. If no channel is set, then this returns ``None``.
discord/guild.py
def system_channel(self): """Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages. Currently this is only for new member joins. If no channel is set, then this returns ``None``. """ channel_id = self._system_channel_id return channel_id and self._channels.get(channel_id)
def system_channel(self): """Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages. Currently this is only for new member joins. If no channel is set, then this returns ``None``. """ channel_id = self._system_channel_id return channel_id and self._channels.get(channel_id)
[ "Optional", "[", ":", "class", ":", "TextChannel", "]", ":", "Returns", "the", "guild", "s", "channel", "used", "for", "system", "messages", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L379-L385
[ "def", "system_channel", "(", "self", ")", ":", "channel_id", "=", "self", ".", "_system_channel_id", "return", "channel_id", "and", "self", ".", "_channels", ".", "get", "(", "channel_id", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.default_role
Gets the @everyone role that all members have by default.
discord/guild.py
def default_role(self): """Gets the @everyone role that all members have by default.""" return utils.find(lambda r: r.is_default(), self._roles.values())
def default_role(self): """Gets the @everyone role that all members have by default.""" return utils.find(lambda r: r.is_default(), self._roles.values())
[ "Gets", "the" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L410-L412
[ "def", "default_role", "(", "self", ")", ":", "return", "utils", ".", "find", "(", "lambda", "r", ":", "r", ".", "is_default", "(", ")", ",", "self", ".", "_roles", ".", "values", "(", ")", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.chunked
Returns a boolean indicating if the guild is "chunked". A chunked guild means that :attr:`member_count` is equal to the number of members stored in the internal :attr:`members` cache. If this value returns ``False``, then you should request for offline members.
discord/guild.py
def chunked(self): """Returns a boolean indicating if the guild is "chunked". A chunked guild means that :attr:`member_count` is equal to the number of members stored in the internal :attr:`members` cache. If this value returns ``False``, then you should request for offline members. """ count = getattr(self, '_member_count', None) if count is None: return False return count == len(self._members)
def chunked(self): """Returns a boolean indicating if the guild is "chunked". A chunked guild means that :attr:`member_count` is equal to the number of members stored in the internal :attr:`members` cache. If this value returns ``False``, then you should request for offline members. """ count = getattr(self, '_member_count', None) if count is None: return False return count == len(self._members)
[ "Returns", "a", "boolean", "indicating", "if", "the", "guild", "is", "chunked", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L515-L527
[ "def", "chunked", "(", "self", ")", ":", "count", "=", "getattr", "(", "self", ",", "'_member_count'", ",", "None", ")", "if", "count", "is", "None", ":", "return", "False", "return", "count", "==", "len", "(", "self", ".", "_members", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.shard_id
Returns the shard ID for this guild if applicable.
discord/guild.py
def shard_id(self): """Returns the shard ID for this guild if applicable.""" count = self._state.shard_count if count is None: return None return (self.id >> 22) % count
def shard_id(self): """Returns the shard ID for this guild if applicable.""" count = self._state.shard_count if count is None: return None return (self.id >> 22) % count
[ "Returns", "the", "shard", "ID", "for", "this", "guild", "if", "applicable", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L530-L535
[ "def", "shard_id", "(", "self", ")", ":", "count", "=", "self", ".", "_state", ".", "shard_count", "if", "count", "is", "None", ":", "return", "None", "return", "(", "self", ".", "id", ">>", "22", ")", "%", "count" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.get_member_named
Returns the first member found that matches the name provided. The name can have an optional discriminator argument, e.g. "Jake#0001" or "Jake" will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work. If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique. If no member is found, ``None`` is returned. Parameters ----------- name: :class:`str` The name of the member to lookup with an optional discriminator. Returns -------- :class:`Member` The member in this guild with the associated name. If not found then ``None`` is returned.
discord/guild.py
def get_member_named(self, name): """Returns the first member found that matches the name provided. The name can have an optional discriminator argument, e.g. "Jake#0001" or "Jake" will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work. If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique. If no member is found, ``None`` is returned. Parameters ----------- name: :class:`str` The name of the member to lookup with an optional discriminator. Returns -------- :class:`Member` The member in this guild with the associated name. If not found then ``None`` is returned. """ result = None members = self.members if len(name) > 5 and name[-5] == '#': # The 5 length is checking to see if #0000 is in the string, # as a#0000 has a length of 6, the minimum for a potential # discriminator lookup. potential_discriminator = name[-4:] # do the actual lookup and return if found # if it isn't found then we'll do a full name lookup below. result = utils.get(members, name=name[:-5], discriminator=potential_discriminator) if result is not None: return result def pred(m): return m.nick == name or m.name == name return utils.find(pred, members)
def get_member_named(self, name): """Returns the first member found that matches the name provided. The name can have an optional discriminator argument, e.g. "Jake#0001" or "Jake" will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work. If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique. If no member is found, ``None`` is returned. Parameters ----------- name: :class:`str` The name of the member to lookup with an optional discriminator. Returns -------- :class:`Member` The member in this guild with the associated name. If not found then ``None`` is returned. """ result = None members = self.members if len(name) > 5 and name[-5] == '#': # The 5 length is checking to see if #0000 is in the string, # as a#0000 has a length of 6, the minimum for a potential # discriminator lookup. potential_discriminator = name[-4:] # do the actual lookup and return if found # if it isn't found then we'll do a full name lookup below. result = utils.get(members, name=name[:-5], discriminator=potential_discriminator) if result is not None: return result def pred(m): return m.nick == name or m.name == name return utils.find(pred, members)
[ "Returns", "the", "first", "member", "found", "that", "matches", "the", "name", "provided", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L542-L586
[ "def", "get_member_named", "(", "self", ",", "name", ")", ":", "result", "=", "None", "members", "=", "self", ".", "members", "if", "len", "(", "name", ")", ">", "5", "and", "name", "[", "-", "5", "]", "==", "'#'", ":", "# The 5 length is checking to s...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.create_text_channel
|coro| Creates a :class:`TextChannel` for the guild. Note that you need the :attr:`~Permissions.manage_channels` permission to create the channel. The ``overwrites`` parameter can be used to create a 'secret' channel upon creation. This parameter expects a :class:`dict` of overwrites with the target (either a :class:`Member` or a :class:`Role`) as the key and a :class:`PermissionOverwrite` as the value. .. note:: Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to :meth:`~TextChannel.edit` will be required to update the position of the channel in the channel list. Examples ---------- Creating a basic channel: .. code-block:: python3 channel = await guild.create_text_channel('cool-channel') Creating a "secret" channel: .. code-block:: python3 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) Parameters ----------- name: :class:`str` The channel's name. overwrites A :class:`dict` of target (either a role or a member) to :class:`PermissionOverwrite` to apply upon creation of a channel. Useful for creating secret channels. category: Optional[:class:`CategoryChannel`] The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided. position: :class:`int` The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. topic: Optional[:class:`str`] The new channel's topic. slowmode_delay: :class:`int` Specifies the slowmode rate limit for user in this channel. The maximum value possible is `120`. nsfw: :class:`bool` To mark the channel as NSFW or not. reason: Optional[:class:`str`] The reason for creating this channel. Shows up on the audit log. Raises ------- Forbidden You do not have the proper permissions to create this channel. HTTPException Creating the channel failed. InvalidArgument The permission overwrite information is not in proper form. Returns ------- :class:`TextChannel` The channel that was just created.
discord/guild.py
async def create_text_channel(self, name, *, overwrites=None, category=None, reason=None, **options): """|coro| Creates a :class:`TextChannel` for the guild. Note that you need the :attr:`~Permissions.manage_channels` permission to create the channel. The ``overwrites`` parameter can be used to create a 'secret' channel upon creation. This parameter expects a :class:`dict` of overwrites with the target (either a :class:`Member` or a :class:`Role`) as the key and a :class:`PermissionOverwrite` as the value. .. note:: Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to :meth:`~TextChannel.edit` will be required to update the position of the channel in the channel list. Examples ---------- Creating a basic channel: .. code-block:: python3 channel = await guild.create_text_channel('cool-channel') Creating a "secret" channel: .. code-block:: python3 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) Parameters ----------- name: :class:`str` The channel's name. overwrites A :class:`dict` of target (either a role or a member) to :class:`PermissionOverwrite` to apply upon creation of a channel. Useful for creating secret channels. category: Optional[:class:`CategoryChannel`] The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided. position: :class:`int` The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. topic: Optional[:class:`str`] The new channel's topic. slowmode_delay: :class:`int` Specifies the slowmode rate limit for user in this channel. The maximum value possible is `120`. nsfw: :class:`bool` To mark the channel as NSFW or not. reason: Optional[:class:`str`] The reason for creating this channel. Shows up on the audit log. Raises ------- Forbidden You do not have the proper permissions to create this channel. HTTPException Creating the channel failed. InvalidArgument The permission overwrite information is not in proper form. Returns ------- :class:`TextChannel` The channel that was just created. """ data = await self._create_channel(name, overwrites, ChannelType.text, category, reason=reason, **options) channel = TextChannel(state=self._state, guild=self, data=data) # temporarily add to the cache self._channels[channel.id] = channel return channel
async def create_text_channel(self, name, *, overwrites=None, category=None, reason=None, **options): """|coro| Creates a :class:`TextChannel` for the guild. Note that you need the :attr:`~Permissions.manage_channels` permission to create the channel. The ``overwrites`` parameter can be used to create a 'secret' channel upon creation. This parameter expects a :class:`dict` of overwrites with the target (either a :class:`Member` or a :class:`Role`) as the key and a :class:`PermissionOverwrite` as the value. .. note:: Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to :meth:`~TextChannel.edit` will be required to update the position of the channel in the channel list. Examples ---------- Creating a basic channel: .. code-block:: python3 channel = await guild.create_text_channel('cool-channel') Creating a "secret" channel: .. code-block:: python3 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) Parameters ----------- name: :class:`str` The channel's name. overwrites A :class:`dict` of target (either a role or a member) to :class:`PermissionOverwrite` to apply upon creation of a channel. Useful for creating secret channels. category: Optional[:class:`CategoryChannel`] The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided. position: :class:`int` The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. topic: Optional[:class:`str`] The new channel's topic. slowmode_delay: :class:`int` Specifies the slowmode rate limit for user in this channel. The maximum value possible is `120`. nsfw: :class:`bool` To mark the channel as NSFW or not. reason: Optional[:class:`str`] The reason for creating this channel. Shows up on the audit log. Raises ------- Forbidden You do not have the proper permissions to create this channel. HTTPException Creating the channel failed. InvalidArgument The permission overwrite information is not in proper form. Returns ------- :class:`TextChannel` The channel that was just created. """ data = await self._create_channel(name, overwrites, ChannelType.text, category, reason=reason, **options) channel = TextChannel(state=self._state, guild=self, data=data) # temporarily add to the cache self._channels[channel.id] = channel return channel
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L622-L705
[ "async", "def", "create_text_channel", "(", "self", ",", "name", ",", "*", ",", "overwrites", "=", "None", ",", "category", "=", "None", ",", "reason", "=", "None", ",", "*", "*", "options", ")", ":", "data", "=", "await", "self", ".", "_create_channel...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.create_voice_channel
|coro| This is similar to :meth:`create_text_channel` except makes a :class:`VoiceChannel` instead, in addition to having the following new parameters. Parameters ----------- bitrate: :class:`int` The channel's preferred audio bitrate in bits per second. user_limit: :class:`int` The channel's limit for number of members that can be in a voice channel.
discord/guild.py
async def create_voice_channel(self, name, *, overwrites=None, category=None, reason=None, **options): """|coro| This is similar to :meth:`create_text_channel` except makes a :class:`VoiceChannel` instead, in addition to having the following new parameters. Parameters ----------- bitrate: :class:`int` The channel's preferred audio bitrate in bits per second. user_limit: :class:`int` The channel's limit for number of members that can be in a voice channel. """ data = await self._create_channel(name, overwrites, ChannelType.voice, category, reason=reason, **options) channel = VoiceChannel(state=self._state, guild=self, data=data) # temporarily add to the cache self._channels[channel.id] = channel return channel
async def create_voice_channel(self, name, *, overwrites=None, category=None, reason=None, **options): """|coro| This is similar to :meth:`create_text_channel` except makes a :class:`VoiceChannel` instead, in addition to having the following new parameters. Parameters ----------- bitrate: :class:`int` The channel's preferred audio bitrate in bits per second. user_limit: :class:`int` The channel's limit for number of members that can be in a voice channel. """ data = await self._create_channel(name, overwrites, ChannelType.voice, category, reason=reason, **options) channel = VoiceChannel(state=self._state, guild=self, data=data) # temporarily add to the cache self._channels[channel.id] = channel return channel
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L707-L725
[ "async", "def", "create_voice_channel", "(", "self", ",", "name", ",", "*", ",", "overwrites", "=", "None", ",", "category", "=", "None", ",", "reason", "=", "None", ",", "*", "*", "options", ")", ":", "data", "=", "await", "self", ".", "_create_channe...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.create_category
|coro| Same as :meth:`create_text_channel` except makes a :class:`CategoryChannel` instead. .. note:: The ``category`` parameter is not supported in this function since categories cannot have categories.
discord/guild.py
async def create_category(self, name, *, overwrites=None, reason=None): """|coro| Same as :meth:`create_text_channel` except makes a :class:`CategoryChannel` instead. .. note:: The ``category`` parameter is not supported in this function since categories cannot have categories. """ data = await self._create_channel(name, overwrites, ChannelType.category, reason=reason) channel = CategoryChannel(state=self._state, guild=self, data=data) # temporarily add to the cache self._channels[channel.id] = channel return channel
async def create_category(self, name, *, overwrites=None, reason=None): """|coro| Same as :meth:`create_text_channel` except makes a :class:`CategoryChannel` instead. .. note:: The ``category`` parameter is not supported in this function since categories cannot have categories. """ data = await self._create_channel(name, overwrites, ChannelType.category, reason=reason) channel = CategoryChannel(state=self._state, guild=self, data=data) # temporarily add to the cache self._channels[channel.id] = channel return channel
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L727-L742
[ "async", "def", "create_category", "(", "self", ",", "name", ",", "*", ",", "overwrites", "=", "None", ",", "reason", "=", "None", ")", ":", "data", "=", "await", "self", ".", "_create_channel", "(", "name", ",", "overwrites", ",", "ChannelType", ".", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.edit
|coro| Edits the guild. You must have the :attr:`~Permissions.manage_guild` permission to edit the guild. Parameters ---------- name: :class:`str` The new name of the guild. description: :class:`str` The new description of the guild. This is only available to guilds that contain `VERIFIED` in :attr:`Guild.features`. icon: :class:`bytes` A :term:`py:bytes-like object` representing the icon. Only PNG/JPEG supported. Could be ``None`` to denote removal of the icon. banner: :class:`bytes` A :term:`py:bytes-like object` representing the banner. Could be ``None`` to denote removal of the banner. splash: :class:`bytes` A :term:`py:bytes-like object` representing the invite splash. Only PNG/JPEG supported. Could be ``None`` to denote removing the splash. Only available for partnered guilds with ``INVITE_SPLASH`` feature. region: :class:`VoiceRegion` The new region for the guild's voice communication. afk_channel: Optional[:class:`VoiceChannel`] The new channel that is the AFK channel. Could be ``None`` for no AFK channel. afk_timeout: :class:`int` The number of seconds until someone is moved to the AFK channel. owner: :class:`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: :class:`VerificationLevel` The new verification level for the guild. default_notifications: :class:`NotificationLevel` The new default notification level for the guild. explicit_content_filter: :class:`ContentFilter` The new explicit content filter for the guild. vanity_code: :class:`str` The new vanity code for the guild. system_channel: Optional[:class:`TextChannel`] The new channel that is used for the system channel. Could be ``None`` for no system channel. reason: Optional[:class:`str`] The reason for editing this guild. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to edit the guild. HTTPException Editing the guild failed. InvalidArgument The image format passed in to ``icon`` is invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.
discord/guild.py
async def edit(self, *, reason=None, **fields): """|coro| Edits the guild. You must have the :attr:`~Permissions.manage_guild` permission to edit the guild. Parameters ---------- name: :class:`str` The new name of the guild. description: :class:`str` The new description of the guild. This is only available to guilds that contain `VERIFIED` in :attr:`Guild.features`. icon: :class:`bytes` A :term:`py:bytes-like object` representing the icon. Only PNG/JPEG supported. Could be ``None`` to denote removal of the icon. banner: :class:`bytes` A :term:`py:bytes-like object` representing the banner. Could be ``None`` to denote removal of the banner. splash: :class:`bytes` A :term:`py:bytes-like object` representing the invite splash. Only PNG/JPEG supported. Could be ``None`` to denote removing the splash. Only available for partnered guilds with ``INVITE_SPLASH`` feature. region: :class:`VoiceRegion` The new region for the guild's voice communication. afk_channel: Optional[:class:`VoiceChannel`] The new channel that is the AFK channel. Could be ``None`` for no AFK channel. afk_timeout: :class:`int` The number of seconds until someone is moved to the AFK channel. owner: :class:`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: :class:`VerificationLevel` The new verification level for the guild. default_notifications: :class:`NotificationLevel` The new default notification level for the guild. explicit_content_filter: :class:`ContentFilter` The new explicit content filter for the guild. vanity_code: :class:`str` The new vanity code for the guild. system_channel: Optional[:class:`TextChannel`] The new channel that is used for the system channel. Could be ``None`` for no system channel. reason: Optional[:class:`str`] The reason for editing this guild. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to edit the guild. HTTPException Editing the guild failed. InvalidArgument The image format passed in to ``icon`` is invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer. """ http = self._state.http try: icon_bytes = fields['icon'] except KeyError: icon = self.icon else: if icon_bytes is not None: icon = utils._bytes_to_base64_data(icon_bytes) else: icon = None try: banner_bytes = fields['banner'] except KeyError: banner = self.banner else: if banner_bytes is not None: banner = utils._bytes_to_base64_data(banner_bytes) else: banner = None try: vanity_code = fields['vanity_code'] except KeyError: pass else: await http.change_vanity_code(self.id, vanity_code, reason=reason) try: splash_bytes = fields['splash'] except KeyError: splash = self.splash else: if splash_bytes is not None: splash = utils._bytes_to_base64_data(splash_bytes) else: splash = None fields['icon'] = icon fields['banner'] = banner fields['splash'] = splash try: default_message_notifications = int(fields.pop('default_notifications')) except (TypeError, KeyError): pass else: fields['default_message_notifications'] = default_message_notifications try: afk_channel = fields.pop('afk_channel') except KeyError: pass else: if afk_channel is None: fields['afk_channel_id'] = afk_channel else: fields['afk_channel_id'] = afk_channel.id try: system_channel = fields.pop('system_channel') except KeyError: pass else: if system_channel is None: fields['system_channel_id'] = system_channel else: fields['system_channel_id'] = system_channel.id if 'owner' in fields: if self.owner != self.me: raise InvalidArgument('To transfer ownership you must be the owner of the guild.') fields['owner_id'] = fields['owner'].id if 'region' in fields: fields['region'] = str(fields['region']) level = fields.get('verification_level', self.verification_level) if not isinstance(level, VerificationLevel): raise InvalidArgument('verification_level field must be of type VerificationLevel') fields['verification_level'] = level.value explicit_content_filter = fields.get('explicit_content_filter', self.explicit_content_filter) if not isinstance(explicit_content_filter, ContentFilter): raise InvalidArgument('explicit_content_filter field must be of type ContentFilter') fields['explicit_content_filter'] = explicit_content_filter.value await http.edit_guild(self.id, reason=reason, **fields)
async def edit(self, *, reason=None, **fields): """|coro| Edits the guild. You must have the :attr:`~Permissions.manage_guild` permission to edit the guild. Parameters ---------- name: :class:`str` The new name of the guild. description: :class:`str` The new description of the guild. This is only available to guilds that contain `VERIFIED` in :attr:`Guild.features`. icon: :class:`bytes` A :term:`py:bytes-like object` representing the icon. Only PNG/JPEG supported. Could be ``None`` to denote removal of the icon. banner: :class:`bytes` A :term:`py:bytes-like object` representing the banner. Could be ``None`` to denote removal of the banner. splash: :class:`bytes` A :term:`py:bytes-like object` representing the invite splash. Only PNG/JPEG supported. Could be ``None`` to denote removing the splash. Only available for partnered guilds with ``INVITE_SPLASH`` feature. region: :class:`VoiceRegion` The new region for the guild's voice communication. afk_channel: Optional[:class:`VoiceChannel`] The new channel that is the AFK channel. Could be ``None`` for no AFK channel. afk_timeout: :class:`int` The number of seconds until someone is moved to the AFK channel. owner: :class:`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: :class:`VerificationLevel` The new verification level for the guild. default_notifications: :class:`NotificationLevel` The new default notification level for the guild. explicit_content_filter: :class:`ContentFilter` The new explicit content filter for the guild. vanity_code: :class:`str` The new vanity code for the guild. system_channel: Optional[:class:`TextChannel`] The new channel that is used for the system channel. Could be ``None`` for no system channel. reason: Optional[:class:`str`] The reason for editing this guild. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to edit the guild. HTTPException Editing the guild failed. InvalidArgument The image format passed in to ``icon`` is invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer. """ http = self._state.http try: icon_bytes = fields['icon'] except KeyError: icon = self.icon else: if icon_bytes is not None: icon = utils._bytes_to_base64_data(icon_bytes) else: icon = None try: banner_bytes = fields['banner'] except KeyError: banner = self.banner else: if banner_bytes is not None: banner = utils._bytes_to_base64_data(banner_bytes) else: banner = None try: vanity_code = fields['vanity_code'] except KeyError: pass else: await http.change_vanity_code(self.id, vanity_code, reason=reason) try: splash_bytes = fields['splash'] except KeyError: splash = self.splash else: if splash_bytes is not None: splash = utils._bytes_to_base64_data(splash_bytes) else: splash = None fields['icon'] = icon fields['banner'] = banner fields['splash'] = splash try: default_message_notifications = int(fields.pop('default_notifications')) except (TypeError, KeyError): pass else: fields['default_message_notifications'] = default_message_notifications try: afk_channel = fields.pop('afk_channel') except KeyError: pass else: if afk_channel is None: fields['afk_channel_id'] = afk_channel else: fields['afk_channel_id'] = afk_channel.id try: system_channel = fields.pop('system_channel') except KeyError: pass else: if system_channel is None: fields['system_channel_id'] = system_channel else: fields['system_channel_id'] = system_channel.id if 'owner' in fields: if self.owner != self.me: raise InvalidArgument('To transfer ownership you must be the owner of the guild.') fields['owner_id'] = fields['owner'].id if 'region' in fields: fields['region'] = str(fields['region']) level = fields.get('verification_level', self.verification_level) if not isinstance(level, VerificationLevel): raise InvalidArgument('verification_level field must be of type VerificationLevel') fields['verification_level'] = level.value explicit_content_filter = fields.get('explicit_content_filter', self.explicit_content_filter) if not isinstance(explicit_content_filter, ContentFilter): raise InvalidArgument('explicit_content_filter field must be of type ContentFilter') fields['explicit_content_filter'] = explicit_content_filter.value await http.edit_guild(self.id, reason=reason, **fields)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L779-L928
[ "async", "def", "edit", "(", "self", ",", "*", ",", "reason", "=", "None", ",", "*", "*", "fields", ")", ":", "http", "=", "self", ".", "_state", ".", "http", "try", ":", "icon_bytes", "=", "fields", "[", "'icon'", "]", "except", "KeyError", ":", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.fetch_member
|coro| Retreives a :class:`Member` from a guild ID, and a member ID. .. note:: This method is an API call. For general usage, consider :meth:`get_member` instead. Parameters ----------- member_id: :class:`int` The member's ID to fetch from. Raises ------- Forbidden You do not have access to the guild. HTTPException Getting the guild failed. Returns -------- :class:`Member` The member from the member ID.
discord/guild.py
async def fetch_member(self, member_id): """|coro| Retreives a :class:`Member` from a guild ID, and a member ID. .. note:: This method is an API call. For general usage, consider :meth:`get_member` instead. Parameters ----------- member_id: :class:`int` The member's ID to fetch from. Raises ------- Forbidden You do not have access to the guild. HTTPException Getting the guild failed. Returns -------- :class:`Member` The member from the member ID. """ data = await self._state.http.get_member(self.id, member_id) return Member(data=data, state=self._state, guild=self)
async def fetch_member(self, member_id): """|coro| Retreives a :class:`Member` from a guild ID, and a member ID. .. note:: This method is an API call. For general usage, consider :meth:`get_member` instead. Parameters ----------- member_id: :class:`int` The member's ID to fetch from. Raises ------- Forbidden You do not have access to the guild. HTTPException Getting the guild failed. Returns -------- :class:`Member` The member from the member ID. """ data = await self._state.http.get_member(self.id, member_id) return Member(data=data, state=self._state, guild=self)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L930-L957
[ "async", "def", "fetch_member", "(", "self", ",", "member_id", ")", ":", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "get_member", "(", "self", ".", "id", ",", "member_id", ")", "return", "Member", "(", "data", "=", "data", ",", "s...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.fetch_ban
|coro| Retrieves the :class:`BanEntry` for a user, which is a namedtuple with a ``user`` and ``reason`` field. See :meth:`bans` for more information. You must have the :attr:`~Permissions.ban_members` permission to get this information. Parameters ----------- user: :class:`abc.Snowflake` The user to get ban information from. Raises ------ Forbidden You do not have proper permissions to get the information. NotFound This user is not banned. HTTPException An error occurred while fetching the information. Returns ------- BanEntry The BanEntry object for the specified user.
discord/guild.py
async def fetch_ban(self, user): """|coro| Retrieves the :class:`BanEntry` for a user, which is a namedtuple with a ``user`` and ``reason`` field. See :meth:`bans` for more information. You must have the :attr:`~Permissions.ban_members` permission to get this information. Parameters ----------- user: :class:`abc.Snowflake` The user to get ban information from. Raises ------ Forbidden You do not have proper permissions to get the information. NotFound This user is not banned. HTTPException An error occurred while fetching the information. Returns ------- BanEntry The BanEntry object for the specified user. """ data = await self._state.http.get_ban(user.id, self.id) return BanEntry( user=User(state=self._state, data=data['user']), reason=data['reason'] )
async def fetch_ban(self, user): """|coro| Retrieves the :class:`BanEntry` for a user, which is a namedtuple with a ``user`` and ``reason`` field. See :meth:`bans` for more information. You must have the :attr:`~Permissions.ban_members` permission to get this information. Parameters ----------- user: :class:`abc.Snowflake` The user to get ban information from. Raises ------ Forbidden You do not have proper permissions to get the information. NotFound This user is not banned. HTTPException An error occurred while fetching the information. Returns ------- BanEntry The BanEntry object for the specified user. """ data = await self._state.http.get_ban(user.id, self.id) return BanEntry( user=User(state=self._state, data=data['user']), reason=data['reason'] )
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L959-L992
[ "async", "def", "fetch_ban", "(", "self", ",", "user", ")", ":", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "get_ban", "(", "user", ".", "id", ",", "self", ".", "id", ")", "return", "BanEntry", "(", "user", "=", "User", "(", "...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.bans
|coro| Retrieves all the users that are banned from the guild. This coroutine returns a :class:`list` of BanEntry objects, which is a namedtuple with a ``user`` field to denote the :class:`User` that got banned along with a ``reason`` field specifying why the user was banned that could be set to ``None``. You must have the :attr:`~Permissions.ban_members` permission to get this information. Raises ------- Forbidden You do not have proper permissions to get the information. HTTPException An error occurred while fetching the information. Returns -------- List[BanEntry] A list of BanEntry objects.
discord/guild.py
async def bans(self): """|coro| Retrieves all the users that are banned from the guild. This coroutine returns a :class:`list` of BanEntry objects, which is a namedtuple with a ``user`` field to denote the :class:`User` that got banned along with a ``reason`` field specifying why the user was banned that could be set to ``None``. You must have the :attr:`~Permissions.ban_members` permission to get this information. Raises ------- Forbidden You do not have proper permissions to get the information. HTTPException An error occurred while fetching the information. Returns -------- List[BanEntry] A list of BanEntry objects. """ data = await self._state.http.get_bans(self.id) return [BanEntry(user=User(state=self._state, data=e['user']), reason=e['reason']) for e in data]
async def bans(self): """|coro| Retrieves all the users that are banned from the guild. This coroutine returns a :class:`list` of BanEntry objects, which is a namedtuple with a ``user`` field to denote the :class:`User` that got banned along with a ``reason`` field specifying why the user was banned that could be set to ``None``. You must have the :attr:`~Permissions.ban_members` permission to get this information. Raises ------- Forbidden You do not have proper permissions to get the information. HTTPException An error occurred while fetching the information. Returns -------- List[BanEntry] A list of BanEntry objects. """ data = await self._state.http.get_bans(self.id) return [BanEntry(user=User(state=self._state, data=e['user']), reason=e['reason']) for e in data]
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L994-L1023
[ "async", "def", "bans", "(", "self", ")", ":", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "get_bans", "(", "self", ".", "id", ")", "return", "[", "BanEntry", "(", "user", "=", "User", "(", "state", "=", "self", ".", "_state", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.prune_members
r"""|coro| Prunes the guild from its inactive members. The inactive members are denoted if they have not logged on in ``days`` number of days and they have no roles. You must have the :attr:`~Permissions.kick_members` permission to use this. To check how many members you would prune without actually pruning, see the :meth:`estimate_pruned_members` function. Parameters ----------- days: :class:`int` The number of days before counting as inactive. reason: Optional[:class:`str`] The reason for doing this action. Shows up on the audit log. compute_prune_count: :class:`bool` Whether to compute the prune count. This defaults to ``True`` which makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this to ``False``. If this is set to ``False``\, then this function will always return ``None``. Raises ------- Forbidden You do not have permissions to prune members. HTTPException An error occurred while pruning members. InvalidArgument An integer was not passed for ``days``. Returns --------- Optional[:class:`int`] The number of members pruned. If ``compute_prune_count`` is ``False`` then this returns ``None``.
discord/guild.py
async def prune_members(self, *, days, compute_prune_count=True, reason=None): r"""|coro| Prunes the guild from its inactive members. The inactive members are denoted if they have not logged on in ``days`` number of days and they have no roles. You must have the :attr:`~Permissions.kick_members` permission to use this. To check how many members you would prune without actually pruning, see the :meth:`estimate_pruned_members` function. Parameters ----------- days: :class:`int` The number of days before counting as inactive. reason: Optional[:class:`str`] The reason for doing this action. Shows up on the audit log. compute_prune_count: :class:`bool` Whether to compute the prune count. This defaults to ``True`` which makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this to ``False``. If this is set to ``False``\, then this function will always return ``None``. Raises ------- Forbidden You do not have permissions to prune members. HTTPException An error occurred while pruning members. InvalidArgument An integer was not passed for ``days``. Returns --------- Optional[:class:`int`] The number of members pruned. If ``compute_prune_count`` is ``False`` then this returns ``None``. """ if not isinstance(days, int): raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days)) data = await self._state.http.prune_members(self.id, days, compute_prune_count=compute_prune_count, reason=reason) return data['pruned']
async def prune_members(self, *, days, compute_prune_count=True, reason=None): r"""|coro| Prunes the guild from its inactive members. The inactive members are denoted if they have not logged on in ``days`` number of days and they have no roles. You must have the :attr:`~Permissions.kick_members` permission to use this. To check how many members you would prune without actually pruning, see the :meth:`estimate_pruned_members` function. Parameters ----------- days: :class:`int` The number of days before counting as inactive. reason: Optional[:class:`str`] The reason for doing this action. Shows up on the audit log. compute_prune_count: :class:`bool` Whether to compute the prune count. This defaults to ``True`` which makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this to ``False``. If this is set to ``False``\, then this function will always return ``None``. Raises ------- Forbidden You do not have permissions to prune members. HTTPException An error occurred while pruning members. InvalidArgument An integer was not passed for ``days``. Returns --------- Optional[:class:`int`] The number of members pruned. If ``compute_prune_count`` is ``False`` then this returns ``None``. """ if not isinstance(days, int): raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days)) data = await self._state.http.prune_members(self.id, days, compute_prune_count=compute_prune_count, reason=reason) return data['pruned']
[ "r", "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1025-L1071
[ "async", "def", "prune_members", "(", "self", ",", "*", ",", "days", ",", "compute_prune_count", "=", "True", ",", "reason", "=", "None", ")", ":", "if", "not", "isinstance", "(", "days", ",", "int", ")", ":", "raise", "InvalidArgument", "(", "'Expected ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.estimate_pruned_members
|coro| Similar to :meth:`prune_members` except instead of actually pruning members, it returns how many members it would prune from the guild had it been called. Parameters ----------- days: :class:`int` The number of days before counting as inactive. Raises ------- Forbidden You do not have permissions to prune members. HTTPException An error occurred while fetching the prune members estimate. InvalidArgument An integer was not passed for ``days``. Returns --------- :class:`int` The number of members estimated to be pruned.
discord/guild.py
async def estimate_pruned_members(self, *, days): """|coro| Similar to :meth:`prune_members` except instead of actually pruning members, it returns how many members it would prune from the guild had it been called. Parameters ----------- days: :class:`int` The number of days before counting as inactive. Raises ------- Forbidden You do not have permissions to prune members. HTTPException An error occurred while fetching the prune members estimate. InvalidArgument An integer was not passed for ``days``. Returns --------- :class:`int` The number of members estimated to be pruned. """ if not isinstance(days, int): raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days)) data = await self._state.http.estimate_pruned_members(self.id, days) return data['pruned']
async def estimate_pruned_members(self, *, days): """|coro| Similar to :meth:`prune_members` except instead of actually pruning members, it returns how many members it would prune from the guild had it been called. Parameters ----------- days: :class:`int` The number of days before counting as inactive. Raises ------- Forbidden You do not have permissions to prune members. HTTPException An error occurred while fetching the prune members estimate. InvalidArgument An integer was not passed for ``days``. Returns --------- :class:`int` The number of members estimated to be pruned. """ if not isinstance(days, int): raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days)) data = await self._state.http.estimate_pruned_members(self.id, days) return data['pruned']
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1094-L1125
[ "async", "def", "estimate_pruned_members", "(", "self", ",", "*", ",", "days", ")", ":", "if", "not", "isinstance", "(", "days", ",", "int", ")", ":", "raise", "InvalidArgument", "(", "'Expected int for ``days``, received {0.__class__.__name__} instead.'", ".", "for...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.invites
|coro| Returns a list of all active instant invites from the guild. You must have the :attr:`~Permissions.manage_guild` permission to get this information. Raises ------- Forbidden You do not have proper permissions to get the information. HTTPException An error occurred while fetching the information. Returns ------- List[:class:`Invite`] The list of invites that are currently active.
discord/guild.py
async def invites(self): """|coro| Returns a list of all active instant invites from the guild. You must have the :attr:`~Permissions.manage_guild` permission to get this information. Raises ------- Forbidden You do not have proper permissions to get the information. HTTPException An error occurred while fetching the information. Returns ------- List[:class:`Invite`] The list of invites that are currently active. """ data = await self._state.http.invites_from(self.id) result = [] for invite in data: channel = self.get_channel(int(invite['channel']['id'])) invite['channel'] = channel invite['guild'] = self result.append(Invite(state=self._state, data=invite)) return result
async def invites(self): """|coro| Returns a list of all active instant invites from the guild. You must have the :attr:`~Permissions.manage_guild` permission to get this information. Raises ------- Forbidden You do not have proper permissions to get the information. HTTPException An error occurred while fetching the information. Returns ------- List[:class:`Invite`] The list of invites that are currently active. """ data = await self._state.http.invites_from(self.id) result = [] for invite in data: channel = self.get_channel(int(invite['channel']['id'])) invite['channel'] = channel invite['guild'] = self result.append(Invite(state=self._state, data=invite)) return result
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1127-L1156
[ "async", "def", "invites", "(", "self", ")", ":", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "invites_from", "(", "self", ".", "id", ")", "result", "=", "[", "]", "for", "invite", "in", "data", ":", "channel", "=", "self", ".", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.fetch_emojis
r"""|coro| Retrieves all custom :class:`Emoji`\s from the guild. .. note:: This method is an API call. For general usage, consider :attr:`emojis` instead. Raises --------- HTTPException An error occurred fetching the emojis. Returns -------- List[:class:`Emoji`] The retrieved emojis.
discord/guild.py
async def fetch_emojis(self): r"""|coro| Retrieves all custom :class:`Emoji`\s from the guild. .. note:: This method is an API call. For general usage, consider :attr:`emojis` instead. Raises --------- HTTPException An error occurred fetching the emojis. Returns -------- List[:class:`Emoji`] The retrieved emojis. """ data = await self._state.http.get_all_custom_emojis(self.id) return [Emoji(guild=self, state=self._state, data=d) for d in data]
async def fetch_emojis(self): r"""|coro| Retrieves all custom :class:`Emoji`\s from the guild. .. note:: This method is an API call. For general usage, consider :attr:`emojis` instead. Raises --------- HTTPException An error occurred fetching the emojis. Returns -------- List[:class:`Emoji`] The retrieved emojis. """ data = await self._state.http.get_all_custom_emojis(self.id) return [Emoji(guild=self, state=self._state, data=d) for d in data]
[ "r", "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1158-L1178
[ "async", "def", "fetch_emojis", "(", "self", ")", ":", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "get_all_custom_emojis", "(", "self", ".", "id", ")", "return", "[", "Emoji", "(", "guild", "=", "self", ",", "state", "=", "self", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.fetch_emoji
|coro| Retrieves a custom :class:`Emoji` from the guild. .. note:: This method is an API call. For general usage, consider iterating over :attr:`emojis` instead. Parameters ------------- emoji_id: :class:`int` The emoji's ID. Raises --------- NotFound The emoji requested could not be found. HTTPException An error occurred fetching the emoji. Returns -------- :class:`Emoji` The retrieved emoji.
discord/guild.py
async def fetch_emoji(self, emoji_id): """|coro| Retrieves a custom :class:`Emoji` from the guild. .. note:: This method is an API call. For general usage, consider iterating over :attr:`emojis` instead. Parameters ------------- emoji_id: :class:`int` The emoji's ID. Raises --------- NotFound The emoji requested could not be found. HTTPException An error occurred fetching the emoji. Returns -------- :class:`Emoji` The retrieved emoji. """ data = await self._state.http.get_custom_emoji(self.id, emoji_id) return Emoji(guild=self, state=self._state, data=data)
async def fetch_emoji(self, emoji_id): """|coro| Retrieves a custom :class:`Emoji` from the guild. .. note:: This method is an API call. For general usage, consider iterating over :attr:`emojis` instead. Parameters ------------- emoji_id: :class:`int` The emoji's ID. Raises --------- NotFound The emoji requested could not be found. HTTPException An error occurred fetching the emoji. Returns -------- :class:`Emoji` The retrieved emoji. """ data = await self._state.http.get_custom_emoji(self.id, emoji_id) return Emoji(guild=self, state=self._state, data=data)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1180-L1208
[ "async", "def", "fetch_emoji", "(", "self", ",", "emoji_id", ")", ":", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "get_custom_emoji", "(", "self", ".", "id", ",", "emoji_id", ")", "return", "Emoji", "(", "guild", "=", "self", ",", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.create_custom_emoji
r"""|coro| Creates a custom :class:`Emoji` for the guild. There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the ``MORE_EMOJI`` feature which extends the limit to 200. You must have the :attr:`~Permissions.manage_emojis` permission to do this. Parameters ----------- name: :class:`str` The emoji name. Must be at least 2 characters. image: :class:`bytes` The :term:`py:bytes-like object` representing the image data to use. Only JPG, PNG and GIF images are supported. roles: Optional[List[:class:`Role`]] A :class:`list` of :class:`Role`\s that can use this emoji. Leave empty to make it available to everyone. reason: Optional[:class:`str`] The reason for creating this emoji. Shows up on the audit log. Raises ------- Forbidden You are not allowed to create emojis. HTTPException An error occurred creating an emoji. Returns -------- :class:`Emoji` The created emoji.
discord/guild.py
async def create_custom_emoji(self, *, name, image, roles=None, reason=None): r"""|coro| Creates a custom :class:`Emoji` for the guild. There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the ``MORE_EMOJI`` feature which extends the limit to 200. You must have the :attr:`~Permissions.manage_emojis` permission to do this. Parameters ----------- name: :class:`str` The emoji name. Must be at least 2 characters. image: :class:`bytes` The :term:`py:bytes-like object` representing the image data to use. Only JPG, PNG and GIF images are supported. roles: Optional[List[:class:`Role`]] A :class:`list` of :class:`Role`\s that can use this emoji. Leave empty to make it available to everyone. reason: Optional[:class:`str`] The reason for creating this emoji. Shows up on the audit log. Raises ------- Forbidden You are not allowed to create emojis. HTTPException An error occurred creating an emoji. Returns -------- :class:`Emoji` The created emoji. """ img = utils._bytes_to_base64_data(image) if roles: roles = [role.id for role in roles] data = await self._state.http.create_custom_emoji(self.id, name, img, roles=roles, reason=reason) return self._state.store_emoji(self, data)
async def create_custom_emoji(self, *, name, image, roles=None, reason=None): r"""|coro| Creates a custom :class:`Emoji` for the guild. There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the ``MORE_EMOJI`` feature which extends the limit to 200. You must have the :attr:`~Permissions.manage_emojis` permission to do this. Parameters ----------- name: :class:`str` The emoji name. Must be at least 2 characters. image: :class:`bytes` The :term:`py:bytes-like object` representing the image data to use. Only JPG, PNG and GIF images are supported. roles: Optional[List[:class:`Role`]] A :class:`list` of :class:`Role`\s that can use this emoji. Leave empty to make it available to everyone. reason: Optional[:class:`str`] The reason for creating this emoji. Shows up on the audit log. Raises ------- Forbidden You are not allowed to create emojis. HTTPException An error occurred creating an emoji. Returns -------- :class:`Emoji` The created emoji. """ img = utils._bytes_to_base64_data(image) if roles: roles = [role.id for role in roles] data = await self._state.http.create_custom_emoji(self.id, name, img, roles=roles, reason=reason) return self._state.store_emoji(self, data)
[ "r", "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1210-L1250
[ "async", "def", "create_custom_emoji", "(", "self", ",", "*", ",", "name", ",", "image", ",", "roles", "=", "None", ",", "reason", "=", "None", ")", ":", "img", "=", "utils", ".", "_bytes_to_base64_data", "(", "image", ")", "if", "roles", ":", "roles",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.create_role
|coro| Creates a :class:`Role` for the guild. All fields are optional. You must have the :attr:`~Permissions.manage_roles` permission to do this. Parameters ----------- name: :class:`str` The role name. Defaults to 'new role'. permissions: :class:`Permissions` The permissions to have. Defaults to no permissions. colour: :class:`Colour` The colour for the role. Defaults to :meth:`Colour.default`. This is aliased to ``color`` as well. hoist: :class:`bool` Indicates if the role should be shown separately in the member list. Defaults to False. mentionable: :class:`bool` Indicates if the role should be mentionable by others. Defaults to False. reason: Optional[:class:`str`] The reason for creating this role. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to create the role. HTTPException Creating the role failed. InvalidArgument An invalid keyword argument was given. Returns -------- :class:`Role` The newly created role.
discord/guild.py
async def create_role(self, *, reason=None, **fields): """|coro| Creates a :class:`Role` for the guild. All fields are optional. You must have the :attr:`~Permissions.manage_roles` permission to do this. Parameters ----------- name: :class:`str` The role name. Defaults to 'new role'. permissions: :class:`Permissions` The permissions to have. Defaults to no permissions. colour: :class:`Colour` The colour for the role. Defaults to :meth:`Colour.default`. This is aliased to ``color`` as well. hoist: :class:`bool` Indicates if the role should be shown separately in the member list. Defaults to False. mentionable: :class:`bool` Indicates if the role should be mentionable by others. Defaults to False. reason: Optional[:class:`str`] The reason for creating this role. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to create the role. HTTPException Creating the role failed. InvalidArgument An invalid keyword argument was given. Returns -------- :class:`Role` The newly created role. """ try: perms = fields.pop('permissions') except KeyError: fields['permissions'] = 0 else: fields['permissions'] = perms.value try: colour = fields.pop('colour') except KeyError: colour = fields.get('color', Colour.default()) finally: fields['color'] = colour.value valid_keys = ('name', 'permissions', 'color', 'hoist', 'mentionable') for key in fields: if key not in valid_keys: raise InvalidArgument('%r is not a valid field.' % key) data = await self._state.http.create_role(self.id, reason=reason, **fields) role = Role(guild=self, data=data, state=self._state) # TODO: add to cache return role
async def create_role(self, *, reason=None, **fields): """|coro| Creates a :class:`Role` for the guild. All fields are optional. You must have the :attr:`~Permissions.manage_roles` permission to do this. Parameters ----------- name: :class:`str` The role name. Defaults to 'new role'. permissions: :class:`Permissions` The permissions to have. Defaults to no permissions. colour: :class:`Colour` The colour for the role. Defaults to :meth:`Colour.default`. This is aliased to ``color`` as well. hoist: :class:`bool` Indicates if the role should be shown separately in the member list. Defaults to False. mentionable: :class:`bool` Indicates if the role should be mentionable by others. Defaults to False. reason: Optional[:class:`str`] The reason for creating this role. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to create the role. HTTPException Creating the role failed. InvalidArgument An invalid keyword argument was given. Returns -------- :class:`Role` The newly created role. """ try: perms = fields.pop('permissions') except KeyError: fields['permissions'] = 0 else: fields['permissions'] = perms.value try: colour = fields.pop('colour') except KeyError: colour = fields.get('color', Colour.default()) finally: fields['color'] = colour.value valid_keys = ('name', 'permissions', 'color', 'hoist', 'mentionable') for key in fields: if key not in valid_keys: raise InvalidArgument('%r is not a valid field.' % key) data = await self._state.http.create_role(self.id, reason=reason, **fields) role = Role(guild=self, data=data, state=self._state) # TODO: add to cache return role
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1252-L1318
[ "async", "def", "create_role", "(", "self", ",", "*", ",", "reason", "=", "None", ",", "*", "*", "fields", ")", ":", "try", ":", "perms", "=", "fields", ".", "pop", "(", "'permissions'", ")", "except", "KeyError", ":", "fields", "[", "'permissions'", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.kick
|coro| Kicks a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.kick_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to kick from their guild. reason: Optional[:class:`str`] The reason the user got kicked. Raises ------- Forbidden You do not have the proper permissions to kick. HTTPException Kicking failed.
discord/guild.py
async def kick(self, user, *, reason=None): """|coro| Kicks a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.kick_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to kick from their guild. reason: Optional[:class:`str`] The reason the user got kicked. Raises ------- Forbidden You do not have the proper permissions to kick. HTTPException Kicking failed. """ await self._state.http.kick(user.id, self.id, reason=reason)
async def kick(self, user, *, reason=None): """|coro| Kicks a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.kick_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to kick from their guild. reason: Optional[:class:`str`] The reason the user got kicked. Raises ------- Forbidden You do not have the proper permissions to kick. HTTPException Kicking failed. """ await self._state.http.kick(user.id, self.id, reason=reason)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1320-L1344
[ "async", "def", "kick", "(", "self", ",", "user", ",", "*", ",", "reason", "=", "None", ")", ":", "await", "self", ".", "_state", ".", "http", ".", "kick", "(", "user", ".", "id", ",", "self", ".", "id", ",", "reason", "=", "reason", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.ban
|coro| Bans a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.ban_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to ban from their guild. delete_message_days: :class:`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[:class:`str`] The reason the user got banned. Raises ------- Forbidden You do not have the proper permissions to ban. HTTPException Banning failed.
discord/guild.py
async def ban(self, user, *, reason=None, delete_message_days=1): """|coro| Bans a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.ban_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to ban from their guild. delete_message_days: :class:`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[:class:`str`] The reason the user got banned. Raises ------- Forbidden You do not have the proper permissions to ban. HTTPException Banning failed. """ await self._state.http.ban(user.id, self.id, delete_message_days, reason=reason)
async def ban(self, user, *, reason=None, delete_message_days=1): """|coro| Bans a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.ban_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to ban from their guild. delete_message_days: :class:`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[:class:`str`] The reason the user got banned. Raises ------- Forbidden You do not have the proper permissions to ban. HTTPException Banning failed. """ await self._state.http.ban(user.id, self.id, delete_message_days, reason=reason)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1346-L1373
[ "async", "def", "ban", "(", "self", ",", "user", ",", "*", ",", "reason", "=", "None", ",", "delete_message_days", "=", "1", ")", ":", "await", "self", ".", "_state", ".", "http", ".", "ban", "(", "user", ".", "id", ",", "self", ".", "id", ",", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.unban
|coro| Unbans a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.ban_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to unban. reason: Optional[:class:`str`] The reason for doing this action. Shows up on the audit log. Raises ------- Forbidden You do not have the proper permissions to unban. HTTPException Unbanning failed.
discord/guild.py
async def unban(self, user, *, reason=None): """|coro| Unbans a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.ban_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to unban. reason: Optional[:class:`str`] The reason for doing this action. Shows up on the audit log. Raises ------- Forbidden You do not have the proper permissions to unban. HTTPException Unbanning failed. """ await self._state.http.unban(user.id, self.id, reason=reason)
async def unban(self, user, *, reason=None): """|coro| Unbans a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.ban_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to unban. reason: Optional[:class:`str`] The reason for doing this action. Shows up on the audit log. Raises ------- Forbidden You do not have the proper permissions to unban. HTTPException Unbanning failed. """ await self._state.http.unban(user.id, self.id, reason=reason)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1375-L1399
[ "async", "def", "unban", "(", "self", ",", "user", ",", "*", ",", "reason", "=", "None", ")", ":", "await", "self", ".", "_state", ".", "http", ".", "unban", "(", "user", ".", "id", ",", "self", ".", "id", ",", "reason", "=", "reason", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.vanity_invite
|coro| Returns the guild's special vanity invite. The guild must be partnered, i.e. have 'VANITY_URL' in :attr:`~Guild.features`. You must have the :attr:`~Permissions.manage_guild` permission to use this as well. Raises ------- Forbidden You do not have the proper permissions to get this. HTTPException Retrieving the vanity invite failed. Returns -------- :class:`Invite` The special vanity invite.
discord/guild.py
async def vanity_invite(self): """|coro| Returns the guild's special vanity invite. The guild must be partnered, i.e. have 'VANITY_URL' in :attr:`~Guild.features`. You must have the :attr:`~Permissions.manage_guild` permission to use this as well. Raises ------- Forbidden You do not have the proper permissions to get this. HTTPException Retrieving the vanity invite failed. Returns -------- :class:`Invite` The special vanity invite. """ # we start with { code: abc } payload = await self._state.http.get_vanity_code(self.id) # get the vanity URL channel since default channels aren't # reliable or a thing anymore data = await self._state.http.get_invite(payload['code']) payload['guild'] = self payload['channel'] = self.get_channel(int(data['channel']['id'])) payload['revoked'] = False payload['temporary'] = False payload['max_uses'] = 0 payload['max_age'] = 0 return Invite(state=self._state, data=payload)
async def vanity_invite(self): """|coro| Returns the guild's special vanity invite. The guild must be partnered, i.e. have 'VANITY_URL' in :attr:`~Guild.features`. You must have the :attr:`~Permissions.manage_guild` permission to use this as well. Raises ------- Forbidden You do not have the proper permissions to get this. HTTPException Retrieving the vanity invite failed. Returns -------- :class:`Invite` The special vanity invite. """ # we start with { code: abc } payload = await self._state.http.get_vanity_code(self.id) # get the vanity URL channel since default channels aren't # reliable or a thing anymore data = await self._state.http.get_invite(payload['code']) payload['guild'] = self payload['channel'] = self.get_channel(int(data['channel']['id'])) payload['revoked'] = False payload['temporary'] = False payload['max_uses'] = 0 payload['max_age'] = 0 return Invite(state=self._state, data=payload)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1401-L1438
[ "async", "def", "vanity_invite", "(", "self", ")", ":", "# we start with { code: abc }", "payload", "=", "await", "self", ".", "_state", ".", "http", ".", "get_vanity_code", "(", "self", ".", "id", ")", "# get the vanity URL channel since default channels aren't", "# ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.ack
|coro| Marks every message in this guild as read. The user must not be a bot user. Raises ------- HTTPException Acking failed. ClientException You must not be a bot user.
discord/guild.py
def ack(self): """|coro| Marks every message in this guild as read. The user must not be a bot user. Raises ------- HTTPException Acking failed. ClientException You must not be a bot user. """ state = self._state if state.is_bot: raise ClientException('Must not be a bot account to ack messages.') return state.http.ack_guild(self.id)
def ack(self): """|coro| Marks every message in this guild as read. The user must not be a bot user. Raises ------- HTTPException Acking failed. ClientException You must not be a bot user. """ state = self._state if state.is_bot: raise ClientException('Must not be a bot account to ack messages.') return state.http.ack_guild(self.id)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1440-L1458
[ "def", "ack", "(", "self", ")", ":", "state", "=", "self", ".", "_state", "if", "state", ".", "is_bot", ":", "raise", "ClientException", "(", "'Must not be a bot account to ack messages.'", ")", "return", "state", ".", "http", ".", "ack_guild", "(", "self", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.audit_logs
Return an :class:`AsyncIterator` that enables receiving the guild's audit logs. You must have the :attr:`~Permissions.view_audit_log` permission to use this. Examples ---------- 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))) Parameters ----------- limit: Optional[:class:`int`] The number of entries to retrieve. If ``None`` retrieve all entries. before: Union[:class:`abc.Snowflake`, datetime] Retrieve entries before this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time. after: Union[:class:`abc.Snowflake`, datetime] Retrieve entries after this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time. oldest_first: :class:`bool` If set to true, return entries in oldest->newest order. Defaults to True if ``after`` is specified, otherwise False. user: :class:`abc.Snowflake` The moderator to filter entries from. action: :class:`AuditLogAction` The action to filter with. Raises ------- Forbidden You are not allowed to fetch audit logs HTTPException An error occurred while fetching the audit logs. Yields -------- :class:`AuditLogEntry` The audit log entry.
discord/guild.py
def audit_logs(self, *, limit=100, before=None, after=None, oldest_first=None, user=None, action=None): """Return an :class:`AsyncIterator` that enables receiving the guild's audit logs. You must have the :attr:`~Permissions.view_audit_log` permission to use this. Examples ---------- 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))) Parameters ----------- limit: Optional[:class:`int`] The number of entries to retrieve. If ``None`` retrieve all entries. before: Union[:class:`abc.Snowflake`, datetime] Retrieve entries before this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time. after: Union[:class:`abc.Snowflake`, datetime] Retrieve entries after this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time. oldest_first: :class:`bool` If set to true, return entries in oldest->newest order. Defaults to True if ``after`` is specified, otherwise False. user: :class:`abc.Snowflake` The moderator to filter entries from. action: :class:`AuditLogAction` The action to filter with. Raises ------- Forbidden You are not allowed to fetch audit logs HTTPException An error occurred while fetching the audit logs. Yields -------- :class:`AuditLogEntry` The audit log entry. """ if user: user = user.id if action: action = action.value return AuditLogIterator(self, before=before, after=after, limit=limit, oldest_first=oldest_first, user_id=user, action_type=action)
def audit_logs(self, *, limit=100, before=None, after=None, oldest_first=None, user=None, action=None): """Return an :class:`AsyncIterator` that enables receiving the guild's audit logs. You must have the :attr:`~Permissions.view_audit_log` permission to use this. Examples ---------- 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))) Parameters ----------- limit: Optional[:class:`int`] The number of entries to retrieve. If ``None`` retrieve all entries. before: Union[:class:`abc.Snowflake`, datetime] Retrieve entries before this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time. after: Union[:class:`abc.Snowflake`, datetime] Retrieve entries after this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time. oldest_first: :class:`bool` If set to true, return entries in oldest->newest order. Defaults to True if ``after`` is specified, otherwise False. user: :class:`abc.Snowflake` The moderator to filter entries from. action: :class:`AuditLogAction` The action to filter with. Raises ------- Forbidden You are not allowed to fetch audit logs HTTPException An error occurred while fetching the audit logs. Yields -------- :class:`AuditLogEntry` The audit log entry. """ if user: user = user.id if action: action = action.value return AuditLogIterator(self, before=before, after=after, limit=limit, oldest_first=oldest_first, user_id=user, action_type=action)
[ "Return", "an", ":", "class", ":", "AsyncIterator", "that", "enables", "receiving", "the", "guild", "s", "audit", "logs", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1460-L1520
[ "def", "audit_logs", "(", "self", ",", "*", ",", "limit", "=", "100", ",", "before", "=", "None", ",", "after", "=", "None", ",", "oldest_first", "=", "None", ",", "user", "=", "None", ",", "action", "=", "None", ")", ":", "if", "user", ":", "use...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Guild.widget
|coro| Returns the widget of the guild. .. note:: The guild must have the widget enabled to get this information. Raises ------- Forbidden The widget for this guild is disabled. HTTPException Retrieving the widget failed. Returns -------- :class:`Widget` The guild's widget.
discord/guild.py
async def widget(self): """|coro| Returns the widget of the guild. .. note:: The guild must have the widget enabled to get this information. Raises ------- Forbidden The widget for this guild is disabled. HTTPException Retrieving the widget failed. Returns -------- :class:`Widget` The guild's widget. """ data = await self._state.http.get_widget(self.id) return Widget(state=self._state, data=data)
async def widget(self): """|coro| Returns the widget of the guild. .. note:: The guild must have the widget enabled to get this information. Raises ------- Forbidden The widget for this guild is disabled. HTTPException Retrieving the widget failed. Returns -------- :class:`Widget` The guild's widget. """ data = await self._state.http.get_widget(self.id) return Widget(state=self._state, data=data)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1522-L1545
[ "async", "def", "widget", "(", "self", ")", ":", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "get_widget", "(", "self", ".", "id", ")", "return", "Widget", "(", "state", "=", "self", ".", "_state", ",", "data", "=", "data", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
AutoShardedClient.latency
:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This operates similarly to :meth:`.Client.latency` except it uses the average latency of every shard's latency. To get a list of shard latency, check the :attr:`latencies` property. Returns ``nan`` if there are no shards ready.
discord/shard.py
def latency(self): """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This operates similarly to :meth:`.Client.latency` except it uses the average latency of every shard's latency. To get a list of shard latency, check the :attr:`latencies` property. Returns ``nan`` if there are no shards ready. """ if not self.shards: return float('nan') return sum(latency for _, latency in self.latencies) / len(self.shards)
def latency(self): """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This operates similarly to :meth:`.Client.latency` except it uses the average latency of every shard's latency. To get a list of shard latency, check the :attr:`latencies` property. Returns ``nan`` if there are no shards ready. """ if not self.shards: return float('nan') return sum(latency for _, latency in self.latencies) / len(self.shards)
[ ":", "class", ":", "float", ":", "Measures", "latency", "between", "a", "HEARTBEAT", "and", "a", "HEARTBEAT_ACK", "in", "seconds", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/shard.py#L163-L172
[ "def", "latency", "(", "self", ")", ":", "if", "not", "self", ".", "shards", ":", "return", "float", "(", "'nan'", ")", "return", "sum", "(", "latency", "for", "_", ",", "latency", "in", "self", ".", "latencies", ")", "/", "len", "(", "self", ".", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
AutoShardedClient.latencies
List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This returns a list of tuples with elements ``(shard_id, latency)``.
discord/shard.py
def latencies(self): """List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This returns a list of tuples with elements ``(shard_id, latency)``. """ return [(shard_id, shard.ws.latency) for shard_id, shard in self.shards.items()]
def latencies(self): """List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This returns a list of tuples with elements ``(shard_id, latency)``. """ return [(shard_id, shard.ws.latency) for shard_id, shard in self.shards.items()]
[ "List", "[", "Tuple", "[", ":", "class", ":", "int", ":", "class", ":", "float", "]]", ":", "A", "list", "of", "latencies", "between", "a", "HEARTBEAT", "and", "a", "HEARTBEAT_ACK", "in", "seconds", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/shard.py#L175-L180
[ "def", "latencies", "(", "self", ")", ":", "return", "[", "(", "shard_id", ",", "shard", ".", "ws", ".", "latency", ")", "for", "shard_id", ",", "shard", "in", "self", ".", "shards", ".", "items", "(", ")", "]" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
AutoShardedClient.request_offline_members
r"""|coro| Requests previously offline members from the guild to be filled up into the :attr:`Guild.members` cache. This function is usually not called. It should only be used if you have the ``fetch_offline_members`` parameter set to ``False``. 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 :attr:`Guild.large` is ``True``. Parameters ----------- \*guilds: :class:`Guild` An argument list of guilds to request offline members for. Raises ------- InvalidArgument If any guild is unavailable or not large in the collection.
discord/shard.py
async def request_offline_members(self, *guilds): r"""|coro| Requests previously offline members from the guild to be filled up into the :attr:`Guild.members` cache. This function is usually not called. It should only be used if you have the ``fetch_offline_members`` parameter set to ``False``. 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 :attr:`Guild.large` is ``True``. Parameters ----------- \*guilds: :class:`Guild` An argument list of guilds to request offline members for. Raises ------- InvalidArgument If any guild is unavailable or not large in the collection. """ if any(not g.large or g.unavailable for g in guilds): raise InvalidArgument('An unavailable or non-large guild was passed.') _guilds = sorted(guilds, key=lambda g: g.shard_id) for shard_id, sub_guilds in itertools.groupby(_guilds, key=lambda g: g.shard_id): sub_guilds = list(sub_guilds) await self._connection.request_offline_members(sub_guilds, shard_id=shard_id)
async def request_offline_members(self, *guilds): r"""|coro| Requests previously offline members from the guild to be filled up into the :attr:`Guild.members` cache. This function is usually not called. It should only be used if you have the ``fetch_offline_members`` parameter set to ``False``. 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 :attr:`Guild.large` is ``True``. Parameters ----------- \*guilds: :class:`Guild` An argument list of guilds to request offline members for. Raises ------- InvalidArgument If any guild is unavailable or not large in the collection. """ if any(not g.large or g.unavailable for g in guilds): raise InvalidArgument('An unavailable or non-large guild was passed.') _guilds = sorted(guilds, key=lambda g: g.shard_id) for shard_id, sub_guilds in itertools.groupby(_guilds, key=lambda g: g.shard_id): sub_guilds = list(sub_guilds) await self._connection.request_offline_members(sub_guilds, shard_id=shard_id)
[ "r", "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/shard.py#L182-L211
[ "async", "def", "request_offline_members", "(", "self", ",", "*", "guilds", ")", ":", "if", "any", "(", "not", "g", ".", "large", "or", "g", ".", "unavailable", "for", "g", "in", "guilds", ")", ":", "raise", "InvalidArgument", "(", "'An unavailable or non-...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
AutoShardedClient.close
|coro| Closes the connection to discord.
discord/shard.py
async def close(self): """|coro| Closes the connection to discord. """ if self.is_closed(): return self._closed = True for vc in self.voice_clients: try: await vc.disconnect() except Exception: pass to_close = [shard.ws.close() for shard in self.shards.values()] if to_close: await asyncio.wait(to_close, loop=self.loop) await self.http.close()
async def close(self): """|coro| Closes the connection to discord. """ if self.is_closed(): return self._closed = True for vc in self.voice_clients: try: await vc.disconnect() except Exception: pass to_close = [shard.ws.close() for shard in self.shards.values()] if to_close: await asyncio.wait(to_close, loop=self.loop) await self.http.close()
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/shard.py#L275-L295
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "is_closed", "(", ")", ":", "return", "self", ".", "_closed", "=", "True", "for", "vc", "in", "self", ".", "voice_clients", ":", "try", ":", "await", "vc", ".", "disconnect", "(", "...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
AutoShardedClient.change_presence
|coro| Changes the client's presence. The activity parameter is a :class:`Activity` object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, :class:`Game` and :class:`Streaming`. Example: :: game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) Parameters ---------- activity: Optional[Union[:class:`Game`, :class:`Streaming`, :class:`Activity`]] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`Status`] Indicates what status to change to. If None, then :attr:`Status.online` is used. afk: :class:`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[:class:`int`] The shard_id to change the presence to. If not specified or ``None``, then it will change the presence of every shard the bot can see. Raises ------ InvalidArgument If the ``activity`` parameter is not of proper type.
discord/shard.py
async def change_presence(self, *, activity=None, status=None, afk=False, shard_id=None): """|coro| Changes the client's presence. The activity parameter is a :class:`Activity` object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, :class:`Game` and :class:`Streaming`. Example: :: game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) Parameters ---------- activity: Optional[Union[:class:`Game`, :class:`Streaming`, :class:`Activity`]] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`Status`] Indicates what status to change to. If None, then :attr:`Status.online` is used. afk: :class:`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[:class:`int`] The shard_id to change the presence to. If not specified or ``None``, then it will change the presence of every shard the bot can see. Raises ------ InvalidArgument If the ``activity`` parameter is not of proper type. """ if status is None: status = 'online' status_enum = Status.online elif status is Status.offline: status = 'invisible' status_enum = Status.offline else: status_enum = status status = str(status) if shard_id is None: for shard in self.shards.values(): await shard.ws.change_presence(activity=activity, status=status, afk=afk) guilds = self._connection.guilds else: shard = self.shards[shard_id] await shard.ws.change_presence(activity=activity, status=status, afk=afk) guilds = [g for g in self._connection.guilds if g.shard_id == shard_id] for guild in guilds: me = guild.me if me is None: continue me.activities = (activity,) me.status = status_enum
async def change_presence(self, *, activity=None, status=None, afk=False, shard_id=None): """|coro| Changes the client's presence. The activity parameter is a :class:`Activity` object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, :class:`Game` and :class:`Streaming`. Example: :: game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) Parameters ---------- activity: Optional[Union[:class:`Game`, :class:`Streaming`, :class:`Activity`]] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`Status`] Indicates what status to change to. If None, then :attr:`Status.online` is used. afk: :class:`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[:class:`int`] The shard_id to change the presence to. If not specified or ``None``, then it will change the presence of every shard the bot can see. Raises ------ InvalidArgument If the ``activity`` parameter is not of proper type. """ if status is None: status = 'online' status_enum = Status.online elif status is Status.offline: status = 'invisible' status_enum = Status.offline else: status_enum = status status = str(status) if shard_id is None: for shard in self.shards.values(): await shard.ws.change_presence(activity=activity, status=status, afk=afk) guilds = self._connection.guilds else: shard = self.shards[shard_id] await shard.ws.change_presence(activity=activity, status=status, afk=afk) guilds = [g for g in self._connection.guilds if g.shard_id == shard_id] for guild in guilds: me = guild.me if me is None: continue me.activities = (activity,) me.status = status_enum
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/shard.py#L297-L359
[ "async", "def", "change_presence", "(", "self", ",", "*", ",", "activity", "=", "None", ",", "status", "=", "None", ",", "afk", "=", "False", ",", "shard_id", "=", "None", ")", ":", "if", "status", "is", "None", ":", "status", "=", "'online'", "statu...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Role.members
Returns a :class:`list` of :class:`Member` with this role.
discord/role.py
def members(self): """Returns a :class:`list` of :class:`Member` with this role.""" all_members = self.guild.members if self.is_default(): return all_members role_id = self.id return [member for member in all_members if member._roles.has(role_id)]
def members(self): """Returns a :class:`list` of :class:`Member` with this role.""" all_members = self.guild.members if self.is_default(): return all_members role_id = self.id return [member for member in all_members if member._roles.has(role_id)]
[ "Returns", "a", ":", "class", ":", "list", "of", ":", "class", ":", "Member", "with", "this", "role", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/role.py#L170-L177
[ "def", "members", "(", "self", ")", ":", "all_members", "=", "self", ".", "guild", ".", "members", "if", "self", ".", "is_default", "(", ")", ":", "return", "all_members", "role_id", "=", "self", ".", "id", "return", "[", "member", "for", "member", "in...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Role.edit
|coro| Edits the role. You must have the :attr:`~Permissions.manage_roles` permission to use this. All fields are optional. Parameters ----------- name: :class:`str` The new role name to change to. permissions: :class:`Permissions` The new permissions to change to. colour: :class:`Colour` The new colour to change to. (aliased to color as well) hoist: :class:`bool` Indicates if the role should be shown separately in the member list. mentionable: :class:`bool` Indicates if the role should be mentionable by others. position: :class:`int` The new role's position. This must be below your top role's position or it will fail. reason: Optional[:class:`str`] The reason for editing this role. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to change the role. HTTPException Editing the role failed. InvalidArgument An invalid position was given or the default role was asked to be moved.
discord/role.py
async def edit(self, *, reason=None, **fields): """|coro| Edits the role. You must have the :attr:`~Permissions.manage_roles` permission to use this. All fields are optional. Parameters ----------- name: :class:`str` The new role name to change to. permissions: :class:`Permissions` The new permissions to change to. colour: :class:`Colour` The new colour to change to. (aliased to color as well) hoist: :class:`bool` Indicates if the role should be shown separately in the member list. mentionable: :class:`bool` Indicates if the role should be mentionable by others. position: :class:`int` The new role's position. This must be below your top role's position or it will fail. reason: Optional[:class:`str`] The reason for editing this role. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to change the role. HTTPException Editing the role failed. InvalidArgument An invalid position was given or the default role was asked to be moved. """ position = fields.get('position') if position is not None: await self._move(position, reason=reason) self.position = position try: colour = fields['colour'] except KeyError: colour = fields.get('color', self.colour) payload = { 'name': fields.get('name', self.name), 'permissions': fields.get('permissions', self.permissions).value, 'color': colour.value, 'hoist': fields.get('hoist', self.hoist), 'mentionable': fields.get('mentionable', self.mentionable) } data = await self._state.http.edit_role(self.guild.id, self.id, reason=reason, **payload) self._update(data)
async def edit(self, *, reason=None, **fields): """|coro| Edits the role. You must have the :attr:`~Permissions.manage_roles` permission to use this. All fields are optional. Parameters ----------- name: :class:`str` The new role name to change to. permissions: :class:`Permissions` The new permissions to change to. colour: :class:`Colour` The new colour to change to. (aliased to color as well) hoist: :class:`bool` Indicates if the role should be shown separately in the member list. mentionable: :class:`bool` Indicates if the role should be mentionable by others. position: :class:`int` The new role's position. This must be below your top role's position or it will fail. reason: Optional[:class:`str`] The reason for editing this role. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to change the role. HTTPException Editing the role failed. InvalidArgument An invalid position was given or the default role was asked to be moved. """ position = fields.get('position') if position is not None: await self._move(position, reason=reason) self.position = position try: colour = fields['colour'] except KeyError: colour = fields.get('color', self.colour) payload = { 'name': fields.get('name', self.name), 'permissions': fields.get('permissions', self.permissions).value, 'color': colour.value, 'hoist': fields.get('hoist', self.hoist), 'mentionable': fields.get('mentionable', self.mentionable) } data = await self._state.http.edit_role(self.guild.id, self.id, reason=reason, **payload) self._update(data)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/role.py#L202-L260
[ "async", "def", "edit", "(", "self", ",", "*", ",", "reason", "=", "None", ",", "*", "*", "fields", ")", ":", "position", "=", "fields", ".", "get", "(", "'position'", ")", "if", "position", "is", "not", "None", ":", "await", "self", ".", "_move", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Role.delete
|coro| Deletes the role. You must have the :attr:`~Permissions.manage_roles` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this role. Shows up on the audit log. Raises -------- Forbidden You do not have permissions to delete the role. HTTPException Deleting the role failed.
discord/role.py
async def delete(self, *, reason=None): """|coro| Deletes the role. You must have the :attr:`~Permissions.manage_roles` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this role. Shows up on the audit log. Raises -------- Forbidden You do not have permissions to delete the role. HTTPException Deleting the role failed. """ await self._state.http.delete_role(self.guild.id, self.id, reason=reason)
async def delete(self, *, reason=None): """|coro| Deletes the role. You must have the :attr:`~Permissions.manage_roles` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this role. Shows up on the audit log. Raises -------- Forbidden You do not have permissions to delete the role. HTTPException Deleting the role failed. """ await self._state.http.delete_role(self.guild.id, self.id, reason=reason)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/role.py#L262-L283
[ "async", "def", "delete", "(", "self", ",", "*", ",", "reason", "=", "None", ")", ":", "await", "self", ".", "_state", ".", "http", ".", "delete_role", "(", "self", ".", "guild", ".", "id", ",", "self", ".", "id", ",", "reason", "=", "reason", ")...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Blueprint.group
Create a list of blueprints, optionally grouping them under a general URL prefix. :param blueprints: blueprints to be registered as a group :param url_prefix: URL route to be prepended to all sub-prefixes
sanic/blueprints.py
def group(*blueprints, url_prefix=""): """ Create a list of blueprints, optionally grouping them under a general URL prefix. :param blueprints: blueprints to be registered as a group :param url_prefix: URL route to be prepended to all sub-prefixes """ def chain(nested): """itertools.chain() but leaves strings untouched""" for i in nested: if isinstance(i, (list, tuple)): yield from chain(i) elif isinstance(i, BlueprintGroup): yield from i.blueprints else: yield i bps = BlueprintGroup(url_prefix=url_prefix) for bp in chain(blueprints): if bp.url_prefix is None: bp.url_prefix = "" bp.url_prefix = url_prefix + bp.url_prefix bps.append(bp) return bps
def group(*blueprints, url_prefix=""): """ Create a list of blueprints, optionally grouping them under a general URL prefix. :param blueprints: blueprints to be registered as a group :param url_prefix: URL route to be prepended to all sub-prefixes """ def chain(nested): """itertools.chain() but leaves strings untouched""" for i in nested: if isinstance(i, (list, tuple)): yield from chain(i) elif isinstance(i, BlueprintGroup): yield from i.blueprints else: yield i bps = BlueprintGroup(url_prefix=url_prefix) for bp in chain(blueprints): if bp.url_prefix is None: bp.url_prefix = "" bp.url_prefix = url_prefix + bp.url_prefix bps.append(bp) return bps
[ "Create", "a", "list", "of", "blueprints", "optionally", "grouping", "them", "under", "a", "general", "URL", "prefix", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L68-L93
[ "def", "group", "(", "*", "blueprints", ",", "url_prefix", "=", "\"\"", ")", ":", "def", "chain", "(", "nested", ")", ":", "\"\"\"itertools.chain() but leaves strings untouched\"\"\"", "for", "i", "in", "nested", ":", "if", "isinstance", "(", "i", ",", "(", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Blueprint.register
Register the blueprint to the sanic app. :param app: Instance of :class:`sanic.app.Sanic` class :param options: Options to be used while registering the blueprint into the app. *url_prefix* - URL Prefix to override the blueprint prefix
sanic/blueprints.py
def register(self, app, options): """ Register the blueprint to the sanic app. :param app: Instance of :class:`sanic.app.Sanic` class :param options: Options to be used while registering the blueprint into the app. *url_prefix* - URL Prefix to override the blueprint prefix """ url_prefix = options.get("url_prefix", self.url_prefix) # Routes for future in self.routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri version = future.version or self.version app.route( uri=uri[1:] if uri.startswith("//") else uri, methods=future.methods, host=future.host or self.host, strict_slashes=future.strict_slashes, stream=future.stream, version=version, name=future.name, )(future.handler) for future in self.websocket_routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri app.websocket( uri=uri, host=future.host or self.host, strict_slashes=future.strict_slashes, name=future.name, )(future.handler) # Middleware for future in self.middlewares: if future.args or future.kwargs: app.register_middleware( future.middleware, *future.args, **future.kwargs ) else: app.register_middleware(future.middleware) # Exceptions for future in self.exceptions: app.exception(*future.args, **future.kwargs)(future.handler) # Static Files for future in self.statics: # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri app.static( uri, future.file_or_directory, *future.args, **future.kwargs ) # Event listeners for event, listeners in self.listeners.items(): for listener in listeners: app.listener(event)(listener)
def register(self, app, options): """ Register the blueprint to the sanic app. :param app: Instance of :class:`sanic.app.Sanic` class :param options: Options to be used while registering the blueprint into the app. *url_prefix* - URL Prefix to override the blueprint prefix """ url_prefix = options.get("url_prefix", self.url_prefix) # Routes for future in self.routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri version = future.version or self.version app.route( uri=uri[1:] if uri.startswith("//") else uri, methods=future.methods, host=future.host or self.host, strict_slashes=future.strict_slashes, stream=future.stream, version=version, name=future.name, )(future.handler) for future in self.websocket_routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri app.websocket( uri=uri, host=future.host or self.host, strict_slashes=future.strict_slashes, name=future.name, )(future.handler) # Middleware for future in self.middlewares: if future.args or future.kwargs: app.register_middleware( future.middleware, *future.args, **future.kwargs ) else: app.register_middleware(future.middleware) # Exceptions for future in self.exceptions: app.exception(*future.args, **future.kwargs)(future.handler) # Static Files for future in self.statics: # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri app.static( uri, future.file_or_directory, *future.args, **future.kwargs ) # Event listeners for event, listeners in self.listeners.items(): for listener in listeners: app.listener(event)(listener)
[ "Register", "the", "blueprint", "to", "the", "sanic", "app", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L95-L164
[ "def", "register", "(", "self", ",", "app", ",", "options", ")", ":", "url_prefix", "=", "options", ".", "get", "(", "\"url_prefix\"", ",", "self", ".", "url_prefix", ")", "# Routes", "for", "future", "in", "self", ".", "routes", ":", "# attach the bluepri...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Blueprint.route
Create a blueprint route from a decorated function. :param uri: endpoint at which the route will be accessible. :param methods: list of acceptable HTTP methods. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param stream: If the route should provide a streaming support :param version: Blueprint Version :param name: Unique name to identify the Route :return a decorated method that when invoked will return an object of type :class:`FutureRoute`
sanic/blueprints.py
def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): """Create a blueprint route from a decorated function. :param uri: endpoint at which the route will be accessible. :param methods: list of acceptable HTTP methods. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param stream: If the route should provide a streaming support :param version: Blueprint Version :param name: Unique name to identify the Route :return a decorated method that when invoked will return an object of type :class:`FutureRoute` """ if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, methods, host, strict_slashes, stream, version, name, ) self.routes.append(route) return handler return decorator
def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): """Create a blueprint route from a decorated function. :param uri: endpoint at which the route will be accessible. :param methods: list of acceptable HTTP methods. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param stream: If the route should provide a streaming support :param version: Blueprint Version :param name: Unique name to identify the Route :return a decorated method that when invoked will return an object of type :class:`FutureRoute` """ if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, methods, host, strict_slashes, stream, version, name, ) self.routes.append(route) return handler return decorator
[ "Create", "a", "blueprint", "route", "from", "a", "decorated", "function", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L166-L207
[ "def", "route", "(", "self", ",", "uri", ",", "methods", "=", "frozenset", "(", "{", "\"GET\"", "}", ")", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "stream", "=", "False", ",", "version", "=", "None", ",", "name", "=", "Non...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Blueprint.websocket
Create a blueprint websocket route from a decorated function. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param version: Blueprint Version :param name: Unique name to identify the Websocket Route
sanic/blueprints.py
def websocket( self, uri, host=None, strict_slashes=None, version=None, name=None ): """Create a blueprint websocket route from a decorated function. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param version: Blueprint Version :param name: Unique name to identify the Websocket Route """ if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, [], host, strict_slashes, False, version, name ) self.websocket_routes.append(route) return handler return decorator
def websocket( self, uri, host=None, strict_slashes=None, version=None, name=None ): """Create a blueprint websocket route from a decorated function. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param version: Blueprint Version :param name: Unique name to identify the Websocket Route """ if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, [], host, strict_slashes, False, version, name ) self.websocket_routes.append(route) return handler return decorator
[ "Create", "a", "blueprint", "websocket", "route", "from", "a", "decorated", "function", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L260-L282
[ "def", "websocket", "(", "self", ",", "uri", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "version", "=", "None", ",", "name", "=", "None", ")", ":", "if", "strict_slashes", "is", "None", ":", "strict_slashes", "=", "self", ".", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Blueprint.add_websocket_route
Create a blueprint websocket route from a function. :param handler: function for handling uri requests. Accepts function, or class instance with a view_class method. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param version: Blueprint Version :param name: Unique name to identify the Websocket Route :return: function or class instance
sanic/blueprints.py
def add_websocket_route( self, handler, uri, host=None, version=None, name=None ): """Create a blueprint websocket route from a function. :param handler: function for handling uri requests. Accepts function, or class instance with a view_class method. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param version: Blueprint Version :param name: Unique name to identify the Websocket Route :return: function or class instance """ self.websocket(uri=uri, host=host, version=version, name=name)(handler) return handler
def add_websocket_route( self, handler, uri, host=None, version=None, name=None ): """Create a blueprint websocket route from a function. :param handler: function for handling uri requests. Accepts function, or class instance with a view_class method. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param version: Blueprint Version :param name: Unique name to identify the Websocket Route :return: function or class instance """ self.websocket(uri=uri, host=host, version=version, name=name)(handler) return handler
[ "Create", "a", "blueprint", "websocket", "route", "from", "a", "function", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L284-L298
[ "def", "add_websocket_route", "(", "self", ",", "handler", ",", "uri", ",", "host", "=", "None", ",", "version", "=", "None", ",", "name", "=", "None", ")", ":", "self", ".", "websocket", "(", "uri", "=", "uri", ",", "host", "=", "host", ",", "vers...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Blueprint.listener
Create a listener from a decorated function. :param event: Event to listen to.
sanic/blueprints.py
def listener(self, event): """Create a listener from a decorated function. :param event: Event to listen to. """ def decorator(listener): self.listeners[event].append(listener) return listener return decorator
def listener(self, event): """Create a listener from a decorated function. :param event: Event to listen to. """ def decorator(listener): self.listeners[event].append(listener) return listener return decorator
[ "Create", "a", "listener", "from", "a", "decorated", "function", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L300-L310
[ "def", "listener", "(", "self", ",", "event", ")", ":", "def", "decorator", "(", "listener", ")", ":", "self", ".", "listeners", "[", "event", "]", ".", "append", "(", "listener", ")", "return", "listener", "return", "decorator" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Blueprint.middleware
Create a blueprint middleware from a decorated function. :param args: Positional arguments to be used while invoking the middleware :param kwargs: optional keyword args that can be used with the middleware.
sanic/blueprints.py
def middleware(self, *args, **kwargs): """ Create a blueprint middleware from a decorated function. :param args: Positional arguments to be used while invoking the middleware :param kwargs: optional keyword args that can be used with the middleware. """ def register_middleware(_middleware): future_middleware = FutureMiddleware(_middleware, args, kwargs) self.middlewares.append(future_middleware) return _middleware # Detect which way this was called, @middleware or @middleware('AT') if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): middleware = args[0] args = [] return register_middleware(middleware) else: if kwargs.get("bp_group") and callable(args[0]): middleware = args[0] args = args[1:] kwargs.pop("bp_group") return register_middleware(middleware) else: return register_middleware
def middleware(self, *args, **kwargs): """ Create a blueprint middleware from a decorated function. :param args: Positional arguments to be used while invoking the middleware :param kwargs: optional keyword args that can be used with the middleware. """ def register_middleware(_middleware): future_middleware = FutureMiddleware(_middleware, args, kwargs) self.middlewares.append(future_middleware) return _middleware # Detect which way this was called, @middleware or @middleware('AT') if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): middleware = args[0] args = [] return register_middleware(middleware) else: if kwargs.get("bp_group") and callable(args[0]): middleware = args[0] args = args[1:] kwargs.pop("bp_group") return register_middleware(middleware) else: return register_middleware
[ "Create", "a", "blueprint", "middleware", "from", "a", "decorated", "function", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L312-L339
[ "def", "middleware", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "register_middleware", "(", "_middleware", ")", ":", "future_middleware", "=", "FutureMiddleware", "(", "_middleware", ",", "args", ",", "kwargs", ")", "self", "....
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Blueprint.exception
This method enables the process of creating a global exception handler for the current blueprint under question. :param args: List of Python exceptions to be caught by the handler :param kwargs: Additional optional arguments to be passed to the exception handler :return a decorated method to handle global exceptions for any route registered under this blueprint.
sanic/blueprints.py
def exception(self, *args, **kwargs): """ This method enables the process of creating a global exception handler for the current blueprint under question. :param args: List of Python exceptions to be caught by the handler :param kwargs: Additional optional arguments to be passed to the exception handler :return a decorated method to handle global exceptions for any route registered under this blueprint. """ def decorator(handler): exception = FutureException(handler, args, kwargs) self.exceptions.append(exception) return handler return decorator
def exception(self, *args, **kwargs): """ This method enables the process of creating a global exception handler for the current blueprint under question. :param args: List of Python exceptions to be caught by the handler :param kwargs: Additional optional arguments to be passed to the exception handler :return a decorated method to handle global exceptions for any route registered under this blueprint. """ def decorator(handler): exception = FutureException(handler, args, kwargs) self.exceptions.append(exception) return handler return decorator
[ "This", "method", "enables", "the", "process", "of", "creating", "a", "global", "exception", "handler", "for", "the", "current", "blueprint", "under", "question", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L341-L359
[ "def", "exception", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "handler", ")", ":", "exception", "=", "FutureException", "(", "handler", ",", "args", ",", "kwargs", ")", "self", ".", "exceptions", ".", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Blueprint.static
Create a blueprint static route from a decorated function. :param uri: endpoint at which the route will be accessible. :param file_or_directory: Static asset.
sanic/blueprints.py
def static(self, uri, file_or_directory, *args, **kwargs): """Create a blueprint static route from a decorated function. :param uri: endpoint at which the route will be accessible. :param file_or_directory: Static asset. """ name = kwargs.pop("name", "static") if not name.startswith(self.name + "."): name = "{}.{}".format(self.name, name) kwargs.update(name=name) strict_slashes = kwargs.get("strict_slashes") if strict_slashes is None and self.strict_slashes is not None: kwargs.update(strict_slashes=self.strict_slashes) static = FutureStatic(uri, file_or_directory, args, kwargs) self.statics.append(static)
def static(self, uri, file_or_directory, *args, **kwargs): """Create a blueprint static route from a decorated function. :param uri: endpoint at which the route will be accessible. :param file_or_directory: Static asset. """ name = kwargs.pop("name", "static") if not name.startswith(self.name + "."): name = "{}.{}".format(self.name, name) kwargs.update(name=name) strict_slashes = kwargs.get("strict_slashes") if strict_slashes is None and self.strict_slashes is not None: kwargs.update(strict_slashes=self.strict_slashes) static = FutureStatic(uri, file_or_directory, args, kwargs) self.statics.append(static)
[ "Create", "a", "blueprint", "static", "route", "from", "a", "decorated", "function", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L361-L377
[ "def", "static", "(", "self", ",", "uri", ",", "file_or_directory", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", ".", "pop", "(", "\"name\"", ",", "\"static\"", ")", "if", "not", "name", ".", "startswith", "(", "self", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Blueprint.get
Add an API URL under the **GET** *HTTP* method :param uri: URL to be tagged to **GET** method of *HTTP* :param host: Host IP or FQDN for the service to use :param strict_slashes: Instruct :class:`sanic.app.Sanic` to check if the request URLs need to terminate with a */* :param version: API Version :param name: Unique name that can be used to identify the Route :return: Object decorated with :func:`route` method
sanic/blueprints.py
def get( self, uri, host=None, strict_slashes=None, version=None, name=None ): """ Add an API URL under the **GET** *HTTP* method :param uri: URL to be tagged to **GET** method of *HTTP* :param host: Host IP or FQDN for the service to use :param strict_slashes: Instruct :class:`sanic.app.Sanic` to check if the request URLs need to terminate with a */* :param version: API Version :param name: Unique name that can be used to identify the Route :return: Object decorated with :func:`route` method """ return self.route( uri, methods=frozenset({"GET"}), host=host, strict_slashes=strict_slashes, version=version, name=name, )
def get( self, uri, host=None, strict_slashes=None, version=None, name=None ): """ Add an API URL under the **GET** *HTTP* method :param uri: URL to be tagged to **GET** method of *HTTP* :param host: Host IP or FQDN for the service to use :param strict_slashes: Instruct :class:`sanic.app.Sanic` to check if the request URLs need to terminate with a */* :param version: API Version :param name: Unique name that can be used to identify the Route :return: Object decorated with :func:`route` method """ return self.route( uri, methods=frozenset({"GET"}), host=host, strict_slashes=strict_slashes, version=version, name=name, )
[ "Add", "an", "API", "URL", "under", "the", "**", "GET", "**", "*", "HTTP", "*", "method" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L380-L401
[ "def", "get", "(", "self", ",", "uri", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "version", "=", "None", ",", "name", "=", "None", ")", ":", "return", "self", ".", "route", "(", "uri", ",", "methods", "=", "frozenset", "(",...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
add_status_code
Decorator used for adding exceptions to :class:`SanicException`.
sanic/exceptions.py
def add_status_code(code): """ Decorator used for adding exceptions to :class:`SanicException`. """ def class_decorator(cls): cls.status_code = code _sanic_exceptions[code] = cls return cls return class_decorator
def add_status_code(code): """ Decorator used for adding exceptions to :class:`SanicException`. """ def class_decorator(cls): cls.status_code = code _sanic_exceptions[code] = cls return cls return class_decorator
[ "Decorator", "used", "for", "adding", "exceptions", "to", ":", "class", ":", "SanicException", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/exceptions.py#L124-L134
[ "def", "add_status_code", "(", "code", ")", ":", "def", "class_decorator", "(", "cls", ")", ":", "cls", ".", "status_code", "=", "code", "_sanic_exceptions", "[", "code", "]", "=", "cls", "return", "cls", "return", "class_decorator" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
abort
Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided. :param status_code: The HTTP status code to return. :param message: The HTTP response body. Defaults to the messages in response.py for the given status code.
sanic/exceptions.py
def abort(status_code, message=None): """ Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided. :param status_code: The HTTP status code to return. :param message: The HTTP response body. Defaults to the messages in response.py for the given status code. """ if message is None: message = STATUS_CODES.get(status_code) # These are stored as bytes in the STATUS_CODES dict message = message.decode("utf8") sanic_exception = _sanic_exceptions.get(status_code, SanicException) raise sanic_exception(message=message, status_code=status_code)
def abort(status_code, message=None): """ Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided. :param status_code: The HTTP status code to return. :param message: The HTTP response body. Defaults to the messages in response.py for the given status code. """ if message is None: message = STATUS_CODES.get(status_code) # These are stored as bytes in the STATUS_CODES dict message = message.decode("utf8") sanic_exception = _sanic_exceptions.get(status_code, SanicException) raise sanic_exception(message=message, status_code=status_code)
[ "Raise", "an", "exception", "based", "on", "SanicException", ".", "Returns", "the", "HTTP", "response", "message", "appropriate", "for", "the", "given", "status", "code", "unless", "provided", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/exceptions.py#L284-L298
[ "def", "abort", "(", "status_code", ",", "message", "=", "None", ")", ":", "if", "message", "is", "None", ":", "message", "=", "STATUS_CODES", ".", "get", "(", "status_code", ")", "# These are stored as bytes in the STATUS_CODES dict", "message", "=", "message", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.add_task
Schedule a task to run later, after the loop has started. Different from asyncio.ensure_future in that it does not also return a future, and the actual ensure_future call is delayed until before server start. :param task: future, couroutine or awaitable
sanic/app.py
def add_task(self, task): """Schedule a task to run later, after the loop has started. Different from asyncio.ensure_future in that it does not also return a future, and the actual ensure_future call is delayed until before server start. :param task: future, couroutine or awaitable """ try: if callable(task): try: self.loop.create_task(task(self)) except TypeError: self.loop.create_task(task()) else: self.loop.create_task(task) except SanicException: @self.listener("before_server_start") def run(app, loop): if callable(task): try: loop.create_task(task(self)) except TypeError: loop.create_task(task()) else: loop.create_task(task)
def add_task(self, task): """Schedule a task to run later, after the loop has started. Different from asyncio.ensure_future in that it does not also return a future, and the actual ensure_future call is delayed until before server start. :param task: future, couroutine or awaitable """ try: if callable(task): try: self.loop.create_task(task(self)) except TypeError: self.loop.create_task(task()) else: self.loop.create_task(task) except SanicException: @self.listener("before_server_start") def run(app, loop): if callable(task): try: loop.create_task(task(self)) except TypeError: loop.create_task(task()) else: loop.create_task(task)
[ "Schedule", "a", "task", "to", "run", "later", "after", "the", "loop", "has", "started", ".", "Different", "from", "asyncio", ".", "ensure_future", "in", "that", "it", "does", "not", "also", "return", "a", "future", "and", "the", "actual", "ensure_future", ...
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L94-L120
[ "def", "add_task", "(", "self", ",", "task", ")", ":", "try", ":", "if", "callable", "(", "task", ")", ":", "try", ":", "self", ".", "loop", ".", "create_task", "(", "task", "(", "self", ")", ")", "except", "TypeError", ":", "self", ".", "loop", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.route
Decorate a function to be registered as a route :param uri: path of the URL :param methods: list or tuple of methods allowed :param host: :param strict_slashes: :param stream: :param version: :param name: user defined route name for url_for :return: decorated function
sanic/app.py
def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): """Decorate a function to be registered as a route :param uri: path of the URL :param methods: list or tuple of methods allowed :param host: :param strict_slashes: :param stream: :param version: :param name: user defined route name for url_for :return: decorated function """ # Fix case where the user did not prefix the URL with a / # and will probably get confused as to why it's not working if not uri.startswith("/"): uri = "/" + uri if stream: self.is_request_stream = True if strict_slashes is None: strict_slashes = self.strict_slashes def response(handler): args = list(signature(handler).parameters.keys()) if not args: raise ValueError( "Required parameter `request` missing " "in the {0}() route?".format(handler.__name__) ) if stream: handler.is_stream = stream self.router.add( uri=uri, methods=methods, handler=handler, host=host, strict_slashes=strict_slashes, version=version, name=name, ) return handler return response
def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): """Decorate a function to be registered as a route :param uri: path of the URL :param methods: list or tuple of methods allowed :param host: :param strict_slashes: :param stream: :param version: :param name: user defined route name for url_for :return: decorated function """ # Fix case where the user did not prefix the URL with a / # and will probably get confused as to why it's not working if not uri.startswith("/"): uri = "/" + uri if stream: self.is_request_stream = True if strict_slashes is None: strict_slashes = self.strict_slashes def response(handler): args = list(signature(handler).parameters.keys()) if not args: raise ValueError( "Required parameter `request` missing " "in the {0}() route?".format(handler.__name__) ) if stream: handler.is_stream = stream self.router.add( uri=uri, methods=methods, handler=handler, host=host, strict_slashes=strict_slashes, version=version, name=name, ) return handler return response
[ "Decorate", "a", "function", "to", "be", "registered", "as", "a", "route" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L149-L205
[ "def", "route", "(", "self", ",", "uri", ",", "methods", "=", "frozenset", "(", "{", "\"GET\"", "}", ")", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "stream", "=", "False", ",", "version", "=", "None", ",", "name", "=", "Non...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.websocket
Decorate a function to be registered as a websocket route :param uri: path of the URL :param subprotocols: optional list of str with supported subprotocols :param host: :return: decorated function
sanic/app.py
def websocket( self, uri, host=None, strict_slashes=None, subprotocols=None, name=None ): """Decorate a function to be registered as a websocket route :param uri: path of the URL :param subprotocols: optional list of str with supported subprotocols :param host: :return: decorated function """ self.enable_websocket() # Fix case where the user did not prefix the URL with a / # and will probably get confused as to why it's not working if not uri.startswith("/"): uri = "/" + uri if strict_slashes is None: strict_slashes = self.strict_slashes def response(handler): async def websocket_handler(request, *args, **kwargs): request.app = self if not getattr(handler, "__blueprintname__", False): request.endpoint = handler.__name__ else: request.endpoint = ( getattr(handler, "__blueprintname__", "") + handler.__name__ ) try: protocol = request.transport.get_protocol() except AttributeError: # On Python3.5 the Transport classes in asyncio do not # have a get_protocol() method as in uvloop protocol = request.transport._protocol ws = await protocol.websocket_handshake(request, subprotocols) # schedule the application handler # its future is kept in self.websocket_tasks in case it # needs to be cancelled due to the server being stopped fut = ensure_future(handler(request, ws, *args, **kwargs)) self.websocket_tasks.add(fut) try: await fut except (CancelledError, ConnectionClosed): pass finally: self.websocket_tasks.remove(fut) await ws.close() self.router.add( uri=uri, handler=websocket_handler, methods=frozenset({"GET"}), host=host, strict_slashes=strict_slashes, name=name, ) return handler return response
def websocket( self, uri, host=None, strict_slashes=None, subprotocols=None, name=None ): """Decorate a function to be registered as a websocket route :param uri: path of the URL :param subprotocols: optional list of str with supported subprotocols :param host: :return: decorated function """ self.enable_websocket() # Fix case where the user did not prefix the URL with a / # and will probably get confused as to why it's not working if not uri.startswith("/"): uri = "/" + uri if strict_slashes is None: strict_slashes = self.strict_slashes def response(handler): async def websocket_handler(request, *args, **kwargs): request.app = self if not getattr(handler, "__blueprintname__", False): request.endpoint = handler.__name__ else: request.endpoint = ( getattr(handler, "__blueprintname__", "") + handler.__name__ ) try: protocol = request.transport.get_protocol() except AttributeError: # On Python3.5 the Transport classes in asyncio do not # have a get_protocol() method as in uvloop protocol = request.transport._protocol ws = await protocol.websocket_handshake(request, subprotocols) # schedule the application handler # its future is kept in self.websocket_tasks in case it # needs to be cancelled due to the server being stopped fut = ensure_future(handler(request, ws, *args, **kwargs)) self.websocket_tasks.add(fut) try: await fut except (CancelledError, ConnectionClosed): pass finally: self.websocket_tasks.remove(fut) await ws.close() self.router.add( uri=uri, handler=websocket_handler, methods=frozenset({"GET"}), host=host, strict_slashes=strict_slashes, name=name, ) return handler return response
[ "Decorate", "a", "function", "to", "be", "registered", "as", "a", "websocket", "route", ":", "param", "uri", ":", "path", "of", "the", "URL", ":", "param", "subprotocols", ":", "optional", "list", "of", "str", "with", "supported", "subprotocols", ":", "par...
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L439-L499
[ "def", "websocket", "(", "self", ",", "uri", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "subprotocols", "=", "None", ",", "name", "=", "None", ")", ":", "self", ".", "enable_websocket", "(", ")", "# Fix case where the user did not pre...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.add_websocket_route
A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class that can handle the websocket request :param host: Host IP or FQDN details :param uri: URL path that will be mapped to the websocket handler :param strict_slashes: If the API endpoint needs to terminate with a "/" or not :param subprotocols: Subprotocols to be used with websocket handshake :param name: A unique name assigned to the URL so that it can be used with :func:`url_for` :return: Objected decorated by :func:`websocket`
sanic/app.py
def add_websocket_route( self, handler, uri, host=None, strict_slashes=None, subprotocols=None, name=None, ): """ A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class that can handle the websocket request :param host: Host IP or FQDN details :param uri: URL path that will be mapped to the websocket handler :param strict_slashes: If the API endpoint needs to terminate with a "/" or not :param subprotocols: Subprotocols to be used with websocket handshake :param name: A unique name assigned to the URL so that it can be used with :func:`url_for` :return: Objected decorated by :func:`websocket` """ if strict_slashes is None: strict_slashes = self.strict_slashes return self.websocket( uri, host=host, strict_slashes=strict_slashes, subprotocols=subprotocols, name=name, )(handler)
def add_websocket_route( self, handler, uri, host=None, strict_slashes=None, subprotocols=None, name=None, ): """ A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class that can handle the websocket request :param host: Host IP or FQDN details :param uri: URL path that will be mapped to the websocket handler :param strict_slashes: If the API endpoint needs to terminate with a "/" or not :param subprotocols: Subprotocols to be used with websocket handshake :param name: A unique name assigned to the URL so that it can be used with :func:`url_for` :return: Objected decorated by :func:`websocket` """ if strict_slashes is None: strict_slashes = self.strict_slashes return self.websocket( uri, host=host, strict_slashes=strict_slashes, subprotocols=subprotocols, name=name, )(handler)
[ "A", "helper", "method", "to", "register", "a", "function", "as", "a", "websocket", "route", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L501-L535
[ "def", "add_websocket_route", "(", "self", ",", "handler", ",", "uri", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "subprotocols", "=", "None", ",", "name", "=", "None", ",", ")", ":", "if", "strict_slashes", "is", "None", ":", "...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd