python - 如何在不和谐中使用命令切换触发 Cog 侦听器
问题描述
我目前正在尝试制作一个不和谐的机器人,当您!purge
在所需的频道中键入命令时,它会不断删除所有发送的消息,当您再次键入时,它将停止删除所有消息。
通过在线学习,我知道我必须使用 Cog 侦听器,但我并不完全知道如何使用命令“触发”它。我需要该@commands.Cog.listener()
段落来使用on_message
侦听器,但我也无法弄清楚如何让它删除!purge
执行命令的通道中的消息。
我已经尝试使用布尔值在键入命令时打开和关闭,它会使用 while 循环不断删除消息,但随后 while 循环会停止。可能是因为命令的会话已过期,但不确定。
关于如何使用它的任何想法?更具体地说,我如何以某种方式将 Cog 链接到命令?谢谢!
(我试图在这里编辑我的代码,但由于不相关而删除了它们)
解决方案
您必须创建一个触发命令,该命令启用或禁用清除模式,然后在您的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')
推荐阅读
- typescript - TypeScript:数组类型到元组类型断言
- selenium - 没有为黄瓜中的场景大纲生成范围报告
- arrays - 我可以指定一个数组不可分配给记录吗?
- oracle - Oracle Database 18c 配置助手失败
- node.js - Bazel Watcher 未终止节点进程(错误:监听 EADDRINUSE:地址已在使用 :::3000)
- python - 是否可以在 Python 中有单独的 lib 和 src 目录?
- sql - SQL Server 中多列的条件批量更新
- scrapy - 蜘蛛不会停止
- python-3.x - Python中的while循环程序用于存储可被10整除的值
- android - Lambda 不适用于 Kotlin 进行多线程操作