python - 事件可以执行命令吗?如果是这样,我怎样才能让我的人这样做?
问题描述
所以我试图有一个事件,一旦用户输入一个特定的单词(不是命令,字面意思是一个单词/字符串),该事件将触发一个现有的命令。是的,您可能想知道“为什么不让用户自己键入命令?” 好吧,为什么不是这样的原因很难解释。看一下这个:
我的活动只有在该人键入“无”(字面意思是“无”)时才会起作用。最终,该人不会期望机器人实际将此作为命令,因此他/她不会将其作为命令输入(带有前缀和所有这些)这是我的代码:
@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)
推荐阅读
- html - Datalist 下拉列表忽略特殊字符并过滤
- reactjs - 为什么我的底部选项卡导航器重新渲染是不必要的?
- intellij-idea - Intellij如何删除所有包含注释的行?
- c# - 在 asp.net 中无法正确重定向
- java - 如何解决 HackerRank 的 Gemstone 问题的最终测试用例
- android - 如何在 Android Jetpack Compose 中更改特定应用变体的颜色?
- git - git diff:指定不同的荧光笔作为命令行选项
- wpf - 如何在自定义用户控件中为 ListBox ItemTemplate 属性设置适当的上下文
- firebase - Firebase 数据库连接被服务器强行终止:不同区域 #flutter
- javascript - 如何可视化 JavaScript 包装器对象?