Advertisement
NaroxEG

Giveaways bot with MySQL DB (2)

Sep 11th, 2023 (edited)
938
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.82 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("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.                
  46.                 if len(joins) == 0:
  47.                     winnersList = []
  48.                 else:
  49.                     if len(joins) <= int(row['winners']):
  50.                         winnersList = random.sample(joins, len(joins))
  51.                     else:
  52.                         winnersList = random.sample(joins, int(row['winners']))
  53.                
  54.                 if len(winnersList) == 0:
  55.                     embed = discord.Embed(title=f"Giveaway by {host.name}",
  56.                                           description="Giveaway has ended, but there are no winners",
  57.                                           color=discord.Color.dark_red())
  58.                 else:
  59.                     embed = discord.Embed(title=f"Giveaway by {host.name}",
  60.                                           description=f"Giveaway has ended. Winners are:\n" +
  61.                                           "\n".join(x for x in winnersList),
  62.                                           color=discord.Color.dark_gold())
  63.                     embed.add_field(name="Prize:", value=row['prize'])
  64.                     embed.add_field(name="Ended at:", value=f"<t:{str(row['end']).split('.')[0]}:f> UTC.")
  65.                
  66.                 await message.edit(embed=embed)
  67.                 cursor.execute("DELETE FROM giveaways WHERE message = %s", (row['message'],))
  68.                 db.commit()
  69.             except Exception as e:
  70.                 print(e)
  71.                 cursor.execute("DELETE FROM giveaways WHERE message = %s", (row['message'],))
  72.                 db.commit()
  73.  
  74.  
  75. @tree.command(name="start", description="start a giveaway")
  76. @app_commands.describe(winners="number of winners", prize="name/description of prize", end="giveaway time for example 1d 20h")
  77. @app_commands.checks.has_permissions(administrator=True)
  78. async def start(interaction: discord.Interaction, winners: int, prize: str, end: str):
  79.     times = end.split(" ")
  80.     end_date = datetime.datetime.utcnow()
  81.     for i in times:
  82.         if i.endswith('d'):
  83.             end_date += datetime.timedelta(days=int(i[:-1]))
  84.         elif i.endswith('h'):
  85.             end_date += datetime.timedelta(hours=int(i[:-1]))
  86.         elif i.endswith('m'):
  87.             end_date += datetime.timedelta(minutes=int(i[:-1]))
  88.         elif i.endswith('s'):
  89.             end_date += datetime.timedelta(seconds=int(i[:-1]))
  90.         else:
  91.             await interaction.response.send_message(f"Invalid format `{i}`", ephemeral=True)
  92.             return
  93.  
  94.     embed = discord.Embed(title=f"Giveaway by {interaction.user.name}", description=f"Ends at {str(end_date).split('.')[0]} UTC.",
  95.                           color=discord.Color.dark_gold())
  96.     embed.add_field(name="Prize:", value=prize)
  97.     embed.add_field(name="Ends:", value=f"<t:{str(end_date.timestamp()).split('.')[0]}:f> UTC.")
  98.     embed.add_field(name="Winners:", value=winners)
  99.     message = await interaction.channel.send(embed=embed)
  100.     await message.add_reaction("🎉")
  101.     sql = "INSERT INTO giveaways (guild, channel, message, host, winners, prize, start, end) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
  102.     val = (interaction.guild.id, interaction.channel.id, message.id, interaction.user.id, winners, prize, datetime.datetime.utcnow().timestamp(), end_date.timestamp())
  103.     cursor.execute(sql, val)
  104.     db.commit()
  105.     await interaction.response.send_message("Giveaway started!", ephemeral=True)
  106.  
  107. client.run("TOKEN")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement