#cannot use slash command.

1 messages · Page 1 of 1 (latest)

ocean tusk
#

I want to use guild slash command. but cannot register.

i can use role command but cannot use set_role

I use ext.Cog. version: 2.0.0rc1

from typing import List

from discord import ApplicationContext, Option, Role
from discord.ext.commands import Cog, Bot, slash_command, command, Context


class RoleManager(Cog):
    def __init__(self, bot: Bot):
        self.bot = bot

    @slash_command(guild_ids=[893402769254404117])
    async def set_role(
            self,
            ctx: ApplicationContext,
            role_id: Option(int, description="Choice Role")
    ):
        role = ctx.guild.get_role(int(role_id))
        if await ctx.author.add_roles(role):
            await ctx.respond(f"{role.mention} added.", ephemeral=True)

    @command()
    async def role(
            self,
            ctx: Context,
            role_id: str
    ):
        if not role_id: return await ctx.send("required role id.")
        if not role_id.isdigit(): return await ctx.send("you type integer number of role.")
        await ctx.author.add_roles(ctx.guild.get_role(int(role_id)))


def setup(bot: Bot):
    bot.add_cog(RoleManager(bot=bot))
ocean tusk
#

and I test 2.0.0b7 again, cannot register.

    r = requests.get(f'https://discord.com/api/applications/{self.user.id}/guilds/893402769254404117/commands',
                         headers={"Authorization": f"Bot {getenv('TOKEN')}"})
    print(r.json())

returned []

balmy saffron
#

Did you invite the bot with the application.commands scope?

ocean tusk
#

OAuth2 URL too.

dark surge
#

Alternatively, you can use @slash_command(name=“role”) or create a command group called set and make a sub command called role.

tardy totemBOT
#

Here's the slash cog groups example.

ocean tusk
#

when I create bot (didn't use cog) , this command worked.

#

and try again with this. cannot use.

    @slash_command(name="role", guild_ids=[893402769254404117, 981736908814155787])
    async def set_role(
            self,
            ctx: ApplicationContext,
            any: Option(str)
    ):
        # print(role_id)
        await ctx.respond("respond!")
plucky olive
serene oyster
plucky olive
#

^

ocean tusk
#

Is this just me this problem?

plucky olive
#

Can you try it without the
ctx: ApplicatipnContext

ocean tusk
#
@slash_command(name="role", guild_ids=guild_ids)
async def set_role(
        self,
        ctx #: ApplicationContext
):
    print("slash")

-> cannot use.

@slash_command(name="role", guild_ids=guild_ids)
async def set_role(
        self,
):
    print("slash")

-> ClientException: Callback for role command is missing "ctx" parameter.

plucky olive
#

im mean jus use ctx

#

(self, ctx)
.
.

ocean tusk
#
@slash_command(name="role", guild_ids=guild_ids)
async def set_role(
        self,
        ctx #: ApplicationContext
):
    print("slash")

cannot use.

serene oyster
#

are you in a class?

ocean tusk
#

ys

#

that's all.↓
role_manager.py

import re
from typing import List, Any

from discord import ApplicationContext, Option, Role
from discord.ext.commands import Cog, Bot, slash_command, command, Context, group

from cogs import guild_ids, kotlin_role, java_role


class RoleManager(Cog):
    def __init__(self, bot: Bot):
        self.bot = bot

    @slash_command(name="role", guild_ids=guild_ids)
    async def set_role(
            self,
            ctx
    ):
        print("WW")
        # if isinstance(any, Role):
        #     if any.id not in (kotlin_role, java_role):
        #         return await ctx.send("no Role.")
        #
        #     await ctx.author.add_roles(any)
        # # print(role_id)
        # await ctx.respond("respond!")

    @group()
    async def set(
            self,
            ctx: Context,
            *args: Any
    ):
        return await ctx.send("no args after ctx.")

    @set.command()
    async def role(
            self,
            ctx: Context,
            _role: str,
            role_id: str
    ):
        if not role_id:
            return await ctx.send(r"required role `\@AnyRole` or id.")

        if role_id.isdigit():
            role = self.bot.get_guild(ctx.guild.id).get_role(int(role_id))

        else:
            role = re.match(r".*(<@&\d{18,19}>)", role_id, 1)
            role = self.bot.get_guild(ctx.guild.id).get_role(int(role.groups()[0])) if role is not None else None

        await ctx.author.add_roles(role) if role else await ctx.send("Invalid role")


def setup(bot: Bot):
    bot.add_cog(RoleManager(bot=bot))
#

main.py

import re
import traceback
from datetime import datetime
from os import getenv
from typing import List, Union

import discord
import requests
from discord import Intents, ExtensionNotFound, ExtensionError, Game
from discord.ext.commands import Bot
from dotenv import load_dotenv


load_dotenv()
INITIAL_EXTENTIONS: List[str] = [
    "cogs.channel_manager",
    "cogs.event",
    "dispand",
    "cogs.role_manager",
]


class Main(Bot):
    def __init__(
            self,
            intents: Intents,
            command_prefix: Union[str, List[str]],
    ):
        super().__init__(
            help_command=None,
            intents=intents,
            command_prefix=command_prefix,
        )
        self.load = self.noload = 0

    async def on_ready(self) -> None:
        for cog in INITIAL_EXTENTIONS:
            try:
                self.load_extension(cog)
                self.load += 1

            except (ExtensionNotFound, ExtensionError) as e:
                print(traceback.TracebackException.from_exception(e))
                self.noload += 1
        x = (len(INITIAL_EXTENTIONS) - (self.load + self.noload))
        await self.change_presence(
            activity=Game(
                name=f"{len(self.users)}人が{self.user.name}",
            )
        )

        print(
            f'already Loaded: {self.load}\n'
            f'cannot Loading: {self.noload}\n'
            f'Files Unloaded: {x if (x >= 0) else 0}'
        )

        print(f'{self.user.id}: {self.user.name} version: {discord.__version__}')
        r = requests.get(f'https://discord.com/api/applications/{self.user.id}/guilds/893402769254404117/commands',
                         headers={"Authorization": f"Bot {getenv('TOKEN')}"})
        print(r.json())


if __name__ == "__main__":
    intents = Intents.all()
    command_prefix = "*"
    main = Main(
        intents=intents,
        command_prefix=command_prefix
    )
    main.run(getenv("TOKEN"))
ocean tusk
#

everyone can make slash command with Cog?

inner slate
#

@bot.command(
name="say_something",
description="say something!",
default_member_permissions=interactions.Permissions.ADMINISTRATOR, # admin-only
scope=931114842021044275,
options = [
interactions.Option(
name="text",
description="What you want to say",
type=interactions.OptionType.STRING,
required=True,
),
],
)
async def my_first_command(ctx: interactions.CommandContext, text: str):
await ctx.send(f"You said '{text}'!")

ocean tusk
#

serene oyster
#

so what is the error you get?

ocean tusk
serene oyster
ocean tusk
#

i write slash command, but cannot register.

ocean tusk
#

Can you guys register slash commands using cog....?

#

Is this only me?
when i don't use cog, i can use..

alpine sail
woven spear
#

IMO, do not load extension nor add cog under on_ready event

ocean tusk
#

and extention was all loaded.

ocean tusk
#

i create new test app and i can register commands. thx everyone.