Files
royal_support
scripts
src
test
.gitignore
KIRO.md
main.py
package.json
README.md
requirements.txt
Code
51 7,861
main.py
import asyncio
import difflib
import json
import logging
import os
import random
import re
from datetime import datetime

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

from royal_support.commands import RoyalCommands
from royal_support.config import Config
from royal_support.database import Database
from royal_support.paystack import Paystack, PaystackError
from royal_support.storefront import (
    CHANNELS,
    OrderOperationsView,
    OrderHistoryView,
    ProductPageView,
    StoreNavigationView,
    SupportPanelView,
    TicketCloseView,
    active_promotion,
    begin_checkout,
    branded_embed,
    configured_bc_products,
    featured_products,
    order_history_embeds,
    panel_payload,
    payment_log_embed,
    product_page_embeds,
    send_staff_alert,
    send_staff_log,
)
from royal_support.web import create_app
from royal_support.staff import STAFF_CHANNELS


class ConversationWelcomeView(discord.ui.View):
    def __init__(self, bot):
        super().__init__(timeout=900)
        self.bot = bot
        for label, action, style in (
            ("๐Ÿ›’ SHOP", "SHOP", discord.ButtonStyle.success),
            ("๐Ÿ“ฆ MY ORDERS", "ORDERS", discord.ButtonStyle.secondary),
            ("๐ŸŽซ SUPPORT", "SUPPORT", discord.ButtonStyle.primary),
        ):
            button = discord.ui.Button(label=label, style=style)

            async def run(interaction: discord.Interaction, action=action):
                await self.bot.handle_conversation_button(interaction, action)

            button.callback = run
            self.add_item(button)


class ConversationChoiceView(discord.ui.View):
    def __init__(self, bot, choices: tuple[tuple[str, str], ...]):
        super().__init__(timeout=900)
        self.bot = bot
        for index, (label, choice) in enumerate(choices):
            button = discord.ui.Button(label=label, style=discord.ButtonStyle.primary, row=index // 3)

            async def choose(interaction: discord.Interaction, choice=choice):
                await self.bot.handle_conversation_choice(interaction, choice)

            button.callback = choose
            self.add_item(button)


class ConversationBuyView(discord.ui.View):
    def __init__(self, bot, product_id: str):
        super().__init__(timeout=900)
        self.bot = bot
        button = discord.ui.Button(label="๐Ÿ›’ BUY NOW", style=discord.ButtonStyle.success)

        async def buy(interaction: discord.Interaction):
            try:
                await begin_checkout(self.bot, interaction, product_id)
            except Exception:
                logging.exception("Conversational checkout could not start")
                try:
                    if interaction.response.is_done():
                        await interaction.followup.send("Royal Support could not start checkout. No payment was verified; please try again or open support.", ephemeral=True)
                    else:
                        await interaction.response.send_message("Royal Support could not start checkout. No payment was verified; please try again or open support.", ephemeral=True)
                except discord.HTTPException:
                    logging.exception("Could not send conversational checkout error")

        button.callback = buy
        self.add_item(button)


class ConversationalAuthor:
    def __init__(self, author, response):
        self._author = author
        self._response = response

    def __getattr__(self, name):
        return getattr(self._author, name)

    async def send(self, *args, **kwargs):
        await self._response.wait_for_response(*args, **kwargs)
        return await self._author.send(*args, **kwargs)


class ConversationalMessage:
    def __init__(self, message: discord.Message, request_text: str):
        self._message = message
        self._request_text = request_text
        self._started_at = asyncio.get_running_loop().time()
        self.author = ConversationalAuthor(message.author, self)

    def __getattr__(self, name):
        return getattr(self._message, name)

    @staticmethod
    def response_text(args, kwargs) -> tuple[str, bool]:
        parts = []
        content = kwargs.get("content")
        if content is None and args and isinstance(args[0], str):
            content = args[0]
        if content:
            parts.append(str(content))
        embeds = kwargs.get("embeds") or ([kwargs["embed"]] if kwargs.get("embed") else [])
        for embed in embeds:
            parts.extend((embed.title or "", embed.description or ""))
            parts.extend(f"{field.name} {field.value}" for field in embed.fields)
        return " ".join(part for part in parts if part), bool(embeds)

    async def wait_for_response(self, *args, **kwargs) -> None:
        response, has_embed = self.response_text(args, kwargs)
        combined = f"{self._request_text} {response}"
        word_count = len(re.findall(r"\S+", combined))
        if (
            len(self._request_text) > 120
            or len(response) > 500
            or word_count > 75
            or re.search(r"\b(explain|walk me through|step by step|and then|afterward|in detail)\b", self._request_text, re.I)
        ):
            minimum, maximum = 2.0, 4.0
        elif not has_embed and len(self._request_text) <= 30 and len(response) <= 100:
            minimum, maximum = 0.8, 1.8
        else:
            minimum, maximum = 1.2, 2.8
        elapsed = asyncio.get_running_loop().time() - self._started_at
        remaining = random.uniform(minimum, maximum) - elapsed
        if remaining > 0:
            await asyncio.sleep(remaining)

    async def reply(self, *args, **kwargs):
        await self.wait_for_response(*args, **kwargs)
        return await self._message.reply(*args, **kwargs)


class RoyalSupportBot(commands.Bot):
    ROLE_ROSTER_TTL = 20
    CUSTOMER_INTENT_WORDS = (
        "hello", "help", "support", "ticket", "admin", "contact", "buy", "purchase", "checkout",
        "shop", "store", "package", "packages", "royal", "cash", "coin", "coins", "price", "cost",
        "cheapest", "biggest", "largest", "promotion", "promotions", "promo", "sale", "sales",
        "offer", "offers", "deal", "deals", "discount", "order", "orders", "paid", "payment",
        "paystack", "pending", "founder", "owner", "creator", "created", "featured", "refund",
        "delivery", "track", "tracking", "problem", "issue", "status",
    )
    CUSTOMER_SHORTHAND = {
        "hiya": "hello",
        "yo": "hello",
        "sup": "hello",
        "wassup": "hello",
        "pls": "please",
        "plz": "please",
        "thx": "thanks",
        "ty": "thanks",
        "wanna": "want to",
        "tryna": "trying to",
        "u": "you",
        "ur": "your",
    }
    PRESENCE_NAMES = (
        "๐ŸŽฎ Playing Royal City",
        "๐Ÿ‘‘ Royal City Roleplay",
        "๐Ÿ’ฐ Managing Royal Cash",
        "๐Ÿ›’ Royal City Store",
        "๐Ÿ’Ž Building the Empire",
        "๐Ÿ™๏ธ Welcome to Royal City",
        "๐ŸŽง Helping Royal City players",
        "๐Ÿ’ฌ Reading your DMs",
        "๐Ÿ‘€ Watching the city",
        "๐Ÿ”ฅ Royal City is alive",
        "๐Ÿ‘‘ Serving Royal City",
        "๐Ÿ’ฐ Buy Royal Cash",
        "๐Ÿ›’ Shop Royal City",
        "๐ŸŽฎ See you in Royal City",
        "๐Ÿš˜ Living the Royal Life",
        "๐Ÿ† Chasing the next level",