Search code examples
pythondiscordbots

How to let a Discord bot run a slash command created by itself


I am currently searching for a solution to my problem: I want to know if it is possible to let a Discord bot run a slash command which was created by the same Discord bot.

This is my current code of the bot:

import discord
from discord import app_commands 

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents = discord.Intents.all())
        self.synced = False #we use this so the bot doesn't sync commands more than once

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced: #check if slash commands have been synced 
            await tree.sync(guild = discord.Object(id=1204091669943816213)) #guild specific: leave blank if global (global registration can take 1-24 hours)
            self.synced = True
        
        channel_id = 1204102053064871946  # Channel ID to clear messages
        channel = self.get_channel(channel_id)
        if channel:
            await channel.purge(limit=1)  # Delete all messages in the channel
            user = client.get_user(int(716235295032344596))
        print(f"We have logged in as {self.user}.")

class button_view(discord.ui.View):
    def __init__(self) -> None:
        super().__init__(timeout=None)
    
    @discord.ui.button(label = "Verify", style = discord.ButtonStyle.green, custom_id = "role_button")
    async def verify(self, interaction: discord.Interaction, button: discord.ui.Button):
        client.role = interaction.guild.get_role(1204110443258318928)
        if client.role not in interaction.user.roles:
            await interaction.user.add_roles(client.role)
            await interaction.response.send_message(f"I have given you {client.role.mention}!", ephemeral = True)

            with open("verified.txt", "w") as file:
                file.write(str(interaction.user.id) + "\n")

        else: await interaction.response.send_message(f"You already have {client.role.mention}!", ephemeral = True)

client = aclient()
tree = app_commands.CommandTree(client)


@tree.command(guild = discord.Object(id=1204091669943816213), name='rules', description='Rules')
async def rules(interaction: discord.Interaction):
    role_id = 1205862534280642640 
    role = discord.utils.get(interaction.guild.roles, id=role_id)
    if role in interaction.user.roles:
        embed2=discord.Embed(title="📜 Rules 📜", description=''' 
        **§1 -** __Be respectful__: Treat others with kindness and respect. Harassment, hate speech, or any form of discrimination will not be tolerated.\n
        **§2 -** __Keep discussions civil__: Debates and discussions are encouraged, but avoid personal attacks or insults. Disagreements should be handled respectfully.\n
        **§3 -** __No spam or self-promotion__: Avoid flooding the chat with unnecessary messages or advertisements.\n
        **§4 -** __Use appropriate content__: Keep conversations and content appropriate for all ages. NSFW (Not Safe For Work) content is strictly prohibited.\n
        **§5 -** __No trolling__: Do not engage in trolling, flaming, or intentionally disrupting the server environment. This includes excessive use of emojis or CAPS LOCK.\n
        **§6 -** __Follow Discord's Terms of Service and Community Guidelines__: Make sure all activities within the server comply with Discord's terms and guidelines.\n
        **§7 -** __Respect server staff__: Follow the instructions of moderators and administrators. Disrespect towards server staff will not be tolerated.\n
        **§8 -** __Use channels appropriately__: Post content in relevant channels and avoid off-topic discussions. If unsure, ask a staff member for guidance.\n
        **§9 -** __Report violations__: If you encounter any violations of the rules or Discord's guidelines, report them to the server staff.
        ''', color=discord.Colour.blue())
        embed2.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Userbox_creeper.svg/800px-Userbox_creeper.svg.png")
        await interaction.response.send_message(embed=embed2, view = button_view())
    else:
        await interaction.response.send_message("You don't have permission to execute this command.", ephemeral=True)

client.run('Token')

In the on_ready Function I want the bot to run the rules slash command after theif channel:.


Solution

  • I want to know if it is possible to let a Discord Bot run a Slash Command which was created by the same Discord Bot.

    No.
    Regardless of who’s command it is, bots cannot execute them.

    Application commands (slash commands) are user initiated hence you not being able to find any documentation on it.

    If you’re looking to send the rules embed again there after your if channel then you need to extract the code creating your rules embed, and call that function inside your if channel

    For example:

    def getRulesEmbed():
            embed2=discord.Embed(title="📜 Rules 📜", description=''' 
            **§1 -** __Be respectful__: Treat others with kindness and respect. Harassment, hate speech, or any form of discrimination will not be tolerated.\n
            **§2 -** __Keep discussions civil__: Debates and discussions are encouraged, but avoid personal attacks or insults. Disagreements should be handled respectfully.\n
            **§3 -** __No spam or self-promotion__: Avoid flooding the chat with unnecessary messages or advertisements.\n
            **§4 -** __Use appropriate content__: Keep conversations and content appropriate for all ages. NSFW (Not Safe For Work) content is strictly prohibited.\n
            **§5 -** __No trolling__: Do not engage in trolling, flaming, or intentionally disrupting the server environment. This includes excessive use of emojis or CAPS LOCK.\n
            **§6 -** __Follow Discord's Terms of Service and Community Guidelines__: Make sure all activities within the server comply with Discord's terms and guidelines.\n
            **§7 -** __Respect server staff__: Follow the instructions of moderators and administrators. Disrespect towards server staff will not be tolerated.\n
            **§8 -** __Use channels appropriately__: Post content in relevant channels and avoid off-topic discussions. If unsure, ask a staff member for guidance.\n
            **§9 -** __Report violations__: If you encounter any violations of the rules or Discord's guidelines, report them to the server staff.
            ''', color=discord.Colour.blue())
            embed2.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Userbox_creeper.svg/800px-Userbox_creeper.svg.png")
            return embed2
    

    And then you can get the rules and send it inside the if statement.

    rules = getRulesEmbed()