Advertisement
xosski

Discord bot hwid bot

Dec 25th, 2024
13
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.50 KB | None | 0 0
  1. import discord
  2. from discord.ext import commands, tasks
  3. import aiohttp
  4. import sqlite3
  5. from datetime import datetime, timedelta
  6.  
  7. # Configuration
  8. TOKEN = "YOUR_DISCORD_BOT_TOKEN"
  9. API_URL = "https://safeguard.lol/api/"
  10. ADMIN_TOKEN = "YOUR_ADMIN_TOKEN"
  11. STAFF_CHANNEL_ID = 123456789012345678 # Replace with your staff channel ID
  12. ALLOWED_ROLES = {"Customer", "Premium Member"} # Allowed roles (use a set for faster lookup)
  13.  
  14. # Initialize bot
  15. intents = discord.Intents.default()
  16. intents.message_content = True
  17. bot = commands.Bot(command_prefix="!", intents=intents)
  18.  
  19. # Database setup
  20. DATABASE_FILE = "hwid_resets.db"
  21. conn = sqlite3.connect(DATABASE_FILE)
  22. cursor = conn.cursor()
  23. cursor.execute("""
  24. CREATE TABLE IF NOT EXISTS hwid_resets (
  25. discord_id TEXT PRIMARY KEY,
  26. key TEXT,
  27. last_reset TIMESTAMP,
  28. first_reset TIMESTAMP,
  29. total_resets INTEGER DEFAULT 0
  30. )
  31. """)
  32. conn.commit()
  33.  
  34. # Streaming activity status
  35. @tasks.loop(seconds=30)
  36. async def update_activity():
  37. await bot.change_presence(
  38. activity=discord.Streaming(name="Reset HWID Bot | /hwid", url="https://twitch.tv/example")
  39. )
  40.  
  41. # Helper function: Log to console
  42. def log_to_console(level: str, message: str):
  43. levels = {
  44. "INFO": "\033[94m[INFO]\033[0m",
  45. "SUCCESS": "\033[92m[SUCCESS]\033[0m",
  46. "ERROR": "\033[91m[ERROR]\033[0m",
  47. "WARNING": "\033[93m[WARNING]\033[0m"
  48. }
  49. print(f"{levels.get(level, '[LOG]')} {datetime.now()} - {message}")
  50.  
  51. # Helper function: Reset HWID via API
  52. async def reset_hwid(hwid: str) -> dict:
  53. async with aiohttp.ClientSession() as session:
  54. headers = {"Content-Type": "application/json", "X-API-Key": ADMIN_TOKEN}
  55. payload = {"type": "admin_command", "command": "reset_hwid", "hwid": hwid}
  56. try:
  57. async with session.post(API_URL, headers=headers, json=payload) as response:
  58. return await response.json()
  59. except aiohttp.ClientError as e:
  60. log_to_console("ERROR", f"API request failed: {str(e)}")
  61. return {"status": "error", "message": "API request failed"}
  62.  
  63. # Helper function: Check user roles
  64. def has_allowed_role(member: discord.Member) -> bool:
  65. return any(role.name in ALLOWED_ROLES for role in member.roles)
  66.  
  67. # Command to reset HWID
  68. @bot.command()
  69. async def hwid(ctx: commands.Context):
  70. # Check if user has the required role
  71. if not has_allowed_role(ctx.author):
  72. await ctx.send("❌ You do not have the required role to use this command.")
  73. log_to_console("WARNING", f"{ctx.author} attempted to use /hwid without proper roles.")
  74. return
  75.  
  76. # Prompt user for the HWID key
  77. await ctx.send("Please enter your HWID key:")
  78. try:
  79. hwid_key_msg = await bot.wait_for(
  80. "message",
  81. check=lambda m: m.author == ctx.author and m.channel == ctx.channel,
  82. timeout=60.0
  83. )
  84. hwid_key = hwid_key_msg.content.strip()
  85. except asyncio.TimeoutError:
  86. await ctx.send("❌ You took too long to respond. Please try again.")
  87. log_to_console("WARNING", f"{ctx.author} took too long to provide an HWID key.")
  88. return
  89.  
  90. # Validate HWID ownership
  91. cursor.execute("SELECT discord_id FROM hwid_resets WHERE key = ?", (hwid_key,))
  92. key_owner = cursor.fetchone()
  93. if key_owner and key_owner[0] != str(ctx.author.id):
  94. await ctx.send("❌ This HWID key is already registered to another user!")
  95. log_to_console("ERROR", f"{ctx.author} attempted to reset another user's HWID key.")
  96. return
  97.  
  98. # Check rate limits
  99. cursor.execute("SELECT last_reset, total_resets, first_reset FROM hwid_resets WHERE discord_id = ?", (str(ctx.author.id),))
  100. user_data = cursor.fetchone()
  101. if user_data:
  102. last_reset, total_resets, first_reset = user_data
  103. last_reset = datetime.fromisoformat(last_reset)
  104. cooldown = timedelta(minutes=30)
  105. if datetime.now() - last_reset < cooldown:
  106. remaining = last_reset + cooldown - datetime.now()
  107. await ctx.send(f"You can reset your HWID again in {remaining.seconds // 60} minutes and {remaining.seconds % 60} seconds.")
  108. log_to_console("WARNING", f"{ctx.author} attempted to reset HWID during cooldown.")
  109. return
  110. else:
  111. total_resets = 0
  112. first_reset = None
  113.  
  114. # Attempt HWID reset
  115. response = await reset_hwid(hwid_key)
  116. if response.get("status") == "success":
  117. # Update database
  118. if not user_data:
  119. first_reset = datetime.now()
  120. cursor.execute("""
  121. INSERT OR REPLACE INTO hwid_resets (discord_id, key, last_reset, first_reset, total_resets)
  122. VALUES (?, ?, ?, ?, ?)
  123. """, (str(ctx.author.id), hwid_key, datetime.now().isoformat(), first_reset or datetime.now().isoformat(), total_resets + 1))
  124. conn.commit()
  125.  
  126. # Notify user
  127. await ctx.send("✅ Your HWID has been reset successfully!")
  128. log_to_console("SUCCESS", f"{ctx.author} successfully reset HWID.")
  129. else:
  130. # Notify user of failure
  131. await ctx.send(f"❌ Failed to reset HWID: {response.get('message', 'Unknown error')}")
  132. log_to_console("ERROR", f"Failed to reset HWID for {ctx.author}: {response.get('message', 'Unknown error')}")
  133.  
  134. # Bot events
  135. @bot.event
  136. async def on_ready():
  137. print("\033[92mBot is online and ready!\033[0m")
  138. log_to_console("INFO", f"Logged in as {bot.user}")
  139. update_activity.start()
  140.  
  141. # Start the bot
  142. bot.run(TOKEN)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement