Skip to content

Saaaru/warera_bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

47 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ€– WarEra Bot - Advanced Discord Intelligence

Python Discord.py License

WarEra Bot is a high-performance Discord tool designed for the WarEra ecosystem. It provides real-time strategic intelligence, deep market analysis, and user management tools by consuming the official tRPC API.


πŸ“Œ Table of Contents

  1. ✨ Features
  2. πŸš€ Quick Start
  3. πŸ—οΈ Core Architecture & Directory Structure
  4. πŸ› οΈ Command Reference Guide
  5. πŸ§‘β€πŸ’» Developer Guide
  6. 🚨 Troubleshooting & Logging

✨ Features

βš”οΈ Strategic Intelligence

  • Battle Analysis: Front-line monitoring, RW triggers, and automatic conflict notifications.
  • Region Management: Resource analysis, building levels, and resistance status (/rw, /searchr).
  • Military Units (MU): Detailed MU rankings, infrastructure status, and member activity.

πŸ’° Economy & Market

  • Live Market Data: Real-time item prices with historical trend analysis (/price).
  • Profit Calculator: Interactive production cycle optimization to maximize ROI (/profit).
  • Market Order Flow: Deep dive into buy/sell spreads and volume (/marketorders).
  • Internal Bot Market: A cross-server trading post for equipments and special items (/sellitem, /market).

πŸ‘₯ User Insights

  • Detailed Profiles: Combat stats, economic rankings, and skill accumulation (/userinfo).
  • Elite Search: Mass-filter players by country, level, and activity (/searchu).

πŸš€ Quick Start

  1. Clone & Setup:

    git clone https://github.com/Saaaru/warera_bot.git
    cd warera_bot
    python -m venv venv
    source venv/bin/activate  # Windows: venv\Scripts\activate
    pip install -r requirements.txt
  2. Configure Environment: Create a .env file in the root directory:

    DISCORD_BOT_TOKEN=your_token_here
    BOT_OWNER_ID=your_discord_id
    TEST_GUILD_ID=your_test_server_id (optional)
  3. Launch:

    python bot.py

πŸ—οΈ Core Architecture & Directory Structure

warera_bot/
β”œβ”€β”€ bot.py             # Main Entry Point (Cog Orchestrator)
β”œβ”€β”€ config.py          # Global Configuration & Static Data Parsing
β”œβ”€β”€ cogs/              # Modular Extensions (Commands & Tasks)
β”‚   β”œβ”€β”€ admin/         # Technical controls & system sync
β”‚   β”œβ”€β”€ background/    # Scheduled tasks & auto-alerts
β”‚   β”œβ”€β”€ info/          # Strategic Intel & Info commands
β”‚   β”œβ”€β”€ market/        # Economic tools & Market data
β”‚   └── user/          # Player analysis & Social commands
β”œβ”€β”€ utils/             # API Helpers, Formatters & Logic Modules
└── data/              # Static JSON Assets (Emojis, Game Data)
Directory Content Type Strategy
/cogs Behavioral Code High-level logic and API orchestration using Discord's Cog pattern.
/utils Technical Tools Reusable helpers (calculators, formatters, and API adapters).
/data Raw Intelligence Static assets, emoji mapping, and local cache databases.
/logs Health Metrics History of execution, errors, and system monitoring.

πŸ› οΈ Command Reference Guide

πŸ›‘οΈ Admin Commands (Owner Only)

  • /sync β€” Synchronizes command tree with Discord.
  • /globalmsg <message_content> [message_title] β€” Broadcasts a message to all guilds.
  • /testchannel <channel_id_to_test> β€” Validates channel availability.
  • /testperm β€” Tests owner security permission checks.

πŸ“Š Data Export Commands

  • /gettransactions <entity_type> <name> [transaction_type] [item] [limit] [format] β€” Exports transactions to Excel/CSV.

ℹ️ Info & Strategic Commands

  • /alerts enable <channel> β€” Enables battle alerts for the server.
  • /alerts disable β€” Disables battle alerts for the server.
  • /alerts status β€” Checks status of the battle alert channels.
  • /monitor set <link> <channel> [time] β€” Starts active monitoring on a specific battle.
  • /monitor unset <link> β€” Disables monitoring on a specific battle.
  • /battles [country_identifier] β€” Lists current active conflicts.
  • /info <country_identifier> β€” Detailed country status (allies, resources, regions).
  • /muinfo <name_or_id> β€” Detailed Military Unit information and ranking.
  • /party <name_or_id> β€” Detailed Political Party analysis.
  • /rw <country_identifier> β€” Displays resistance wars status and building levels.
  • /searchr <resource_name> β€” Searches for regions producing a specific resource.
  • /topbonusproduccion β€” Shows top 3 countries by production bonus.

πŸ“ˆ Market & Trading Commands

  • /company <username> β€” Detailed overview of a player's business infrastructure.
  • /marketorders <item1> [item2] β€” Analyses top orders and spreads.
  • /price [item] β€” Real-time price monitor & historical variations.
  • /itemprice β€” Equipment production calculator based on active market prices.
  • /profit β€” Interactive production profitability ROI calculator.
  • /sellitem <item> <stats> <price> β€” Lists an item on the bot's custom cross-server market.
  • /market [user_filter] β€” Displays active items in the bot's market.
  • /buyitem <id> β€” Express interest in buying an item (notifies the seller via DM).
  • /removelisting <id> β€” Deletes your listing from the market.

πŸ‘€ User Commands

  • /builds <country_id> [min_level] β€” Analyzes builds (Fighter/Hybrid/Eco) inside a country.
  • /searchu <country_id> [min_level] [activity_within_days] β€” Finds and groups active players in a country.
  • /setalert <resource_name> β€” Single notification alert for resource availability.
  • /userinfo <username> β€” Profile, stats, and power ranking dashboard.
  • /userinfoskill <username> β€” In-depth breakdown of user combat & economic skill points.

πŸ§‘β€πŸ’» Developer Guide

This section defines the architecture, data contracts, and implementation patterns required to build new features on the WarEra Bot platform.

1. Modular Design: The Cog Pattern

The bot uses discord.ext.commands.Cog. Modules are loaded recursively from the cogs/ directory.

Crucial Pattern: Every Cog must define a setup function:

async def setup(bot: commands.Bot):
    await bot.add_cog(MyCog(bot))

2. Configuration & Static Data (config.py)

config.py is the Single Source of Truth. Never load JSON files manually within a Cog.

  • EMOJIS: Dictionary of custom emojis for UI consistency.
  • ITEM_DATA: Metadata for game items (production points, recipes).
  • COUNTRIES / REGIONS: Pre-processed maps of game entities.
  • LOGGER: Global logger configured to write to logs/bot.log.
  • Static Assets: Emojis and game constants are cached in memory at startup in config.py.

3. Data Lifecycle & API Contract

tRPC API Integration

The bot communicates with https://api2.warera.io/trpc. URLs are built using a specific format: {BASE_URL}/{endpoint}?batch=1&input={urlencoded_json_payload}

Common Endpoints (config.TRPC_ENDPOINTS):

  • user.getUserLite: Fetch player profiles.
  • itemTrading.getPrices: Fetch global market snapshot.
  • country.getCountryById: Fetch country-level strategic data.

πŸ’Ύ Caching Strategy

  • Autocomplete Cache: bot._game_data_cache_for_autocomplete is updated every 15 mins via BackgroundTasks.
  • Price History: Stored in price_history/prices_YYYY-WW.json for trend analysis.
  • Internal Market: Persistent listings in data/internal_market.json with incremental ID tracking.

4. Design System (The "Premium" Feel)

The bot focuses on high-quality visual feedback using Discord Embeds and Custom Emojis.

  • Emoji Mapping: Use utils.formatters.get_custom_emoji_string(item_name) to retrieve the appropriate emoji from data/emojis.json.
    • Flags: config.FLAGS_MAP
    • Items: config.EMOJIS['items']
  • Visual Components: Progress bars in /userinfoskill representing health/hunger.
  • Currency Formatting: Prices are always formatted using utils.formatters.format_currency().

5. Feature Implementation Workflow

Step 1: Define the Command in a Cog

Create or modify a file in cogs/.

from discord import app_commands
from discord.ext import commands
import config

class NewFeature(commands.Cog):
    @app_commands.command(name="new_cmd", description="Does something cool")
    async def new_cmd(self, interaction: discord.Interaction):
        await interaction.response.defer()
        # Logic here...

Step 2: Use API Helpers

Interact with utils.api_helpers to fetch data. This ensures consistent error handling and timeout management.

Step 3: Format the Output

Use utils.formatters to generate a professional discord.Embed.

  • Title: Use emojis in the title.
  • Color: Use a theme color (e.g., discord.Color.blue()).
  • Footer: Always include a timestamp and a "Data from WarEra" note.

🚨 Troubleshooting & Logging

  • Logs: Check logs/bot.log. There is no console output for standard logs.
  • Sync: If a command doesn't appear, use /sync (admin command) or restart the bot to trigger setup_hook.
  • Timezone: Always use config.SERVER_TIMEZONE (Etc/GMT-2) for time calculations.

When building for this project, prioritize:

  1. Asynchronous performance (asyncio.gather for multiple API calls).
  2. Visual excellence (Rich Embeds, proper spacing, unique emojis).
  3. Robustness (Handle None results and TimeoutError).

Independent tool. Not officially affiliated with WarEra.

About

No description, website, or topics provided.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages