Ask Your Question
1

How can I get my existing bot to function with my slash command using Discord.Py?

asked 2022-10-21 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-02-05 16:00:00 +0000

lakamha gravatar image

You can use the @client.command() decorator to create a function for your slash command. You will also need to create an application command on the Discord Developer Portal and update your bot's OAuth2 scope to include the applications.commands permission.

Here's an example:

import discord
from discord.ext import commands

client = commands.Bot(command_prefix='!')

@client.event
async def on_ready():
    print('Bot is ready')

@client.command()
async def mycommand(ctx):
    await ctx.send('This is my command')

client.run('your_token_here')

To convert this to a slash command, we need to make a few changes:

import discord
from discord_slash import SlashCommand, SlashContext
from discord.ext import commands

client = commands.Bot(command_prefix='!')
slash = SlashCommand(client, sync_commands=True)

@client.event
async def on_ready():
    print('Bot is ready')
    guild_ids = [your_guild_id_here] # replace with your server id
    await slash.sync_all_commands(guild_ids=guild_ids)

@slash.slash(name='mycommand')
async def _mycommand(ctx: SlashContext):
    await ctx.send('This is my command')

client.run('your_token_here')

In this example, we import the discord_slash library and create a SlashCommand object. We also update the on_ready event to call slash.sync_all_commands() to create the application command on Discord.

Finally, we add the @slash.slash() decorator to our function and replace ctx with SlashContext. Now, when a user enters the slash command /mycommand, the bot will respond with "This is my command".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-21 11:00:00 +0000

Seen: 10 times

Last updated: Feb 05 '22