on_消息事件的不一致py Cog问题,不工作

2024-09-30 06:32:53 发布

您现在位置:Python中文网/ 问答频道 /正文

最近,我的bot正在增长,我花时间重写代码,使其能够与Discord Py的cogs系统一起工作

我已经正确地修改了所有代码,但是我已经停止工作的所有on_message事件都没有抛出任何类型的错误消息

模块加载正确,没有语法错误,因此我无法理解可能发生的情况

我的一些代码:

import discord
import random
import datetime
from discord.ext import commands

class eastereggs(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.Cog.listener()
    async def on_message(self,message):
        Cheers= ["Hi", "hi", "Hello", "hello"]
        if message.content in Cheers:
            await message.channel.send('Hello again')
            await self.bot.process_commands(message)

def setup(bot):
    bot.add_cog(eastereggs(bot))

但是,它不会对数组中的任何问候语作出反应

我编辑:我有多个带数组的on_消息事件

但似乎只有一个可行


Tags: 代码importself消息messagehelloondef
2条回答

问题在于不能有两个同名函数。如果你这样做,它只会调用最后一个。将加载该文件,但不会给出任何错误。由于所有事件都是on_message事件,因此只有最后一个事件可以工作。但是,你可以告诉听众“听”什么

您可以使用@Cog.listener("on_message")(或以相同方式使用其他事件),然后以不同的名称调用函数

    @Cog.listener("on_message")
    async def greet(self,message):
        Cheers= ["Hi", "hi", "Hello", "hello"]
        if message.content in Cheers:
            await message.channel.send('Hello again')
            await self.client.process_commands(message)

    @Cog.listener("on_message")
    async def agree(self,message):
        Agree = ["yes", "yep", "ok"]
        if message.content in Agree:
            await message.channel.send('good')
            await self.client.process_commands(message)


    @Cog.listener("on_message")
    async def dAgree(self,message):
        dAgree= ["no", "nope"]
        if message.content in dAgree:
            await message.channel.send('why')
            await self.client.process_commands(message)

您需要取消登录process_commands

@commands.Cog.listener()
async def on_message(self, message):
    # some code

    await self.bot.process_commands(message)

在你的每一次活动中, 另外,如果您想让代码更干净、更健壮,还有bot.dispatch来创建自定义事件,遗憾的是,没有关于它的文档

@commands.Cog.listener()
async def on_message(self, message):
    if message.content in ['some', 'values']:
                          # name of the event, args
        self.bot.dispatch('custom_event', message)

    await self.bot.process_commands(message)


@commands.Cog.listener()
async def on_custom_event(self, message):
    # custom event

相关问题 更多 >

    热门问题