Files
bot.py
config.py
db.py
payments.py
README.md
requirements.txt
security.py
views.py
Code
8 1,042
bot.py
import asyncio
import logging
import discord
from aiohttp import web
from discord import app_commands
from discord.ext import commands, tasks
from config import load_settings
from db import Database
from payments import PaymentManager, PROVIDERS
from security import SecretBox
from views import DashboardView, ProductBuyView, BalancePanelView, money
class StoreBot(commands.Bot):
def __init__(self, settings):
intents = discord.Intents.default()
intents.members = True
super().__init__(command_prefix="!", intents=intents)
self.settings = settings
self.db = Database(settings.database_path)
self.secrets = SecretBox(settings.master_key)
self.payments = PaymentManager(self.db, settings, self.secrets)
self.payment_names = PROVIDERS
self.web_runner = None
async def setup_hook(self):
await self.tree.sync()
for row in self.db._all("SELECT id FROM products WHERE for_sale=1"):
self.add_view(ProductBuyView(self, row["id"]))
for row in self.db._all("SELECT store_id FROM settings WHERE balance_channel_id IS NOT NULL"):
self.add_view(BalancePanelView(self, row["store_id"]))
self.expirer.start()
await self.start_webhook_server()
@tasks.loop(minutes=5)
async def expirer(self): self.db.expire_old_carts()
async def start_webhook_server(self):
app = web.Application()
app.router.add_post("/webhooks/{provider}", self.webhook_handler)
app.router.add_get("/health", lambda request: web.json_response({"ok": True}))
self.web_runner = web.AppRunner(app); await self.web_runner.setup()
site = web.TCPSite(self.web_runner, "0.0.0.0", self.settings.webhook_port); await site.start()
logging.info("Servidor de webhooks ouvindo na porta %s", self.settings.webhook_port)
async def webhook_handler(self, request):
provider = request.match_info["provider"]
if provider not in PROVIDERS or provider == "manual": return web.Response(status=404)
try:
cart_id = await self.payments.webhook(provider, await request.read(), dict(request.headers))
if cart_id:
await self.deliver(cart_id)
return web.json_response({"received": True})
except Exception:
logging.exception("Webhook inválido para %s", provider)
return web.json_response({"received": False}, status=400)
async def confirm_cart(self, cart_id):
ok = await self.payments.check(cart_id)
if ok: await self.deliver(cart_id)
return ok
async def deliver(self, cart_id):
delivery = self.db.claim_delivery(cart_id)
if not delivery: return False
try:
user = await self.fetch_user(delivery["user_id"])
await user.send(f"Entrega de **{delivery['product_name']}**\n\n```\n{delivery['content']}\n```")
guild = self.get_guild(self.db.store_for_owner(self.db._one("SELECT owner_id FROM stores WHERE id=?", (delivery["store_id"],))["owner_id"])["guild_id"])
if guild and delivery["role_id"]:
member = guild.get_member(delivery["user_id"]) or await guild.fetch_member(delivery["user_id"])
role = guild.get_role(delivery["role_id"])
if role: await member.add_roles(role, reason="Compra confirmada")
return True
except discord.HTTPException:
logging.exception("Não foi possível enviar a entrega do carrinho %s", cart_id)
return False
async def publish_product(self, channel, product_id):
product = self.db.product(product_id)
embed = discord.Embed(title=product["name"], description=product["description"], color=discord.Color.blurple())
embed.add_field(name="Preço", value=money(product["price_cents"]), inline=True)
count = "∞" if product["infinite_stock"] else str(self.db.stock_count(product_id))
embed.add_field(name="Estoque", value=count, inline=True)
await channel.send(embed=embed, view=ProductBuyView(self, product_id))
def owner_check(interaction):
return interaction.guild is not None and (interaction.user.id == interaction.guild.owner_id or interaction.user.guild_permissions.manage_guild)
settings = load_settings()
logging.basicConfig(level=getattr(logging, settings.log_level.upper(), logging.INFO), format="%(asctime)s %(levelname)s %(message)s")
bot = StoreBot(settings)
@bot.tree.command(name="painel", description="Abre o painel de gerenciamento da sua loja")
async def painel(interaction: discord.Interaction):
if not owner_check(interaction): await interaction.response.send_message("Apenas o dono ou um administrador pode usar este comando.", ephemeral=True); return
store = bot.db.ensure_store(interaction.user.id, interaction.guild.id)
embed = discord.Embed(title=store["name"], description=store["description"] or "Painel de gerenciamento", color=discord.Color.blurple())
await interaction.response.send_message(embed=embed, view=DashboardView(bot, store), ephemeral=True)
@bot.tree.command(name="addsaldo", description="Adiciona saldo manualmente a um usuário")
@app_commands.describe(usuario="Usuário que receberá o saldo", valor="Valor em reais")
async def addsaldo(interaction, usuario: discord.Member, valor: float):
if not owner_check(interaction): await interaction.response.send_message("Sem permissão.", ephemeral=True); return
cents = int(round(valor * 100))
if cents <= 0: await interaction.response.send_message("O valor deve ser positivo.", ephemeral=True); return
bot.db.add_balance(usuario.id, cents)
await interaction.response.send_message(f"{money(cents)} adicionados a {usuario.mention}. Saldo atual: {money(bot.db.balance(usuario.id))}.", ephemeral=True)
@bot.tree.command(name="criar_cupom", description="Cria ou atualiza um cupom de desconto")
async def criar_cupom(interaction, codigo: str, desconto: app_commands.Range[int, 1, 100]):
if not owner_check(interaction): await interaction.response.send_message("Sem permissão.", ephemeral=True); return
store = bot.db.ensure_store(interaction.user.id, interaction.guild.id)
bot.db.create_coupon(store["id"], codigo, desconto)
await interaction.response.send_message(f"Cupom `{codigo.upper()}` criado com {desconto}% de desconto.", ephemeral=True)
@bot.tree.command(name="delivery", description="Entrega um produto diretamente para um usuário")
async def delivery(interaction, usuario: discord.Member, produto_id: int):
if not owner_check(interaction): await interaction.response.send_message("Sem permissão.", ephemeral=True); return
store = bot.db.ensure_store(interaction.user.id, interaction.guild.id); product = bot.db.product(produto_id)
if not product or product["store_id"] != store["id"]: await interaction.response.send_message("Produto não encontrado na sua loja.", ephemeral=True); return
cart = bot.db.create_cart(store["id"], usuario.id, product_id=produto_id)
bot.db.set_payment(cart["id"], "manual", "delivery")
bot.db.settle_cart(cart["id"], "manual", "delivery")
if await bot.deliver(cart["id"]): await interaction.response.send_message("Produto entregue.", ephemeral=True)
else: await interaction.response.send_message("Não foi possível entregar: estoque vazio ou DM bloqueada.", ephemeral=True)
@bot.tree.command(name="entregar", description="Aprova e entrega manualmente um carrinho")
async def entregar(interaction, carrinho_id: int):
if not owner_check(interaction): await interaction.response.send_message("Sem permissão.", ephemeral=True); return
cart = bot.db.cart_details(carrinho_id)
if not cart or cart["owner_id"] != interaction.user.id: await interaction.response.send_message("Carrinho não encontrado.", ephemeral=True); return
if cart["status"] == "pending": bot.db.settle_cart(carrinho_id, "manual", "manual-approval")
if await bot.deliver(carrinho_id): await interaction.response.send_message("Carrinho aprovado e produto entregue.", ephemeral=True)
else: await interaction.response.send_message("Sem estoque, DM bloqueada ou carrinho já entregue.", ephemeral=True)
saldo = app_commands.Group(name="saldo", description="Comandos de saldo")
bot.tree.add_command(saldo)
@saldo.command(name="painel", description="Publica o painel de adicionar saldo")
async def saldo_painel(interaction, canal: discord.TextChannel, descricao: str = "Escolha um valor para adicionar ao seu saldo."):
if not owner_check(interaction): await interaction.response.send_message("Sem permissão.", ephemeral=True); return
store = bot.db.ensure_store(interaction.user.id, interaction.guild.id)
bot.db.set_balance_panel(store["id"], canal.id, descricao)
embed = discord.Embed(title="Adicionar saldo", description=descricao, color=discord.Color.green())
await canal.send(embed=embed, view=BalancePanelView(bot, store["id"]))
await interaction.response.send_message(f"Painel enviado em {canal.mention}.", ephemeral=True)
@bot.tree.command(name="vendas", description="Consulta as vendas da sua loja")
async def vendas(interaction):
if not owner_check(interaction): await interaction.response.send_message("Sem permissão.", ephemeral=True); return
store = bot.db.store_for_owner(interaction.user.id)
if not store: await interaction.response.send_message("Sua loja ainda não foi criada. Use /painel.", ephemeral=True); return
rows = bot.db.sales(store["id"])
embed = discord.Embed(title="Vendas recebidas", color=discord.Color.green())
embed.description = "\n".join(f"`#{r['id']}` {r['product_name'] or 'Saldo'} · {money(r['amount_cents'])} · <@{r['buyer_id']}>" for r in rows) or "Nenhuma venda registrada."
await interaction.response.send_message(embed=embed, ephemeral=True)
metodo = app_commands.Group(name="metodo", description="Configuração de pagamentos")
bot.tree.add_command(metodo)
class PaymentConfigModal(discord.ui.Modal, title="Configurar pagamento"):
credentials = discord.ui.TextInput(label="Credenciais/configuração JSON", style=discord.TextStyle.paragraph, max_length=4000, placeholder='Stripe: {"secret_key":"...","webhook_secret":"..."}')
def __init__(self, store, provider): super().__init__(); self.store, self.provider = store, provider
async def on_submit(self, interaction):
import json
try: data = json.loads(self.credentials.value)
except json.JSONDecodeError: await interaction.response.send_message("Envie um JSON válido.", ephemeral=True); return
required = {"stripe": ("secret_key", "webhook_secret"), "mercadopago": ("access_token",), "efi": ("create_url", "status_url"), "mistic": ("create_url", "status_url"), "manual": ("information",)}[self.provider]
if any(not data.get(key) for key in required): await interaction.response.send_message("Faltam campos obrigatórios: " + ", ".join(required), ephemeral=True); return
try: encrypted = self.bot.secrets.encrypt(json.dumps(data)) if False else None
except RuntimeError: encrypted = None
# The bot instance is attached by the command before displaying this modal.
try: encrypted = interaction.client.secrets.encrypt(json.dumps(data))
except RuntimeError as exc: await interaction.response.send_message(str(exc), ephemeral=True); return
interaction.client.db.save_payment_method(self.store["id"], self.provider, encrypted)
await interaction.response.send_message(f"{PROVIDERS[self.provider]} habilitado com credenciais criptografadas.", ephemeral=True)
@metodo.command(name="pagamento", description="Habilita um método de pagamento")
async def metodo_pagamento(interaction, provedor: str):
if not owner_check(interaction): await interaction.response.send_message("Sem permissão.", ephemeral=True); return
if provedor not in PROVIDERS: await interaction.response.send_message("Provedor inválido: " + ", ".join(PROVIDERS), ephemeral=True); return
store = bot.db.ensure_store(interaction.user.id, interaction.guild.id)
await interaction.response.send_modal(PaymentConfigModal(store, provedor))