如何在 ON_MESSAGE 中使用清除命令

时间:2021-03-20 16:12:07

标签: python discord discord.py bots

我找到了一个清除命令,但它对我不起作用,因为我使用 client = discord.Client(command_prefix = '$', description = ' ') 而不是 client = commands.Bot(command_prefix = '$') 而且我在

中使用了很多命令
@client.event 
async def on_message(message):

所以我也想在 on_message 中使用清除命令。谢谢!

清除命令:

@client.command()
async def clear(ctx, amount = 5):
    await ctx.channel.purge(limit = amount)

2 个答案:

答案 0 :(得分:1)

您必须对 on_message 事件中的其他命令执行相同的 if-Statement。由于您在 on_message 事件中使用它,您实际上无法设置使用该命令的数量,因此您必须预先定义它。

定义数量并定义要清除的通道。 您可以通过使用 discord.Client.get_channel 或选择消息已发送到 message.channel 的频道来获取频道。

答案 1 :(得分:1)

我删除了我的第一个答案,因为我看到我可以改进,我最终发现你可以做到

ctx = await client.get_context(message)
split = message.content.split()
if split[0] == "$clear": #Checking if the message is the clear command, you can also use message.content.tolower().startswith("$clear"):
    if len(split) == 2:
        num = 0
        try:
            num = int(split[1]) #checking if the second param <amount> is an int
        except ValueError:
            await message.channel.send("<amount> in $clear <amount> must be a number")
            return
        await ctx.channel.purge(limit = num)
    else:
        await message.channel.send("Please enter the command as $clear <amount>")

对我来说效果很好。客户也必须

client = commands.Bot(params)