I'll help you create a comprehensive Discord giveaway bot using discord.py with button interactions. I'll break this down into multiple components:
python
import discord
from discord.ext import commands
import random
import asyncio
import sqlite3
from datetime import datetime, timedelta
class GiveawayBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
super().__init__(command_prefix='!', intents=intents)
# Setup SQLite database
self.setup_database()
def setup_database(self):
"""Initialize SQLite database for giveaway tracking"""
self.conn = sqlite3.connect('giveaways.db')
self.cursor = self.conn.cursor()
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS giveaways (
message_id INTEGER PRIMARY KEY,
channel_id INTEGER,
guild_id INTEGER,
prize TEXT,
host_id INTEGER,
end_time DATETIME,
winner_id INTEGER,
participants TEXT
)
''')
self.conn.commit()
class GiveawayView(discord.ui.View):
def __init__(self, bot, prize, host, duration):
super().__init__(timeout=None)
self.bot = bot
self.prize = prize
self.host = host
self.duration = duration
self.participants = set()
@discord.ui.button(label="Enter Giveaway", style=discord.ButtonStyle.green, emoji="🎉")
async def enter_giveaway(self, interaction: discord.Interaction, button: discord.ui.Button):
# Check if user already participated
if interaction.user.id in self.participants:
await interaction.response.send_message("You've already entered this giveaway!", ephemeral=True)
return
# Add participant
self.participants.add(interaction.user.id)
await interaction.response.send_message(f"You've entered the giveaway for {self.prize}!", ephemeral=True)
class Giveaway(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="giveaway")
@commands.has_permissions(manage_guild=True)
async def start_giveaway(self, ctx, duration: str, *, prize: str):
"""Start a giveaway with specified duration and prize"""
# Parse duration
duration_map = {
's': 1,
'm': 60,
'h': 3600,
'd': 86400
}
# Extract numeric value and time unit
value = int(duration[:-1])
unit = duration[-1].lower()
if unit not in duration_map:
await ctx.send("Invalid duration format. Use format like '1h', '30m', '7d'")
return
# Calculate end time
seconds = value * duration_map[unit]
end_time = datetime.now() + timedelta(seconds=seconds)
# Create giveaway embed
embed = discord.Embed(
title="🎉 Giveaway! 🎉",
description=f"**Prize:** {prize}\n"
f"**Hosted by:** {ctx.author.mention}\n"
f"**Ends:** <t:{int(end_time.timestamp())}:R>",
color=discord.Color.gold()
)
# Create view with giveaway button
view = GiveawayView(self.bot, prize, ctx.author.id, seconds)
# Send giveaway message
giveaway_message = await ctx.send(embed=embed, view=view)
# Store giveaway in database
self.bot.cursor.execute('''
INSERT INTO giveaways
(message_id, channel_id, guild_id, prize, host_id, end_time, participants)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
giveaway_message.id,
ctx.channel.id,
ctx.guild.id,
prize,
ctx.author.id,
end_time,
','.join(map(str, view.participants))
))
self.bot.conn.commit()
# Wait and end giveaway
await asyncio.sleep(seconds)
await self.end_giveaway(giveaway_message)
async def end_giveaway(self, message):
"""End the giveaway and select a winner"""
# Retrieve giveaway details
self.bot.cursor.execute('SELECT * FROM giveaways WHERE message_id = ?', (message.id,))
giveaway = self.bot.cursor.fetchone()
if not giveaway:
return
# Get channel and participants
channel = self.bot.get_channel(giveaway[1])
participants = [int(p) for p in giveaway[7].split(',') if p]
if not participants:
await channel.send("No participants in the giveaway!")
return
# Select winner
winner_id = random.choice(participants)
winner = await self.bot.fetch_user(winner_id)
# Create winner embed
embed = discord.Embed(
title="🎉 Giveaway Ended! 🎉",
description=f"**Prize:** {giveaway[3]}\n"
f"**Winner:** {winner.mention}",
color=discord.Color.green()
)
await message.edit(embed=embed, view=None)
await channel.send(f"Congratulations {winner.mention}! You won {giveaway[3]}!")
# Update database
self.bot.cursor.execute('''
UPDATE giveaways
SET winner_id = ?
WHERE message_id = ?
''', (winner_id, message.id))
self.bot.conn.commit()
async def main():
bot = GiveawayBot()
await bot.add_cog(Giveaway(bot))
await bot.start('YOUR_BOT_TOKEN')
if __name__ == "__main__":
import asyncio
asyncio.run(main())
Would you like me to elaborate on any part of the bot or explain any specific functionality?