Python discord.ext.commands.Context() Examples

The following are 30 code examples of discord.ext.commands.Context(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord.ext.commands , or try the search function .
Example #1
Source File: wolfram.py    From bot with MIT License 1111 votes vote down vote up
def send_embed(
        ctx: Context,
        message_txt: str,
        colour: int = Colours.soft_red,
        footer: str = None,
        img_url: str = None,
        f: discord.File = None
) -> None:
    """Generate & send a response embed with Wolfram as the author."""
    embed = Embed(colour=colour)
    embed.description = message_txt
    embed.set_author(name="Wolfram Alpha",
                     icon_url=WOLF_IMAGE,
                     url="https://www.wolframalpha.com/")
    if footer:
        embed.set_footer(text=footer)

    if img_url:
        embed.set_image(url=img_url)

    await ctx.send(embed=embed, file=f) 
Example #2
Source File: maths.py    From cyberdisc-bot with MIT License 35 votes vote down vote up
def challenge(self, ctx: Context, number: int = 1):
        """Show the provided challenge number."""
        challenge = await get_challenge(number)
        description = challenge["challenge"]
        if len(description) > 2048:
            description = description[:2045] + "..."
        embed = Embed(
            title=challenge["title"],
            colour=Colour(0xE5E242),
            url=f"https://www.kingsmathsschool.com/weekly-maths-challenge/{challenge['slug']}",
            description=description,
        )

        embed.set_image(url=challenge["image"])
        embed.set_thumbnail(
            url="https://pbs.twimg.com/profile_images/502115424121528320/hTQzj_-R.png"
        )
        embed.set_author(name="King's Maths School")
        embed.set_footer(
            text=f"Challenge Released: {challenge['published']} | Category: {challenge['category']}"
        )
        return await ctx.send(embed=embed) 
Example #3
Source File: off_topic_names.py    From bot with MIT License 11 votes vote down vote up
def search_command(self, ctx: Context, *, query: OffTopicName) -> None:
        """Search for an off-topic name."""
        result = await self.bot.api_client.get('bot/off-topic-channel-names')
        in_matches = {name for name in result if query in name}
        close_matches = difflib.get_close_matches(query, result, n=10, cutoff=0.70)
        lines = sorted(f"• {name}" for name in in_matches.union(close_matches))
        embed = Embed(
            title="Query results",
            colour=Colour.blue()
        )

        if lines:
            await LinePaginator.paginate(lines, ctx, embed, max_size=400, empty=False)
        else:
            embed.description = "Nothing found."
            await ctx.send(embed=embed) 
Example #4
Source File: reminders.py    From bot with MIT License 6 votes vote down vote up
def edit_reminder_content(self, ctx: Context, id_: int, *, content: str) -> None:
        """Edit one of your reminder's content."""
        # Send the request to update the reminder in the database
        reminder = await self.bot.api_client.patch(
            'bot/reminders/' + str(id_),
            json={'content': content}
        )

        # Parse the reminder expiration back into a datetime for the confirmation message
        expiration = isoparse(reminder['expiration']).replace(tzinfo=None)

        # Send a confirmation message to the channel
        await self._send_confirmation(
            ctx,
            on_success="That reminder has been edited successfully!",
            reminder_id=id_,
            delivery_dt=expiration,
        )
        await self._reschedule_reminder(reminder) 
Example #5
Source File: tags.py    From bot with MIT License 6 votes vote down vote up
def _send_matching_tags(self, ctx: Context, keywords: str, matching_tags: list) -> None:
        """Send the result of matching tags to user."""
        if not matching_tags:
            pass
        elif len(matching_tags) == 1:
            await ctx.send(embed=Embed().from_dict(matching_tags[0]['embed']))
        else:
            is_plural = keywords.strip().count(' ') > 0 or keywords.strip().count(',') > 0
            embed = Embed(
                title=f"Here are the tags containing the given keyword{'s' * is_plural}:",
                description='\n'.join(tag['title'] for tag in matching_tags[:10])
            )
            await LinePaginator.paginate(
                sorted(f"**»**   {tag['title']}" for tag in matching_tags),
                ctx,
                embed,
                footer_text=FOOTER_TEXT,
                empty=False,
                max_lines=15
            ) 
Example #6
Source File: help_channels.py    From bot with MIT License 6 votes vote down vote up
def close_command(self, ctx: commands.Context) -> None:
        """
        Make the current in-use help channel dormant.

        Make the channel dormant if the user passes the `dormant_check`,
        delete the message that invoked this,
        and reset the send permissions cooldown for the user who started the session.
        """
        log.trace("close command invoked; checking if the channel is in-use.")
        if ctx.channel.category == self.in_use_category:
            if await self.dormant_check(ctx):

                # Remove the claimant and the cooldown role
                await self.help_channel_claimants.delete(ctx.channel.id)
                await self.remove_cooldown_role(ctx.author)

                # Ignore missing task when cooldown has passed but the channel still isn't dormant.
                self.cancel_task(ctx.author.id, ignore_missing=True)

                await self.move_to_dormant(ctx.channel, "command")
                self.cancel_task(ctx.channel.id)
        else:
            log.debug(f"{ctx.author} invoked command 'dormant' outside an in-use help channel") 
Example #7
Source File: error_handler.py    From bot with MIT License 6 votes vote down vote up
def handle_api_error(ctx: Context, e: ResponseCodeError) -> None:
        """Send an error message in `ctx` for ResponseCodeError and log it."""
        if e.status == 404:
            await ctx.send("There does not seem to be anything matching your query.")
            log.debug(f"API responded with 404 for command {ctx.command}")
            ctx.bot.stats.incr("errors.api_error_404")
        elif e.status == 400:
            content = await e.response.json()
            log.debug(f"API responded with 400 for command {ctx.command}: %r.", content)
            await ctx.send("According to the API, your request is malformed.")
            ctx.bot.stats.incr("errors.api_error_400")
        elif 500 <= e.status < 600:
            await ctx.send("Sorry, there seems to be an internal issue with the API.")
            log.warning(f"API responded with {e.status} for command {ctx.command}")
            ctx.bot.stats.incr("errors.api_internal_server_error")
        else:
            await ctx.send(f"Got an unexpected status code from the API (`{e.status}`).")
            log.warning(f"Unexpected API response for command {ctx.command}: {e.status}")
            ctx.bot.stats.incr(f"errors.api_error_{e.status}") 
Example #8
Source File: verification.py    From bot with MIT License 6 votes vote down vote up
def unsubscribe_command(self, ctx: Context, *_) -> None:  # We don't actually care about the args
        """Unsubscribe from announcement notifications by removing the role from yourself."""
        has_role = False

        for role in ctx.author.roles:
            if role.id == constants.Roles.announcements:
                has_role = True
                break

        if not has_role:
            await ctx.send(f"{ctx.author.mention} You're already unsubscribed!")
            return

        log.debug(f"{ctx.author} called !unsubscribe. Removing the 'Announcements' role.")
        await ctx.author.remove_roles(Object(constants.Roles.announcements), reason="Unsubscribed from announcements")

        log.trace(f"Deleting the message posted by {ctx.author}.")

        await ctx.send(
            f"{ctx.author.mention} Unsubscribed from <#{constants.Channels.announcements}> notifications."
        )

    # This cannot be static (must have a __func__ attribute). 
Example #9
Source File: verification.py    From bot with MIT License 6 votes vote down vote up
def subscribe_command(self, ctx: Context, *_) -> None:  # We don't actually care about the args
        """Subscribe to announcement notifications by assigning yourself the role."""
        has_role = False

        for role in ctx.author.roles:
            if role.id == constants.Roles.announcements:
                has_role = True
                break

        if has_role:
            await ctx.send(f"{ctx.author.mention} You're already subscribed!")
            return

        log.debug(f"{ctx.author} called !subscribe. Assigning the 'Announcements' role.")
        await ctx.author.add_roles(Object(constants.Roles.announcements), reason="Subscribed to announcements")

        log.trace(f"Deleting the message posted by {ctx.author}.")

        await ctx.send(
            f"{ctx.author.mention} Subscribed to <#{constants.Channels.announcements}> notifications.",
        ) 
Example #10
Source File: wolfram.py    From bot with MIT License 6 votes vote down vote up
def wolfram_cut_command(self, ctx: Context, *, query: str) -> None:
        """
        Requests a drawn image of given query.

        Keywords worth noting are, "like curve", "curve", "graph", "pokemon", etc.
        """
        pages = await get_pod_pages(ctx, self.bot, query)

        if not pages:
            return

        if len(pages) >= 2:
            page = pages[1]
        else:
            page = pages[0]

        await send_embed(ctx, page[0], colour=Colours.soft_orange, img_url=page[1]) 
Example #11
Source File: extensions.py    From bot with MIT License 6 votes vote down vote up
def reload_command(self, ctx: Context, *extensions: Extension) -> None:
        r"""
        Reload extensions given their fully qualified or unqualified names.

        If an extension fails to be reloaded, it will be rolled-back to the prior working state.

        If '\*' is given as the name, all currently loaded extensions will be reloaded.
        If '\*\*' is given as the name, all extensions, including unloaded ones, will be reloaded.
        """  # noqa: W605
        if not extensions:
            await ctx.send_help(ctx.command)
            return

        if "**" in extensions:
            extensions = EXTENSIONS
        elif "*" in extensions:
            extensions = set(self.bot.extensions.keys()) | set(extensions)
            extensions.remove("*")

        msg = self.batch_manage(Action.RELOAD, *extensions)

        await ctx.send(msg) 
Example #12
Source File: extensions.py    From bot with MIT License 6 votes vote down vote up
def unload_command(self, ctx: Context, *extensions: Extension) -> None:
        r"""
        Unload currently loaded extensions given their fully qualified or unqualified names.

        If '\*' or '\*\*' is given as the name, all loaded extensions will be unloaded.
        """  # noqa: W605
        if not extensions:
            await ctx.send_help(ctx.command)
            return

        blacklisted = "\n".join(UNLOAD_BLACKLIST & set(extensions))

        if blacklisted:
            msg = f":x: The following extension(s) may not be unloaded:```{blacklisted}```"
        else:
            if "*" in extensions or "**" in extensions:
                extensions = set(self.bot.extensions.keys()) - UNLOAD_BLACKLIST

            msg = self.batch_manage(Action.UNLOAD, *extensions)

        await ctx.send(msg) 
Example #13
Source File: off_topic_names.py    From bot with MIT License 5 votes vote down vote up
def delete_command(self, ctx: Context, *, name: OffTopicName) -> None:
        """Removes a off-topic name from the rotation."""
        await self.bot.api_client.delete(f'bot/off-topic-channel-names/{name}')

        log.info(f"{ctx.author} deleted the off-topic channel name '{name}'")
        await ctx.send(f":ok_hand: Removed `{name}` from the names list.") 
Example #14
Source File: defcon.py    From bot with MIT License 5 votes vote down vote up
def defcon_group(self, ctx: Context) -> None:
        """Check the DEFCON status or run a subcommand."""
        await ctx.send_help(ctx.command) 
Example #15
Source File: off_topic_names.py    From bot with MIT License 5 votes vote down vote up
def list_command(self, ctx: Context) -> None:
        """
        Lists all currently known off-topic channel names in a paginator.

        Restricted to Moderator and above to not spoil the surprise.
        """
        result = await self.bot.api_client.get('bot/off-topic-channel-names')
        lines = sorted(f"• {name}" for name in result)
        embed = Embed(
            title=f"Known off-topic names (`{len(result)}` total)",
            colour=Colour.blue()
        )
        if result:
            await LinePaginator.paginate(lines, ctx, embed, max_size=400, empty=False)
        else:
            embed.description = "Hmmm, seems like there's nothing here yet."
            await ctx.send(embed=embed) 
Example #16
Source File: off_topic_names.py    From bot with MIT License 5 votes vote down vote up
def _add_name(self, ctx: Context, name: str) -> None:
        """Adds an off-topic channel name to the site storage."""
        await self.bot.api_client.post('bot/off-topic-channel-names', params={'name': name})

        log.info(f"{ctx.author} added the off-topic channel name '{name}'")
        await ctx.send(f":ok_hand: Added `{name}` to the names list.") 
Example #17
Source File: bot.py    From bot with MIT License 5 votes vote down vote up
def about_command(self, ctx: Context) -> None:
        """Get information about the bot."""
        embed = Embed(
            description="A utility bot designed just for the Python server! Try `!help` for more info.",
            url="https://github.com/python-discord/bot"
        )

        embed.add_field(name="Total Users", value=str(len(self.bot.get_guild(Guild.id).members)))
        embed.set_author(
            name="Python Bot",
            url="https://github.com/python-discord/bot",
            icon_url=URLs.bot_avatar
        )

        await ctx.send(embed=embed) 
Example #18
Source File: bot.py    From bot with MIT License 5 votes vote down vote up
def echo_command(self, ctx: Context, channel: Optional[TextChannel], *, text: str) -> None:
        """Repeat the given message in either a specified channel or the current channel."""
        if channel is None:
            await ctx.send(text)
        else:
            await channel.send(text) 
Example #19
Source File: error_handler.py    From bot with MIT License 5 votes vote down vote up
def try_silence(self, ctx: Context) -> bool:
        """
        Attempt to invoke the silence or unsilence command if invoke with matches a pattern.

        Respecting the checks if:
        * invoked with `shh+` silence channel for amount of h's*2 with max of 15.
        * invoked with `unshh+` unsilence channel
        Return bool depending on success of command.
        """
        command = ctx.invoked_with.lower()
        silence_command = self.bot.get_command("silence")
        ctx.invoked_from_error_handler = True
        try:
            if not await silence_command.can_run(ctx):
                log.debug("Cancelling attempt to invoke silence/unsilence due to failed checks.")
                return False
        except errors.CommandError:
            log.debug("Cancelling attempt to invoke silence/unsilence due to failed checks.")
            return False
        if command.startswith("shh"):
            await ctx.invoke(silence_command, duration=min(command.count("h")*2, 15))
            return True
        elif command.startswith("unshh"):
            await ctx.invoke(self.bot.get_command("unsilence"))
            return True
        return False 
Example #20
Source File: clean.py    From bot with MIT License 5 votes vote down vote up
def clean_all(
        self,
        ctx: Context,
        amount: Optional[int] = 10,
        channels: commands.Greedy[TextChannel] = None
    ) -> None:
        """Delete all messages, regardless of poster, stop cleaning after traversing `amount` messages."""
        await self._clean_messages(amount, ctx, channels=channels) 
Example #21
Source File: clean.py    From bot with MIT License 5 votes vote down vote up
def clean_user(
        self,
        ctx: Context,
        user: User,
        amount: Optional[int] = 10,
        channels: commands.Greedy[TextChannel] = None
    ) -> None:
        """Delete messages posted by the provided user, stop cleaning after traversing `amount` messages."""
        await self._clean_messages(amount, ctx, user=user, channels=channels) 
Example #22
Source File: clean.py    From bot with MIT License 5 votes vote down vote up
def clean_group(self, ctx: Context) -> None:
        """Commands for cleaning messages in channels."""
        await ctx.send_help(ctx.command) 
Example #23
Source File: security.py    From bot with MIT License 5 votes vote down vote up
def check_on_guild(self, ctx: Context) -> bool:
        """Check if the context is in a guild."""
        if ctx.guild is None:
            raise NoPrivateMessage("This command cannot be used in private messages.")
        return True 
Example #24
Source File: eval.py    From bot with MIT License 5 votes vote down vote up
def eval(self, ctx: Context, *, code: str) -> None:
        """Run eval in a REPL-like format."""
        code = code.strip("`")
        if re.match('py(thon)?\n', code):
            code = "\n".join(code.split("\n")[1:])

        if not re.search(  # Check if it's an expression
                r"^(return|import|for|while|def|class|"
                r"from|exit|[a-zA-Z0-9]+\s*=)", code, re.M) and len(
                    code.split("\n")) == 1:
            code = "_ = " + code

        await self._eval(ctx, code) 
Example #25
Source File: eval.py    From bot with MIT License 5 votes vote down vote up
def internal_group(self, ctx: Context) -> None:
        """Internal commands. Top secret!"""
        if not ctx.invoked_subcommand:
            await ctx.send_help(ctx.command) 
Example #26
Source File: reminders.py    From bot with MIT License 5 votes vote down vote up
def delete_reminder(self, ctx: Context, id_: int) -> None:
        """Delete one of your active reminders."""
        await self._delete_reminder(id_)
        await self._send_confirmation(
            ctx,
            on_success="That reminder has been deleted successfully!",
            reminder_id=id_,
            delivery_dt=None,
        ) 
Example #27
Source File: reminders.py    From bot with MIT License 5 votes vote down vote up
def edit_reminder_group(self, ctx: Context) -> None:
        """Commands for modifying your current reminders."""
        await ctx.send_help(ctx.command) 
Example #28
Source File: reminders.py    From bot with MIT License 5 votes vote down vote up
def remind_group(self, ctx: Context, expiration: Duration, *, content: str) -> None:
        """Commands for managing your reminders."""
        await ctx.invoke(self.new_reminder, expiration=expiration, content=content) 
Example #29
Source File: extensions.py    From bot with MIT License 5 votes vote down vote up
def cog_check(self, ctx: Context) -> bool:
        """Only allow moderators and core developers to invoke the commands in this cog."""
        return with_role_check(ctx, *MODERATION_ROLES, Roles.core_developers)

    # This cannot be static (must have a __func__ attribute). 
Example #30
Source File: extensions.py    From bot with MIT License 5 votes vote down vote up
def list_command(self, ctx: Context) -> None:
        """
        Get a list of all extensions, including their loaded status.

        Grey indicates that the extension is unloaded.
        Green indicates that the extension is currently loaded.
        """
        embed = Embed()
        lines = []

        embed.colour = Colour.blurple()
        embed.set_author(
            name="Extensions List",
            url=URLs.github_bot_repo,
            icon_url=URLs.bot_avatar
        )

        for ext in sorted(list(EXTENSIONS)):
            if ext in self.bot.extensions:
                status = Emojis.status_online
            else:
                status = Emojis.status_offline

            ext = ext.rsplit(".", 1)[1]
            lines.append(f"{status}  {ext}")

        log.debug(f"{ctx.author} requested a list of all cogs. Returning a paginated list.")
        await LinePaginator.paginate(lines, ctx, embed, max_size=300, empty=False)