Here's a fully functional Discord bot with a giveaway system using Python and the discord.py library. This bot includes commands to start, end, and reroll giveaways, with features like reaction-based entry and random winner selection.
import discord
from discord.ext import commands, tasks
import random
import asyncio
import datetime
# Bot setup
intents = discord.Intents.default()
intents.message_content = True
intents.reactions = True
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
# Store active giveaways
giveaways = {}
# Event: Bot is ready
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
check_giveaways.start()
# Command: Start a giveaway
@bot.command()
@commands.has_permissions(manage_guild=True)
async def giveaway(ctx, duration: int, winners: int, *, prize: str):
"""
Start a giveaway
Usage: !giveaway <duration_in_minutes> <number_of_winners> <prize>
Example: !giveaway 60 1 "Nitro Subscription"
"""
if duration <= 0 or winners <= 0:
await ctx.send("Duration and number of winners must be greater than 0!")
return
# Create embed for giveaway
embed = discord.Embed(
title="🎉 New Giveaway! 🎉",
description=f"**Prize:** {prize}\n"
f"**Winners:** {winners}\n"
f"**Ends in:** {duration} minutes\n"
f"React with 🎉 to participate!",
color=discord.Color.green()
)
embed.set_footer(text=f"Started by {ctx.author.name}", icon_url=ctx.author.avatar.url if ctx.author.avatar else None)
# Send giveaway message
giveaway_msg = await ctx.send(embed=embed)
await giveaway_msg.add_reaction("🎉")
# Store giveaway data
end_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=duration)
giveaways[giveaway_msg.id] = {
'channel_id': ctx.channel.id,
'prize': prize,
'winners': winners,
'end_time': end_time,
'host': ctx.author.id,
'message_id': giveaway_msg.id
}
await ctx.send(f"Giveaway started! It will end in {duration} minutes.")
# Command: End a giveaway manually
@bot.command()
@commands.has_permissions(manage_guild=True)
async def endgiveaway(ctx, message_id: int):
"""
End a giveaway early
Usage: !endgiveaway <message_id>
"""
if message_id not in giveaways:
await ctx.send("No active giveaway found with that message ID!")
return
await end_giveaway(message_id)
await ctx.send("Giveaway ended manually!")
# Command: Reroll a giveaway
@bot.command()
@commands.has_permissions(manage_guild=True)
async def reroll(ctx, message_id: int):
"""
Reroll winners for a giveaway
Usage: !reroll <message_id>
"""
if message_id not in giveaways:
await ctx.send("No giveaway found with that message ID!")
return
giveaway = giveaways[message_id]
channel = bot.get_channel(giveaway['channel_id'])
message = await channel.fetch_message(message_id)
# Get participants
users = set()
for reaction in message.reactions:
if str(reaction.emoji) == "🎉":
async for user in reaction.users():
if not user.bot:
users.add(user)
if not users:
await ctx.send("No valid participants found!")
return
# Select new winners
winner_count = giveaway['winners']
winners = random.sample(list(users), min(winner_count, len(users)))
winner_mentions = " ".join(winner.mention for winner in winners)
await ctx.send(f"🎉 Rerolled! New winner(s) for '{giveaway['prize']}': {winner_mentions}")
# Function to end giveaway
async def end_giveaway(message_id):
if message_id not in giveaways:
return
giveaway = giveaways[message_id]
channel = bot.get_channel(giveaway['channel_id'])
message = await channel.fetch_message(message_id)
# Get participants
users = set()
for reaction in message.reactions:
if str(reaction.emoji) == "🎉":
async for user in reaction.users():
if not user.bot:
users.add(user)
if not users:
embed = discord.Embed(
title="🎉 Giveaway Ended! 🎉",
description=f"**Prize:** {giveaway['prize']}\n"
f"No winners! No valid participants.",
color=discord.Color.red()
)
await message.edit(embed=embed)
else:
# Select winners
winner_count = giveaway['winners']
winners = random.sample(list(users), min(winner_count, len(users)))
winner_mentions = " ".join(winner.mention for winner in winners)
embed = discord.Embed(
title="🎉 Giveaway Ended! 🎉",
description=f"**Prize:** {giveaway['prize']}\n"
f"**Winner(s):** {winner_mentions}",
color=discord.Color.blue()
)
await message.edit(embed=embed)
await channel.send(f"Congratulations {winner_mentions}! You won **{giveaway['prize']}**!")
# Remove giveaway from active giveaways
del giveaways[message_id]
# Task: Check for expired giveaways
@tasks.loop(minutes=1)
async def check_giveaways():
current_time = datetime.datetime.utcnow()
expired_giveaways = [
msg_id for msg_id, data in giveaways.items()
if current_time >= data['end_time']
]
for message_id in expired_giveaways:
await end_giveaway(message_id)
# Error handling
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You don't have permission to use this command!")
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Missing required arguments! Check the command usage.")
else:
await ctx.send(f"An error occurred: {str(error)}")
# Run the bot
bot.run('YOUR_BOT_TOKEN_HERE')
Features of this Bot:
-
Giveaway System:
!giveaway <duration> <winners> <prize>: Starts a giveaway with a specified duration (in minutes), number of winners, and prize.
- Users participate by reacting with 🎉 to the giveaway message.
- The bot automatically ends the giveaway when the time is up and selects random winners.
!endgiveaway <message_id>: Manually ends a giveaway early.
!reroll <message_id>: Rerolls the winners of a giveaway.
-
Permission Checks:
- Only users with the
manage_guild permission can start, end, or reroll giveaways.
-
Error Handling:
- The bot handles common errors like missing permissions or invalid arguments.
-
Background Task:
- A background task (
check_giveaways) runs every minute to check for expired giveaways and end them automatically.
How to Use:
-
Install Required Libraries:
Make sure you have Python installed, then install the required library:
pip install discord.py
-
Set Up Your Bot:
- Go to the Discord Developer Portal and create a new application.
- Create a bot and copy its token.
- Enable the necessary intents (Message Content, Server Members, and Reactions) in the "Bot" section of the Developer Portal.
- Invite the bot to your server with the required permissions (e.g., Manage Server, Send Messages, Embed Links, Add Reactions).
-
Run the Bot:
- Replace
'YOUR_BOT_TOKEN_HERE' in the code with your bot's token.
- Save the code in a file (e.g.,
bot.py) and run it:
python bot.py
-
Commands:
!giveaway 60 1 "Nitro Subscription": Starts a giveaway for a "Nitro Subscription" lasting 60 minutes with 1 winner.
!endgiveaway <message_id>: Ends a giveaway early (get the message ID by right-clicking the giveaway message and selecting "Copy ID").
!reroll <message_id>: Rerolls the winners of a giveaway.
Notes:
- Make sure to enable "Developer Mode" in Discord to easily copy message IDs (User Settings > Appearance > Developer Mode).
- The bot requires the
manage_guild permission to restrict giveaway commands to moderators or administrators.
- This is a basic implementation; you can extend it with features like giveaway requirements (e.g., specific roles), database storage for persistent giveaways, or custom reaction emojis.
Let me know if you need help with setup or want to add more features!