首页 > 解决方案 > 为什么我的 on_message 事件打印日志两次?

问题描述

这是我的 on_message 命令的日志记录位,每当我发送“ping”时,它都会检查以确保它在其命令列表中然后记录它,但它会记录两次并发送一次(它应该只发送一次)...

async def on_message(message):
    # Check if the message was from server
    if message.content != "":
        # Test if User/ Bot
        if message.author == bot.user:
            return
        # Report Comamnd used
        else:
            splitCommand = message.content.split(" ")
            join = " "
            join = join.join(splitCommand)
            time = "[UTC " + str(message.created_at) + "]"
            singleCommand = "\nCommand: \'" + splitCommand[0] + "\'"
            multiCommand = "\nCommand: \'" + join + "\'"
            user = "\nFrom User: \'<@" + str(message.author.id) + "> | (" + str(message.author) + ")\'"
            # Single word commands
            if splitCommand[0].lower() in commandList:
                print(time + singleCommand + user)
            # Multi-word commands
            if any(x.isalpha() or x.isspace() for x in join):
                if join.lower() in commandList:
                    print(time + multiCommand + user)
                elif regex.search(join) != None and join.lower() in commandList:
                    print(time + multiCommand + user)
            # Deletes Commands
            if message.content[0] == prefix:
                userMessage =  message
                await userMessage.delete()
                print("Deleted Command")
    else:
        pass

一个示例输出是:

[UTC 2020-11-24 08:21:42.587000]
Command: 'ping'
From User: '<@379355817700491264> | (24Kings#0001)'
[UTC 2020-11-24 08:21:42.587000]
Command: 'ping'
From User: '<@379355817700491264> | (24Kings#0001)'
Sent: 'pong'

但它应该只记录一次? 任何关于它为什么记录两次和修复的想法都将非常感激!:D

标签: pythondiscord.py

解决方案


首先最好使用discord.ext.commands,之后你有三个选择。

@bot.event
async def on_command_completion(ctx):
    print(f'{ctx.command} has been used by {ctx.author.display_name}')

对于命令,这里是一个参考


推荐阅读