Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import discord
- from discord.ext import commands, tasks
- from discord import app_commands
- import mysql.connector
- import datetime
- import random
- intents = discord.Intents.default()
- intents.members = True
- client = commands.Bot(command_prefix="-", intents=intents)
- tree = client.tree
- db = mysql.connector.connect(
- host="localhost",
- user="root",
- password="",
- database="giveaways"
- )
- cursor = db.cursor(dictionary=True)
- @client.event
- async def on_ready():
- synced = await client.tree.sync()
- print(f"Synced {len(synced)} command(s).")
- checkGiveaways.start()
- @tasks.loop(seconds=10)
- async def checkGiveaways():
- cursor.execute("SELECT * FROM giveaways")
- giveaways = cursor.fetchall()
- for row in giveaways:
- if float(row['end']) - float(datetime.datetime.utcnow().timestamp()) <= 0:
- try:
- channel = await client.fetch_channel(int(row['channel']))
- message = await channel.fetch_message(int(row['message']))
- host = await client.fetch_user(int(row['host']))
- joins = []
- for reaction in message.reactions:
- if str(reaction.emoji) == "🎉":
- users = reaction.users()
- async for user in users:
- if not user.id == client.user.id:
- joins.append(user.mention)
- continue
- if len(joins) == 0:
- winnersList = []
- else:
- if len(joins) <= int(row['winners']):
- winnersList = random.sample(joins, len(joins))
- else:
- winnersList = random.sample(joins, int(row['winners']))
- if len(winnersList) == 0:
- embed = discord.Embed(title=f"Giveaway by {host.name}",
- description="Giveaway has ended, but there are no winners",
- color=discord.Color.dark_red())
- else:
- embed = discord.Embed(title=f"Giveaway by {host.name}",
- description=f"Giveaway has ended. Winners are:\n" +
- "\n".join(x for x in winnersList),
- color=discord.Color.dark_gold())
- embed.add_field(name="Prize:", value=row['prize'])
- embed.add_field(name="Ended at:", value=f"<t:{str(row['end']).split('.')[0]}:f> UTC.")
- await message.edit(embed=embed)
- cursor.execute("DELETE FROM giveaways WHERE message = %s", (row['message'],))
- db.commit()
- except Exception as e:
- print(e)
- cursor.execute("DELETE FROM giveaways WHERE message = %s", (row['message'],))
- db.commit()
- @tree.command(name="start", description="start a giveaway")
- @app_commands.describe(winners="number of winners", prize="name/description of prize", end="giveaway time for example 1d 20h")
- @app_commands.checks.has_permissions(administrator=True)
- async def start(interaction: discord.Interaction, winners: int, prize: str, end: str):
- times = end.split(" ")
- end_date = datetime.datetime.utcnow()
- for i in times:
- if i.endswith('d'):
- end_date += datetime.timedelta(days=int(i[:-1]))
- elif i.endswith('h'):
- end_date += datetime.timedelta(hours=int(i[:-1]))
- elif i.endswith('m'):
- end_date += datetime.timedelta(minutes=int(i[:-1]))
- elif i.endswith('s'):
- end_date += datetime.timedelta(seconds=int(i[:-1]))
- else:
- await interaction.response.send_message(f"Invalid format `{i}`", ephemeral=True)
- return
- embed = discord.Embed(title=f"Giveaway by {interaction.user.name}", description=f"Ends at {str(end_date).split('.')[0]} UTC.",
- color=discord.Color.dark_gold())
- embed.add_field(name="Prize:", value=prize)
- embed.add_field(name="Ends:", value=f"<t:{str(end_date.timestamp()).split('.')[0]}:f> UTC.")
- embed.add_field(name="Winners:", value=winners)
- message = await interaction.channel.send(embed=embed)
- await message.add_reaction("🎉")
- sql = "INSERT INTO giveaways (guild, channel, message, host, winners, prize, start, end) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
- val = (interaction.guild.id, interaction.channel.id, message.id, interaction.user.id, winners, prize, datetime.datetime.utcnow().timestamp(), end_date.timestamp())
- cursor.execute(sql, val)
- db.commit()
- await interaction.response.send_message("Giveaway started!", ephemeral=True)
- client.run("TOKEN")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement