text
stringlengths
81
112k
A helper utility to send the page output from :attr:`paginator` to the destination. async def send_pages(self): """A helper utility to send the page output from :attr:`paginator` to the destination.""" destination = self.get_destination() for page in self.paginator.pages: await destination.send(page)
Adds the minified bot heading with commands to the output. The formatting should be added to the :attr:`paginator`. The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands that belong to the heading. heading: :class:`str` The heading to add to the line. def add_bot_commands_formatting(self, commands, heading): """Adds the minified bot heading with commands to the output. The formatting should be added to the :attr:`paginator`. The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands that belong to the heading. heading: :class:`str` The heading to add to the line. """ if commands: # U+2002 Middle Dot joined = '\u2002'.join(c.name for c in commands) self.paginator.add_line('__**%s**__' % heading) self.paginator.add_line(joined)
Adds formatting information on a subcommand. The formatting should be added to the :attr:`paginator`. The default implementation is the prefix and the :attr:`Command.qualified_name` optionally followed by an En dash and the command's :attr:`Command.short_doc`. Parameters ----------- command: :class:`Command` The command to show information of. def add_subcommand_formatting(self, command): """Adds formatting information on a subcommand. The formatting should be added to the :attr:`paginator`. The default implementation is the prefix and the :attr:`Command.qualified_name` optionally followed by an En dash and the command's :attr:`Command.short_doc`. Parameters ----------- command: :class:`Command` The command to show information of. """ fmt = '{0}{1} \N{EN DASH} {2}' if command.short_doc else '{0}{1}' self.paginator.add_line(fmt.format(self.clean_prefix, command.qualified_name, command.short_doc))
Adds the formatting information on a command's aliases. The formatting should be added to the :attr:`paginator`. The default implementation is the :attr:`aliases_heading` bolded followed by a comma separated list of aliases. This is not called if there are no aliases to format. Parameters ----------- aliases: Sequence[:class:`str`] A list of aliases to format. def add_aliases_formatting(self, aliases): """Adds the formatting information on a command's aliases. The formatting should be added to the :attr:`paginator`. The default implementation is the :attr:`aliases_heading` bolded followed by a comma separated list of aliases. This is not called if there are no aliases to format. Parameters ----------- aliases: Sequence[:class:`str`] A list of aliases to format. """ self.paginator.add_line('**%s** %s' % (self.aliases_heading, ', '.join(aliases)), empty=True)
A utility function to format commands and groups. Parameters ------------ command: :class:`Command` The command to format. def add_command_formatting(self, command): """A utility function to format commands and groups. Parameters ------------ command: :class:`Command` The command to format. """ if command.description: self.paginator.add_line(command.description, empty=True) signature = self.get_command_signature(command) if command.aliases: self.paginator.add_line(signature) self.add_aliases_formatting(command.aliases) else: self.paginator.add_line(signature, empty=True) if command.help: try: self.paginator.add_line(command.help, empty=True) except RuntimeError: for line in command.help.splitlines(): self.paginator.add_line(line) self.paginator.add_line()
|coro| Disconnects this voice client from voice. async def disconnect(self, *, force=False): """|coro| Disconnects this voice client from voice. """ if not force and not self.is_connected(): return self.stop() self._connected.clear() try: if self.ws: await self.ws.close() await self.terminate_handshake(remove=True) finally: if self.socket: self.socket.close()
|coro| Moves you to a different voice channel. Parameters ----------- channel: :class:`abc.Snowflake` The channel to move to. Must be a voice channel. async def move_to(self, channel): """|coro| Moves you to a different voice channel. Parameters ----------- channel: :class:`abc.Snowflake` The channel to move to. Must be a voice channel. """ guild_id, _ = self.channel._get_voice_state_pair() await self.main_ws.voice_state(guild_id, channel.id)
Plays an :class:`AudioSource`. The finalizer, ``after`` is called after the source has been exhausted or an error occurred. If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. Parameters ----------- source: :class:`AudioSource` The audio source we're reading from. after The finalizer that is called after the stream is exhausted. All exceptions it throws are silently discarded. This function must have a single parameter, ``error``, that denotes an optional exception that was raised during playing. Raises ------- ClientException Already playing audio or not connected. TypeError source is not a :class:`AudioSource` or after is not a callable. def play(self, source, *, after=None): """Plays an :class:`AudioSource`. The finalizer, ``after`` is called after the source has been exhausted or an error occurred. If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. Parameters ----------- source: :class:`AudioSource` The audio source we're reading from. after The finalizer that is called after the stream is exhausted. All exceptions it throws are silently discarded. This function must have a single parameter, ``error``, that denotes an optional exception that was raised during playing. Raises ------- ClientException Already playing audio or not connected. TypeError source is not a :class:`AudioSource` or after is not a callable. """ if not self.is_connected(): raise ClientException('Not connected to voice.') if self.is_playing(): raise ClientException('Already playing audio.') if not isinstance(source, AudioSource): raise TypeError('source must an AudioSource not {0.__class__.__name__}'.format(source)) self._player = AudioPlayer(source, self, after=after) self._player.start()
Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool Indicates if ``data`` should be encoded into Opus. Raises ------- ClientException You are not connected. OpusError Encoding the data failed. def send_audio_packet(self, data, *, encode=True): """Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool Indicates if ``data`` should be encoded into Opus. Raises ------- ClientException You are not connected. OpusError Encoding the data failed. """ self.checked_add('sequence', 1, 65535) if encode: encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME) else: encoded_data = data packet = self._get_voice_packet(encoded_data) try: self.socket.sendto(packet, (self.endpoint_ip, self.voice_port)) except BlockingIOError: log.warning('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp) self.checked_add('timestamp', self.encoder.SAMPLES_PER_FRAME, 4294967295)
|coro| The default error handler provided by the client. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. Check :func:`discord.on_error` for more details. async def on_error(self, event_method, *args, **kwargs): """|coro| The default error handler provided by the client. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. Check :func:`discord.on_error` for more details. """ print('Ignoring exception in {}'.format(event_method), file=sys.stderr) traceback.print_exc()
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. 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.') await self._connection.request_offline_members(guilds)
|coro| Logs in the client with the specified credentials. This function can be used in two different ways. .. warning:: Logging on with a user token is against the Discord `Terms of Service <https://support.discordapp.com/hc/en-us/articles/115002192352>`_ and doing so might potentially get your account banned. Use this at your own risk. Parameters ----------- token: :class:`str` The authentication token. Do not prefix this token with anything as the library will do it for you. bot: :class:`bool` Keyword argument that specifies if the account logging on is a bot token or not. Raises ------ LoginFailure The wrong credentials are passed. HTTPException An unknown HTTP related error occurred, usually when it isn't 200 or the known incorrect credentials passing status code. async def login(self, token, *, bot=True): """|coro| Logs in the client with the specified credentials. This function can be used in two different ways. .. warning:: Logging on with a user token is against the Discord `Terms of Service <https://support.discordapp.com/hc/en-us/articles/115002192352>`_ and doing so might potentially get your account banned. Use this at your own risk. Parameters ----------- token: :class:`str` The authentication token. Do not prefix this token with anything as the library will do it for you. bot: :class:`bool` Keyword argument that specifies if the account logging on is a bot token or not. Raises ------ LoginFailure The wrong credentials are passed. HTTPException An unknown HTTP related error occurred, usually when it isn't 200 or the known incorrect credentials passing status code. """ log.info('logging in using static token') await self.http.static_login(token, bot=bot) self._connection.is_bot = bot
|coro| Creates a websocket connection and lets the websocket listen to messages from discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated. Parameters ----------- reconnect: :class:`bool` If we should attempt reconnecting, either due to internet failure or a specific failure on Discord's part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens). Raises ------- GatewayNotFound If the gateway to connect to discord is not found. Usually if this is thrown then there is a discord API outage. ConnectionClosed The websocket connection has been terminated. async def connect(self, *, reconnect=True): """|coro| Creates a websocket connection and lets the websocket listen to messages from discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated. Parameters ----------- reconnect: :class:`bool` If we should attempt reconnecting, either due to internet failure or a specific failure on Discord's part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens). Raises ------- GatewayNotFound If the gateway to connect to discord is not found. Usually if this is thrown then there is a discord API outage. ConnectionClosed The websocket connection has been terminated. """ backoff = ExponentialBackoff() while not self.is_closed(): try: await self._connect() except (OSError, HTTPException, GatewayNotFound, ConnectionClosed, aiohttp.ClientError, asyncio.TimeoutError, websockets.InvalidHandshake, websockets.WebSocketProtocolError) as exc: self.dispatch('disconnect') if not reconnect: await self.close() if isinstance(exc, ConnectionClosed) and exc.code == 1000: # clean close, don't re-raise this return raise if self.is_closed(): return # We should only get this when an unhandled close code happens, # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc) # sometimes, discord sends us 1000 for unknown reasons so we should reconnect # regardless and rely on is_closed instead if isinstance(exc, ConnectionClosed): if exc.code != 1000: await self.close() raise retry = backoff.delay() log.exception("Attempting a reconnect in %.2fs", retry) await asyncio.sleep(retry, loop=self.loop)
|coro| Closes the connection to discord. async def close(self): """|coro| Closes the connection to discord. """ if self._closed: return await self.http.close() self._closed = True for voice in self.voice_clients: try: await voice.disconnect() except Exception: # if an error happens during disconnects, disregard it. pass if self.ws is not None and self.ws.open: await self.ws.close() self._ready.clear()
Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed` and :meth:`.is_ready` both return ``False`` along with the bot's internal cache cleared. def clear(self): """Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed` and :meth:`.is_ready` both return ``False`` along with the bot's internal cache cleared. """ self._closed = False self._ready.clear() self._connection.clear() self.http.recreate()
|coro| A shorthand coroutine for :meth:`login` + :meth:`connect`. async def start(self, *args, **kwargs): """|coro| A shorthand coroutine for :meth:`login` + :meth:`connect`. """ bot = kwargs.pop('bot', True) reconnect = kwargs.pop('reconnect', True) await self.login(*args, bot=bot) await self.connect(reconnect=reconnect)
A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use :meth:`start` coroutine or :meth:`connect` + :meth:`login`. Roughly Equivalent to: :: try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # cancel all tasks lingering finally: loop.close() .. warning:: This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns. def run(self, *args, **kwargs): """A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use :meth:`start` coroutine or :meth:`connect` + :meth:`login`. Roughly Equivalent to: :: try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # cancel all tasks lingering finally: loop.close() .. warning:: This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns. """ async def runner(): try: await self.start(*args, **kwargs) finally: await self.close() try: self.loop.run_until_complete(runner()) except KeyboardInterrupt: log.info('Received signal to terminate bot and event loop.') finally: log.info('Cleaning up tasks.') _cleanup_loop(self.loop)
|coro| Waits for a WebSocket event to be dispatched. This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way. The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default, it does not timeout. Note that this does propagate the :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for ease of use. In case the event returns multiple arguments, a :class:`tuple` containing those arguments is returned instead. Please check the :ref:`documentation <discord-api-events>` for a list of events and their parameters. This function returns the **first event that meets the requirements**. Examples --------- Waiting for a user reply: :: @client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send('Hello {.author}!'.format(msg)) Waiting for a thumbs up reaction from the message author: :: @client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('\N{THUMBS DOWN SIGN}') else: await channel.send('\N{THUMBS UP SIGN}') Parameters ------------ event: :class:`str` The event name, similar to the :ref:`event reference <discord-api-events>`, but without the ``on_`` prefix, to wait for. check: Optional[predicate] A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for. timeout: Optional[:class:`float`] The number of seconds to wait before timing out and raising :exc:`asyncio.TimeoutError`. Raises ------- asyncio.TimeoutError If a timeout is provided and it was reached. Returns -------- Any Returns no arguments, a single argument, or a :class:`tuple` of multiple arguments that mirrors the parameters passed in the :ref:`event reference <discord-api-events>`. def wait_for(self, event, *, check=None, timeout=None): """|coro| Waits for a WebSocket event to be dispatched. This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way. The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default, it does not timeout. Note that this does propagate the :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for ease of use. In case the event returns multiple arguments, a :class:`tuple` containing those arguments is returned instead. Please check the :ref:`documentation <discord-api-events>` for a list of events and their parameters. This function returns the **first event that meets the requirements**. Examples --------- Waiting for a user reply: :: @client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send('Hello {.author}!'.format(msg)) Waiting for a thumbs up reaction from the message author: :: @client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('\N{THUMBS DOWN SIGN}') else: await channel.send('\N{THUMBS UP SIGN}') Parameters ------------ event: :class:`str` The event name, similar to the :ref:`event reference <discord-api-events>`, but without the ``on_`` prefix, to wait for. check: Optional[predicate] A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for. timeout: Optional[:class:`float`] The number of seconds to wait before timing out and raising :exc:`asyncio.TimeoutError`. Raises ------- asyncio.TimeoutError If a timeout is provided and it was reached. Returns -------- Any Returns no arguments, a single argument, or a :class:`tuple` of multiple arguments that mirrors the parameters passed in the :ref:`event reference <discord-api-events>`. """ future = self.loop.create_future() if check is None: def _check(*args): return True check = _check ev = event.lower() try: listeners = self._listeners[ev] except KeyError: listeners = [] self._listeners[ev] = listeners listeners.append((future, check)) return asyncio.wait_for(future, timeout, loop=self.loop)
A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api-events>`. The events must be a |corourl|_, if not, :exc:`TypeError` is raised. Example --------- .. code-block:: python3 @client.event async def on_ready(): print('Ready!') Raises -------- TypeError The coroutine passed is not actually a coroutine. def event(self, coro): """A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api-events>`. The events must be a |corourl|_, if not, :exc:`TypeError` is raised. Example --------- .. code-block:: python3 @client.event async def on_ready(): print('Ready!') Raises -------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('event registered must be a coroutine function') setattr(self, coro.__name__, coro) log.debug('%s has successfully been registered as an event', coro.__name__) return coro
|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 --------- .. code-block:: python3 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. Raises ------ InvalidArgument If the ``activity`` parameter is not the proper type. async def change_presence(self, *, activity=None, status=None, afk=False): """|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 --------- .. code-block:: python3 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. Raises ------ InvalidArgument If the ``activity`` parameter is not the 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) await self.ws.change_presence(activity=activity, status=status, afk=afk) for guild in self._connection.guilds: me = guild.me if me is None: continue me.activities = (activity,) me.status = status_enum
|coro| Retrieves an :class:`.AsyncIterator` that enables receiving your guilds. .. note:: Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`, :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`. .. note:: This method is an API call. For general usage, consider :attr:`guilds` instead. All parameters are optional. Parameters ----------- limit: Optional[:class:`int`] The number of guilds to retrieve. If ``None``, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 100. before: :class:`.abc.Snowflake` or :class:`datetime.datetime` Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. after: :class:`.abc.Snowflake` or :class:`datetime.datetime` Retrieve guilds after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. Raises ------ HTTPException Getting the guilds failed. Yields -------- :class:`.Guild` The guild with the guild data parsed. Examples --------- Usage :: async for guild in client.fetch_guilds(limit=150): print(guild.name) Flattening into a list :: guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild... def fetch_guilds(self, *, limit=100, before=None, after=None): """|coro| Retrieves an :class:`.AsyncIterator` that enables receiving your guilds. .. note:: Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`, :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`. .. note:: This method is an API call. For general usage, consider :attr:`guilds` instead. All parameters are optional. Parameters ----------- limit: Optional[:class:`int`] The number of guilds to retrieve. If ``None``, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 100. before: :class:`.abc.Snowflake` or :class:`datetime.datetime` Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. after: :class:`.abc.Snowflake` or :class:`datetime.datetime` Retrieve guilds after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. Raises ------ HTTPException Getting the guilds failed. Yields -------- :class:`.Guild` The guild with the guild data parsed. Examples --------- Usage :: async for guild in client.fetch_guilds(limit=150): print(guild.name) Flattening into a list :: guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild... """ return GuildIterator(self, limit=limit, before=before, after=after)
|coro| Retrieves a :class:`.Guild` from an ID. .. note:: Using this, you will not receive :attr:`.Guild.channels`, :class:`.Guild.members`, :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`. .. note:: This method is an API call. For general usage, consider :meth:`get_guild` instead. Parameters ----------- guild_id: :class:`int` The guild's ID to fetch from. Raises ------ Forbidden You do not have access to the guild. HTTPException Getting the guild failed. Returns -------- :class:`.Guild` The guild from the ID. async def fetch_guild(self, guild_id): """|coro| Retrieves a :class:`.Guild` from an ID. .. note:: Using this, you will not receive :attr:`.Guild.channels`, :class:`.Guild.members`, :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`. .. note:: This method is an API call. For general usage, consider :meth:`get_guild` instead. Parameters ----------- guild_id: :class:`int` The guild's ID to fetch from. Raises ------ Forbidden You do not have access to the guild. HTTPException Getting the guild failed. Returns -------- :class:`.Guild` The guild from the ID. """ data = await self.http.get_guild(guild_id) return Guild(data=data, state=self._connection)
|coro| Creates a :class:`.Guild`. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`VoiceRegion` The region for the voice communication server. Defaults to :attr:`.VoiceRegion.us_west`. icon: :class:`bytes` The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected. Raises ------ HTTPException Guild creation failed. InvalidArgument Invalid icon image format given. Must be PNG or JPG. Returns ------- :class:`.Guild` The guild created. This is not the same guild that is added to cache. async def create_guild(self, name, region=None, icon=None): """|coro| Creates a :class:`.Guild`. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`VoiceRegion` The region for the voice communication server. Defaults to :attr:`.VoiceRegion.us_west`. icon: :class:`bytes` The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected. Raises ------ HTTPException Guild creation failed. InvalidArgument Invalid icon image format given. Must be PNG or JPG. Returns ------- :class:`.Guild` The guild created. This is not the same guild that is added to cache. """ if icon is not None: icon = utils._bytes_to_base64_data(icon) if region is None: region = VoiceRegion.us_west.value else: region = region.value data = await self.http.create_guild(name, region, icon) return Guild(data=data, state=self._connection)
|coro| Gets an :class:`.Invite` from a discord.gg URL or ID. .. note:: If the invite is for a guild you have not joined, the guild and channel attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and :class:`PartialInviteChannel` respectively. Parameters ----------- url: :class:`str` The discord invite ID or URL (must be a discord.gg URL). with_counts: :class:`bool` Whether to include count information in the invite. This fills the :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count` fields. Raises ------- NotFound The invite has expired or is invalid. HTTPException Getting the invite failed. Returns -------- :class:`.Invite` The invite from the URL/ID. async def fetch_invite(self, url, *, with_counts=True): """|coro| Gets an :class:`.Invite` from a discord.gg URL or ID. .. note:: If the invite is for a guild you have not joined, the guild and channel attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and :class:`PartialInviteChannel` respectively. Parameters ----------- url: :class:`str` The discord invite ID or URL (must be a discord.gg URL). with_counts: :class:`bool` Whether to include count information in the invite. This fills the :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count` fields. Raises ------- NotFound The invite has expired or is invalid. HTTPException Getting the invite failed. Returns -------- :class:`.Invite` The invite from the URL/ID. """ invite_id = utils.resolve_invite(url) data = await self.http.get_invite(invite_id, with_counts=with_counts) return Invite.from_incomplete(state=self._connection, data=data)
|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. 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| 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. 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| Retrieve's the bot's application information. Raises ------- HTTPException Retrieving the information failed somehow. Returns -------- :class:`.AppInfo` A namedtuple representing the application info. 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| 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. 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| 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. 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| 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. 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)
:class:`Asset`: The same operation as :meth:`Guild.icon_url_as`. 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.banner_url_as`. 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.splash_url_as`. 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)
|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. 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| 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. 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)
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. 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 channel IDs matched with the syntax of <#channel_id> in the message 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 role IDs matched with the syntax of <@&role_id> in the message 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 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. 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)
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. 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)
|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. 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| 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. 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| 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. 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| 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. 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| 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. 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| 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. 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| 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. 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| 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. 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)
Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity if applicable. 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 small image asset of this activity if applicable. 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)
:class:`str`: The album cover image URL from Spotify's CDN. 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
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 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
|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. 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)
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. 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)
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`. 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
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. 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
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') 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]
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__``. 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
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 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
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. 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
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. 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)
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. 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)
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. 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)
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. 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
|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. 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
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. 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
|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. 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| 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. 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)
: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. 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
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. 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
Similar to :attr:`Client.user` except an instance of :class:`Member`. This is essentially used to get the member version of yourself. 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)
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. 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:`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. 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
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. 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
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``. 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)
Gets the @everyone role that all members have by default. 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())
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. 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 the shard ID for this guild if applicable. 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 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. 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)
|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. 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| 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. 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| 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. 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| 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. 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| 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. 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| 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. 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| 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. 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]
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``. 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']
|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. 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| 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. 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
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. 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]
|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. 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)
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. 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)
|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. 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| 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. 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| 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. 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| 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. 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| 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. 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| 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. 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)
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. 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)
|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. 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)