【问题标题】:Im trying to setup a clear/purge command for my discord.py bot. There are no errors but when I run the command, nothing happens我试图为我的 discord.py 机器人设置一个清除/清除命令。没有错误,但是当我运行命令时,什么也没有发生
【发布时间】:2021-04-19 15:47:40
【问题描述】:

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

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)

【问题讨论】:

  • 嗨,你在哪里找到“keep_alive”python 模块?
  • @IODEV 我相信 OP 正在使用 repl.it 在 repl 上,不可能 24/7 运行,因此制作了一个 keep_alive 脚本。它实现了 uptimerobot 和烧瓶。如果你愿意,你可以问这个问题。或者,快速 repl 搜索也可以。

标签: python discord


【解决方案1】:

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

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


我首先创建了一个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,如下所示:

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

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


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

谢谢! :)

【讨论】:

  • 睡一秒钟有什么意义?
  • 我认为它只会延迟命令一秒钟的执行。更好的安排。我的意思是这是为了我的方便。不需要。
  • @BhavyadeepYadav 我已经导入了 asyncio 和 datetime 并添加了代码并将其修改为我想要的,但机器人仍然什么都不做。要我把代码发给你吗?
  • @BhavyadeepYadav 很抱歉回复晚了..我真的让它工作了!感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2021-12-03
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 2021-07-25
  • 2018-11-05
相关资源
最近更新 更多