Python 3.6 Discord bot Bot事件冲突

时间:2018-01-29 10:32:01

标签: python bots discord discord.py

所以我有两个bot事件 一个回应消息" 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 个答案:

答案 0 :(得分: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块的内容分解为自己的功能,以使脚本更易于阅读,但我会将其保留为一旦你完成其余的工作,你就可以锻炼身体。