BenWornes
BenWornes

Reputation: 91

How to pass arguments into a command being passed into bot.get_command() in a discord bot?

I am dabbling in the creation of a discord bot for my private discord server and I have run into an issue.

I have three functions that load, unload and reload extensions in the form of cogs. The creation of the load and unload commands are totally fine but I am having trouble with the reload command.

In the interest of not repeating code, I want to call unload(extension) and load(extension inside of the reload(extension) command, however, I have not yet been able to figure out how to do so.

Here is my code:

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)

I also have an example_cog.py I use to test the functionality of the load, unload and reload commands. There are no commands in this file, just the basics needed to function as a 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))

When I use the bot on my private discord server and try to reload, it does not work. I have read the documentation and I cannot figure out how to pass arguments into the bot.get_command() function. I would vastly appreciate help on this issue.

I have tried many different ways of using the bot.get_command() function but none of them work. These include:

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


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

Thanks, Ben

Upvotes: 0

Views: 2874

Answers (1)

user12991524
user12991524

Reputation:

You need to pass name of command in string type. Example:

@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

Upvotes: 1

Related Questions