我正在尝试为我的 discord.py 机器人设置清除/清除命令。没有错误,但是当我运行命令时,没有任何反应

时间:2021-04-19 06:45:55

标签: python discord

这是代码的开始。是不是我在代码中输入了错误导致命令不起作用?

import discord
import os
from keep_alive import keep_alive
from discord.ext import commands
import random

client = commands.Bot(command_prefix= '>')

@client.event
async def on_ready():
    print('The bot is online')
    await client.change_presence(
        activity=discord.Game('>help ┃ Created by ColeTMK'))

@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=6):
  await ctx.channel.purge(limit=amount)

1 个答案:

答案 0 :(得分:3)

我已经正确解释了如何做到这一点。使用协程是可能的。

您的代码中似乎没有错误。我只想说创建我在下面提到的命令,然后再试一次。


我首先创建了一个 purge 命令,其中包含以下代码:

@nucleobot.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx, limit: int):
    await ctx.message.delete()
    await asyncio.sleep(1)
    await ctx.channel.purge(limit=limit)
    purge_embed = discord.Embed(title='Purge [!purge]', description=f'Successfully purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
    purge_embed.set_footer(text=str(datetime.datetime.now()))
    await ctx.channel.send(embed=purge_embed, delete_after=True)

此代码如何工作?

  1. 命令用法被删除,即!purge 10在发送到聊天时会被删除。

  2. 由于 await asyncio.sleep(1),它会暂停 1 秒。您需要导入 asyncio 才能使用它。 (你可能已经知道:D)

  3. 使用await ctx.message.delete(limit=limit)(这是一个discord.py协程)从频道中清除您输入的消息数

  4. purge_embed 是嵌入变量,用于在删除后发送嵌入。我已经使用 datetime 模块在嵌入中添加命令完成的时间。 (您还需要导入日期时间,但前提是您想使用它。如果没有,请删除页脚代码。)

这将构成您完整且有效的 purge 命令。 :D


图片示例。

我创建了一个新频道并添加了 10 条消息,数字从 1 到 10,如下所示:

Messages in Trail

然后我在消息框中输入了命令,就像(我知道不需要但没关系):

Command Entered

在我发送此消息并执行命令后,bot 发布了清除成功嵌入:

Successful Purge


我很高兴能帮上忙。任何混淆的疑问表示赞赏。随时问我。 :D

谢谢! :)