首页 > 解决方案 > 事件可以执行命令吗?如果是这样,我怎样才能让我的人这样做?

问题描述

所以我试图有一个事件,一旦用户输入一个特定的单词(不是命令,字面意思是一个单词/字符串),该事件将触发一个现有的命令。是的,您可能想知道“为什么不让用户自己键入命令?” 好吧,为什么不是这样的原因很难解释。看一下这个:

我的活动只有在该人键入“无”(字面意思是“无”)时才会起作用。最终,该人不会期望机器人实际将此作为命令,因此他/她不会将其作为命令输入(带有前缀和所有这些)这是我的代码:

@client.command()
async def menu(ctx)
#here, well, goes what I want the command to do but it's not the issue

@client.event
async def on_message(message):
    if message.content.startswith("nothing"):
        #here idk how to execute the command up there. That's my question

我希望我清楚我的问题。不要担心命令执行什么,或者为什么事件的消息是“无”。我真的很想知道如何使这项工作。

有朋友建议我调用这个命令,但是我真的不知道怎么做,每次尝试都不行。其他人建议调用该函数,但我也尝试过,它不起作用。我不知道我是否输入正确或者它根本不起作用。我希望有人在这里帮助我。提前致谢。

标签: pythondiscord.py

解决方案


如果您的客户端是一个Bot实例,您可以使用Bot.get_context()创建您自己的上下文并从那里调用命令:

import discord
from discord.ext import commands

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

@bot.command()
async def menu(ctx):
    await ctx.send('bar')

@bot.event
async def on_message(message):
    if message.content.startswith('foo'):
        ctx = await bot.get_context(message, cls=commands.Context)
        ctx.command = bot.get_command('menu')
        await bot.invoke(ctx)

    await bot.process_commands(message)

推荐阅读