当另一个事件存在时,discord bot 会忽略该事件。 (python)

Event get's ignored by discord bot when another exists. (python)

我正在使用 discord.py 创建一个 discord 机器人,它的主要功能是在给出命令时输入故事。 只有2个命令存在:一个是帮助功能,另一个是开始故事。寻求帮助的命令是 r!help 而开始故事的命令是 r!start 但是由于某种原因 bot 似乎无法识别 r!help 已被发送一个用户,只响应 r!start 以下是我对这些事件的代码。

import discord

client = discord.Client()

@client.event
async def on_message(message):
    if message.content.startswith('r!help'):
        channel = message.channel
        await channel.send('Help')

# bring up help

@client.event
async def on_message(message):
    if message.content.startswith('r!start'):
        channel = message.channel
        await channel.send('Starting Story...')

#start story

我的 IDE (pycharm) 没有显示任何错误,该机器人似乎在服务器上在线并且确实用 starting story 回复 r!help .它只是不响应帮助命令。 我确实注意到,当 r!start 事件被注释掉时,帮助事件确实有效,所以我认为问题出在故事事件中。

@client.event
async def on_message(message):
    if message.content.startswith('r!help'):
        channel = message.channel
        await channel.send('Help')


# bring up help

#@client.event
#async def on_message(message):
 #   if message.content.startswith('r!start'):
  #      channel = message.channel
   #     await channel.send('Starting Spam...')
#works when this section is not there

那是因为您定义了同一个函数两次,然后再次更改它。要让它识别两者,您必须将它们都放在同一个函数中。

@client.event
async def on_message(message):
    if message.content.startswith('r!start'):
        channel = message.channel
        await channel.send('Starting Story...')
    elif message.content.startswith('r!help'):
        channel = message.channel
        await channel.send('Help')

像这样,您定义函数一次,不要更改它,然后检查两个命令。

另一种方法是,如果您想将代码分成两个函数,则使用 bot.listen

文档:Here

此外,如果您想要一个完全受控的机器人,您可能需要使用 discord.ext.commands.Bot,然后使用 @bot.command()

定义多个命令

示例:Here