API Reference
API Reference
Module Structure
Main Modules
main.py
Entry point and core bot functionality.
Key Functions:
load_config()- Load configuration from JSONsave_config()- Save configuration to JSONis_admin()- Check admin permissionshas_required_role()- Check role requirements
Global Variables:
bot- Discord bot instanceconfig- Configuration dictionaryprompts- Prompt templatesmax_tokens- Token limits
chatgpt.py
ChatGPT integration and conversation management.
Key Functions:
set_globals()- Initialize module globalsget_chatgpt_response()- Get AI responseinit_conversation_db()- Initialize databasesave_conversation()- Save chat historyload_conversation()- Load chat historydelete_thread_data()- Clean up threadformat_time_duration()- Format time displaysetup_cleanup_task()- Start cleanup task
Classes:
- Uses OpenAI client:
OpenAI(api_key=key)
fishing_game.py
Complete fishing game implementation.
Key Functions:
init_fishing_db()- Initialize databaserecord_catch()- Save catch recordget_fish_list()- Get available fishformat_time_display()- Format cooldowncheck_cooldown()- Check user cooldownfish_command()- Main fishing logicsetup_fishing()- Register commands
Global Variables:
FISH_CONFIG- Fish configurationmember_catch_ratio- Member catch chancecooldown_seconds- Fishing cooldownlast_fish_time- Cooldown tracking
games.py
Mini-games implementation and registration.
Key Functions:
setup_games(bot, is_feature_enabled)- Registers all game commandsflip_coin()- Core coin flip logicroll_dice(count, sides)- Core dice roll logicmagic_8_ball()- Random 8-ball response
Commands Registered:
!flip,!roll,!8ball,!rps,!rpsstats,!choose
Databases:
games_stats.db— Stores per-guild RPS stats (wins, losses, draws, last_played)
casino.py
Casino economy and games (Slots, Hi‑Lo, Roulette) with a chips ledger.
Key Functions / Commands:
setup_casino(bot, is_feature_enabled)— Registers casino commands!chips,!faucet,!givechips!slots,!slotshelp!hilo,!hilohelp!roulette,!roulettehelp,!roulettetable
Internals:
- Ledger helpers:
_get_balance,_adjust_balance,_set_last_faucet - First-play grant:
_grant_first_play_if_needed - Game helpers: slots spin/payout, Hi‑Lo view/buttons, roulette parsing/payout
Databases:
games_stats.db— Stores casino tables listed below
Database Schemas
conversations.db
conversations table:
CREATE TABLE conversations (
thread_id TEXT PRIMARY KEY,
messages TEXT NOT NULL,
last_updated DATETIME NOT NULL
);
thread_meta table:
CREATE TABLE thread_meta (
thread_id TEXT PRIMARY KEY,
creator_id TEXT NOT NULL,
created_at DATETIME NOT NULL
);
fishing_game.db
catches table:
CREATE TABLE catches (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT,
user_name TEXT,
catch_type TEXT, -- 'fish' or 'user'
catch_name TEXT,
weight REAL,
points INTEGER,
timestamp DATETIME
);
games_stats.db
rps_stats table:
CREATE TABLE rps_stats (
guild_id TEXT NOT NULL,
user_id TEXT NOT NULL,
wins INTEGER NOT NULL DEFAULT 0,
losses INTEGER NOT NULL DEFAULT 0,
draws INTEGER NOT NULL DEFAULT 0,
last_played DATETIME NOT NULL,
PRIMARY KEY (guild_id, user_id)
);
CREATE INDEX idx_rps_stats_guild ON rps_stats(guild_id);
casino_chips table:
CREATE TABLE casino_chips (
guild_id TEXT NOT NULL,
user_id TEXT NOT NULL,
balance INTEGER NOT NULL DEFAULT 0,
last_updated DATETIME NOT NULL,
last_faucet DATETIME,
PRIMARY KEY (guild_id, user_id)
);
casino_ledger table:
CREATE TABLE casino_ledger (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
user_id TEXT NOT NULL,
game TEXT NOT NULL,
delta INTEGER NOT NULL,
balance_after INTEGER NOT NULL,
ts DATETIME NOT NULL,
meta TEXT
);
slots_rounds table:
CREATE TABLE slots_rounds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
user_id TEXT NOT NULL,
bet INTEGER NOT NULL,
payout INTEGER NOT NULL,
symbols TEXT NOT NULL,
ts DATETIME NOT NULL
);
roulette_rounds table:
CREATE TABLE roulette_rounds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
user_id TEXT NOT NULL,
bet INTEGER NOT NULL,
payout INTEGER NOT NULL,
selection TEXT NOT NULL,
result_number INTEGER NOT NULL,
result_color TEXT NOT NULL,
ts DATETIME NOT NULL
);
Configuration Schemas
myconfig.json
{
required_role: string | null,
token_usage_display: boolean,
chat_thread_retention_days: number,
max_tokens: {
[command: string]: number
},
prompts: {
[command: string]: {
[variant: string]: string
}
}
}
my_fishing_game_config.json
{
member_catch_ratio: number,
cooldown_seconds: number,
fish: Array<{
name: string,
min_size_cm: number,
max_size_cm: number,
min_weight_kg: number,
max_weight_kg: number
}>
}
OpenAI Integration
Chat Completion
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
max_tokens=150,
temperature=0.8
)
Image Generation
response = client.images.generate(
prompt="A sunset over mountains",
n=1,
size="1024x1024"
)
Discord.py Events
Used Events
on_ready- Bot startupon_message- Message handlingon_command_error- Error handling
Custom Events
- Thread cleanup task (async loop)
- Conversation monitoring
Error Handling
Standard Pattern
try:
# Operation
except SpecificException as e:
print(f"Specific error: {e}")
# Handle gracefully
except Exception as e:
print(f"Unexpected error: {e}")
# Fallback behavior
Database Connections
with get_db_connection() as conn:
c = conn.cursor()
# Database operations
conn.commit()
Async Patterns
Command Structure
@bot.command(help="Description", aliases=["alt"])
async def command_name(ctx, *, parameter: str = None):
async with ctx.typing():
# Long operation
await ctx.send(response)
Thread Safety
- Use
asyncio.sleep()for delays - Avoid blocking operations
- Use
async withfor resources
Extension Points
Adding Commands
- Add to appropriate module
- Use
@bot.command()decorator - Include help text
- Handle errors gracefully
Adding Fish Species
- Add image to assets folder
- Update configuration
- No code changes needed
Custom Prompts
- Modify prompts in config
- Use placeholders:
{topic} - Test thoroughly
Performance Considerations
Database
- Use indexes on frequent queries
- Connection pooling via context managers
- Parameterized queries for safety
Discord API
- Respect rate limits
- Use embeds for rich content
- Chunk long messages
OpenAI API
- Cache responses where appropriate
- Monitor token usage
- Set reasonable limits
Generated from repository docs. Last build: 2025-09-12 11:03 UTC