0% found this document useful (0 votes)
510 views4 pages

discord_bot_code

This document contains a Discord bot code that manages gift codes through commands and notifications. It includes functionalities for encoding data, claiming gift code rewards, and notifying admins about new gift codes found on a specified website. The bot uses various libraries and APIs to handle requests and interactions with Discord users.

Uploaded by

extracrow2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
510 views4 pages

discord_bot_code

This document contains a Discord bot code that manages gift codes through commands and notifications. It includes functionalities for encoding data, claiming gift code rewards, and notifying admins about new gift codes found on a specified website. The bot uses various libraries and APIs to handle requests and interactions with Discord users.

Uploaded by

extracrow2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

# Código del bot de Discord con comandos y manejo de gift codes

import discord
from discord.ext import commands, tasks
from discord import app_commands
from datetime import datetime
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import hashlib
import json
import aiohttp
import re
import random

# Variables globales y URLs relevantes


wos_player_info_url = "https://wos-giftcode-api.centurygame.com/api/player"
wos_giftcode_url = "https://wos-giftcode-api.centurygame.com/api/gift_code"
wos_giftcode_redemption_url = "https://wos-giftcode.centurygame.com"
wos_encrypt_key = "tB87#kPtkxqOS2"
retry_config = Retry(
total=5,
backoff_factor=1,
status_forcelist=[429],
allowed_methods=["POST"]
)
url = "https://www.wosrewards.com"

# Clase para comandos relacionados con Gift Codes


class GiftCommand(commands.Cog):
def __init__(self, bot, conn):
self.bot = bot
self.conn = conn
self.c = conn.cursor()

def encode_data(self, data):


secret = wos_encrypt_key
sorted_keys = sorted(data.keys())
encoded_data = "&".join(
[
f"{key}={json.dumps(data[key]) if isinstance(data[key], dict) else
data[key]}"
for key in sorted_keys
]
)
sign = hashlib.md5(f"{encoded_data}{secret}".encode()).hexdigest()
return {"sign": sign, **data}

def get_stove_info_wos(self, player_id):


session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry_config))
headers = {
"accept": "application/json, text/plain, */*",
"content-type": "application/x-www-form-urlencoded",
"origin": wos_giftcode_redemption_url,
}
data_to_encode = {
"fid": f"{player_id}",
"time": f"{int(datetime.now().timestamp())}",
}
data = self.encode_data(data_to_encode)
response_stove_info = session.post(
wos_player_info_url,
headers=headers,
data=data,
)
return session, response_stove_info

def claim_giftcode_rewards_wos(self, player_id, giftcode):


session, response_stove_info = self.get_stove_info_wos(player_id=player_id)
if response_stove_info.json().get("msg") == "success":
data_to_encode = {
"fid": f"{player_id}",
"cdk": giftcode,
"time": f"{int(datetime.now().timestamp())}",
}
data = self.encode_data(data_to_encode)
response_giftcode = session.post(
wos_giftcode_url,
data=data,
)
response_json = response_giftcode.json()
if response_json.get("msg") == "SUCCESS":
return session, "SUCCESS"
elif response_json.get("msg") == "RECEIVED." and
response_json.get("err_code") == 40008:
return session, "ALREADY_RECEIVED"
elif response_json.get("msg") == "CDK NOT FOUND." and
response_json.get("err_code") == 40014:
return session, "CDK_NOT_FOUND"
elif response_json.get("msg") == "SAME TYPE EXCHANGE." and
response_json.get("err_code") == 40011:
return session, "ALREADY_RECEIVED"
else:
return session, "ERROR"

async def giftcode_autocomplete(


self, interaction: discord.Interaction, current: str
) -> list[app_commands.Choice]:
self.c.execute("SELECT giftcode, date FROM gift_codes ORDER BY date DESC
LIMIT 1")
latest_code = self.c.fetchone()
self.c.execute("SELECT giftcode, date FROM gift_codes")
gift_codes = self.c.fetchall()
return [
app_commands.Choice(
name=f"{code} - {date} {'(Most recently shared)' if (code, date) ==
latest_code else ''}",
value=code
)
for code, date in gift_codes if current.lower() in code.lower()
][:25]

@app_commands.command(name="gift", description="Usar el gift code para todos


los usuarios de la alianza.")
@app_commands.describe(giftcode="Elige un gift code")
@app_commands.autocomplete(giftcode=giftcode_autocomplete)
async def use_giftcode(self, interaction: discord.Interaction, giftcode: str):
# Implementación del comando aquí.
pass

def cog_unload(self):
pass

# Clase para la gestión de gift codes y notificaciones


class Gift(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.conn = None
self.c = None
self.giftcode_check_loop.start()

async def fetch(self, session, url):


async with session.get(url) as response:
return await response.text()

async def extract_giftcodes(self):


async with aiohttp.ClientSession() as session:
html_content = await self.fetch(session, url)
pattern = r'<div[^>]*class=["'][^"']*bg-white dark:bg-gray-800 shadow-
md rounded-lg overflow-hidden[^"']*["'][^>]*>(.*?)</div>'
matches = re.findall(pattern, html_content, re.DOTALL)
giftcodes = []
for match in matches:
h5_matches = re.findall(r'<h5[^>]*>(.*?)</h5>', match, re.DOTALL)
for h5 in h5_matches:
giftcodes.append(h5.strip())
return giftcodes

async def notify_admins(self, new_codes):


self.c.execute("SELECT id FROM admin")
admin_ids = self.c.fetchall()
for admin_id in admin_ids:
try:
admin_user = await self.bot.fetch_user(admin_id[0])
embed = discord.Embed(
title="¡Nuevos Gift Codes Encontrados!",
description="
".join(f"**{code}**" for code in new_codes),
color=discord.Color.green(),
)
embed.set_footer(text="Verifica y utiliza los códigos a tiempo.")
await admin_user.send(embed=embed)
except Exception as e:
print(f"Error notificando al admin {admin_id[0]}: {e}")

@tasks.loop(hours=1)
async def giftcode_check_loop(self):
try:
if not self.conn or not self.c:
self.conn = self.bot.conn
self.c = self.conn.cursor()
new_codes = []
giftcodes = await self.extract_giftcodes()
for code in giftcodes:
self.c.execute("SELECT 1 FROM gift_codes WHERE giftcode = ?",
(code,))
if not self.c.fetchone():
self.c.execute(
"INSERT INTO gift_codes (giftcode, date) VALUES (?,
DATE('now'))", (code,)
)
new_codes.append(code)
self.conn.commit()
if new_codes:
await self.notify_admins(new_codes)
except Exception as e:
print(f"Error en la búsqueda de gift codes: {e}")

def cog_unload(self):
self.giftcode_check_loop.cancel()

# Configuración del bot y registro de los cogs


async def setup(bot):
await bot.add_cog(GiftCommand(bot, bot.conn))
await bot.add_cog(Gift(bot))

You might also like