No chat to show

This project's files are all here to explore.

Files
tests
bot.py
database.py
fairness.py
payments.py
README.md
requirements.txt
Code
7 1,125
bot.py
import asyncio
import logging
import os
import re
import time
from datetime import datetime, timezone
from decimal import Decimal, InvalidOperation, ROUND_DOWN

import aiohttp
import discord
from aiohttp import web
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv

from database import Database, InsufficientFunds, InvalidOperationError
from fairness import FairRandom, commitment_for
from payments import NowPayments, callback_handler

load_dotenv()
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"), format="%(asctime)s %(levelname)s %(name)s: %(message)s")
log = logging.getLogger("crypto_casino")

TOKEN = os.getenv("DISCORD_TOKEN", "")
DATABASE_URL = os.getenv("DATABASE_URL", "")
MIN_BET = Decimal(os.getenv("MIN_BET", "0.10"))
MAX_BET = Decimal(os.getenv("MAX_BET", "1000"))
DAILY_REWARD = Decimal(os.getenv("DAILY_REWARD", "10"))
HOUSE_EDGE = Decimal(os.getenv("HOUSE_EDGE", "0.05"))
LARGE_BET_THRESHOLD = Decimal(os.getenv("LARGE_BET_THRESHOLD", "100"))
ADMIN_ROLE_ID = int(os.getenv("ADMIN_ROLE_ID", "0") or 0)
ADMIN_CHANNEL_ID = int(os.getenv("ADMIN_CHANNEL_ID", "0") or 0)
CALLBACK_URL = os.getenv("NOWPAYMENTS_CALLBACK_URL", "https://qtcgtobq.kodaribots.com/nowpayments/ipn")
SERVER_PORT = int(os.getenv("SERVER_PORT", "8080"))
ADDRESS_PATTERN = re.compile(r"^[A-Za-z0-9]{20,128}$")
AMOUNT_PATTERN = re.compile(r"^\d{1,10}(?:\.\d{1,2})?$")
EDGE_FACTOR = Decimal("1") - HOUSE_EDGE
COINS = [
    app_commands.Choice(name="Bitcoin (BTC)", value="BTC"),
    app_commands.Choice(name="Ethereum (ETH)", value="ETH"),
    app_commands.Choice(name="Tether (USDT)", value="USDT"),
    app_commands.Choice(name="Litecoin (LTC)", value="LTC"),
]


def amount(value: str, *, minimum: Decimal = Decimal("0.01"), maximum: Decimal | None = None) -> Decimal:
    if not AMOUNT_PATTERN.fullmatch(value):
        raise ValueError("Enter a positive amount with at most two decimal places.")
    try:
        parsed = Decimal(value)
    except InvalidOperation as exc:
        raise ValueError("Invalid amount.") from exc
    if parsed < minimum or (maximum is not None and parsed > maximum):
        raise ValueError(f"Amount must be between {minimum:.2f} and {maximum:.2f}.")
    return parsed


def chips(value: Decimal) -> Decimal:
    return value.quantize(Decimal("0.00000001"), rounding=ROUND_DOWN)


def is_admin(member: discord.Member) -> bool:
    return member.guild_permissions.administrator or (ADMIN_ROLE_ID != 0 and any(role.id == ADMIN_ROLE_ID for role in member.roles))


def admin_check():
    async def predicate(interaction: discord.Interaction) -> bool:
        return isinstance(interaction.user, discord.Member) and is_admin(interaction.user)
    return app_commands.check(predicate)


_command_cooldowns: dict[tuple[int, str], float] = {}
_component_cooldowns: dict[tuple[int, int], float] = {}


def limited(seconds: float = 2.0):
    async def predicate(interaction: discord.Interaction) -> bool:
        key = (interaction.user.id, interaction.command.name if interaction.command else "unknown")
        now = time.monotonic()
        if now - _command_cooldowns.get(key, 0) < seconds:
            raise app_commands.CheckFailure("Please wait a moment before using that command again.")
        _command_cooldowns[key] = now
        return True
    return app_commands.check(predicate)


class CasinoBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned, intents=discord.Intents.default())
        self.db: Database | None = None
        self.payments: NowPayments | None = None
        self.http_runner: web.AppRunner | None = None

    async def setup_hook(self) -> None:
        if not TOKEN or not DATABASE_URL:
            raise RuntimeError("DISCORD_TOKEN and DATABASE_URL are required. See README.md.")
        if not Decimal("0") <= HOUSE_EDGE < Decimal("1"):
            raise RuntimeError("HOUSE_EDGE must be at least 0 and less than 1.")
        if MIN_BET <= 0 or MAX_BET < MIN_BET or DAILY_REWARD < 0:
            raise RuntimeError("MIN_BET, MAX_BET, or DAILY_REWARD configuration is invalid.")
        self.db = Database(DATABASE_URL)
        await self.db.open()
        self.payments = NowPayments(self.db)
        self.payments.audit = self.audit
        await self.payments.open()
        app = web.Application()
        app.router.add_post("/nowpayments/ipn", callback_handler(self.payments))
        self.http_runner = web.AppRunner(app)
        await self.http_runner.setup()
        await web.TCPSite(self.http_runner, "0.0.0.0", SERVER_PORT).start()
        await self.tree.sync()

    async def close(self) -> None:
        if self.http_runner:
            await self.http_runner.cleanup()
        if self.payments:
            await self.payments.close()
        if self.db:
            await self.db.close()
        await super().close()

    async def audit(self, message: str) -> None:
        if not ADMIN_CHANNEL_ID:
            return
        channel = self.get_channel(ADMIN_CHANNEL_ID)
        if channel is None:
            try:
                channel = await self.fetch_channel(ADMIN_CHANNEL_ID)
            except (discord.NotFound, discord.Forbidden, discord.HTTPException):
                log.warning("Could not access configured audit channel.")
                return
        if isinstance(channel, (discord.TextChannel, discord.Thread)):
            try:
                await channel.send(message[:1900])
            except discord.HTTPException:
                log.warning("Could not send audit message.")


bot = CasinoBot()


def require_db() -> Database:
    if bot.db is None:
        raise RuntimeError("Database is unavailable.")
    return bot.db


async def send_error(interaction: discord.Interaction, text: str) -> None:
    if interaction.response.is_done():
        await interaction.followup.send(text, ephemeral=True)
    else:
        await interaction.response.send_message(text, ephemeral=True)


async def command_error(interaction: discord.Interaction, error: app_commands.AppCommandError) -> None:
    if isinstance(error, app_commands.CheckFailure):
        message = str(error) or "You do not have permission to use that command."
    elif isinstance(error, (ValueError, InsufficientFunds, InvalidOperationError)):
        message = str(error)
    else:
        log.error("Slash command failed (%s).", type(error).__name__)
        message = "That action could not be completed. Please try again later."
    await send_error(interaction, message)


bot.tree.on_error = command_error


@bot.event
async def on_ready() -> None:
    log.info("Connected as %s", bot.user)
    print("KODARI_READY", flush=True)


@bot.tree.command(name="balance", description="Show your casino chip balance")
@limited()
async def balance(interaction: discord.Interaction) -> None:
    value = await require_db().balance(interaction.user.id)
    await interaction.response.send_message(f"Your balance: **${value:.2f} chips**", ephemeral=True)


@bot.tree.command(name="deposit", description="Create a cryptocurrency deposit invoice")
@app_commands.choices(coin=COINS)
@limited(5)
async def deposit(interaction: discord.Interaction, coin: app_commands.Choice[str], amount_usd: str) -> None:
    value = amount(amount_usd, minimum=Decimal("1.00"), maximum=Decimal("10000.00"))
    provider = bot.payments
    if provider is None or not provider.configured:
        raise ValueError("Deposits are disabled until NOWPAYMENTS_API_KEY, NOWPAYMENTS_IPN_SECRET, and callback configuration are supplied.")
    await interaction.response.defer(ephemeral=True, thinking=True)
    db = require_db()
    order_id = await db.create_deposit_order(interaction.user.id, value, coin.value)
    try:
        invoice = await provider.create_invoice(order_id, interaction.user.id, value, coin.value, CALLBACK_URL)
        await db.attach_deposit_invoice(order_id, invoice)
    except Exception as exc:
        await db.fail_deposit_order(order_id)
        log.warning("Invoice creation failed (%s).", type(exc).__name__)
        raise ValueError("Payment provider could not create an invoice. Check NOWPayments credentials, supported currency settings, and account status.") from exc
    await interaction.followup.send(