A full-featured giveaway bot with buttons! That's a great project. Here's a comprehensive example of a Discord.py bot that includes:
- Giveaway creation: Users can create giveaways with various options (e.g., prize, duration, number of winners, required role, etc.).
- Button interactions: Users can participate in giveaways by clicking a button.
- Giveaway management: The bot can list, edit, cancel, and reroll giveaways.
- Automatic giveaway ending: The bot will automatically end giveaways when the duration is over.
- Embed-rich responses: Pretty, informative embeds for all interactions.
Requirements:
- discord.py 2.0 or higher (
pip install discord.py)
- discord.py's
buttons feature ( included in 2.0+)
Here's the full code:
import discord
from discord.ext import commands, tasks
import asyncio
from datetime import datetime, timedelta
import random
# Bot setup
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
# Giveaway storage
giveaways = {}
# Helper function to convert time (e.g., "1d" -> 86400 seconds)
def convert_time(time_str):
units = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
if time_str[-1] in units:
return int(time_str[:-1]) * units[time_str[-1]]
else:
raise ValueError("Invalid time format. Use: Xs, Xm, Xh, Xd, Xw")
# Task to end giveaways automatically
@tasks.loop(seconds=60)
async def check_giveaways():
for giveaway_id, giveaway_data in list(giveaways.items()):
if giveaway_data["end_time"] <= datetime.now():
await end_giveaway(giveaway_id)
# Event to start the task
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
check_giveaways.start()
# Button class for giveaway participation
class ParticipateButton(discord.ui.Button):
def __init__(self, giveaway_id):
super().__init__(label="Participate", style=discord.ButtonStyle.green, emoji="🎉")
self.giveaway_id = giveaway_id
async def callback(self, interaction: discord.Interaction):
user = interaction.user
giveaway_data = giveaways.get(self.giveaway_id)
if not giveaway_data:
return await interaction.response.send_message("Giveaway not found!", ephemeral=True)
if user.id in giveaway_data["participants"]:
return await interaction.response.send_message("You're already participating!", ephemeral=True)
required_role_id = giveaway_data.get("required_role_id")
if required_role_id and required_role_id not in [r.id for r in user.roles]:
return await interaction.response.send_message(f"You need the <@&{required_role_id}> role to participate!", ephemeral=True)
giveaways[self.giveaway_id]["participants"].append(user.id)
await interaction.response.send_message("You've participated in the giveaway! Good luck!", ephemeral=True)
# Update the giveaway message
channel = bot.get_channel(giveaway_data["channel_id"])
message = await channel.fetch_message(self.giveaway_id)
participants_num = len(giveaway_data["participants"])
embed = message.embeds[0]
embed.set_field_at(1, name="Participants", value=str(participants_num), inline=True)
await message.edit(embed=embed)
# Function to create a new giveaway
@bot.slash_command(name="giveaway", description="Create a new giveaway")
async def create_giveaway(ctx,
prize: str,
duration: str,
winners: int = 1,
required_role: discord.Role = None):
try:
duration_seconds = convert_time(duration)
except ValueError as e:
return await ctx.respond(str(e), ephemeral=True)
end_time = datetime.now() + timedelta(seconds=duration_seconds)
giveaway_id = int(datetime.now().timestamp() * 1000) # Unique ID
view = discord.ui.View(timeout=None)
view.add_item(ParticipateButton(giveaway_id))
embed = discord.Embed(title="🎉 New Giveaway! 🎉", color=0x00ff00)
embed.add_field(name="Prize", value=prize, inline=False)
embed.add_field(name="Participants", value="0", inline=True)
embed.add_field(name="Winners", value=str(winners), inline=True)
embed.add_field(name="Ends", value=f"<t:{int(end_time.timestamp())}:R>", inline=False)
if required_role:
embed.add_field(name="Required Role", value=required_role.mention, inline=False)
message = await ctx.respond(embed=embed, view=view)
message_id = message.id
giveaways[message_id] = {
"prize": prize,
"channel_id": ctx.channel_id,
"end_time": end_time,
"winners": winners,
"required_role_id": required_role.id if required_role else None,
"participants": []
}
await asyncio.sleep(duration_seconds)
await end_giveaway(message_id)
# Function to end a giveaway
async def end_giveaway(giveaway_id):
giveaway_data = giveaways.pop(giveaway_id, None)
if not giveaway_data:
return
channel = bot.get_channel(giveaway_data["channel_id"])
message = await channel.fetch_message(giveaway_id)
# Reroll if there are participants
if giveaway_data["participants"]:
winners = random.sample(giveaway_data["participants"], min(giveaway_data["winners"], len(giveaway_data["participants"])))
winner_mentions = ", ".join(f"<@{winner_id}>" for winner_id in winners)
embed = discord.Embed(title="🎉 Giveaway Ended! 🎉", color=0xff0000)
embed.add_field(name="Prize", value=giveaway_data["prize"], inline=False)
embed.add_field(name="Winner(s)", value=winner_mentions, inline=False)
await channel.send(embed=embed)
else:
await channel.send("Giveaway ended with no participants!")
# Disable the participate button
view = discord.ui.View(timeout=None)
for item in message.components:
for button in item.children:
button.disabled = True
await message.edit(view=view)
# Command to list all active giveaways
@bot.slash_command(name="giveaways", description="List all active giveaways")
async def list_giveaways(ctx):
if not giveaways:
return await ctx.respond("No active giveaways!", ephemeral=True)
embed = discord.Embed(title="Active Giveaways", color=0x00ff00)
for giveaway_id, giveaway_data in giveaways.items():
channel = bot.get_channel(giveaway_data["channel_id"])
message = await channel.fetch_message(giveaway_id)
embed.add_field(name=giveaway_data["prize"],
value=f"[Jump to Giveaway]({message.jump_url}) | Ends: <t:{int(giveaway_data['end_time'].timestamp())}:R>",
inline=False)
await ctx.respond(embed=embed)
# Command to edit a giveaway (duration, winners, required role)
@bot.slash_command(name="edit-giveaway", description="Edit an existing giveaway")
async def edit_giveaway(ctx,
message_id: str,
duration: str = None,
winners: int = None,
required_role: discord.Role = None):
try:
message_id = int(message_id)
except ValueError:
return await ctx.respond("Invalid message ID!", ephemeral=True)
giveaway_data = giveaways.get(message_id)
if not giveaway_data:
return await ctx.respond("Giveaway not found!", ephemeral=True)
if duration:
try:
duration_seconds = convert_time(duration)
except ValueError as e:
return await ctx.respond(str(e), ephemeral=True)
giveaway_data["end_time"] = datetime.now() + timedelta(seconds=duration_seconds)
if winners:
giveaway_data["winners"] = winners
if required_role:
giveaway_data["required_role_id"] = required_role.id
channel = bot.get_channel(giveaway_data["channel_id"])
message = await channel.fetch_message(message_id)
embed = message.embeds[0]
# Update relevant fields in the embed
if duration:
embed.set_field_at(2, name="Ends", value=f"<t:{int(giveaway_data['end_time'].timestamp())}:R>", inline=False)
if winners:
embed.set_field_at(1, name="Winners", value=str(winners), inline=True)
if required_role:
if len(embed.fields) > 4:
embed.set_field_at(3, name="Required Role", value=required_role.mention, inline=False)
else:
embed.add_field(name="Required Role", value=required_role.mention, inline=False)
await message.edit(embed=embed)
await ctx.respond("Giveaway updated!", ephemeral=True)
# Command to cancel a giveaway
@bot.slash_command(name="cancel-giveaway", description="Cancel an existing giveaway")
async def cancel_giveaway(ctx, message_id: str):
try:
message_id = int(message_id)
except ValueError:
return await ctx.respond("Invalid message ID!", ephemeral=True)
giveaway_data = giveaways.pop(message_id, None)
if not giveaway_data:
return await ctx.respond("Giveaway not found!", ephemeral=True)
channel = bot.get_channel(giveaway_data["channel_id"])
message = await channel.fetch_message(message_id)
# Disable the participate button
view = discord.ui.View(timeout=None)
for item in message.components:
for button in item.children:
button.disabled = True
button.label = "Cancelled"
button.style = discord.ButtonStyle.red
await message.edit(view=view)
await ctx.respond("Giveaway cancelled!", ephemeral=True)
# Command to reroll a giveaway's winners
@bot.slash_command(name="reroll-giveaway", description="Reroll the winner(s) of a giveaway")
async def reroll_giveaway(ctx, message_id: str):
try:
message_id = int(message_id)
except ValueError:
return await ctx.respond("Invalid message ID!", ephemeral=True)
giveaway_data = giveaways.get(message_id)
if not giveaway_data:
return await ctx.respond("Giveaway not found!", ephemeral=True)
if not giveaway_data["participants"]:
return await ctx.respond("No participants to reroll!", ephemeral=True)
winners = random.sample(giveaway_data["participants"], min(giveaway_data["winners"], len(giveaway_data["participants"])))
winner_mentions = ", ".join(f"<@{winner_id}>" for winner_id in winners)
embed = discord.Embed(title="🎉 Giveaway Rerolled! 🎉", color=0x00ff00)
embed.add_field(name="Prize", value=giveaway_data["prize"], inline=False)
embed.add_field(name="New Winner(s)", value=winner_mentions, inline=False)
await ctx.respond(embed=embed)
# Run the bot with your token (replace 'YOUR_BOT_TOKEN')
bot.run('YOUR_BOT_TOKEN')
How it works:
-
create_giveaway command: Users create a giveaway with prize, duration (e.g., "1d", "2h", "30m"), number of winners, and an optional required role.
- A unique message ID serves as the giveaway ID.
- A button (via
ParticipateButton class) is attached to the giveaway message for users to participate.
- Giveaway details are stored in the
giveaways dictionary.
-
ParticipateButton class: Handles button clicks.
- Checks if the user has the required role (if any).
- Adds the user's ID to the giveaway's participants list.
- Updates the participant count in the giveaway embed.
-
check_giveaways task: Runs every minute, checks for ended giveaways, and calls end_giveaway.
-
end_giveaway function:
- Picks winner(s) randomly from participants (if any).
- Sends an embed announcing the winner(s).
- Disables the participate button.
-
Other commands:
list_giveaways: Shows all active giveaways with links.
edit_giveaway: Modifies a giveaway's duration, winners, or required role.
cancel_giveaway: Stops a giveaway and disables its button.
reroll_giveaway: Picks new winner(s) for an existing (ended or active) giveaway.
To invite your bot:
- Go to the Discord Developer Portal.
- Select your application.
- Go to "OAuth2" > "URL Generator".
- Select
bot and applications.commands scopes.
- Choose permissions:
Send Messages, Embed Links, Manage Messages, Use Application Commands.
- Copy the generated URL, open it in your browser, and select a server to invite the bot.
Replace 'YOUR_BOT_TOKEN' with your actual bot token from the Discord Developer Portal.
Now, enjoy your fancy giveaway bot with buttons! 🎉
Example Use Cases:
!giveaway "A cool role" 7d 1 @SpecialMembers - Starts a 7-day giveaway for the "A cool role" prize, 1 winner, requiring the "SpecialMembers" role.
!giveaways - Lists all ongoing giveaways.
!edit-giveaway 123456789012345678 3d - Extends the giveaway with message ID 123456789012345678 to 3 days.
!cancel-giveaway 123456789012345678 - Cancels that giveaway.
!reroll-giveaway 123456789012345678 - Picks new winner(s) for the giveaway.
Happy coding, and may the odds be ever in your favor! 🍀