Files
.gitignore
bot.py
database.py
README.md
requirements.txt
Code
5 1,065
bot.py
import logging
import math
import os
import time
from datetime import datetime, timezone
import discord
from discord import app_commands
from discord.ext import commands, tasks
from dotenv import load_dotenv
from pymongo.errors import PyMongoError
from database import GameDatabase
load_dotenv()
logging.basicConfig(
level=os.getenv("LOG_LEVEL", "INFO").upper(),
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
log = logging.getLogger("idle_miner")
MINES = {
"coal": {"name": "Coal Mine", "cost": 0, "ores": {"coal": 1.0}},
"iron": {"name": "Iron Mine", "cost": 250, "ores": {"coal": 0.2, "iron": 0.8}},
"gold": {"name": "Gold Mine", "cost": 900, "ores": {"iron": 0.25, "gold": 0.75}},
"diamond": {"name": "Diamond Mine", "cost": 3000, "ores": {"gold": 0.3, "diamond": 0.7}},
"emerald": {"name": "Emerald Mine", "cost": 9000, "ores": {"diamond": 0.35, "emerald": 0.65}},
"ruby": {"name": "Ruby Mine", "cost": 25000, "ores": {"emerald": 0.4, "ruby": 0.6}},
"mythril": {"name": "Mythril Mine", "cost": 70000, "ores": {"ruby": 0.45, "mythril": 0.55}},
}
ORE_VALUES = {
"coal": 5,
"iron": 12,
"gold": 30,
"diamond": 75,
"emerald": 160,
"ruby": 350,
"mythril": 800,
}
ORE_EMOJI = {
"coal": "⚫",
"iron": "⛓️",
"gold": "🟡",
"diamond": "💎",
"emerald": "🟢",
"ruby": "🔴",
"mythril": "✨",
}
QUESTS = {
"first_ore": ("Mine 10 ores", "total_mined", 10, 100),
"deep_pockets": ("Mine 100 ores", "total_mined", 100, 500),
"merchant": ("Sell 25 ores", "total_sold", 25, 250),
"hiring_manager": ("Hire 3 miners", "miners", 3, 300),
}
ACHIEVEMENTS = [
("⛏️ First Swing", 1, "total_mined"),
("🪨 Getting Started", 50, "total_mined"),
("💰 First Sale", 1, "total_sold"),
("🏆 Master Miner", 1000, "total_mined"),
]
COLOR = discord.Color.from_rgb(42, 143, 117)
def make_embed(title: str, description: str = ""):
return discord.Embed(title=title, description=description, color=COLOR)
async def send_embed(interaction: discord.Interaction, title: str, description: str):
await interaction.response.send_message(embed=make_embed(title, description))
def is_configured_admin(interaction: discord.Interaction):
admin_ids = {
int(user_id.strip())
for user_id in os.getenv("ADMIN_USER_IDS", "").split(",")
if user_id.strip().isdecimal()
}
return interaction.user.id in admin_ids
class MiningCog(commands.Cog):
admin = app_commands.Group(name="admin", description="Mining game administration")
def __init__(self, bot):
self.bot = bot
self.db = bot.game
self.max_offline = int(os.getenv("MAX_OFFLINE_HOURS", "24")) * 3600
self.backpack_base = int(os.getenv("BACKPACK_BASE_CAPACITY", "100"))
async def cog_load(self):
self.automatic_mining.start()
def cog_unload(self):
self.automatic_mining.cancel()
def player(self, user_id: int):
return self.db.get_player(user_id)
async def require_player(self, interaction: discord.Interaction):
player = self.player(interaction.user.id)
if player is None:
await send_embed(interaction, "⚠️ Mining profile required", "Start your mining profile first with `/start`.")
return player
def capacity(self, player):
return self.backpack_base + (player["backpack_level"] - 1) * 50
def add_xp(self, user_id: int, amount: int):
player = self.player(user_id)
xp = player["xp"] + amount
level = max(1, int(math.sqrt(xp / 100)) + 1)
self.db.update_player(user_id, xp=xp, level=level)
def add_with_capacity(self, user_id: int, item: str, amount: int, capacity: int):
space = max(0, capacity - self.db.inventory_total(user_id))
added = min(max(amount, 0), space)
self.db.add_item(user_id, item, added)
return added
def prices(self):
day = datetime.now(timezone.utc).date().toordinal()
values = {}
for ore, base in ORE_VALUES.items():
seed = sum((index + 1) * ord(char) for index, char in enumerate(ore))
factor = 0.9 + ((day + seed) % 21) / 100
values[ore] = max(1, round(base * factor))
return values
async def collect_idle(self, user_id: int, now: int):
player = self.player(user_id)
if not player:
return 0, 0
capacity = self.capacity(player)
space = max(0, capacity - self.db.inventory_total(user_id))
max_seconds = max(0, self.max_offline)
earned = 0
elapsed_total = 0
for miner in self.db.miners(user_id):
actual_elapsed = max(0, now - miner["last_claim"])
elapsed = min(actual_elapsed, max_seconds)
elapsed_total = max(elapsed_total, elapsed)
units = int((elapsed / 60) * miner["quantity"] * miner["level"] * 0.5)
mine = MINES.get(miner["mine"], MINES["coal"])
weights = mine["ores"]
allocations = {
ore: int(units * weight) for ore, weight in weights.items()
}
remainder = units - sum(allocations.values())
for ore, _ in sorted(weights.items(), key=lambda entry: entry[1], reverse=True)[:remainder]:
allocations[ore] += 1
for ore, quantity in allocations.items():
added = self.add_with_capacity(user_id, ore, min(quantity, space), capacity)
space -= added
earned += added
rate = miner["quantity"] * miner["level"] * 0.5
remainder_seconds = (
int(elapsed - units * 60 / rate) if actual_elapsed <= max_seconds else 0
)
next_claim = now - remainder_seconds
self.db.set_miners(
user_id, miner["mine"], miner["quantity"], miner["level"], next_claim
)
if earned:
self.db.update_player(
user_id, total_mined=player["total_mined"] + earned
)
self.add_xp(user_id, earned)
return earned, elapsed_total
@tasks.loop(seconds=60)
async def automatic_mining(self):
now = int(time.time())
for user_id in self.db.active_miner_users():
try:
await self.collect_idle(user_id, now)
except Exception:
log.exception("Automatic mining failed for user %s", user_id)
@automatic_mining.before_loop
async def before_automatic_mining(self):
await self.bot.wait_until_ready()
def mine_name(self, key: str):
return MINES[key]["name"]
def valid_mine(self, key: str):
return key.lower().strip() in MINES
@app_commands.command(name="start", description="Create your mining profile")
async def start(self, interaction: discord.Interaction):
now = int(time.time())
player = self.db.create_player(interaction.user.id, now)
if not self.db.miners(interaction.user.id):
self.db.set_miners(interaction.user.id, "coal", 1, 1, now)
embed = make_embed(
"⛏️ Your mining operation is ready!",
"Your free Coal Mine miner is already working automatically. Sell mined ores with `/sell-all`.",
)
embed.add_field(name="Balance", value=f"🪙 {player['coins']:,} coins", inline=True)