Advertisement
NaroxEG

Giveaways bot with MySQL DB

Sep 8th, 2023 (edited)
1,115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.64 KB | None | 0 0
  1. import discord
  2. from discord.ext import commands, tasks
  3. from discord import app_commands
  4. import mysql.connector
  5. import datetime
  6. import random
  7.  
  8. intents = discord.Intents.default()
  9. intents.members = True
  10. client = commands.Bot(command_prefix="-", intents=intents)
  11. tree = client.tree
  12.  
  13. db = mysql.connector.connect(
  14.     host="localhost",
  15.     user="root",
  16.     password="",
  17.     database="giveaways"
  18. )
  19. cursor = db.cursor(dictionary=True)
  20.  
  21. @client.event
  22. async def on_ready():
  23.     synced = await client.tree.sync()
  24.     print(f"Synced {len(synced)} command(s).")
  25.     checkGiveaways.start()
  26.  
  27. @tasks.loop(seconds=10)
  28. async def checkGiveaways():
  29.     cursor.execute(f"SELECT * FROM giveaways")
  30.     giveaways = cursor.fetchall()
  31.     for row in giveaways:
  32.         if float(row['end']) - float(datetime.datetime.utcnow().timestamp()) <= 0:
  33.             try:
  34.                 channel = await client.fetch_channel(int(row['channel']))
  35.                 message = await channel.fetch_message(int(row['message']))
  36.                 host = await client.fetch_user(int(row['host']))
  37.                 joins = []
  38.                 for reaction in message.reactions:
  39.                     if str(reaction.emoji) == "🎉":
  40.                         users = reaction.users()
  41.                         async for user in users:
  42.                             if not user.id == client.user.id:
  43.                                 joins.append(user.mention)
  44.                         continue
  45.                 if len(joins) == 0:
  46.                     winnersList=[]
  47.                 else:
  48.                     winnersList= random.sample(joins, int(row['winners']))
  49.                
  50.                 if len(winnersList) == 0:
  51.                     embed = discord.Embed(title=f"Giveaway by {host.name}", description=f"Giveaway ended but there are no winners",
  52.                                           color=discord.Color.dark_red())
  53.                 else:
  54.                     embed=discord.Embed(title=f"Giveaway by {host.name}",
  55.                                         description="Giveaway has ended. Winners are:\n" + "\n".join(x for x in winnersList),
  56.                                         color=discord.Color.dark_gold())
  57.                     embed.add_field(name="Prize:", value=row['prize'])
  58.                     embed.add_field(name="Winners:", value=row['winners'])
  59.                     embed.add_field(name="Ended at:", value=f"<t:{str(row['end']).split('.')[0]}:f> UTC.")
  60.                
  61.                 await message.edit(embed=embed)
  62.                 cursor.execute(f"DELETE FROM giveaways WHERE message={row['message']}")
  63.                 db.commit()
  64.             except Exception as e:
  65.                 print(e)
  66.                 cursor.execute(f"DELETE FROM giveaways WHERE message={row['message']}")
  67.                 db.commit()
  68.                 pass
  69.        
  70.  
  71. @tree.command(name="start", description="start a giveaway")
  72. @app_commands.describe(winners="number of winners", prize="name/description of prize", end="giveaway time for example 1d 20h")
  73. @app_commands.checks.has_permissions(administrator=True)
  74. async def start(interaction: discord.Interaction, winners: int, prize: str, end: str):
  75.     times = end.split(" ")
  76.     end_date = datetime.datetime.utcnow()
  77.     for i in times:
  78.         if i.endswith('d'):
  79.             end_date += datetime.timedelta(days=int(i[:-1]))
  80.         elif i.endswith('h'):
  81.             end_date += datetime.timedelta(hours=int(i[:-1]))
  82.         elif i.endswith('m'):
  83.             end_date += datetime.timedelta(minutes=int(i[:-1]))
  84.         elif i.endswith('s'):
  85.             end_date += datetime.timedelta(seconds=int(i[:-1]))
  86.         else:
  87.             await interaction.response.send_message(f"Invalid format `{i}`", ephemeral=True)
  88.             return
  89.  
  90.     embed = discord.Embed(title=f"Giveaway by {interaction.user.name}", description=f"Ends at {str(end_date).split('.')[0]} UTC.",
  91.                           color=discord.Color.dark_gold())
  92.     embed.add_field(name="Prize:", value=prize)
  93.     embed.add_field(name="Ends:", value=f"<t:{str(end_date.timestamp()).split('.')[0]}:f> UTC.")
  94.     embed.add_field(name="Winners:", value=winners)
  95.     message = await interaction.channel.send(embed=embed)
  96.     await message.add_reaction("🎉")
  97.     sql = "INSERT INTO giveaways (guild, channel, message, host, winners, prize, start, end) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
  98.     val = (interaction.guild.id, interaction.channel.id, message.id, interaction.user.id, winners, prize, datetime.datetime.utcnow().timestamp(), end_date.timestamp())
  99.     cursor.execute(sql, val)
  100.     db.commit()
  101.     await interaction.response.send_message("Giveaway started!", ephemeral=True)
  102.  
  103. client.run("TOKEN")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement