I'll help you create a Discord bot with a giveaway system using discord.py. This bot will include commands to start, end, and manage giveaways.
First, make sure you have discord.py installed:
pip install discord.py
Here's the complete bot code:
import discord
from discord.ext import commands, tasks
import asyncio
import random
import json
import os
from datetime import datetime, timedelta
import re
# Bot configuration
intents = discord.Intents.default()
intents.message_content = True
intents.reactions = True
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
# File to store active giveaways
GIVEAWAYS_FILE = 'giveaways.json'
# Dictionary to store active giveaways in memory
active_giveaways = {}
# Load giveaways from file
def load_giveaways():
if os.path.exists(GIVEAWAYS_FILE):
with open(GIVEAWAYS_FILE, 'r') as f:
return json.load(f)
return {}
# Save giveaways to file
def save_giveaways():
with open(GIVEAWAYS_FILE, 'w') as f:
json.dump(active_giveaways, f, indent=4)
# Parse duration string (e.g., "1h30m", "2d", "30s")
def parse_duration(duration_str):
regex = re.compile(r'(\d+)([dhms])')
matches = regex.findall(duration_str.lower())
if not matches:
return None
total_seconds = 0
for value, unit in matches:
value = int(value)
if unit == 'd':
total_seconds += value * 86400
elif unit == 'h':
total_seconds += value * 3600
elif unit == 'm':
total_seconds += value * 60
elif unit == 's':
total_seconds += value
return total_seconds
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
# Load saved giveaways
global active_giveaways
active_giveaways = load_giveaways()
# Start checking giveaways
check_giveaways.start()
@bot.command(name='gstart', help='Start a giveaway. Usage: !gstart <duration> <winners> <prize>')
@commands.has_permissions(manage_guild=True)
async def start_giveaway(ctx, duration: str, winners: int, *, prize: str):
# Parse duration
seconds = parse_duration(duration)
if not seconds:
await ctx.send("Invalid duration format! Use format like: 1h30m, 2d, 30s")
return
if winners < 1:
await ctx.send("Number of winners must be at least 1!")
return
# Create giveaway embed
end_time = datetime.utcnow() + timedelta(seconds=seconds)
embed = discord.Embed(
title="🎉 GIVEAWAY 🎉",
description=f"**Prize:** {prize}\n**Winners:** {winners}\n**Ends:** <t:{int(end_time.timestamp())}:R>",
color=discord.Color.blue(),
timestamp=end_time
)
embed.set_footer(text=f"Hosted 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
giveaway_data = {
'channel_id': ctx.channel.id,
'message_id': giveaway_msg.id,
'prize': prize,
'winners': winners,
'end_time': end_time.isoformat(),
'host_id': ctx.author.id,
'ended': False
}
active_giveaways[str(giveaway_msg.id)] = giveaway_data
save_giveaways()
await ctx.send(f"Giveaway started! It will end in {duration}.")
@bot.command(name='gend', help='End a giveaway early. Usage: !gend <message_id>')
@commands.has_permissions(manage_guild=True)
async def end_giveaway(ctx, message_id: int):
message_id_str = str(message_id)
if message_id_str not in active_giveaways:
await ctx.send("Giveaway not found!")
return
giveaway = active_giveaways[message_id_str]
if giveaway['ended']:
await ctx.send("This giveaway has already ended!")
return
# End the giveaway
await finish_giveaway(message_id_str)
await ctx.send("Giveaway ended!")
@bot.command(name='greroll', help='Reroll a giveaway. Usage: !greroll <message_id>')
@commands.has_permissions(manage_guild=True)
async def reroll_giveaway(ctx, message_id: int):
message_id_str = str(message_id)
if message_id_str not in active_giveaways:
await ctx.send("Giveaway not found!")
return
giveaway = active_giveaways[message_id_str]
if not giveaway['ended']:
await ctx.send("This giveaway hasn't ended yet!")
return
# Get the channel and message
channel = bot.get_channel(giveaway['channel_id'])
if not channel:
await ctx.send("Giveaway channel not found!")
return
try:
message = await channel.fetch_message(giveaway['message_id'])
except:
await ctx.send("Giveaway message not found!")
return
# Get reactions
reaction = None
for r in message.reactions:
if str(r.emoji) == "🎉":
reaction = r
break
if not reaction:
await ctx.send("No reactions found!")
return
# Get users who reacted
users = []
async for user in reaction.users():
if not user.bot:
users.append(user)
if not users:
await ctx.send("No valid participants!")
return
# Select new winners
num_winners = min(giveaway['winners'], len(users))
winners = random.sample(users, num_winners)
# Announce reroll
winner_mentions = ", ".join([winner.mention for winner in winners])
await channel.send(f"🎉 **GIVEAWAY REROLL** 🎉\nNew winner(s): {winner_mentions}\nPrize: **{giveaway['prize']}**")
async def finish_giveaway(message_id_str):
giveaway = active_giveaways[message_id_str]
# Get the channel and message
channel = bot.get_channel(giveaway['channel_id'])
if not channel:
return
try:
message = await channel.fetch_message(giveaway['message_id'])
except:
return
# Get reactions
reaction = None
for r in message.reactions:
if str(r.emoji) == "🎉":
reaction = r
break
if not reaction:
await channel.send(f"No one participated in the giveaway for **{giveaway['prize']}**!")
giveaway['ended'] = True
save_giveaways()
return
# Get users who reacted
users = []
async for user in reaction.users():
if not user.bot:
users.append(user)
if not users:
await channel.send(f"No valid participants for the giveaway of **{giveaway['prize']}**!")
giveaway['ended'] = True
save_giveaways()
return
# Select winners
num_winners = min(giveaway['winners'], len(users))
winners = random.sample(users, num_winners)
# Update embed
embed = message.embeds[0]
embed.color = discord.Color.green()
embed.description = f"**Prize:** {giveaway['prize']}\n**Winners:** {', '.join([w.mention for w in winners])}"
await message.edit(embed=embed)
# Announce winners
winner_mentions = ", ".join([winner.mention for winner in winners])
await channel.send(f"🎉 **GIVEAWAY ENDED** 🎉\nCongratulations {winner_mentions}! You won **{giveaway['prize']}**!")
# Mark as ended
giveaway['ended'] = True
save_giveaways()
@tasks.loop(seconds=5)
async def check_giveaways():
current_time = datetime.utcnow()
for message_id, giveaway in list(active_giveaways.items()):
if giveaway['ended']:
continue
end_time = datetime.fromisoformat(giveaway['end_time'])
if current_time >= end_time:
await finish_giveaway(message_id)
@bot.command(name='glist', help='List all active giveaways')
async def list_giveaways(ctx):
active = [g for g in active_giveaways.values() if not g['ended']]
if not active:
await ctx.send("No active giveaways!")
return
embed = discord.Embed(
title="Active Giveaways",
color=discord.Color.blue()
)
for giveaway in active:
end_time = datetime.fromisoformat(giveaway['end_time'])
embed.add_field(
name=f"Prize: {giveaway['prize']}",
value=f"Winners: {giveaway['winners']}\nEnds: <t:{int(end_time.timestamp())}:R>\nMessage ID: {giveaway['message_id']}",
inline=False
)
await ctx.send(embed=embed)
@bot.command(name='ghelp', help='Show giveaway commands')
async def giveaway_help(ctx):
embed = discord.Embed(
title="Giveaway Bot Commands",
description="Here are all the available giveaway commands:",
color=discord.Color.blue()
)
embed.add_field(
name="!gstart <duration> <winners> <prize>",
value="Start a new giveaway\nExample: `!gstart 1h 2 Discord Nitro`",
inline=False
)
embed.add_field(
name="!gend <message_id>",
value="End a giveaway early\nExample: `!gend 123456789`",
inline=False
)
embed.add_field(
name="!greroll <message_id>",
value="Reroll winners for an ended giveaway\nExample: `!greroll 123456789`",
inline=False
)
embed.add_field(
name="!glist",
value="List all active giveaways",
inline=False
)
embed.add_field(
name="Duration Format",
value="Use combinations of: `d` (days), `h` (hours), `m` (minutes), `s` (seconds)\nExamples: `1h30m`, `2d`, `30s`",
inline=False
)
await ctx.send(embed=embed)
# 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(f"Missing required argument: {error.param.name}")
elif isinstance(error, commands.BadArgument):
await ctx.send("Invalid argument provided!")
else:
print(f"Error: {error}")
# Run the bot
if __name__ == "__main__":
# Replace 'YOUR_BOT_TOKEN' with your actual bot token
bot.run('YOUR_BOT_TOKEN')
To set up and use this bot:
-
Create a Discord Application and Bot:
-
Invite the Bot to Your Server:
- In the OAuth2 section, select "bot" scope
- Select permissions: Send Messages, Read Messages, Add Reactions, Manage Messages, Embed Links
- Use the generated URL to invite the bot
-
Configure and Run:
- Replace
'YOUR_BOT_TOKEN' with your actual bot token
- Run the script:
python bot.py
Features:
!gstart <duration> <winners> <prize> - Start a giveaway
!gend <message_id> - End a giveaway early
!greroll <message_id> - Reroll winners
!glist - List active giveaways
!ghelp - Show help message
The bot automatically saves active giveaways to a JSON file, so they persist even if the bot restarts. Winners are randomly selected from users who react with 🎉 to the giveaway message.