【问题标题】:How to pass arguments into a command being passed into bot.get_command() in a discord bot?如何将参数传递给不和谐机器人中传递给 bot.get_command() 的命令?
【发布时间】:2020-06-27 18:40:24
【问题描述】:

我正在为我的私人不和谐服务器创建一个不和谐机器人,但遇到了一个问题。

我有三个函数,loadunloadreload 以 cogs 的形式扩展。 loadunload 命令的创建完全没问题,但我在使用 reload 命令时遇到了问题。

为了不重复代码,我想在reload(extension) 命令中调用unload(extension)load(extension,但是,我还没有弄清楚该怎么做。

这是我的代码:

import discord
from discord.ext import commands
import os
from settings import BOT_TOKEN

client = commands.Bot(command_prefix=(".", "!", "?", "-"))

@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.idle)
    print("Discord_Bot is ready")

@client.command()
async def load(ctx, extension):
    client.load_extension("cogs.{0}".format(extension))

@client.command()
async def unload(ctx, extension):
    client.unload_extension("cogs.{0}".format(extension))

@client.command()
async def reload(ctx, extension):
    await ctx.invoke(client.get_command("unload({0}".format(extension)))
    await ctx.invoke(client.get_command("load({0})".format(extension)))

# Load Cogs on Boot
for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        client.load_extension("cogs.{0}".format(filename[:-3]))


client.run(BOT_TOKEN)

我还有一个example_cog.py 用于测试loadunloadreload 命令的功能。此文件中没有命令,只是作为 cog 运行所需的基本命令。

example_cog.py

import discord
from discord.ext import commands

class Example_Cog(commands.Cog):
    def __init__(self, client):
        self.client = client


def setup(client):
    client.add_cog(Example_Cog(client))

当我在我的私人不和谐服务器上使用机器人并尝试重新加载时,它不起作用。我已阅读文档,但无法弄清楚如何将参数传递给 bot.get_command() 函数。对于这个问题,我将不胜感激。

我尝试了许多不同的方法来使用bot.get_command() 函数,但没有一种方法有效。其中包括:

await ctx.invoke(client.get_command("unload {0}".format(extension)))


await ctx.invoke(client.get_command("unload({0})".format(extension)))

谢谢,本

【问题讨论】:

    标签: python discord.py discord.py-rewrite


    【解决方案1】:

    您需要以字符串类型传递命令名称。示例:

    @bot.event
    async def on_ready():
        # call command without args
        await bot.get_command('examplecommand').callback()
        # call command with args
        await bot.get_command('exampleArgsCommand').callback(ctx, message)
    
    @bot.command()
    async def examplecommand():
        pass
    
    @bot.command()
    async def exampleArgsCommand(ctx, message):
        pass
    

    【讨论】:

    • 我意识到我需要将命令的名称作为字符串传递,但我已经做到了。尝试输入该命令的参数时出现问题。
    • 您不需要为命令传递参数。你想调用这个命令吗?
    • 是的,我想调用卸载命令。但是,卸载命令接受一个扩展参数。这告诉命令要卸载哪个扩展。如果我不传递参数,它怎么知道要卸载哪个扩展?
    • 试试这个方法,我觉得对你有帮助。
    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    相关资源
    最近更新 更多