Advertisement
xosski

Hwid bot discord

Dec 25th, 2024
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.90 KB | None | 0 0
  1. import discord
  2. from discord import app_commands
  3. from discord.ext import commands, tasks
  4. import aiohttp
  5. import sqlite3
  6. from datetime import datetime, timedelta
  7. import logging
  8.  
  9. # Configuration
  10. TOKEN = "YOUR_DISCORD_BOT_TOKEN"
  11. API_URL = "https://safeguard.lol/api/"
  12. ADMIN_TOKEN = "YOUR_ADMIN_TOKEN"
  13. STAFF_CHANNEL_ID = 123456789012345678 # Replace with your staff channel ID
  14. ALLOWED_ROLES = {"lifetime client", "ghosty", "admin"} # Set of allowed roles (case-insensitive)
  15.  
  16. # Logging setup
  17. logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
  18.  
  19. # Initialize bot
  20. intents = discord.Intents.default()
  21. bot = commands.Bot(command_prefix="!", intents=intents)
  22. tree = app_commands.CommandTree(bot)
  23.  
  24. # Database setup
  25. DATABASE_FILE = "hwid_resets.db"
  26. conn = sqlite3.connect(DATABASE_FILE)
  27. cursor = conn.cursor()
  28. cursor.execute("""
  29. CREATE TABLE IF NOT EXISTS hwid_resets (
  30. discord_id TEXT PRIMARY KEY,
  31. key TEXT,
  32. last_reset TIMESTAMP,
  33. first_reset TIMESTAMP,
  34. total_resets INTEGER DEFAULT 0
  35. )
  36. """)
  37. conn.commit()
  38.  
  39. # Streaming activity status
  40. @tasks.loop(seconds=30)
  41. async def update_activity():
  42. """Updates the bot's activity status periodically."""
  43. await bot.change_presence(
  44. activity=discord.Streaming(name="Reset HWID Bot | /hwid", url="https://twitch.tv/example")
  45. )
  46.  
  47. # Helper function: Reset HWID via API
  48. async def reset_hwid(hwid: str) -> dict:
  49. """Sends a reset HWID request to the API."""
  50. async with aiohttp.ClientSession() as session:
  51. headers = {
  52. "Content-Type": "application/json",
  53. "X-API-Key": ADMIN_TOKEN,
  54. }
  55. payload = {
  56. "type": "admin_command",
  57. "command": "reset_hwid",
  58. "hwid": hwid,
  59. }
  60. try:
  61. async with session.post(API_URL, headers=headers, json=payload) as response:
  62. if response.status == 200:
  63. return await response.json()
  64. return {"status": "error", "message": f"HTTP {response.status}"}
  65. except Exception as e:
  66. logging.error(f"API error: {str(e)}")
  67. return {"status": "error", "message": str(e)}
  68.  
  69. # Helper function: Check user roles
  70. def has_allowed_role(user: discord.Member) -> bool:
  71. """Checks if the user has at least one allowed role."""
  72. user_roles = {role.name.lower() for role in user.roles}
  73. return not ALLOWED_ROLES.isdisjoint(user_roles)
  74.  
  75. # Event: Bot ready
  76. @bot.event
  77. async def on_ready():
  78. """Handles the bot's ready event."""
  79. logging.info(f"Bot logged in as {bot.user}")
  80. update_activity.start()
  81. await tree.sync()
  82. logging.info("Slash commands synced.")
  83.  
  84. # Slash command: Reset HWID
  85. @tree.command(name="hwid", description="Reset your HWID key.")
  86. async def hwid(interaction: discord.Interaction):
  87. """Handles the /hwid command to reset a user's HWID."""
  88. user = interaction.user
  89.  
  90. # Check role permissions
  91. if not has_allowed_role(user):
  92. await interaction.response.send_message(
  93. "❌ You do not have the required role to use this command.", ephemeral=True
  94. )
  95. logging.warning(f"Unauthorized HWID reset attempt by {user}.")
  96. return
  97.  
  98. # Prompt for HWID key
  99. await interaction.response.send_message("Please enter your HWID key:", ephemeral=True)
  100. try:
  101. message = await bot.wait_for(
  102. "message",
  103. check=lambda m: m.author == user and m.channel == interaction.channel,
  104. timeout=60.0
  105. )
  106. hwid_key = message.content.strip()
  107. except asyncio.TimeoutError:
  108. await interaction.followup.send("You took too long to respond. Please try again.", ephemeral=True)
  109. logging.warning(f"{user} did not respond with an HWID key in time.")
  110. return
  111.  
  112. # Validate HWID ownership
  113. cursor.execute("SELECT discord_id FROM hwid_resets WHERE key = ?", (hwid_key,))
  114. key_owner = cursor.fetchone()
  115. if key_owner and key_owner[0] != str(user.id):
  116. await interaction.followup.send("❌ This HWID key is already registered to another user!", ephemeral=True)
  117. logging.error(f"{user} tried to reset a key owned by another user: {hwid_key}")
  118. return
  119.  
  120. # Check rate limits
  121. cursor.execute("SELECT last_reset, total_resets, first_reset FROM hwid_resets WHERE discord_id = ?", (str(user.id),))
  122. result = cursor.fetchone()
  123. if result:
  124. last_reset, total_resets, first_reset = result
  125. last_reset = datetime.fromisoformat(last_reset)
  126. cooldown = timedelta(minutes=30)
  127. if datetime.now() - last_reset < cooldown:
  128. remaining = last_reset + cooldown - datetime.now()
  129. await interaction.followup.send(
  130. f"You can reset your HWID again in {remaining.seconds // 60} minutes and {remaining.seconds % 60} seconds.",
  131. ephemeral=True
  132. )
  133. logging.warning(f"{user} attempted an HWID reset during cooldown.")
  134. return
  135. else:
  136. total_resets = 0
  137. first_reset = datetime.now()
  138.  
  139. # Attempt HWID reset via API
  140. response = await reset_hwid(hwid_key)
  141. if response["status"] == "success":
  142. # Update database
  143. cursor.execute("""
  144. INSERT OR REPLACE INTO hwid_resets (discord_id, key, last_reset, first_reset, total_resets)
  145. VALUES (?, ?, ?, ?, ?)
  146. """, (str(user.id), hwid_key, datetime.now().isoformat(), first_reset.isoformat(), total_resets + 1))
  147. conn.commit()
  148.  
  149. # Notify user
  150. await interaction.followup.send("✅ Your HWID has been reset successfully!", ephemeral=True)
  151. logging.info(f"HWID reset successful for {user} (Key: {hwid_key}).")
  152.  
  153. # Log to staff channel
  154. staff_channel = bot.get_channel(STAFF_CHANNEL_ID)
  155. embed = discord.Embed(
  156. title="🔧 HWID Reset Log",
  157. color=discord.Color.green(),
  158. timestamp=datetime.utcnow()
  159. )
  160. embed.add_field(name="User", value=f"{user.mention} (`{user.id}`)", inline=False)
  161. embed.add_field(name="HWID Key", value=f"`{hwid_key}`", inline=False)
  162. embed.add_field(name="Total Resets", value=str(total_resets + 1), inline=False)
  163. embed.add_field(name="First Reset", value=first_reset.strftime('%Y-%m-%d %H:%M:%S'), inline=False)
  164. embed.add_field(name="Last Reset", value=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), inline=False)
  165. embed.add_field(name="Status", value="✅ Success", inline=False)
  166. embed.set_footer(text="HWID Reset System")
  167. await staff_channel.send(embed=embed)
  168. else:
  169. # Notify user of failure
  170. await interaction.followup.send(f"❌ Failed to reset HWID: {response.get('message', 'Unknown error')}", ephemeral=True)
  171. logging.error(f"HWID reset failed for {user} - Error: {response.get('message', 'Unknown error')}")
  172.  
  173. # Start the bot
  174. bot.run(TOKEN)
Tags: discord bot
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement