簡體   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