#Slash Command Not Working With Cogs

1 messages · Page 1 of 1 (latest)

quaint mulch
#

Does the reload command appear?

random heart
#

did you invite the bot with app cmd scope checked?

quaint mulch
#

Do you intend to use prefix commands?

#

ie !command

random heart
#

and ur sure the id in sgi is correct

quaint mulch
#
intents = disnake.Intents().all()
bot = commands.InteractionBot(
    command_sync_flags=commands.CommandSyncFlags.default(),
    intents=intents
)
#

add comand_sunc_flags

random heart
#

try to add print statements for ur load function too. see if they are properly loading

quaint mulch
#

I also believe you need to either supply doc strings or add a description to commands so add @bot.slash_command(description="Test Command")

candid carbon
#

Doc strings aren't required

#

nor is description

#

Add sync_commands_debug=True to InteractionBot(..., sync_commands_debug=True)

#

Then share the output

#

after you run the bot

#

Also, python version and disnake version?

#

in command, py --version

#

pip show disnake, i think

#

OK.

#

Checks out because of that warning, then

#

So do InteractionBot(..., command_sync_flags.commands.CommandSyncFlags.sync_commands_debug)

quaint mulch
#

command_sync_flags=commands.CommandSyncFlags.default() can change this to .all() to enable debug

#

Since its the only one left out of default

candid carbon
#

or yeah.. use all

#

But it should hve some output

#

So we can see the sync process

#

hmm

#

Remove the test guilds

#

If you're going to use them in each command anyway, just do it once in the Bot() instance with test_guilds=[]

#

but we'll add that back

#

Check the guild settings > integrations

#

See if it's even appearing there

#

So not even the /reload command appears...

#

🤔

quaint mulch
#

Really strange since the reload command should register no problem in this setup

candid carbon
#

Can we try a super simple barebones example?

quaint mulch
#

comment out he asyncio run main and only take out the bot.run at the bottom

candid carbon
#

Wait..

#

you're getting token from os.getenv.

#

So you have the token already in the environment. It's starting, just not registering any commands, right?

#

OK.

#
import os

import disnake
from disnake.ext import commands


bot = commands.InteractionBot(intents=disnake.Intents.default())

@bot.listen()
async def on_ready():
  print(f"{bot.user} is online")

@bot.slash_command(name='test')
async def test(inter: disnake.GuildCommandInteraction):
    await inter.response.send_message("Success")


bot.run(os.getenv('TOKEN'))
quaint mulch
#

Would be very worried if it did not x)

candid carbon
#

Lol. Me too 😄

#

Sure.

quaint mulch
#

Champ, how do you feel about starting the bot through asyncio.run()?

candid carbon
#

It's how I start mine.

#

Just preparing for the inevitable await bot.load_extension()

quaint mulch
#

Really strange problem, in any case then load should not be async here either right?
Don't see anything obviously wrong here so im intrigued

candid carbon
#

I don't imagine it hurts anything to make it async.

#

My load_extensions() is the same, just wraps the synchronous load_extension() method, but when the time comes, it's the matter of just awaiting that one method call and should be good to go.

quaint mulch
#

Hmm. got it to work

#
# imports

import asyncio
import os
import disnake

from disnake.ext import commands
from dotenv import load_dotenv

# vars
load_dotenv('.env')
red = 0xE74C3C
green = 0x2ECC71
sgi = [934462932669038732]

# bot

intents = disnake.Intents().all()
bot = commands.InteractionBot(
    command_sync_flags=commands.CommandSyncFlags.all(),
    intents=intents
)

# cogs

@bot.event
async def on_ready():
    await load()

@bot.slash_command(guild_ids=sgi)
async def reload(ctx, group):
  if group != "dev":
    await ctx.send("invalid input")
  else:
    for filename in os.listdir('./cogs'):
      if filename.startswith(group) and filename.endswith('.py'):
        bot.reload_extension(f'cogs.{filename[:-3]}')
        await ctx.send(f"refreshing {group} cog")

async def load():
  for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
      bot.load_extension(f'cogs.{filename[:-3]}')


bot.run(os.getenv("TOKEN"))
#
Application command synchronization:
COMMANDS IN 934462932669038732
===============================
| Update is required: True
| To upsert:
|     <SlashCommand name='alohaz'>
| To edit:
|     -
| To delete:
|     -
| No changes:
|     <SlashCommand name='reload'>
Command synchronization task has finished
candid carbon
#

on_ready() can be called more than once, though.

#

As the bot gets larger, it tends to be more of an issue.

quaint mulch
#

Or if you have spotty internet

candid carbon
#

or that.

#

Or even just a hiccup in between you and the gateway

#

Usually a good idea to not do much of anything in on_ready for that reason, though

quaint mulch
#

Not sure why i could not get it to run with asyncio

#

same symptoms, it logged on but nothing happened

candid carbon
#
"""
A simple boilerplate bot main module to create a bot and load
the available cogs.

More for my testing and not really for your use
"""

import asyncio
import os
import sys

import disnake
from disnake.ext import commands
from dotenv import load_dotenv
from loguru import logger

load_dotenv(".env", override=True)


INTENTS = disnake.Intents.all()
TOKEN = os.getenv("TOKEN")


class MyBot(commands.InteractionBot):
    """base bot instance"""

    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)

    async def on_ready(self) -> None:
        print("Ready")

    def load_extensions(self, path: str) -> None:

        for module in os.listdir(path):
            name, ext = os.path.splitext(module)

            if "__" in name or ext != ".py":
                continue

            extension = f"cogs.{name}"

            super().load_extension(extension)
            logger.info(f"Cog loaded: {extension}")


async def main() -> None:
    """Constructs bot, load extensions, and starts bot"""

    bot = MyBot(intents=INTENTS, reload=True)

    try:
        bot.load_extensions("cogs/")
    except Exception:
        await bot.close()
        raise

    logger.info("Starting bot")
    await bot.start(TOKEN or "")


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))

this is my main from my module testing bot

#

works just fine.

#

though in this example, load_extensions isn't async

#

It's more focused on just running for testing various cogs that I'm working on

quaint mulch
#

Couldn't you use the built in load_extentions?

candid carbon
#

Yes.

#

But some of the code came from a different bot.

#

And the cogs were setup like: cog.sub.module

#

I could have just redid it, but I just changed a couple lines instead after copying it over, and I just added a log.info line as it's loading them

#

But the point was more that that has no issues using a main() func and starting it with asyncio.run()

quaint mulch
#

Yeah, that worked fine

candid carbon
#

I'm completely confused why their version at the top wasn't working.

quaint mulch
#

More confused why its half working x) Because its obviously doing something. Just not syncing commands

#

moving the bot definition inside main helped

#
async def load(bot):
  for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
      bot.load_extension(f'cogs.{filename[:-3]}')

async def main() -> None:
    """Constructs bot, load extensions, and starts bot"""
    bot = commands.InteractionBot(
    command_sync_flags=commands.CommandSyncFlags.all(),
    intents=intents
)

    try:
        await load(bot)
        await bot.start(TOKEN)

    except Exception:
        await bot.close()
        raise


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))
#

That also means the reload command needs to be moved inside too

candid carbon
#

Yeah. Jay had an issue with that, too

#

For some reason it doesn't like having the bot instantiated outside main then run called within main

#

MAYBE, async def main(bot) would make it less cranky about it, but.. 🤷

random heart
normal wagon
#

it's just really bad design

candid carbon
#

Oh right