Build the requested Stripe invoice redemption Discord bot in this Python Discord bot project. The source is currently empty. Requirements:

  • Users can press a persistent “Claim Buyer Role” button, enter a Stripe invoice ID in a modal, and receive the configured Buyer/customer Discord role automatically.
  • The panel must show exactly this content: title Claim Buyer Role; description You can automatically obtain the Buyer role and access to the Customer section by utilizing the button below.; footer ZYLO | Delivering Premium Service•.
  • Provide a slash command such as /setup for an administrator to post the panel in the current text channel. Restrict setup to administrators. Make the button persistent across bot restarts.
  • Verify the submitted ID with Stripe’s official Python SDK, retrieving that exact invoice. Only grant access if Stripe confirms it is paid (status == "paid" and/or paid is True); reject invalid, unpaid, or inaccessible invoices with clear ephemeral responses. Never expose secrets or Stripe exception details to Discord users.
  • Read configuration from environment variables: DISCORD_TOKEN, STRIPE_SECRET_KEY, and BUYER_ROLE_ID. Validate missing/invalid configuration and document setup and deployment in README. Add the Stripe SDK to the project's dependency manifest in the appropriate way.
  • Prevent a single invoice from being claimed by different Discord users. Persist successful invoice-to-user claims in SQLite so this remains true across restarts. Treat repeat claims by the same user as idempotent; grant the role if they do not currently have it. Handle Discord role/permission or role-not-found errors safely.
  • Include sensible logging and defer interactions while doing network calls. Do not add tests. Implement feature code and user-facing setup instructions only; do not attempt a build.
Kodari AI
KodariNov 4 at 8:09 pm 2
StripeRedeemBot
A Discord bot that lets customers redeem Stripe invoices for a Buyer role. Users click a persistent "Claim Buyer Role" button, enter their Stripe invoice ID in a modal, and the bot verifies payment via the Stripe SDK before granting the configured role. Includes an admin-only /setup command to post the panel, SQLite persistence to prevent invoice reuse across users, idempotent role granting, and secure error handling that never exposes secrets. Configuration is managed via environment variables with comprehensive logging.
  1. Build the persistent claim panel and Stripe verification flow.

  2. Store invoice claims in SQLite and handle role assignment safely.

  3. Add configuration and deployment instructions.

Built the Stripe invoice redemption bot with a persistent claim panel, paid-invoice verification, and SQLite claim tracking.

Configure the credentials and role ID in .env, then deploy and run /setup as an administrator. See README.md for permissions and setup details.

Invoice IDs act as claim credentials, so share them only with the intended buyer.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 201
bot.py
import asyncio
import logging
import os
import sqlite3

import discord
import stripe
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("invoice_redemption")


def load_config():
    token = os.getenv("DISCORD_TOKEN", "").strip()
    stripe_key = os.getenv("STRIPE_SECRET_KEY", "").strip()
    role_id = os.getenv("BUYER_ROLE_ID", "").strip()
    if not token or not stripe_key or not role_id:
        raise ValueError("DISCORD_TOKEN, STRIPE_SECRET_KEY and BUYER_ROLE_ID are required")
    if not role_id.isascii() or not role_id.isdecimal() or int(role_id) <= 0:
        raise ValueError("BUYER_ROLE_ID must be a positive Discord role ID")
    if not stripe_key.startswith(("sk_", "rk_")):
        raise ValueError("STRIPE_SECRET_KEY must be a Stripe secret or restricted key")
    return token, stripe_key, int(role_id)


TOKEN, STRIPE_KEY, BUYER_ROLE_ID = load_config()


class ClaimModal(discord.ui.Modal, title="Claim Buyer Role"):
    invoice_id = discord.ui.TextInput(
        label="Stripe invoice ID", placeholder="in_...", max_length=255
    )

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.defer(ephemeral=True, thinking=True)
        if interaction.guild is None or not isinstance(interaction.user, discord.Member):
            await interaction.followup.send("Please use this button in the server.", ephemeral=True)
            return

        invoice_id = str(self.invoice_id).strip()
        if not invoice_id.startswith("in_") or len(invoice_id) <= 3:
            await interaction.followup.send("Please enter a valid Stripe invoice ID starting with `in_`.", ephemeral=True)
            return

        try:
            invoice = await asyncio.to_thread(
                stripe.Invoice.retrieve, invoice_id, api_key=STRIPE_KEY
            )
        except stripe.error.StripeError:
            logger.warning("Stripe invoice lookup failed", exc_info=True)
            await interaction.followup.send(
                "That invoice could not be verified. Check the ID and try again, or contact support.",
                ephemeral=True,
            )
            return
        except Exception:
            logger.exception("Unexpected invoice lookup failure")
            await interaction.followup.send("Invoice verification is temporarily unavailable. Please try again later.", ephemeral=True)
            return

        if invoice.get("status") != "paid" and invoice.get("paid") is not True:
            await interaction.followup.send("This invoice is not paid, so it cannot be claimed.", ephemeral=True)
            return

        role = interaction.guild.get_role(BUYER_ROLE_ID)
        if role is None:
            logger.error("Configured buyer role was not found in guild %s", interaction.guild.id)
            await interaction.followup.send("The Buyer role is unavailable. Please contact an administrator.", ephemeral=True)
            return

        bot_member = interaction.guild.me
        if (bot_member is None or not bot_member.guild_permissions.manage_roles
                or role.is_default() or role.managed or role >= bot_member.top_role):
            logger.error("Cannot assign buyer role in guild %s: permissions or role hierarchy", interaction.guild.id)
            await interaction.followup.send("I cannot assign the Buyer role. Please contact an administrator.", ephemeral=True)
            return

        async with bot.claim_lock:
            try:
                with sqlite3.connect("claims.sqlite3") as db:
                    existing = db.execute(
                        "SELECT user_id FROM claims WHERE invoice_id = ?", (invoice_id,)
                    ).fetchone()
                    if existing and existing[0] != str(interaction.user.id):
                        await interaction.followup.send("This invoice has already been claimed by another user.", ephemeral=True)
                        return
                    if not existing:
                        db.execute(
                            "INSERT INTO claims (invoice_id, user_id) VALUES (?, ?)",
                            (invoice_id, str(interaction.user.id)),
                        )
            except sqlite3.Error:
                logger.exception("Could not reserve invoice claim")
                await interaction.followup.send("Claims are temporarily unavailable. Please try again later.", ephemeral=True)
                return

            try:
                if role not in interaction.user.roles:
                    await interaction.user.add_roles(role, reason="Paid Stripe invoice claim")
            except discord.HTTPException:
                logger.exception("Failed to assign buyer role")
                if not existing:
                    try:
                        with sqlite3.connect("claims.sqlite3") as db:
                            db.execute("DELETE FROM claims WHERE invoice_id = ? AND user_id = ?", (invoice_id, str(interaction.user.id)))
                    except sqlite3.Error:
                        logger.exception("Failed to remove unsuccessful claim reservation")
                await interaction.followup.send("I could not assign the Buyer role. Please contact an administrator.", ephemeral=True)
                return

        await interaction.followup.send("Your invoice was verified and you have the Buyer role.", ephemeral=True)


class ClaimView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Claim Buyer Role", style=discord.ButtonStyle.primary, custom_id="claim_buyer_role:v1")
    async def claim(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_modal(ClaimModal())


class RedemptionBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned, intents=discord.Intents.default())
        self.claim_lock = asyncio.Lock()

    async def setup_hook(self):
        with sqlite3.connect("claims.sqlite3") as db:
            db.execute("CREATE TABLE IF NOT EXISTS claims (invoice_id TEXT PRIMARY KEY, user_id TEXT NOT NULL)")
        self.add_view(ClaimView())
        await self.tree.sync()

    async def on_ready(self):
        logger.info("Logged in as %s", self.user)
        print("KODARI_READY", flush=True)


bot = RedemptionBot()


@bot.tree.command(name="setup", description="Post the buyer role claim panel")
@app_commands.guild_only()
@app_commands.default_permissions(administrator=True)
@app_commands.checks.has_permissions(administrator=True)
async def setup(interaction: discord.Interaction):
    await interaction.response.defer(ephemeral=True, thinking=True)
    embed = discord.Embed(
        title="Claim Buyer Role",
        description="You can automatically obtain the Buyer role and access to the Customer section by utilizing the button below.",
    )
    embed.set_footer(text="ZYLO | Delivering Premium Service•")
    try:
        await interaction.channel.send(embed=embed, view=ClaimView())
    except (discord.HTTPException, AttributeError):
        logger.exception("Could not post claim panel")
        await interaction.followup.send("I could not post the panel here. Check my channel permissions.", ephemeral=True)
        return
    await interaction.followup.send("Claim panel posted.", ephemeral=True)


@setup.error
async def setup_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.MissingPermissions):
        message = "Only administrators can use this command."
    else:
        logger.error("Setup command failed: %s", error, exc_info=error)
        message = "The setup command failed. Please try again later."
    if interaction.response.is_done():
        await interaction.followup.send(message, ephemeral=True)
    else:
        await interaction.response.send_message(message, ephemeral=True)


if __name__ == "__main__":
    bot.run(TOKEN)