【问题标题】:Python 3.6 Discord bot Bot events conflictPython 3.6 Discord bot Bot 事件冲突
【发布时间】:2018-07-08 00:34:02
【问题描述】:

所以我有两个机器人事件 用“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)

那么我怎样才能让它们不冲突呢?

【问题讨论】:

    标签: python bots discord discord.py


    【解决方案1】:

    您已经定义了函数on_message() 两次。

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

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

    您的代码中也存在同样的问题。

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

    @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 块的内容分解成它们自己的函数,以使脚本更易于阅读,但我将把它留给你作为练习,一旦你让其余部分正常工作。

    【讨论】:

    • 非常感谢,我真的很感激,你的表现超出了我的预期,谢谢。这种洞察力真的很有意义,
    • 如果我解决了您的问题,请将其标记为已接受的答案。它给了我那些甜蜜甜蜜的堆栈溢出点。 :D
    猜你喜欢
    • 2020-08-11
    • 2019-03-07
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2021-08-13
    • 2021-06-15
    相关资源
    最近更新 更多