首页 > 解决方案 > 如何在不和谐中使用命令切换触发 Cog 侦听器

问题描述

我目前正在尝试制作一个不和谐的机器人,当您!purge在所需的频道中键入命令时,它会不断删除所有发送的消息,当您再次键入时,它将停止删除所有消息。

通过在线学习,我知道我必须使用 Cog 侦听器,但我并不完全知道如何使用命令“触发”它。我需要该@commands.Cog.listener()段落来使用on_message侦听器,但我也无法弄清楚如何让它删除!purge执行命令的通道中的消息。

我已经尝试使用布尔值在键入命令时打开和关闭,它会使用 while 循环不断删除消息,但随后 while 循环会停止。可能是因为命令的会话已过期,但不确定。

关于如何使用它的任何想法?更具体地说,我如何以某种方式将 Cog 链接到命令?谢谢!

(我试图在这里编辑我的代码,但由于不相关而删除了它们)

我发现的齿轮线程:https ://stackoverflow.com/a/53528504/11805086

标签: pythonpython-3.xdiscorddiscord.py

解决方案


您必须创建一个触发命令,该命令启用或禁用清除模式,然后在您的on_message函数中,您必须检查是否启用了清除模式。

操作方法如下(在一个 cog 内): 由海报编辑

  • 在 cogs.py
from discord.ext import commands

class Purge_Cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.channels = {}

    @commands.command()
    async def purge(self, ctx):
        try:
            if self.channels[ctx.channel]:
                self.channels[ctx.channel] = False
                await ctx.channel.send("Purge mode disabled!")
            else:
                self.channels[ctx.channel] = True
                await ctx.channel.send("Purge mode enabled!")
        except:
           self.channels[ctx.channel] = True
           await ctx.channel.send("Purge mode enabled!")

    @commands.Cog.listener()
    async def on_message(self, message):
        try:
            if self.channels[message.channel]:
                await message.channel.purge(limit=999)
        except:
            pass

def setup(bot):
    bot.add_cog(Purge_Cog(bot))
  • 在你的主文件中添加这个(bot.py 或 main.py)
import discord
from discord.ext import commands

initial_extensions = ['cogs.cogs']

if __name__ == '__main__':
    for extension in initial_extensions:
        bot.load_extension(extension)

bot.run('Your token')

推荐阅读