Skip to main content

How to Create a Button on Your Python Discord Bot

1. Log In to Your Panel


2. Select the ‘Files’ Tab

Cybrancee Panel in the files page, "Files" tab on the sidebar is highlighted

3. Create Your Main Bot’s File

Create a new file called index.py then paste the following code.

Pterodactyl Panel, Create File dialog. Enter File Name (index.py)

What this code does:

  • It creates a Discord bot that sends interactive buttons when the /ping command is used.
  • The buttons allow users to perform quick actions with a single click: Ping! – Checks the bot’s latency and replies with the result.
  • The bot registers the /ping slash command automatically using the setup_hook when it starts.
  • Button interactions are handled so that responses are ephemeral, meaning only the user who clicked sees the reply.
  • The code demonstrates using discord.ui.View and discord.ui.Button for a modern, structured interaction flow.
# Calling our requirements
import discord
from discord import app_commands

# Setting our variables
TOKEN = 'YOUR_BOT_TOKEN'

class MyBot(discord.Client):
    def __init__(self):
        # Setting our intents
        intents = discord.Intents.default()
        super().__init__(intents=intents)
        # Register the /ping command via the CommandTree
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        # Synchronizes slash commands with Discord
        await self.tree.sync()
        print(f"Logged in as {self.user.name}")
        print("Slash command registered")

client = MyBot()

# --- Button Logic ---

class PingView(discord.ui.View):
    def __init__(self, bot_client):
        super().__init__()
        self.bot_client = bot_client

    # Creating the button
    @discord.ui.button(label="Ping!", style=discord.ButtonStyle.secondary, custom_id="ping_button")
    async def ping_button_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
        # Sends the response after the button was clicked
        # Calculate latency in milliseconds
        latency = round(self.bot_client.latency * 1000)
        await interaction.response.send_message(f"Pong! Latency is {latency}ms", ephemeral=True)

# --- Slash Command ---

@client.tree.command(name="ping", description="Sends a ping button")
async def ping(interaction: discord.Interaction):
    # When the command is used it sends the button attached to a view
    await interaction.response.send_message("Click the button to check latency:", view=PingView(client))

# Log in to Discord
client.run(TOKEN)

Button Example:

Discord Bot Example of Button

Discord Bot Hosting

Starts at $1.49

External link icon

Was this article helpful?
Please Share Your Feedback
How Can We Improve This Article?
Table of Contents