Files
tests
.gitignore
bot.py
Dockerfile
README.md
requirements.txt
store.py
Code
7 481
bot.py
import asyncio
import logging
import os
import time
import aiohttp
from aiohttp import web
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
from store import Store, verify_signature
load_dotenv()
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s %(message)s')
log = logging.getLogger('digital-store')
required = ('DISCORD_TOKEN', 'OWNER_IDS', 'RAZORPAY_KEY_ID', 'RAZORPAY_KEY_SECRET', 'RAZORPAY_WEBHOOK_SECRET', 'INVENTORY_ENCRYPTION_KEY')
if any(not os.getenv(name) or os.getenv(name) == 'your_discord_bot_token_here' for name in required):
raise RuntimeError('Set all required environment variables before starting.')
owners = {int(value.strip()) for value in os.environ['OWNER_IDS'].split(',') if value.strip()}
store = Store(os.getenv('DATABASE_PATH', 'store.db'), os.environ['INVENTORY_ENCRYPTION_KEY'])
class StoreBot(commands.Bot):
async def setup_hook(self):
self.http_session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=15), auth=aiohttp.BasicAuth(os.environ['RAZORPAY_KEY_ID'], os.environ['RAZORPAY_KEY_SECRET']))
app = web.Application(client_max_size=128 * 1024)
app.router.add_post('/webhooks/razorpay', webhook)
app.router.add_get('/health', lambda request: web.Response(text='ok'))
self.runner = web.AppRunner(app, access_log=None)
await self.runner.setup()
await web.TCPSite(self.runner, '0.0.0.0', int(os.getenv('SERVER_PORT', '8080'))).start()
await self.tree.sync()
async def close(self):
await self.runner.cleanup()
await self.http_session.close()
store.db.close()
await super().close()
bot = StoreBot(command_prefix='!', intents=discord.Intents.default())
@bot.event
async def on_ready():
log.info('Connected as %s', bot.user)
print('KODARI_READY', flush=True)
async def razorpay(method, path, data=None):
async with bot.http_session.request(method, 'https://api.razorpay.com/v1/' + path, json=data, allow_redirects=False) as response:
if response.status >= 400:
log.error('Razorpay returned HTTP %s for %s', response.status, path.split('/')[0])
raise RuntimeError('Payment provider request failed.')
return await response.json()
async def webhook(request):
body = await request.read()
if not verify_signature(os.environ['RAZORPAY_WEBHOOK_SECRET'], body, request.headers.get('X-Razorpay-Signature')):
return web.Response(status=401)
try:
payload = await request.json()
if payload.get('event') != 'payment_link.paid':
return web.Response(status=200)
entity = payload['payload']['payment_link']['entity']
link_id = entity['id']
link = await razorpay('GET', 'payment_links/' + link_id)
if link['status'] != 'paid' or link['amount_paid'] != link['amount']:
return web.Response(status=409)
payments = link.get('payments') or []
if len(payments) != 1:
log.warning('Payment link %s requires manual review: unexpected payment count', link_id)
return web.Response(status=409)
payment = await razorpay('GET', 'payments/' + payments[0]['payment_id'])
if payment['status'] != 'captured' or payment['amount'] != link['amount'] or payment['currency'] != link['currency']:
return web.Response(status=409)
order_id = link['reference_id']
newly_paid = store.confirm_payment(order_id, link_id, link['amount'], link['currency'], payment['id'])
if newly_paid:
row = store.db.execute('SELECT user_id FROM orders WHERE id=?', (order_id,)).fetchone()
try:
user = await bot.fetch_user(row['user_id'])
await user.send(f'Your DIGITAL STORE order `{order_id}` is paid. Use `/delivery order_id:{order_id}` to retrieve your item privately.')
except discord.HTTPException:
log.warning('Could not notify customer for order %s', order_id)
return web.Response(status=200)
except (KeyError, ValueError, TypeError):
log.warning('Rejected invalid payment webhook')
return web.Response(status=400)
except Exception:
log.exception('Webhook processing failed')
return web.Response(status=500)
def owner_only():
async def predicate(interaction):
return interaction.user.id in owners
return app_commands.check(predicate)
@bot.tree.command(description='Browse or search DIGITAL STORE products')
@app_commands.checks.cooldown(3, 10.0, key=lambda i: i.user.id)
async def shop(interaction: discord.Interaction, search: str = ''):
products = store.products(search[:100])
embed = discord.Embed(title='DIGITAL STORE', description='Browse products and use /buy to check out.', color=0x8b5cf6)
for p in products:
embed.add_field(name=f"#{p['id']} · {p['name']} · ₹{p['price']/100:.2f}", value=f"{p['category']} · {p['stock']} available\n{p['description']}", inline=False)
if not products:
embed.description = 'No products found.'
await interaction.response.send_message(embed=embed, ephemeral=True)
@bot.tree.command(description='Purchase one product securely through Razorpay')
@app_commands.checks.cooldown(1, 20.0, key=lambda i: i.user.id)
async def buy(interaction: discord.Interaction, product_id: int):
await interaction.response.defer(ephemeral=True, thinking=True)
try:
order = store.create_order(interaction.user.id, product_id)
except ValueError as exc:
await interaction.followup.send(str(exc), ephemeral=True)
return
try:
link = await razorpay('POST', 'payment_links', {'amount': order['amount'], 'currency': 'INR', 'accept_partial': False, 'reference_id': order['id'], 'description': 'DIGITAL STORE order ' + order['id'], 'expire_by': int(time.time()) + 3600, 'reminder_enable': False})
store.attach_link(order['id'], link['id'], link['short_url'])
except Exception:
# A timed-out provider request may still have created a payable link; retain the reservation for reconciliation.
log.exception('Payment-link creation uncertain for order %s', order['id'])
await interaction.followup.send(f'Checkout could not be completed. Contact support with order `{order["id"]}`.', ephemeral=True)
return
await interaction.followup.send(f'Order `{order["id"]}`: [Pay securely with Razorpay]({link["short_url"]}). Use /orders to track it.', ephemeral=True)
@bot.tree.command(description='View your recent orders and payment status')
async def orders(interaction: discord.Interaction):
rows = store.db.execute('SELECT id,amount,status,created FROM orders WHERE user_id=? ORDER BY created DESC LIMIT 15', (interaction.user.id,)).fetchall()
text = '\n'.join(f"`{r['id']}` · ₹{r['amount']/100:.2f} · {r['status']}" for r in rows) or 'No orders yet.'
await interaction.response.send_message(text, ephemeral=True)
@bot.tree.command(description='Retrieve your paid digital item privately')
@app_commands.checks.cooldown(3, 10.0, key=lambda i: i.user.id)
async def delivery(interaction: discord.Interaction, order_id: str):
content = store.get_delivery(interaction.user.id, order_id)
await interaction.response.send_message(content if content else 'No paid delivery found for this order.', ephemeral=True, allowed_mentions=discord.AllowedMentions.none())
@bot.tree.command(description='Request review of a paid order refund')
@app_commands.checks.cooldown(2, 60.0, key=lambda i: i.user.id)
async def refund_request(interaction: discord.Interaction, order_id: str, reason: str):
try:
store.request_refund(interaction.user.id, order_id, reason)
await interaction.response.send_message('Refund request recorded for staff review; this does not issue a refund.', ephemeral=True)
except ValueError as exc:
await interaction.response.send_message(str(exc), ephemeral=True)
@bot.tree.command(description='Get help with DIGITAL STORE')
async def store_help(interaction: discord.Interaction):
await interaction.response.send_message('Use /shop to browse, /buy to check out, /orders to track purchases, /delivery to retrieve an item, and /refund_request to request a review. Contact the server staff for support.', ephemeral=True)
@bot.tree.command(description='Owner: create a product; price is in paise')
@owner_only()
async def product_add(interaction: discord.Interaction, name: str, category: str, description: str, price_paise: int):
try:
product_id = store.add_product(interaction.user.id, name, category, description, price_paise)
await interaction.response.send_message(f'Created product #{product_id}.', ephemeral=True)
except ValueError as exc:
await interaction.response.send_message(str(exc), ephemeral=True)
@bot.tree.command(description='Owner: add one private inventory item through a modal')
@owner_only()
async def stock_add(interaction: discord.Interaction, product_id: int):
class StockModal(discord.ui.Modal, title='Add digital inventory'):
content = discord.ui.TextInput(label='Secret item content', style=discord.TextStyle.paragraph, max_length=1500)
async def on_submit(self, modal_interaction: discord.Interaction):
if modal_interaction.user.id not in owners:
await modal_interaction.response.send_message('Not authorized.', ephemeral=True)
return
try:
store.add_stock(modal_interaction.user.id, product_id, str(self.content))
await modal_interaction.response.send_message('Inventory item encrypted and added.', ephemeral=True)
except ValueError as exc:
await modal_interaction.response.send_message(str(exc), ephemeral=True)
await interaction.response.send_modal(StockModal())
@bot.tree.command(description='Owner: view recent refund requests')
@owner_only()
async def refund_queue(interaction: discord.Interaction):
rows = store.db.execute("SELECT id,order_id,reason FROM refunds WHERE status='requested' ORDER BY created LIMIT 10").fetchall()
text = '\n'.join(f"#{r['id']} · `{r['order_id']}` · {r['reason'][:120]}" for r in rows) or 'No open requests.'
await interaction.response.send_message(text, ephemeral=True, allowed_mentions=discord.AllowedMentions.none())