discord.py一起使用on_message()和command()

时间:2020-05-03 05:54:49

标签: python discord discord.py

在下面的代码中,我的机器人打印了我编写的内容,但命令不起作用。我认为顺序是问题。因此,我尝试先编码@ bot.command(),然后再编码@ bot.event,但仍然无法正常工作。

import discord
from discord.ext import commands, tasks
import time
import datetime

bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"))
token = ''

@bot.event #working
async def on_message_delete(message):
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    print('<' + st + '>' '메시지 삭제 ' + message.author.name + ':' + message.content)


@bot.event #working
async def on_message_edit(before, after):
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    fmt = '**{0.author}** 가 메시지를 수정했습니다.:\n{0.content} -> {1.content}'
    print('<' + st + '>' + fmt.format(before, after))


@bot.event #working
async def on_message(message):
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    print('<' + st + '> ' + message.author.name + " : " + message.content)


@bot.command() #Not working
async def test(ctx):
    embed = discord.Embed \
            (
                title='노노봇 명령어 입니다',
                description='',
                colour=discord.Colour.blue()
            )
    embed.add_field(name='~', value='~', inline=False)
    await ctx.channel.send(embed=embed)


bot.run(token)

1 个答案:

答案 0 :(得分:1)

覆盖提供的默认on_message禁止运行任何其他命令。要解决此问题,请在on_message的末尾添加bot.process_commands(message)行。例如:

@bot.event
   async def on_message(message):
   # do some extra stuff here

await bot.process_commands(message)

https://discordpy.readthedocs.io/en/latest/faq.html?why-does-on-message-make-my-commands-stop-working#why-does-on-message-make-my-commands-stop-working