I’m working on a Discord bot and I need to figure out how to make it execute one of its own slash commands programmatically. Specifically, I want the bot to trigger a slash command that it registered during the on_ready event.
Here’s my bot setup:
import discord
from discord import app_commands
class MyBot(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.all())
self.commands_synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.commands_synced:
await command_tree.sync(guild=discord.Object(id=1234567890123456789))
self.commands_synced = True
target_channel_id = 9876543210987654321
target_channel = self.get_channel(target_channel_id)
if target_channel:
await target_channel.purge(limit=1)
# I want to programmatically run the /welcome command here
print(f"Bot is ready: {self.user}")
class WelcomeView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Accept", style=discord.ButtonStyle.primary, custom_id="accept_btn")
async def accept_terms(self, interaction: discord.Interaction, button: discord.ui.Button):
member_role = interaction.guild.get_role(1111111111111111111)
if member_role not in interaction.user.roles:
await interaction.user.add_roles(member_role)
await interaction.response.send_message(f"Welcome! You now have {member_role.mention}!", ephemeral=True)
else:
await interaction.response.send_message(f"You already have {member_role.mention}!", ephemeral=True)
bot = MyBot()
command_tree = app_commands.CommandTree(bot)
@command_tree.command(guild=discord.Object(id=1234567890123456789), name='welcome', description='Display welcome message')
async def welcome_command(interaction: discord.Interaction):
required_role_id = 2222222222222222222
required_role = discord.utils.get(interaction.guild.roles, id=required_role_id)
if required_role in interaction.user.roles:
welcome_embed = discord.Embed(
title="🎉 Welcome to the Server! 🎉",
description="Please read and accept our terms to continue.",
color=discord.Color.green()
)
await interaction.response.send_message(embed=welcome_embed, view=WelcomeView())
else:
await interaction.response.send_message("Access denied.", ephemeral=True)
bot.run('YOUR_TOKEN')
I need the bot to automatically execute the /welcome slash command in the on_ready method after clearing the channel. Is this possible and how would I implement it?