本文整理汇总了Python中discord.ext.commands.Context方法的典型用法代码示例。如果您正苦于以下问题:Python commands.Context方法的具体用法?Python commands.Context怎么用?Python commands.Context使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类discord.ext.commands
的用法示例。
在下文中一共展示了commands.Context方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: challenge
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
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)
示例2: assess
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
def assess(self, ctx: Context, challenge_num: int):
"""
Gets information about a specific CyberStart Assess level and challenge.
"""
NO_HINTS_MSG = f"**:warning: Remember, other people can't give hints after challenge {HINTS_LIMIT}**"
# Gather Assess data from JSON file.
with open("cdbot/data/assess.json") as f:
assess_docs = load(f)
if not 0 < challenge_num <= len(assess_docs):
await ctx.send("Invalid challenge number!")
else:
# Select the needed challenge
challenge_raw = assess_docs[challenge_num - 1]
challenge_title = challenge_raw["title"]
challenge_difficulty = challenge_raw["difficulty"]
challenge_text = challenge_raw["description"]
if challenge_num > HINTS_LIMIT:
challenge_text = NO_HINTS_MSG + "\n" + challenge_text
embed = Embed(
title=f"CyberStart Assess Challenge {challenge_num} - {challenge_title}",
description=challenge_text,
colour=0x4262F4,
url=f"https://assess.joincyberdiscovery.com/challenge-{challenge_num:02d}",
)
embed.set_author(name="Cyber Discovery", icon_url=CYBERDISC_ICON_URL)
embed.set_footer(text=f"Difficulty: {challenge_difficulty}")
await ctx.send(embed=embed)
示例3: subscribe_command
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
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.",
)
示例4: unsubscribe_command
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
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).
示例5: close_command
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
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")
示例6: _send_matching_tags
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
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
)
示例7: vote
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
def vote(self, ctx: Context, title: str, *options: str) -> None:
"""
Build a quick voting poll with matching reactions with the provided options.
A maximum of 20 options can be provided, as Discord supports a max of 20
reactions on a single message.
"""
if len(options) < 2:
raise BadArgument("Please provide at least 2 options.")
if len(options) > 20:
raise BadArgument("I can only handle 20 options!")
codepoint_start = 127462 # represents "regional_indicator_a" unicode value
options = {chr(i): f"{chr(i)} - {v}" for i, v in enumerate(options, start=codepoint_start)}
embed = Embed(title=title, description="\n".join(options.values()))
message = await ctx.send(embed=embed)
for reaction in options:
await message.add_reaction(reaction)
示例8: send_embed
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
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)
示例9: wolfram_page_command
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
def wolfram_page_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
embed = Embed()
embed.set_author(name="Wolfram Alpha",
icon_url=WOLF_IMAGE,
url="https://www.wolframalpha.com/")
embed.colour = Colours.soft_orange
await ImagePaginator.paginate(pages, ctx, embed)
示例10: wolfram_cut_command
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
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])
示例11: unload_command
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
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)
示例12: reload_command
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
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)
示例13: _send_confirmation
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
def _send_confirmation(
ctx: Context,
on_success: str,
reminder_id: str,
delivery_dt: t.Optional[datetime],
) -> None:
"""Send an embed confirming the reminder change was made successfully."""
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.title = random.choice(POSITIVE_REPLIES)
embed.description = on_success
footer_str = f"ID: {reminder_id}"
if delivery_dt:
# Reminder deletion will have a `None` `delivery_dt`
footer_str = f"{footer_str}, Due: {delivery_dt.strftime('%Y-%m-%dT%H:%M:%S')}"
embed.set_footer(text=footer_str)
await ctx.send(embed=embed)
示例14: edit_reminder_content
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
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)
示例15: handle_api_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Context [as 别名]
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}")