New Answer
Discord.py 2.0 Allows for use of Buttons and Dropdowns, and has new added support for Slash Commands. A 3rd party repository is no longer necessary. However, if you don’t want to use the default one for some reason, you can checkout discord_slash
.
To upgrade to Discord.py 2.0:
Windows:
pip install -U git+https://github.com/Rapptz/discord.py
MacOS and Linux:
pip3 install -U git+https://github.com/Rapptz/discord.py
Old Answer:
(This Answer is OUTDATED.)
As of right now, you can get a library called discord_components
to use buttons.
To install this library, use pip install --upgrade discord-components
(Sometimes the command would be pip3 install --upgrade discord-components
).
To import Discord Component Buttons, use
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
Then just add this code in the bot’s on_ready()
:
DiscordComponents(bot, change_discord_methods=True)
(Make sure to replace bot
with the name of your bot, the same one you use for @something.command()
)
To add a button to a message, do this:
await ctx.send(type=InteractionType.ChannelMessageWithSource, content="Message Here", components=[Button(style=ButtonStyle.URL, label="Example Invite Button", url="https://google.com"), Button(style=ButtonStyle.blue, label="Default Button", custom_id="button")])
(A message is required)
To do something when the button is clicked, you can do something like this:
@bot.event
async def on_button_click(interaction):
if interaction.component.label.startswith("Default Button"):
await interaction.respond(type=InteractionType.ChannelMessageWithSource, content="Button Clicked")
This method even survives reboots!
Here’s an example I put together for you if you need it:
import discord
from discord.ext import commands
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
bot = commands.Bot(command_prefix=prefix, description="Desc", help_command=None)
@bot.event
async def on_ready():
DiscordComponents(bot, change_discord_methods=True)
await bot.change_presence(activity=discord.Game(name=f"{prefix}help"))
print("Bot has successfully logged in as: {}".format(bot.user))
print("Bot ID: {}\n".format(bot.user.id))
@bot.command()
async def button(ctx):
await ctx.send(type=InteractionType.ChannelMessageWithSource, content="Message Here", components=[Button(style=ButtonStyle.URL, label="Example Invite Button", url="https://google.com"), Button(style=ButtonStyle.blue, label="Default Button", custom_id="button")])
bot.run("token")
Hope this Helps!
Tip: If you want the buttons to be in one row, use [[]] instead of just [] for Example: [[btn1, btn2],[btn3, btn4]] will result in:
[btn 1][btn 2]
[btn 3][btn 4]
Extra Tip: You can also set a variable as a button then send the variable