繁体   English   中英

事件可以执行命令吗? 如果是这样,我怎样才能让我的人这样做?

[英]Can an event execute a command? If so, how can I make my one do so?

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

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

@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

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

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

如果您的客户端是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)

get_context ,这需要一个消息对象。 然后invoke . 请记住,使用此方法有 3 个缺点。

  1. 转换器(类型提示)不会被触发。 您需要将正确的类型传递给参数。
  2. 检查将被绕过。 您可以使用非所有者调用仅所有者命令,它仍然可以工作。 如果您仍想运行所有检查,请参阅can_run ,它将运行所有检查并在任何检查失败时引发错误。
  3. 如果ctx.invoke在命令之外调用(例如 eval),错误处理程序将不会触发。
@client.command()
async def menu(ctx):
    await ctx.send("Hello")


@client.event
async def on_message(message):
    if message.content.startswith("nothing"):
        ctx = await client.get_context(message)
        await ctx.invoke(menu)
    await client.process_commands(message)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM