【问题标题】:How to make both commands can puts in to discord.py如何使这两个命令都可以放入 discord.py
【发布时间】:2021-05-31 14:14:10
【问题描述】:

有趣的是,当我添加@bot.command()时(此代码用于在检测到命令时发送图像,它会在discord.py中发送图像,它可以工作)。 但是如果我在discord.py中加了@bot.event()(这个代码是用来搜索关键字的,如果搜索到任何关键字都会发消息回复),就不行了。 这意味着我不能将 discord.py 中的这两个函数放在一起,我该如何解决? 这是我的代码:

@bot.command()
async def Send a photo(ctx):
    await ctx.send('image_1')

@bot.event
async def on_message(msg):
    keyword = ['morning','goodbye']
    for key in keyword:
        if key in msg.content and key == keyword[0] and msg.author != bot.user:
            random_morning = random.choice(jdata['GOODMORNING'])
            await msg.channel.send(random_morning)
            break 
        elif key in msg.content and key == keyword[1] and msg.author != bot.user:
            random_goodbye = random.choice(jdata['GOODBYE'])
            await msg.channel.send(random_goodbye)
            break

【问题讨论】:

  • 这是一种非常低效的方法......你为什么不做一些没有for循环的事情:if keyword[0] in msg.content ...:

标签: python discord.py


【解决方案1】:

文档的常见问题页面提到了如何解决这个问题:https://discordpy.readthedocs.io/en/latest/faq.html#why-does-on-message-make-my-commands-stop-working

基本上,覆盖默认提供的 on_message 不允许运行任何额外的命令。要解决此问题,请在 on_message 末尾添加 bot.process_commands(msg) 行。所以只需使用:

async def on_message(msg):
    keyword = ['morning','goodbye']
    for key in keyword:
        if key in msg.content and key == keyword[0] and msg.author != bot.user:
            random_morning = random.choice(jdata['GOODMORNING'])
            await msg.channel.send(random_morning)
            break 
        elif key in msg.content and key == keyword[1] and msg.author != bot.user:
            random_goodbye = random.choice(jdata['GOODBYE'])
            await msg.channel.send(random_goodbye)
            break
    bot.process_commands(msg)

顺便提一下代码

keyword = ['morning','goodbye']
    for key in keyword:
        if key in msg.content and key == keyword[0] and msg.author != bot.user:
            random_morning = random.choice(jdata['GOODMORNING'])
            await msg.channel.send(random_morning)
            break 
        elif key in msg.content and key == keyword[1] and msg.author != bot.user:
            random_goodbye = random.choice(jdata['GOODBYE'])
            await msg.channel.send(random_goodbye)
            break

可以缩短为

if "morning" in msg.content:
    random_morning = random.choice(jdata['GOODMORNING'])
    await msg.channel.send(random_morning)
elif "goodbye" in msg.content:
    random_goodbye = random.choice(jdata['GOODBYE'])
    await msg.channel.send(random_goodbye)

【讨论】:

    猜你喜欢
    • 2021-01-13
    • 2021-09-03
    • 2021-02-28
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 2021-06-04
    • 2021-07-14
    相关资源
    最近更新 更多