Contents

discord-components simple bot example

0
Contents

Here is a simple Python script that uses the discord-components library to create a simple Discord bot with interactive components:

import discord
from discord_components import DiscordComponents, Button, ButtonStyle

# Create a new bot client
client = discord.Client(intents=discord.Intents.default())
# Initialize the DiscordComponents extension
DiscordComponents(client)

@client.event
async def on_ready():
    print(f"We have logged in as {client.user}")

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content == "!interactive":
        # Send a message with interactive buttons
        await message.channel.send(
            "Click a button:",
            components=[
                Button(style=ButtonStyle.blue, label="Blue Button", custom_id="blue_button"),
                Button(style=ButtonStyle.green, label="Green Button", custom_id="green_button"),
            ],
        )

@client.event
async def on_button_click(interaction):
    if interaction.component.custom_id == "blue_button":
        await interaction.respond(content="You clicked the blue button!")
    elif interaction.component.custom_id == "green_button":
        await interaction.respond(content="You clicked the green button!")

# Replace 'YOUR_TOKEN' with your bot token
client.run('YOUR_TOKEN')

Make sure you have the discord.py and discord-components libraries installed before running this script. You can install them using pip:

pip install discord.py discord-components

Remember to replace 'YOUR_TOKEN' with your actual bot token, which you can obtain by creating a bot application on the Discord Developer Portal.

This script sets up a Discord bot that responds to the command !interactive by sending a message with two interactive buttons. When a button is clicked, the on_button_click event handler is triggered, and the bot responds accordingly with a message.

Note that you need to have the necessary permissions to add and interact with components in your Discord server.

About discord.py

discord.py - A Python wrapper for the Discord API.

About discord-components

discord-components - An unofficial library for discord components.