本文整理汇总了Python中discord.ext.commands.CommandError方法的典型用法代码示例。如果您正苦于以下问题:Python commands.CommandError方法的具体用法?Python commands.CommandError怎么用?Python commands.CommandError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类discord.ext.commands
的用法示例。
在下文中一共展示了commands.CommandError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: approve
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def approve(self, ctx, *, template_name):
"""
Approve a template
__Arguments__
**template_name**: The name of the template
"""
template_name = template_name.lower().replace(" ", "_")
template = await ctx.db.templates.find_one(template_name)
if template is None:
raise cmd.CommandError(f"There is **no template** with the name `{template_name}`.")
await ctx.send(**ctx.em(f"Successfully **approved template**.", type="success"))
await self._approve(template)
示例2: feature
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def feature(self, ctx, *, template_name):
"""
Feature a template
__Arguments__
**template_name**: The name of the template
"""
feature = True
if ctx.invoked_with == "unfeature":
feature = False
template_name = template_name.lower().replace(" ", "_")
template = await ctx.db.templates.find_one(template_name)
if template is None:
raise cmd.CommandError(f"There is **no template** with the name `{template_name}`.")
await ctx.send(**ctx.em(f"Successfully **{'un' if not feature else ''}featured template**.", type="success"))
await self._feature(template, state=feature)
示例3: delete
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def delete(self, ctx, *, template_name):
"""
Delete a template
__Arguments__
**template_name**: The name of the template
"""
template_name = template_name.lower().replace(" ", "_")
template = await ctx.db.templates.find_one(template_name)
if template is None:
raise cmd.CommandError(f"There is **no template** with the name `{template_name}`.")
await self._delete(template, ctx.author, ctx.channel)
await ctx.send(**ctx.em("Successfully **deleted/denied template**.", type="success"))
示例4: info
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def info(self, ctx, *, template_name):
"""
Get information about a template
__Arguments__
**template_name**: The name of the template
__Examples__
```{c.prefix}template info starter```
"""
template_name = template_name.lower().replace(" ", "_")
template = await ctx.db.templates.find_one(template_name)
if template is None:
raise cmd.CommandError(f"There is **no template** with the name `{template_name}`.")
embed = self._template_info(template)
embed._fields.insert(1, {"name": "Uses", "value": str(template.get("used") or 0), "inline": True})
await ctx.send(embed=embed)
示例5: su
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def su(self, ctx, member: discord.User, *, msg):
"""
Execute a command in place of another user
__Arguments__
**member**: The user (must be a member of this guild)
**msg**: The message, doesn't need to be a command
"""
if member.id == ctx.bot.owner_id:
raise cmd.CommandError("How about ... **no**?")
webhook = await ctx.channel.create_webhook(name="sudo")
await webhook.send(content=msg, username=member.name, avatar_url=member.avatar_url)
await webhook.delete()
await asyncio.sleep(1) # Webhooks are slow
message = ctx.message
message.author = member
message.content = msg
await self.bot.process_commands(message)
示例6: check_role_on_support_guild
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def check_role_on_support_guild(role_name):
async def predicate(ctx):
support_guild = ctx.bot.get_guild(ctx.config.support_guild)
if support_guild is None:
log.warning("Support Guild is unavailable")
raise cmd.CommandError(
"The support guild is currently unavailable. Please try again later."
)
try:
member = await support_guild.fetch_member(ctx.author.id)
except discord.NotFound:
raise cmd.CommandError("You need to be on the support guild to use this command.")
roles = filter(lambda r: r.name == role_name, member.roles)
if len(list(roles)) == 0:
raise cmd.CommandError(
f"You are **missing** the `{role_name}` **role** on the support guild."
)
return True
return predicate
示例7: __init__
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def __init__(
self,
manager: "ThreadManager",
recipient: typing.Union[discord.Member, discord.User, int],
channel: typing.Union[discord.DMChannel, discord.TextChannel] = None,
):
self.manager = manager
self.bot = manager.bot
if isinstance(recipient, int):
self._id = recipient
self._recipient = None
else:
if recipient.bot:
raise CommandError("Recipient cannot be a bot.")
self._id = recipient.id
self._recipient = recipient
self._channel = channel
self.genesis_message = None
self._ready_event = asyncio.Event()
self.close_task = None
self.auto_close_task = None
示例8: convert
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def convert(self, ctx, argument):
err = None
try:
logged_emote = await LoggedEmote().convert(ctx, argument)
except commands.CommandError as exc:
pass
else:
return logged_emote
try:
db_emote = await self.db_conv.convert(ctx, argument)
except commands.CommandError as exc:
raise commands.BadArgument(
_('Failed to interpret {argument} as a logged emote message or an emote in my database.')
.format(argument=argument))
return db_emote
示例9: command_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def command_error(self, ctx: Context, error: CommandError) -> None:
"""Local error handler for the Snake Cog."""
embed = Embed()
embed.colour = Colour.red()
if isinstance(error, BadArgument):
embed.description = str(error)
embed.title = random.choice(ERROR_REPLIES)
elif isinstance(error, OSError):
log.error(f"snake_card encountered an OSError: {error} ({error.original})")
embed.description = "Could not generate the snake card! Please try again."
embed.title = random.choice(ERROR_REPLIES)
else:
log.error(f"Unhandled tag command error: {error} ({error.original})")
return
await ctx.send(embed=embed)
# endregion
示例10: ensure_voice
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def ensure_voice(self, ctx):
if ctx.voice_client is None:
if ctx.author.voice:
await ctx.author.voice.channel.connect()
else:
await ctx.send("You are not connected to a voice channel.")
raise commands.CommandError("Author not connected to a voice channel.")
elif ctx.voice_client.is_playing():
ctx.voice_client.stop()
示例11: __init__
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def __init__(self, bot):
self.bot = bot
@bot.check
async def not_blacklisted(ctx):
entry = await ctx.db.users.find_one({"_id": ctx.author.id, "blacklist.state": True})
if entry is None:
return True
raise cmd.CommandError("Sorry, **you are blacklisted**.\n\n"
f"**Reason**: {entry['blacklist']['reason']}")
示例12: run
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def run(self):
self.msg = await self.ctx.send(embed=self._create_embed())
options = {
**{f"{i + 1}\u20e3": self._switch_option(i) for i in range(9)},
"◀": self._prev_page,
"▶": self._next_page,
"❎": self._cancel,
"✅": self._finish,
}
for option in options:
await self.msg.add_reaction(option)
try:
async for reaction, user in helpers.IterWaitFor(
self.ctx.bot,
event="reaction_add",
check=lambda r, u: u.id == self.ctx.author.id and
r.message.id == self.msg.id and
str(r.emoji) in options.keys(),
timeout=3 * 60
):
self.ctx.bot.loop.create_task(self.msg.remove_reaction(reaction.emoji, user))
if not await options[str(reaction.emoji)]():
try:
await self.msg.clear_reactions()
except Exception:
pass
return {name: value for page in self.pages for name, value in page["options"]}
await self.update()
except asyncio.TimeoutError:
try:
await self.msg.clear_reactions()
except Exception:
pass
raise cmd.CommandError("**Canceled build process**, because you didn't do anything.")
示例13: _cancel
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def _cancel(self):
try:
await self.msg.clear_reactions()
except Exception:
pass
raise cmd.CommandError("You canceled the build process.")
示例14: create
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def create(self, ctx):
"""
Create a backup
__Examples__
```{c.prefix}backup create```
"""
backup_count = await ctx.db.backups.count_documents({"creator": ctx.author.id})
if backup_count >= max_backups:
raise cmd.CommandError("You have **exceeded the maximum count** of backups.\n\n"
f"Upgrade to Pro (`x!pro`) to be able to create more than **{max_backups}**. "
f"backups **or delete one of your old backups** (`x!backup list` "
f"& `x!backup delete <id>`).")
status = await ctx.send(**ctx.em("**Creating backup** ... Please wait", type="working"))
handler = BackupSaver(self.bot, self.bot.session, ctx.guild)
backup = await handler.save()
id = await self._save_backup(ctx.author.id, backup)
embed = ctx.em(f"Successfully **created backup** with the id `{id}`.\n", type="success")["embed"]
embed.add_field(name="Usage",
value=f"```{ctx.prefix}backup load {id}```\n```{ctx.prefix}backup info {id}```")
await status.edit(embed=embed)
try:
if ctx.author.is_on_mobile():
await ctx.author.send(f"{ctx.prefix}backup load {id}")
else:
embed = ctx.em(
f"Created backup of **{ctx.guild.name}** with the backup id `{id}`\n", type="info")["embed"]
embed.add_field(name="Usage",
value=f"```{ctx.prefix}backup load {id}```\n```{ctx.prefix}backup info {id}```")
await ctx.author.send(embed=embed)
except Exception:
pass
示例15: purge
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandError [as 别名]
def purge(self, ctx):
"""
Delete all your backups
__**This cannot be undone**__
__Examples__
```{c.prefix}backup purge```
"""
warning = await ctx.send(
**ctx.em("Are you sure that you want to delete all your backups?\n"
"__**This cannot be undone!**__",
type="warning"))
await warning.add_reaction("✅")
await warning.add_reaction("❌")
try:
reaction, user = await self.bot.wait_for(
"reaction_add",
check=lambda r, u: r.message.id == warning.id and u.id == ctx.author.id,
timeout=60)
except TimeoutError:
await warning.delete()
raise cmd.CommandError(
"Please make sure to **click the ✅ reaction** to delete all of your backups.")
if str(reaction.emoji) != "✅":
ctx.command.reset_cooldown(ctx)
await warning.delete()
return
await ctx.db.backups.delete_many({"creator": ctx.author.id})
await ctx.send(**ctx.em("Deleted all your backups.", type="success"))