Files
bot.py
integrations.py
requirements.txt
storage.py
Code
4 1,572
bot.py
import asyncio
import base64
import hashlib
import hmac
import io
import json
import logging
import os
import re
import time
import uuid
from decimal import Decimal, InvalidOperation
import aiohttp
import discord
from aiohttp import web
from discord import app_commands
from discord.ext import commands, tasks
from dotenv import load_dotenv
from integrations import MercadoPago, RobloxOpenCloud
from storage import Database
load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("eb-votex")
def money(cents: int) -> str:
return f"R$ {cents // 100:,}".replace(",", ".") + f",{cents % 100:02d}"
def parse_price(value: str) -> int:
normalized = value.strip().replace("R$", "").replace(" ", "")
if "," in normalized:
normalized = normalized.replace(".", "").replace(",", ".")
try:
amount = Decimal(normalized)
except InvalidOperation as error:
raise ValueError("Informe um preço válido, por exemplo 19,90.") from error
cents = int((amount * 100).quantize(Decimal("1")))
if cents < 1 or cents > 100_000_000:
raise ValueError("O preço deve ser maior que zero e menor que R$ 1.000.000,00.")
return cents
def safe_text(value: str, limit: int) -> str:
value = (value or "").strip()
return value if len(value) <= limit else value[: limit - 1] + "…"
def status_label(sale: dict) -> str:
payment = {
"creating": "gerando cobrança",
"pending": "aguardando pagamento",
"approved": "pago",
"failed": "falha ao gerar cobrança",
"refunded": "estornado",
}.get(sale.get("payment_status"), sale.get("payment_status", "desconhecido"))
service = {
"awaiting_payment": "aguardando pagamento",
"paid": "aguardando vendedor",
"in_service": "em atendimento",
"completed": "concluído",
"closed": "fechado",
}.get(sale.get("service_status"), sale.get("service_status", "desconhecido"))
return f"Pagamento: **{payment}** · Atendimento: **{service}**"
def embed_color(settings: dict) -> int:
try:
return int(settings.get("embed_color", "5865F2").lstrip("#"), 16)
except (TypeError, ValueError):
return 0x5865F2
async def reply(interaction: discord.Interaction, content: str, ephemeral=True):
if interaction.response.is_done():
await interaction.followup.send(content, ephemeral=ephemeral)
else:
await interaction.response.send_message(content, ephemeral=ephemeral)
def is_admin(interaction: discord.Interaction) -> bool:
return bool(interaction.guild and interaction.user.guild_permissions.administrator)
def parse_ids(value: str) -> list[str]:
return list(dict.fromkeys(re.findall(r"\d+", value)))
class SalesBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="!", intents=discord.Intents.default())
self.db = Database(os.getenv("BOT_DB_PATH", "vendas.sqlite3"))
self.mercado_pago = MercadoPago()
self.web_runner = None
async def setup_hook(self):
await self.db.open()
products = await self.db.get_products()
for panel in await self.db.get_panels():
self.add_view(
SalesPanelView(self, int(panel["message_id"]), panel["page"], products),
message_id=int(panel["message_id"]),
)
for sale in await self.db.get_open_ticket_sales():
self.add_view(TicketView(self, sale), message_id=int(sale["ticket_message_id"]) if sale["ticket_message_id"] else None)
app = web.Application()
app.router.add_post("/mercadopago", self.mercado_pago_webhook)
self.web_runner = web.AppRunner(app)
await self.web_runner.setup()
site = web.TCPSite(self.web_runner, "0.0.0.0", int(os.getenv("WEBHOOK_PORT", "8080")))
await site.start()
self.payment_poll.start()
await self.tree.sync()
logger.info("Comandos sincronizados; webhook Pix ativo.")
async def close(self):
if self.payment_poll.is_running():
self.payment_poll.cancel()
if self.web_runner is not None:
await self.web_runner.cleanup()
await self.db.close()
await super().close()
async def on_ready(self):
logger.info("Bot conectado como %s", self.user)
async def seller_role_ids(self, guild_id: int) -> list[str]:
raw = await self.db.get_setting(f"{guild_id}:seller_role_ids", "[]")
try:
return [str(item) for item in json.loads(raw)]
except (json.JSONDecodeError, TypeError):
return []
async def is_seller(self, interaction: discord.Interaction) -> bool:
if not interaction.guild or not isinstance(interaction.user, discord.Member):
return False
configured = set(await self.seller_role_ids(interaction.guild.id))
return any(str(role.id) in configured for role in interaction.user.roles)
async def log_action(self, guild_id: int, message: str, error=False):
channel_id = await self.db.get_setting(f"{guild_id}:log_channel_id")
if not channel_id:
return
channel = self.get_channel(int(channel_id))
if not isinstance(channel, discord.TextChannel):
return
settings = await self.db.get_settings()
try:
await channel.send(embed=discord.Embed(
description=safe_text(message, 4000),
color=discord.Color.red() if error else embed_color(settings),
))
except discord.HTTPException:
logger.exception("Não foi possível enviar uma entrada ao canal de logs.")
async def ticket_embed(self, sale: dict):
settings = await self.db.get_settings()
embed = discord.Embed(
title=f"Venda {sale['id'][:8]}",
description=status_label(sale),
color=embed_color(settings),
)
embed.add_field(name="Cliente", value=f"<@{sale['user_id']}>", inline=True)
embed.add_field(name="Produto", value=sale["product_name"], inline=True)
embed.add_field(name="Valor", value=money(sale["price_cents"]), inline=True)
embed.add_field(name="Pagamento", value=sale.get("payment_status", "desconhecido"), inline=True)
embed.add_field(name="Atendimento", value=sale.get("service_status", "desconhecido"), inline=True)
embed.add_field(name="Vendedor", value=f"<@{sale['claimed_by']}>" if sale.get("claimed_by") else "Não assumido", inline=True)
if sale.get("roblox_username"):
embed.add_field(name="Nick Roblox", value=sale["roblox_username"], inline=True)
if sale.get("product_kind") == "family":
product = await self.db.get_product(sale["product_id"]) if sale.get("product_id") else None
if product and product.get("delivery_info"):
embed.add_field(name="Informações para entrega", value=safe_text(product["delivery_info"], 1000), inline=False)
embed.set_footer(text=f"ID da venda: {sale['id']}")
return embed
async def refresh_ticket(self, sale_id: str):
sale = await self.db.get_sale(sale_id)
if not sale or not sale.get("ticket_id"):
return
channel = self.get_channel(int(sale["ticket_id"]))
if not isinstance(channel, discord.TextChannel):
return
view = TicketView(self, sale)
if sale.get("ticket_message_id"):
try:
message = await channel.fetch_message(int(sale["ticket_message_id"]))
await message.edit(embed=await self.ticket_embed(sale), view=view)
return
except discord.NotFound:
pass
await channel.send(embed=await self.ticket_embed(sale), view=view)
async def process_payment(self, payment_id: str):
settings = await self.db.get_settings()
access_token = settings.get("mercadopago_access_token")