Files
.gitignore
api_client.py
bot.py
config.json
README.md
requirements.txt
Code
6 451
bot.py
import discord
from discord.ext import commands
from discord import app_commands
import os
import logging
from dotenv import load_dotenv
import json
from api_client import BigGamesAPIClient
# Load environment variables
load_dotenv()
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('IronClanBot')
# Load configuration
with open('config.json', 'r') as f:
config = json.load(f)
# Bot setup
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
# Initialize API client
api_client = BigGamesAPIClient(config['api_base_url'])
@bot.event
async def on_ready():
logger.info(f'Bot is ready! Logged in as {bot.user}')
try:
synced = await bot.tree.sync()
logger.info(f'Synced {len(synced)} command(s)')
except Exception as e:
logger.error(f'Failed to sync commands: {e}')
@bot.tree.command(name="place", description="Display the current location of the Iron clan")
async def place(interaction: discord.Interaction):
"""Display the current location of the Iron clan"""
await interaction.response.defer()
try:
clan_data = await api_client.get_clan_data(config['clan_name'])
if not clan_data:
await interaction.followup.send("❌ Unable to fetch clan data. Please try again later.")
logger.warning(f"No data returned for clan: {config['clan_name']}")
return
location = clan_data.get('location', 'Unknown')
server = clan_data.get('server', 'Unknown')
members_online = clan_data.get('members_online', 0)
embed = discord.Embed(
title=f"📍 {config['clan_name']} Clan Location",
color=discord.Color.blue(),
description=f"Current location and server information"
)
embed.add_field(name="Location", value=location, inline=False)
embed.add_field(name="Server", value=server, inline=True)
embed.add_field(name="Members Online", value=str(members_online), inline=True)
embed.set_footer(text="Data from biggames.io")
await interaction.followup.send(embed=embed)
logger.info(f"Place command executed for {interaction.user}")
except Exception as e:
logger.error(f"Error in place command: {e}")
await interaction.followup.send("❌ An error occurred while fetching clan location. Please try again later.")
@bot.tree.command(name="pets", description="Display pets organized by categories")
@app_commands.describe(
sort_by="Choose how to organize the pets (alphabetical, size, or all)"
)
@app_commands.choices(sort_by=[
app_commands.Choice(name="Alphabetical", value="alphabetical"),
app_commands.Choice(name="By Size", value="size"),
app_commands.Choice(name="All Categories", value="all")
])
async def pets(interaction: discord.Interaction, sort_by: app_commands.Choice[str]):
"""Display pets organized by different categories"""
await interaction.response.defer()
try:
clan_pets = await api_client.get_clan_pets(config['clan_name'])
if not clan_pets:
await interaction.followup.send("❌ Unable to fetch pets data. Please try again later.")
logger.warning(f"No pets data returned for clan: {config['clan_name']}")
return
if sort_by.value == "alphabetical":
await send_alphabetical_pets(interaction, clan_pets)
elif sort_by.value == "size":
await send_size_categorized_pets(interaction, clan_pets)
else:
await send_all_categories(interaction, clan_pets)
logger.info(f"Pets command executed for {interaction.user} with sort_by={sort_by.value}")
except Exception as e:
logger.error(f"Error in pets command: {e}")
await interaction.followup.send("❌ An error occurred while fetching pets data. Please try again later.")
async def send_alphabetical_pets(interaction: discord.Interaction, pets: list):
"""Send pets sorted alphabetically"""
sorted_pets = sorted(pets, key=lambda x: x['name'].lower())
embed = discord.Embed(
title=f"🐾 {config['clan_name']} Clan Pets (Alphabetical)",
color=discord.Color.green(),
description=f"Total pets: {len(sorted_pets)}"
)
pet_list = []
for pet in sorted_pets[:25]:
size_emoji = get_size_emoji(pet.get('size', 'normal'))
pet_list.append(f"{size_emoji} {pet['name']} - {pet.get('size', 'Normal').capitalize()}")
if pet_list:
embed.add_field(name="Pet List", value="\n".join(pet_list), inline=False)
if len(sorted_pets) > 25:
embed.set_footer(text=f"Showing 25 of {len(sorted_pets)} pets | Data from biggames.io")
else:
embed.set_footer(text="Data from biggames.io")
await interaction.followup.send(embed=embed)
async def send_size_categorized_pets(interaction: discord.Interaction, pets: list):
"""Send pets categorized by size"""
huge_pets = [pet for pet in pets if pet.get('size', '').lower() == 'huge']
titanic_pets = [pet for pet in pets if pet.get('size', '').lower() == 'titanic']
gargantuan_pets = [pet for pet in pets if pet.get('size', '').lower() == 'gargantuan']
normal_pets = [pet for pet in pets if pet.get('size', '').lower() not in ['huge', 'titanic', 'gargantuan']]
embed = discord.Embed(
title=f"🐾 {config['clan_name']} Clan Pets (By Size)",
color=discord.Color.purple(),
description=f"Total pets: {len(pets)}"
)
if gargantuan_pets:
gargantuan_list = [f"⭐ {pet['name']}" for pet in sorted(gargantuan_pets, key=lambda x: x['name'].lower())[:10]]
embed.add_field(name=f"🌟 Gargantuan ({len(gargantuan_pets)})", value="\n".join(gargantuan_list), inline=False)
if titanic_pets:
titanic_list = [f"💎 {pet['name']}" for pet in sorted(titanic_pets, key=lambda x: x['name'].lower())[:10]]
embed.add_field(name=f"💎 Titanic ({len(titanic_pets)})", value="\n".join(titanic_list), inline=False)
if huge_pets:
huge_list = [f"✨ {pet['name']}" for pet in sorted(huge_pets, key=lambda x: x['name'].lower())[:10]]
embed.add_field(name=f"✨ Huge ({len(huge_pets)})", value="\n".join(huge_list), inline=False)
if normal_pets:
embed.add_field(name=f"📦 Normal ({len(normal_pets)})", value=f"{len(normal_pets)} normal pets", inline=False)
embed.set_footer(text="Showing top 10 per category | Data from biggames.io")
await interaction.followup.send(embed=embed)
async def send_all_categories(interaction: discord.Interaction, pets: list):
"""Send pets in all categories"""
sorted_alphabetically = sorted(pets, key=lambda x: x['name'].lower())
huge_pets = [pet for pet in pets if pet.get('size', '').lower() == 'huge']
titanic_pets = [pet for pet in pets if pet.get('size', '').lower() == 'titanic']
gargantuan_pets = [pet for pet in pets if pet.get('size', '').lower() == 'gargantuan']
embed = discord.Embed(
title=f"🐾 {config['clan_name']} Clan Pets (All Categories)",
color=discord.Color.gold(),
description=f"Total pets: {len(pets)}"
)
alpha_list = [f"{get_size_emoji(pet.get('size', 'normal'))} {pet['name']}" for pet in sorted_alphabetically[:15]]
if alpha_list:
embed.add_field(name="📝 Alphabetical (Top 15)", value="\n".join(alpha_list), inline=False)
embed.add_field(name="📊 Size Statistics",
value=f"🌟 Gargantuan: {len(gargantuan_pets)}\n💎 Titanic: {len(titanic_pets)}\n✨ Huge: {len(huge_pets)}",
inline=False)
embed.set_footer(text="Data from biggames.io")
await interaction.followup.send(embed=embed)
def get_size_emoji(size: str) -> str:
"""Get emoji based on pet size"""