首页 文章

Python 3.6 Discord bot Bot事件冲突

提问于
浏览
2

所以我有两个机器人事件一个响应消息“k”用“k”和一个简单的猜测我的数字在1-10之间问题是它们冲突并且只有一个工作(下面的那个)IDK我是什么我失踪了 . 码:

@client.event
async def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return
    if message.author.bot: return
    if message.content==('k'):
        msg = 'k'.format(message)
        await client.send_message(message.channel, msg)

    await client.process_commands(message)




@client.event
async def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return

    if message.content.startswith('!guess'):
        await client.send_message(message.channel, 'Guess a number     between 1 to 10')

        def guess_check(m):
            return m.content.isdigit()

        guess = await client.wait_for_message(timeout=10.0,    author=message.author, check=guess_check)
        answer = random.randint(1, 10)
        if guess is None:
            fmt = 'Sorry, you took too long. It was {}.'
            await client.send_message(message.channel,     fmt.format(answer))
            return
        if int(guess.content) == answer:
            await client.send_message(message.channel, 'You are right!')
        else:
            await client.send_message(message.channel, 'Sorry. It is     actually {}.'.format(answer))

    await client.process_commands(message)

那么如何制作它们以免它们发生冲突呢?

1 回答

  • 3

    您已将函数 on_message() 定义了两次 .

    为了演示这个问题,如果我运行以下代码,你会期望输出是什么?

    def f(x):
        print(x)
    
    def f(x):
        print('Nothing useful')
    
    f(3)
    

    您的代码中存在同样的问题 .

    假设discord框架在收到消息时将调用一个名为 on_message() 的函数,则需要一个处理任何输入的 on_message() 函数 . 因此,它看起来像这样:

    @client.event
    async def on_message(message):
        # we do not want the bot to reply to itself
        if message.author == client.user:
            return
    
        if message.content==('k'):
            ...
    
        if message.content.startswith('!guess'):
            ...
    

    如果你感觉特别时髦,你可以将 if 块的内容分解成它们自己的函数,使脚本更容易阅读,但是我会把它作为练习留给你,一旦你有其余部分工作 .

相关问题