Files
bot.py
requirements.txt
Code
2 212
bot.py
import logging
import os
import random
import sqlite3
import time
from datetime import datetime, timezone
import discord
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("tromar")
STARTING_CASH = 500
MAX_BET = 100_000
db = sqlite3.connect("tromar.db")
db.execute("""CREATE TABLE IF NOT EXISTS accounts (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
balance INTEGER NOT NULL DEFAULT 500,
last_work INTEGER NOT NULL DEFAULT 0,
last_daily INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (guild_id, user_id)
)""")
db.commit()
bot = commands.Bot(command_prefix="!", intents=discord.Intents.default(), help_command=None)
def account(guild_id: int, user_id: int) -> tuple[int, int, int]:
db.execute("INSERT OR IGNORE INTO accounts (guild_id, user_id, balance) VALUES (?, ?, ?)",
(guild_id, user_id, STARTING_CASH))
db.commit()
return db.execute("SELECT balance, last_work, last_daily FROM accounts WHERE guild_id = ? AND user_id = ?",
(guild_id, user_id)).fetchone()
def change_balance(guild_id: int, user_id: int, amount: int) -> int:
db.execute("UPDATE accounts SET balance = balance + ? WHERE guild_id = ? AND user_id = ?",
(amount, guild_id, user_id))
db.commit()
return db.execute("SELECT balance FROM accounts WHERE guild_id = ? AND user_id = ?",
(guild_id, user_id)).fetchone()[0]
def card(title: str, description: str) -> discord.Embed:
return discord.Embed(title=title, description=description, color=discord.Color.purple())
async def validate_bet(interaction: discord.Interaction, amount: int) -> bool:
balance, _, _ = account(interaction.guild_id, interaction.user.id)
if amount > balance:
await interaction.response.send_message(f"You only have **{balance:,}** Tromar coins.", ephemeral=True)
return False
return True
@bot.event
async def on_ready():
print("KODARI_READY", flush=True)
logger.info("Tromar is online as %s", bot.user)
try:
await bot.tree.sync()
except discord.DiscordException:
logger.exception("Could not sync slash commands")
@bot.tree.command(name="help", description="See Tromar's commands")
async def help_command(interaction: discord.Interaction):
embed = card("๐ฒ Tromar", "Play with virtual coins only โ no real money or prizes.")
embed.add_field(name="๐ฐ Earn & explore", value="`/balance` ยท `/work` ยท `/daily` ยท `/leaderboard`", inline=False)
embed.add_field(name="๐ฐ Gamble", value="`/coinflip` ยท `/slots` ยท `/dice`", inline=False)
embed.add_field(name="โจ Fun", value="`/8ball` ยท `/joke` ยท `/roll`", inline=False)
embed.set_footer(text="Each server has its own economy. New players start with 500 coins.")
await interaction.response.send_message(embed=embed)
@bot.tree.command(name="balance", description="Check your Tromar coins")
@app_commands.guild_only()
async def balance(interaction: discord.Interaction, member: discord.Member = None):
member = member or interaction.user
coins, _, _ = account(interaction.guild_id, member.id)
await interaction.response.send_message(embed=card("๐ฐ Balance", f"**{discord.utils.escape_markdown(member.display_name)}** has **{coins:,}** coins."))
@bot.tree.command(name="work", description="Work for some coins once an hour")
@app_commands.guild_only()
async def work(interaction: discord.Interaction):
_, last_work, _ = account(interaction.guild_id, interaction.user.id)
now = int(time.time())
if now < last_work + 3600:
await interaction.response.send_message(f"You're tired! Work again <t:{last_work + 3600}:R>.", ephemeral=True)
return
earnings = random.randint(100, 350)
db.execute("UPDATE accounts SET balance = balance + ?, last_work = ? WHERE guild_id = ? AND user_id = ?",
(earnings, now, interaction.guild_id, interaction.user.id))
db.commit()
job = random.choice(["delivered pizzas", "walked a dragon", "debugged a toaster", "washed a spaceship"])
await interaction.response.send_message(embed=card("๐ ๏ธ Work", f"You {job} and earned **{earnings:,}** coins!"))
@bot.tree.command(name="daily", description="Claim your daily coins")
@app_commands.guild_only()
async def daily(interaction: discord.Interaction):
_, _, last_daily = account(interaction.guild_id, interaction.user.id)
now = int(time.time())
if now < last_daily + 86400:
await interaction.response.send_message(f"Your next daily is ready <t:{last_daily + 86400}:R>.", ephemeral=True)
return
db.execute("UPDATE accounts SET balance = balance + 500, last_daily = ? WHERE guild_id = ? AND user_id = ?",
(now, interaction.guild_id, interaction.user.id))
db.commit()
await interaction.response.send_message(embed=card("๐ Daily reward", "You claimed **500** coins! Come back in 24 hours."))
@bot.tree.command(name="leaderboard", description="See the richest players in this server")
@app_commands.guild_only()
async def leaderboard(interaction: discord.Interaction):
rows = db.execute("SELECT user_id, balance FROM accounts WHERE guild_id = ? ORDER BY balance DESC, user_id LIMIT 10",
(interaction.guild_id,)).fetchall()
lines = [f"**{i}.** <@{user_id}> โ **{coins:,}** coins" for i, (user_id, coins) in enumerate(rows, 1)]
await interaction.response.send_message(embed=card("๐ Richest players", "\n".join(lines) or "No players yet!"),
allowed_mentions=discord.AllowedMentions.none())
@bot.tree.command(name="coinflip", description="Bet on heads or tails; win double your bet")
@app_commands.guild_only()
@app_commands.choices(choice=[app_commands.Choice(name="Heads", value="heads"), app_commands.Choice(name="Tails", value="tails")])
async def coinflip(interaction: discord.Interaction, amount: app_commands.Range[int, 1, MAX_BET], choice: app_commands.Choice[str]):
if not await validate_bet(interaction, amount):
return
result = random.choice(["heads", "tails"])
won = result == choice.value
new_balance = change_balance(interaction.guild_id, interaction.user.id, amount if won else -amount)
await interaction.response.send_message(embed=card("๐ช Coin flip", f"It landed **{result}**! You {'won' if won else 'lost'} **{amount:,}** coins.\nBalance: **{new_balance:,}**"))
@bot.tree.command(name="slots", description="Spin the slots; three matching symbols win 5x your bet")
@app_commands.guild_only()
async def slots(interaction: discord.Interaction, amount: app_commands.Range[int, 1, MAX_BET]):
if not await validate_bet(interaction, amount):
return
reels = [random.choice(["๐", "๐", "๐", "๐"]) for _ in range(3)]
won = len(set(reels)) == 1
# A 5x payout includes the original stake, so the net profit is 4x.
delta = amount * 4 if won else -amount
new_balance = change_balance(interaction.guild_id, interaction.user.id, delta)
await interaction.response.send_message(embed=card("๐ฐ Slots", f"{' | '.join(reels)}\n{'Jackpot! You won' if won else 'You lost'} **{abs(delta):,}** coins.\nBalance: **{new_balance:,}**"))
@bot.tree.command(name="dice", description="Guess a die roll; win 5x your bet if correct")
@app_commands.guild_only()
async def dice(interaction: discord.Interaction, amount: app_commands.Range[int, 1, MAX_BET], guess: app_commands.Range[int, 1, 6]):
if not await validate_bet(interaction, amount):
return
result = random.randint(1, 6)
won = guess == result
delta = amount * 4 if won else -amount
new_balance = change_balance(interaction.guild_id, interaction.user.id, delta)
await interaction.response.send_message(embed=card("๐ฒ Dice", f"The die rolled **{result}**! You {'won' if won else 'lost'} **{abs(delta):,}** coins.\nBalance: **{new_balance:,}**"))
@bot.tree.command(name="8ball", description="Ask Tromar's magic 8-ball a question")
@app_commands.describe(question="What would you like to know?")
async def eight_ball(interaction: discord.Interaction, question: app_commands.Range[str, 1, 300]):
answer = random.choice(["Definitely!", "The signs point to yes.", "Ask again later.", "I wouldn't count on it.", "Absolutely not.", "Only if you bring snacks."])
await interaction.response.send_message(embed=card("๐ฑ Magic 8-ball", f"**Question:** {discord.utils.escape_markdown(question)}\n**Answer:** {answer}"), allowed_mentions=discord.AllowedMentions.none())
@bot.tree.command(name="joke", description="Hear a questionable joke")
async def joke(interaction: discord.Interaction):
await interaction.response.send_message(embed=card("๐ Joke", random.choice([
"Why did the scarecrow win an award? He was outstanding in his field.",
"What do you call a sleeping dinosaur? A dino-snore.",
"Why don't skeletons fight each other? They don't have the guts.",
"I told my computer I needed a break. It gave me a KitKat.",
])))
@bot.tree.command(name="roll", description="Roll a die for fun")
async def roll(interaction: discord.Interaction, sides: app_commands.Range[int, 2, 100] = 6):
await interaction.response.send_message(embed=card("๐ฒ Roll", f"You rolled **{random.randint(1, sides)}** on a {sides}-sided die."))
@bot.tree.error
async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.NoPrivateMessage):
message = "This command can only be used in a server."
elif isinstance(error, app_commands.CommandOnCooldown):
message = f"Slow down! Try again in {error.retry_after:.1f} seconds."
else:
logger.error("Slash command failed", exc_info=(type(error), error, error.__traceback__))
message = "Something went wrong. Please try again later."
try:
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else: