Discord python bot on_message return 语句中断命令

时间:2021-07-20 00:05:21

标签: python discord discord.py

首先,我知道 await bot.process_commands(message) 需要位于 on_message 函数的末尾,所以我知道这不是问题。

我编写了一个机器人,它应该查看来自一个频道的所有消息(忽略来自所有其他频道的消息)并查看所有频道中的命令。因此,我首先在 on_message() 函数中进行通道检查。如果它不是适当的通道,则返回 None 并停止该函数。但是,我发现这也会导致我的命令中断并不再运行。

这是一个测试机器人,可帮助重现我的错误的基础

import datetime
import discord
from discord.ext import commands


DISCORD_TOKEN='<TOKEN>'

bot = commands.Bot(command_prefix='$')

@bot.event
async def on_ready():
    print(f"Online:\t{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

@bot.command()
async def command_(ctx):

    print(f"\t{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} This was seen as a command")

@bot.event
async def on_message(message):

    if message.channel.id != <CHANNEL_ID>:
        return

    print(f"\t{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} This was seen as a message")    
    await bot.process_commands(message)

bot.run(DISCORD_TOKEN)

如果我删除通道检查(第 21-22 行),则消息将被视为消息,但命令将按此顺序同时视为消息和命令。由于返回(如果消息没有在特定通道中发生,则中断函数),并且因为 on_message() 似乎总是首先被调用,命令永远不会被调用,我没有得到任何输出在我的终端中。

关于我可以做些什么来导航这个的任何输入?

1 个答案:

答案 0 :(得分:1)

此代码将如您所愿。正如我在评论中所描述的,使用 create_task 函数,您可以在没有 await 语句的情况下调用异步函数,因此,不会等待该函数结束进程。 导入日期时间 进口不和谐 from discord.ext 导入命令

DISCORD_TOKEN='<TOKEN>'

bot = commands.Bot(command_prefix='$')

@bot.event
async def on_ready():
    print(f"Online:\t{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

@bot.command()
async def command_(ctx):

    print(f"\t{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} This was seen as a command")
async def check_message(message):
  if message.channel.id != <CHANNEL_ID>:
        return
  print(f"\t{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} This was seen as a message")  
@bot.event
async def on_message(message):

    # You can use bot.loop.create_task() function to create a new task in the loop. 
    # The task will not be waited to end the process, so while checking the message, you can process commands at the same time
    bot.loop.create_task(check_message(message))
    await bot.process_commands(message)

bot.run(DISCORD_TOKEN)