小能豆

如何为 DM 创建自动回复事件

py

我有此代码,但我无法使用命令运行它,所以我可以打开和关闭它:

auto_dm = "off"

@bot.command()
async def autoreply(ctx, mode: str):
""" On or Off """
    await ctx.message.delete()
    auto_dm = mode


class Events(commands.Cog):
    @commands.Cog.listener()
    async def on_message(self, message):
        while auto_dm == "on":
            if isinstance(message.channel, discord.channel.DMChannel):
                if message.author.id != bot.user.id:
                    automsg = config.get("automessage")
                    await message.channel.send(automsg)
                    time = datetime.datetime.now().strftime("%H:%M")
                    print(f"{time} | {Fore.LIGHTCYAN_EX}[Event]{Fore.RESET} | Auto Reply Message send to {message.author}")
                else:
                    pass
            else:
                pass
        else:
            pass

我的问题是,当我将事件设置为“开”时,它没有被监听。


阅读 25

收藏
2025-01-06

共1个答案

小能豆

这绝不是on因为您没有编辑auto_dm变量,您需要globalautoreply命令中使用关键字才能更改它

@bot.command()
async def autoreply(ctx, mode: str):
    global auto_dm
    await ctx.message.delete()
    auto_dm = mode

你的代码也有几个错误

  1. 齿轮Events没有__init__方法
  2. 你不需要在on_message事件中使用 while 循环,因为这样做没有任何意义
  3. 你应该使用布尔值而不是on/off
  4. 你不需要else: pass,干脆就不要放

齿轮已修复

class Events(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author == self.bot.user:
            return # Exiting if the author of the message is ourself

        if auto_dm == 'on': # I'd really recommend you using True/False
            if isinstance(message.channel, discord.DMChannel):
                automsg = config.get("automessage")
                await message.channel.send(automsg)
                time = datetime.datetime.now().strftime("%H:%M")
                print(f"{time} | {Fore.LIGHTCYAN_EX}[Event]{Fore.RESET} | Auto Reply Message send to {message.author}")
2025-01-06