【问题标题】:Discord python bot on_message return statement breaks commandsDiscord python bot on_message return 语句中断命令
【发布时间】:2021-07-20 08:38:05
【问题描述】:

首先,我知道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() 似乎总是首先被调用,所以命令永远不会被调用,而且我没有得到任何输出在我的终端中。

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

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    此代码将按您的意愿工作。正如我在 cmets 中所描述的,使用 create_task 函数,您可以在没有 await 语句的情况下调用异步函数,因此,不会等待函数结束进程。 导入日期时间 导入不和谐 从 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)
    

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2018-10-21
      • 2021-03-01
      • 2021-04-11
      • 1970-01-01
      • 2020-08-11
      • 2021-02-17
      • 2019-03-07
      • 2021-07-09
      相关资源
      最近更新 更多