원클릭으로
dinogochi-project-guidelines
Guidelines for architecture, models, configurations, and game mechanics of Telegram DinoGochi bot
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
Guidelines for architecture, models, configurations, and game mechanics of Telegram DinoGochi bot
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
Safety rules for DinoGochi project: prohibits any modifications to the production database, prohibits git push operations, and enforces a mandatory token/secret scan before completing any work session.
Sync and translate localizations when modifying Russian keys. Automatically runs trs_openrouter.py.
Skill for precise inspection and synchronization of JSON files (localizations, configs) without loading entire files.
SOC 직업 분류 기준
| name | dinogochi_project_guidelines |
| description | Guidelines for architecture, models, configurations, and game mechanics of Telegram DinoGochi bot |
This document describes the architecture, structure, database models, and core game mechanics of the DinoGochi Telegram bot (a virtual Tamagotchi-dinosaur game with RPG elements).
dinogochi database.matplotlib for generating charts of game statistics.The general structure of the project directory is organized as follows:
DinoGochi/
├── .agents/
│ └── skills/
│ └── dinogochi_project_guidelines/
│ └── SKILL.md # This guidelines file
├── bot/
│ ├── config.py # Settings loader and validator
│ ├── const.py # Constants & static data loader
│ ├── dbmanager.py # Database connection, Beanie ODM init & APM logger
│ ├── exec.py # Bot execution setup and polling initiation
│ ├── taskmanager.py # Async loop scheduler
│ ├── models/ # Beanie ODM/Pydantic schemas
│ │ ├── user.py
│ │ ├── dinosaur.py
│ │ ├── items.py
│ │ ├── market.py
│ │ ├── activity.py
│ │ ├── tavern.py
│ │ ├── tracking.py
│ │ ├── group.py
│ │ └── other.py
│ ├── dataclasess/ # Type definitions and data schemas
│ │ ├── items/
│ │ │ └── base.py
│ │ └── minigame.py
│ ├── handlers/ # aiogram handler modules
│ │ └── states.py
│ ├── json/ # Static game databases
│ │ ├── settings.json
│ │ └── journey.json
│ ├── localization/ # Localization files (JSON)
│ │ └── en.json
│ ├── modules/ # Core game logic and subsystems
│ │ ├── dinosaur/
│ │ │ ├── dinosaur.py
│ │ │ └── mood.py
│ │ ├── states_fabric/
│ │ │ └── state_handlers.py
│ │ ├── user/
│ │ │ └── user.py
│ │ ├── functransport.py
│ │ ├── images.py
│ │ ├── localization.py
│ │ └── notifications.py
│ └── tasks/ # Background schedulers/workers
│ └── incubation.py
├── main.py # Bot startup entrypoint
└── requirements.txt # Project dependencies
main.py — The application entry point. Initializes and runs the bot.bot/exec.py — Declares Bot and Dispatcher instances (using MongoStorage for FSM state storage) and manages the polling startup lifecycle.bot/config.py — Config deserialization and settings manager using config.json.bot/dbmanager.py — Verifies MongoDB connectivity, creates missing databases, collections, and indexes, and populates required documents.bot/const.py — Global helper that loads static JSON game configurations (mobs, items, dinosaur structures).bot/taskmanager.py — Handles task loop registration and execution on the asyncio event loop.bot/tasks/ — Submodules representing periodic checks (e.g. state/mood checks, sleep decay, journey ticks, auction checks).bot/handlers/ — Telegram user action, command, message, and inline callback handlers.bot/modules/ — The core logic layer containing business logic models (dinosaur actions, user tracking, inventory handling, localization utilities).bot/dataclasess/ — Helper dataclasses (e.g., base item descriptions, craft structures).bot/json/ — Static JSON configurations defining database collections, items, achievements, quests, etc.bot/localization/ — Localization dictionaries for translating interface text (ru.json, en.json, es.json, id.json).All database models are implemented using Beanie ODM (inheriting from beanie.Document) and are stored in a single unified database named dinogochi on the MongoDB server.
bot/models/)bot/models/user.py
UserModel (collection users): Tracks user ID, balances (coins, super_coins), experience (xp, lvl), settings, and notification preferences.LangModel (collection lang): Stores user interface language settings.ReferralModel (collection referals), FriendModel (collection friends), SubscriptionModel (collection subscriptions), AdModel (collection ads), DinoCollectionModel (collection dino_collection), AchievementModel (collection achievements).bot/models/dinosaur.py
DinoModel (collection dinosaurs): Core stats (health, hunger, play, mood, energy), RPG characteristics, quality/rarity, activ_items, memories.EggModel (collection incubation): Incubation timers, quality, chosen pool, choosing status.DeadDinoModel (collection dead_dinos), DinoOwnersModel (collection dino_owners), DinoMoodModel (collection dino_mood), StateModel (collection state).bot/models/items.py
ItemModel (collection items): User inventory items (owner_id, items_data, count).ItemCraftModel (collection item_craft): Ongoing desktop item crafting progress.FarmModel (collection farm).bot/models/market.py
ProductModel (collection products): Trade deals (fixed items-for-coins, barters, auctions).SellerModel (collection sellers): Player-owned shops (earned coins, total sales, description).PreferentialModel (collection preferential), PuhsModel (collection puhs).activity.py (kd_activity, long_activity, kindergarten).tavern.py (quests, tavern, daily_award, inside_shop).tracking.py (links, tracking_members).group.py (groups, messages, group_users).other.py (management, statistic, events, promo, dead_users, companies, message_log, states, boosters, onetime_rewards, lottery, lottery_members, online).The custom ActiveRecord-like Python wrapper classes (User in bot/modules/user/user.py, Dino and Egg in bot/modules/dinosaur/dinosaur.py) interact with the database. A compatibility proxy layer in bot/dbmanager.py wraps the mongo_client to transparently route all legacy database calls (mongo_client.user.users) to the unified dinogochi database and rename clashing collections (group.users -> group_users, etc.).
bot/tasks/incubation.py polls incubation times, creates the dinosaur object via insert_dino(), and alerts the player.add_mood().bot/tasks/journey_check.py evaluates random wilderness events based on the configuration bot/json/journey_config.json.6% chance to drop special items: Resurrection Stones (stone_resurrection), Transport Eggs (transport_egg), random upgrades/runes, or broken weapons and shields.endurance = 0 and a random level (0, 1, or 2). They dynamically receive gender-correct prefixes "Сломанный/Сломанная/Сломанное " in the Russian locale.friend field of the JourneyActivity model.combat_role: "dino") join the player's team (team_x) for the next battle, while hostile/angry companions (combat_role: "mob") join the enemies (team_y).max_hp, role, weapons, and shields, and behave like mobs during combat simulation (dying at 0 HP). The companion is reset to None after the combat resolves."trigger_immediate_battle" directive. When resolved, the next pending event in the pregenerated journey path is dynamically converted into a battle event and scheduled to trigger on the next check.D and the location's total_danger (scaled via loc_scale = max(0.0, total_danger - 1.0)).power, dexterity, charisma) scale from 1 (in Forest) up to 11 (in Magic Forest). Evasion is scaled down in early zones (e.g., 5-7% in early/medium locations vs. 25% in hard locations).0.0) for mobs in early/medium locations (total_danger <= 1.1), ensuring early-game dinosaurs can deal 100% full weapon damage.1 opponent for early/medium locations (total_danger <= 1.1) to avoid overwhelming players, and scales up to randint(1, 2) (or more) in harder zones.abilities keys in the database are initialized with their default endurance and lvl=0 during CombatParticipant setup to ensure they are active and functional during combat simulation.bot/modules/states_fabric/state_handlers.py and routed in bot/handlers/states.py.GeneralStates (StatesGroup subclass) to define generic states: ChooseDino, ChooseInt, ChooseString, ChooseConfirm, ChooseOption, ChoosePagesState, and ChooseCustom.BaseStateHandler (e.g. ChooseDinoHandler, ChooseConfirmHandler). When setting up a state, they convert transition callbacks to string functions via functransport.py (func_to_str and str_to_func). This serializes callbacks into the state data in MongoDB, allowing transitions to survive server reboots, file reloads, and long-term user inactivity.bot/handlers/states.py catch state-filtered messages, retrieve the active FSM parameters, perform value/format validation, clear the FSM state, and invoke the dynamically mapped callback.bot/modules/markup.py.users collection, last_markup field).markups_menu(userid, markup_key, language_code, last_markup) function creates ReplyKeyboardMarkup blocks dynamically.markup_key is set to 'last_menu', the constructor resolves the previous menu screen by walking back the navigation pathways defined in back_menu(). Main buttons are translated on the fly using localization keys under the commands_name. prefix.bot/modules/notifications.py.dino_notification): Alerts owners when stats run low (e.g. low food/health/energy warnings) or when mood states trigger (inspiration/breakdown).
notifications dictionary as timestamps. These are checked before sending a new alert, and are deleted ($unset) once stats recovery conditions are met.user_notification): Sends transactional alerts (donations, referral codes, egg hatching readiness, crafting success, level-ups). Level-up notifications generate custom Pillow-rendered certificates.replics_notifications list. The system randomly selects one of several contextual translation lines ("replics") from localization configurations, adding personality to the dinosaur's alerts.bot/handlers/blacksmith.py and registered in bot/handlers/transition.py. Presents a main welcome menu using a standard ReplyKeyboardMarkup containing:
blacksmith_prices and default chances under blacksmith_chances in bot/json/settings.json. Max durability endurance_max scales geometrically by 1.5x per level: int(base_endurance * (1.5 ** lvl)).repair_tool in bot/modules/items/craft_recipe.py) clamp durability to the level-adjusted maximum durability get_item_endurance_max of the item being repaired instead of the base level 0 maximum.'rune' item type. Players can apply runes during blacksmith upgrades to modify outcomes:
abilities under 'lvl') using level-aware helper functions in bot/modules/items/item.py. Getters on the Item model include get_level(), get_damage(), get_endurance_max(), get_reflection(), get_capacity(), get_effectiv(), and get_ability().Safe Database Queries (DBconstructor):
DBconstructor wrapping the motor collection.comment parameter on query method calls (such as update_one or find_one). This comment is printed in logs to track query performance:
await dinosaurs.update_one({"_id": dino_id}, {"$set": {"stats.eat": 100}}, comment="dino_feed_max")
Localization & Multi-Language Support:
t(key, locale, **kwargs) function imported from bot/modules/localization.py:
text = t("incubation.ready_message", lang, user_name=name)
Registering Asynchronous Loop Tasks:
asyncio.create_task().add_task in bot/taskmanager.py:
from bot.taskmanager import add_task
add_task(my_periodic_check, repeat_time=60.0, delay=5.0)
Dockerization & Static Assets:
fonts/ and images/ are not copied during the Docker build stage to keep the image lightweight. They are mounted as read-only volumes (ro) via docker-compose.yml..venv/), local database storage (mongodb/), backups, and logs are excluded using .dockerignore.Configuration & Environment Variables:
config.json or docker-compose.yml..env file is used to define MONGO_USERNAME and MONGO_PASSWORD.config.json, use placeholders like mongodb://${MONGO_USERNAME}:${MONGO_PASSWORD}@mongo:27017.bot/config.py automatically parses .env at startup and interpolates placeholders of the form ${VAR} with corresponding environment variables.webhook_mode to true in config.json. Under this mode, the bot starts an aiohttp web server bound to webhook_host and webhook_port (defaulting to 0.0.0.0:8080), and registers the webhook URL built from webhook_domain and webhook_path (defaulting to /webhook). If webhook_mode is false, the bot defaults to polling mode.Data Access Layer & Beanie ODM:
LazyCollection proxies in non-task code. Load documents using model classmethods (e.g., User.find_one, Dino.find_one).add_coins, remove_coins, add_super_coins, remove_super_coins, set_name, set_avatar, set_last_markup, set_profile_background, inc_quests_ended on the User or Dino models) which handle the field modifications and call self.save() internally. Direct updates or field modifications followed by doc.save() outside the model classes are prohibited.Database Migration, Backup & Recovery Utilities:
tools/migration_merge_dbs.py handles merging all collections from separate databases (including dungeon database lobby data and deleted_dungeon_lobby) into the primary dinogochi database.tools/backup_db.py and tools/restore_db.py. They natively run mongodump and mongorestore under gzipped compression and drop existing collections for consistency.Guidelines for Writing Tests:
Subscription.award_premium(userid, end_time), User.add_coins(col), etc.) instead of executing raw database inserts or updates. This ensures model validations and lifecycles are correctly simulated.[!IMPORTANT] When modifying the codebase, adding new features, database collections, or changing existing gameplay systems, the AI agent is REQUIRED to automatically update this
SKILL.mdfile. This maintains documentation accuracy for future development tasks.
When adding a new type/class of item to the bot, you must update the following files and locations:
Item Type Definition:
TYPES literal in [bot/dataclasess/items/base.py](file:///c:/Папки/коды/Telegram DinoGochi/DinoGochi/bot/dataclasess/items/base.py).Item Data Class:
bot/dataclasess/items/nullitems.py](file:///c:/Папки/коды/Telegram DinoGochi/DinoGochi/bot/dataclasess/items/nullitems.py) (or a separate file under bot/dataclasess/items/), inheriting from BaseItem. Declare any specific properties (e.g. time_boost for IncubationBoost).Type Registry Mapping:
ITEM_CLASSES inside [bot/modules/items/collect_items.py](file:///c:/Папки/коды/Telegram DinoGochi/DinoGochi/bot/modules/items/collect_items.py).Item Info Formatting:
item_info function in [bot/modules/items/item.py](file:///c:/Папки/коды/Telegram DinoGochi/DinoGochi/bot/modules/items/item.py).Localization Files:
item_info.type_info.<new_type_name> in all localization JSON files (ru.json, en.json, es.json, id.json). This includes specifying type_name (display name of the item class) and add_text (template for displaying properties like durability, capacity, etc.)./premium products are configured in bot/json/premium_shop.json.
support_command.products_bio in every localization file.support_command.pages./premium page structure is defined by SUPPORT_PAGES in bot/handlers/profile_menu/support.py.SUPPORT_ITEMS_PER_PAGE; main category buttons are shown two per row.support_command.choose, a two-button choice between the super shop and donations; /premium opens the donation shop directly.CRYPTO_PAY_TOKEN and CRYPTO_PAY_NETWORK (testnet/mainnet).bot/tasks/cryptobot_check.py.donate_discount event can be active, which dynamically applies a discount (e.g. 10% - 50%) to both Telegram Stars and CryptoBot invoice amounts./super shop products are configured in bot/json/settings.json under super_shop.
items list and a price in super coins.products or super_shop must exist in one of the files under bot/json/items/.Weapons and armor items support combat properties with level scaling and priority sorting:
bot/modules/items/combat_properties.py using CombatPropertyModel. Supported types include multi_strike, ignore_armor, aoe, apply_effect_enemy, apply_effect_self (weapons) and ignore_effects, self_repair, counter_attack (armor).dexterity, power).lvl_scale dynamic math (base_value + level * multiplier) or explicit level overrides in lvls[lvl]['properties'] inside the items config.format_all_properties, opened by the 🔮 Свойства button.🔮 Эффекты уровней button displays properties scaled for all levels.⚙ Приоритет навыков button is displayed on the properties page and allows players to change activation priorities. Priorities are stored in the item's database document under abilities.skills_priority./give_quest command generates and assigns a custom quest based on <quest_type> (e.g. feed, collecting, fishing, etc.) and optional [complexity] (1-5) and [userid].ChooseMultiInventoryHandler) supports storing and pre-populating previously selected items via the selected dictionary in the MultiInventoryStepData step. This allows users during the journey setup to click the Back button from location selection and return to the bag assembly screen with their chosen items pre-selected instead of reset.items_names dictionary in ru.json, en.json, es.json, id.json are restructured into separate keys: "name" (only the text name of the item) and "emoji" (only the emoji).{item_name:item_id} — Resolves to item emoji + space + name.{item_emoji:item_id} — Resolves to only the item's emoji.bot/json/custom_emojis.json. Maps custom emoji keys (e.g. play) to custom Telegram emoji ID and alternative fallbacks.{custom_emoji:name:index} or {custom_emoji:name} — Dynamically resolves to  if the owner (first admin in conf.bot_devs) has Telegram Premium, or the fallback alternative emoji if not. Falls back to index 0 if not specified.bot.get_chat(owner_id) and caches the result in memory for 1 day, resolving updates asynchronously in the background.get_name(item_id, lang, abilities, with_emoji=True) in bot/modules/items/item.py accepts a with_emoji flag to allow getting either name + emoji (default) or name only.get_emoji(item_id, lang) returns only the item's emoji.list_to_keyboard and list_to_inline inside bot/modules/data_format.py support buttons as dictionaries with keys like text, style (e.g. 'danger', 'success', 'primary'), and custom_emoji_id (or icon_custom_emoji_id).resolve_button_data. If the owner has Telegram Premium, it sets icon_custom_emoji_id. If not, it falls back to prepending the standard emoji alternative (from bot/json/custom_emojis.json) to the button text.🎒 callback subpage (user_profile inventory <userid> <page>)."profiles_items_per_page" in settings.json) sorted from rarest (mythical) to most common (common).*💛 Легендарный*:), displaying each item's formatted name with emoji (via get_name) and count.user_profile.achievements_count).user_profile.rating_places) displays the user's current Solo and Group Arena ranking places (fetched from rating:arena_solo and rating:arena_group).top_invite_count, top_market_count, top_market_coins, etc.) dynamically calculate leader candidates and demand max_value > 0 before awarding leader achievements. top_invite_count aggregates referral codes using Referral collection type == "sub" and maps to inviter general documents.virtual_pages directly into FSM state data so swipe_page dynamically updates reply keyboards when filtering or searching items.player.elo_solo and player.elo_group), as well as the active operating status (Open/Closed with countdown timers).00:00–01:00, 06:00–07:00, 12:00–13:00, 18:00–19:00 UTC). Configured via schedule_interval_hours (6) and open_duration_hours (1) in settings.json.ArenaQueueModel are automatically evicted, refunded their spent attempts and items, and notified via Telegram. Ongoing battles and confirmation prompts are allowed to finish.wornoutticket (wornout tickets), up to 7/day for standard players and 10/day for premium. Limits reset daily at 00:00 UTC.same_opponent_cooldown: 1800s). All constants are configurable under arena in settings.json.arena.rewards in settings.json). All player ratings are then reset to 1000 to start the next season.ArenaQueueModel collection. Matchmaking extends the acceptable rating range by $\pm 50$ Elo points every 15 seconds.ArenaMatchModel is created, and a 30-second confirmation window is shown to both players with Ready/Decline options.AutoCombat). Dinosaurs receive no real damage (their HP remains unchanged after battle).ChooseDinoListHandler in bot/modules/states_fabric/state_handlers.py.ChooseDinoHandler for a single-choice interface, wrapping the selected ID in a list for downstream compatibility.first_user achievement.arena_win_fewer_dinos), verified dynamically during search/rollover and retroactively during static checks.arena_streak_seasons_{category}_{count}) are calculated and awarded dynamically during the seasonal rollover phase.TutorialProgress in bot/models/other.py (collection tutorial), storing userid, step, pinned_message_id, and active.bot/modules/tutorial.py manages step flow, message editing, signal message dispatch, and step advancement via advance_tutorial_if_step(userid, chatid, lang, bot, expected_step).egg_selected → Prompting user to start tutorial after egg choice.egg_incubation → Instructing user to open dinosaur profile.egg_boost → Instructing user to use free incubation boost.dino_menu → Explaining dinosaur state image and stats.profile_info → Explaining player level, coins, inventory, achievements.actions_intro → Guiding through actions menu categories (Speed, Skills, Work, Live).feed_wait → Expecting player to feed dinosaur.collecting → Expecting player to send dinosaur on food collecting.map_market → Explaining world map and market.tavern → Explaining Dino-Tavern and quests.blacksmith → Explaining Blacksmith equipment upgrades.bot/handlers/tutorial.py provides tutorial_start, tutorial_skip, and tutorial_stop callback handlers.bot/json/lvl_awards.json for levels 5 through 200 (every 5th level), defining rewards in coins, super_coins, and items.add_xp_lvl in bot/models/user.py, when a user reaches a level defined in lvl_award, rewards are credited automatically and notified via lvl_award_notification.info_menu): Pressing "Информация" in the Profile reply keyboard menu opens info_menu, containing "Мой профиль" (main user profile card), "Достижения" (achievements view), and "Уровни" (levels view).user_levels_info): Paginated view (user_profile levels <userid> <page>) styled like achievements using %%BLOCKQUOTESTART%%, detailing level rewards, unlock statuses, and key game unlocks (Market creation at Lvl 2, Arena at Lvl 10, Dino Slots at Lvl 20, 40, 60, 80).