Files
bot.py
requirements.txt
Code
2 313
bot.py
import asyncio
import logging
import os
import random
import time
import aiosqlite
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("mimi_bot")
DAILY_COOLDOWN = 24 * 60 * 60
WORK_COOLDOWN = 60
WORK_TASKS = (
"helped a villager with their farm",
"delivered a package across town",
"mined a pocket of shiny ores",
"served snacks at the community café",
"found a lost wallet and earned a thank-you",
)
class MimiBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="!", intents=discord.Intents.default())
self.db = None
self.db_lock = asyncio.Lock()
async def setup_hook(self):
self.db = await aiosqlite.connect("mimi_data.sqlite3")
await self.db.execute("PRAGMA journal_mode=WAL")
await self.db.execute(
"""CREATE TABLE IF NOT EXISTS accounts (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
wallet INTEGER NOT NULL DEFAULT 0,
bank INTEGER NOT NULL DEFAULT 0,
daily_at INTEGER NOT NULL DEFAULT 0,
work_at INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (guild_id, user_id)
)"""
)
await self.db.commit()
synced = await self.tree.sync()
logger.info("Synced %s application commands", len(synced))
async def close(self):
if self.db is not None:
await self.db.close()
await super().close()
bot = MimiBot()
async def ensure_account(guild_id: int, user_id: int):
await bot.db.execute(
"INSERT OR IGNORE INTO accounts (guild_id, user_id) VALUES (?, ?)",
(guild_id, user_id),
)
async def get_account(guild_id: int, user_id: int):
async with bot.db_lock:
cursor = await bot.db.execute(
"SELECT wallet, bank FROM accounts WHERE guild_id = ? AND user_id = ?",
(guild_id, user_id),
)
row = await cursor.fetchone()
return row if row is not None else (0, 0)
def format_coins(amount: int) -> str:
return f"🪙 {amount:,}"
def cooldown_text(seconds: int) -> str:
hours, remainder = divmod(seconds, 3600)
minutes, secs = divmod(remainder, 60)
return f"{hours}h {minutes}m {secs}s"
@bot.tree.command(name="help", description="See Mimi's available commands")
@app_commands.guild_only()
async def help_command(interaction: discord.Interaction):
embed = discord.Embed(
title="Mimi • Community Economy",
description="Earn coins, save them, and share them with your server friends.",
color=discord.Color.blurple(),
)
embed.add_field(
name="Earn and check coins",
value="`/balance` · `/daily` · `/work` · `/leaderboard`",
inline=False,
)
embed.add_field(
name="Manage coins",
value="`/pay` · `/deposit` · `/withdraw`",
inline=False,
)
await interaction.response.send_message(embed=embed, ephemeral=True)
@bot.tree.command(name="balance", description="Check your or another member's wallet and bank")
@app_commands.guild_only()
@app_commands.describe(member="The member whose balance you want to check")
async def balance(interaction: discord.Interaction, member: discord.Member | None = None):
target = member or interaction.user
wallet, bank = await get_account(interaction.guild_id, target.id)
embed = discord.Embed(title=f"{target.display_name}'s balance", color=discord.Color.gold())
embed.add_field(name="Wallet", value=format_coins(wallet))
embed.add_field(name="Bank", value=format_coins(bank))
embed.add_field(name="Total", value=format_coins(wallet + bank), inline=False)
await interaction.response.send_message(embed=embed)
@bot.tree.command(name="daily", description="Claim your daily coin reward")
@app_commands.guild_only()
async def daily(interaction: discord.Interaction):
guild_id = interaction.guild_id
now = int(time.time())
async with bot.db_lock:
await ensure_account(guild_id, interaction.user.id)
cursor = await bot.db.execute(
"SELECT daily_at FROM accounts WHERE guild_id = ? AND user_id = ?",
(guild_id, interaction.user.id),
)
daily_at = (await cursor.fetchone())[0]
remaining = DAILY_COOLDOWN - (now - daily_at)
if remaining > 0:
await interaction.response.send_message(
f"Your next daily reward is ready in **{cooldown_text(remaining)}**.", ephemeral=True
)
return
reward = random.randint(100, 250)
await bot.db.execute(
"UPDATE accounts SET wallet = wallet + ?, daily_at = ? WHERE guild_id = ? AND user_id = ?",
(reward, now, guild_id, interaction.user.id),
)
await bot.db.commit()
await interaction.response.send_message(
f"You claimed your daily reward of **{format_coins(reward)}**! Come back tomorrow for more."
)
@bot.tree.command(name="work", description="Do a quick job to earn coins")
@app_commands.guild_only()
async def work(interaction: discord.Interaction):
guild_id = interaction.guild_id
now = int(time.time())
async with bot.db_lock:
await ensure_account(guild_id, interaction.user.id)
cursor = await bot.db.execute(
"SELECT work_at FROM accounts WHERE guild_id = ? AND user_id = ?",
(guild_id, interaction.user.id),
)
work_at = (await cursor.fetchone())[0]
remaining = WORK_COOLDOWN - (now - work_at)
if remaining > 0:
await interaction.response.send_message(
f"Take a breather—you can work again in **{cooldown_text(remaining)}**.", ephemeral=True
)
return
reward = random.randint(20, 80)
task = random.choice(WORK_TASKS)
await bot.db.execute(
"UPDATE accounts SET wallet = wallet + ?, work_at = ? WHERE guild_id = ? AND user_id = ?",
(reward, now, guild_id, interaction.user.id),
)
await bot.db.commit()
await interaction.response.send_message(f"You {task} and earned **{format_coins(reward)}**!")
@bot.tree.command(name="pay", description="Send coins from your wallet to another member")
@app_commands.guild_only()
@app_commands.describe(member="Who to pay", amount="The number of coins to send")
async def pay(
interaction: discord.Interaction,
member: discord.Member,
amount: app_commands.Range[int, 1, 1_000_000_000],
):
if member.id == interaction.user.id:
await interaction.response.send_message("You can't pay yourself.", ephemeral=True)
return
guild_id = interaction.guild_id
async with bot.db_lock:
await ensure_account(guild_id, interaction.user.id)
await ensure_account(guild_id, member.id)
cursor = await bot.db.execute(
"UPDATE accounts SET wallet = wallet - ? WHERE guild_id = ? AND user_id = ? AND wallet >= ?",
(amount, guild_id, interaction.user.id, amount),
)
if cursor.rowcount == 0:
await interaction.response.send_message(
"You don't have enough coins in your wallet.", ephemeral=True