我执行了此命令,它将清除您所说的消息数量,即>“清除10”将删除10条消息,我不知道如何检查输入是否为小数,您可以帮忙吗 代码:
@client.command(pass_context=True)
async def purge(ctx, amount=300):
if ctx.message.author.server_permissions.manage_messages:
channel = ctx.message.channel
messages = []
async for message in client.logs_from(channel, limit=int(amount) + 1):
messages.append(message)
await client.delete_messages(messages)
await client.say('Purged {} message(s)!'.format(len(messages)-1))
else:
embed = discord.Embed(
title = ':x: Insufficient Permissions',
description = 'You need to have the Manage Messages premission to execute this command.',
colour = 0xff0000
)
await client.say(embed=embed)
答案 0 :(得分:2)
您可以使用类型注释为协程提供converter(请注意,这是discord.py-rewrite文档,但这也可以在异步分支中使用)。然后,您可以指定另一个错误处理程序,该错误处理程序可以实现用于处理错误输入的逻辑。
@client.command(pass_context=True)
async def purge(ctx, amount: int=300):
...
@purge.error
async def purge_error(error, ctx):
if isinstance(error, commands.BadArgument):
await client.send_message(ctx.message.channel, "Cannot convert input to integer")
您可能还想看看Client.purge_from
。我没看完你所有的协程,但看起来你在重新发明轮子。
答案 1 :(得分:0)
您可以删除amount
的默认值,并捕获当用户写错内容时引发的ValueError
@client.command(pass_context=True)
async def purge(ctx, amount):
try:
if ctx.message.author.server_permissions.manage_messages:
channel = ctx.message.channel
messages = []
async for message in client.logs_from(channel, limit=int(amount) + 1):
messages.append(message)
try:
await client.delete_messages(messages)
await client.say('Purged {} message(s)!'.format(len(messages)-1))
except Exception as inst:
await client.say("One or more messages older than 14 days\n{}".format(inst))
else:
embed = discord.Embed(
title = ':x: Insufficient Permissions',
description = 'You need to have the Manage Messages premission to execute this command.',
colour = 0xff0000
)
await client.say(embed=embed)
except ValueError as va:
await client.say(va)
我还添加了try /,除非其中至少一封邮件已过期14天,因此无法删除