NewFPV / documentation

NEXUSTG WIKI

The complete, code-verified guide to running your AI-powered Telegram userbot: installation, onboarding, every bundled module, safe operation, maintenance, and recovery.

Release 2.2.1 Python 3.11 AGPL-3.0 Main 2c39d49
Read before connecting your account

NexusTG signs in as your Telegram user account and can read private chat history, send messages, download media, create groups, and perform account actions enabled by its modules. Use a trusted machine, protect the data/ directory, obtain consent where required, and understand Telegram's rules before enabling automation.

01 / overview

What NexusTG is

NexusTG combines a private Telegram settings bot with a userbot connected to your personal account. The settings bot is the control panel; the userbot observes and acts inside your chats; Gemini handles language, search, transcription, media understanding, and content generation.

AUTOMATION

AI Twin

Optional replies in private chats with per-chat prompts, search, sleep hours, realistic delays, typing bursts, reactions, and manual override.

AI TOOLS

On-demand commands

Ask AI, check a claim, summarize YouTube, restructure text, transcribe media, or turn notes into native Telegram checklists.

MEDIA

Context and downloads

Understands recent photos, video, voice, audio, and YouTube context; downloads supported TikTok and Instagram Reel links.

MEMORY

Local state

Stores setup, module settings, session data, AI cooldowns, media descriptions, YouTube context, and saver indexes in local SQLite files.

CONTROL

Global and per-chat rules

Most automatic features can be controlled globally and overridden for an individual private chat from one inline menu.

EXTENSIBLE

Drop-in modules

Python files in modules/ are discovered at startup and can register settings UI, chat UI, userbot handlers, and startup tasks.

Current documentation target

This guide was verified against main commit 2c39d49 from June 29, 2026. The newest tagged release is v2.2.1; current main also contains later Text Structurer and Voice Transcriber fixes.

02 / system design

How the pieces connect

Settings botAiogram pollingFirst-run wizardInline control menus
NexusTG coreModule loaderSQLite repositoriesTask and cache helpers
User accountKurigram sessionChat handlersTelegram actions

Control plane

The BotFather bot token starts the Aiogram control bot. The first person who sends /start becomes the stored administrator. All setup and settings messages are handled in that bot chat; the implementation tries to keep a single menu message updated in place.

Userbot plane

During onboarding, NexusTG signs in to your Telegram account with the API ID and API hash from my.telegram.org. It exports an in-memory session into the local database and uses that session on later starts. Bundled handlers are registered before the userbot starts.

AI and data plane

Gemini API keys and model names are stored in data/core_database.db. Requests walk the configured key/model fallback chain. SQLite also stores per-chat overrides, media-description cache, YouTube context, ignored generated messages, and command-thread tracking. Message Saver uses a second database because it needs a durable event cache.

The database is local, not encrypted

The current source stores the Telegram session string, phone number, API credentials, Gemini keys, prompts, and module configuration in ordinary SQLite. Filesystem access to data/ should be treated as access to the connected account.

03 / prerequisites

Requirements

ComponentWhy it is neededRequired
Telegram accountThe account controlled by the userbotYes
BotFather tokenStarts the private settings botYes
Telegram API ID/hashMTProto login for the userbot; create at my.telegram.orgYes
Gemini API keyAI replies, transcription, summaries, structuring, and media analysisYes for AI features
Python 3.11Native runtime; project metadata allows 3.11 and 3.12Native install
Docker + Compose v2Isolated Linux/VPS deployment and persistent data volumeDocker install
Git and internet accessInstallation, Telegram, Gemini, media sites, and updatesYes
Netscape cookies.txtHelps yt-dlp access YouTube, Instagram, and TikTok when anonymous access failsOptional

Supported deployment paths

  • Windows native installation with uv and a desktop shortcut.
  • Debian/Ubuntu-style Linux or VPS installation with Docker Compose.
  • Manual Docker Compose on any host that can run the image.
  • Manual Python environment for users who want direct process control.

The Linux installer specifically uses apt-get, systemctl, and sudo. On other distributions, install Git, Docker, and the Compose plugin yourself, then follow the manual Docker instructions.

04 / install

Installation

Review remote scripts when possible

The one-line installers are convenient, but they download and execute the current script from GitHub. You can open install.ps1 or install.sh before running it.

Windows installer

powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://raw.githubusercontent.com/newfpv/NexusTG/main/install.ps1 | iex"

The installer clones or updates %USERPROFILE%\NexusTG, installs Git with winget if necessary, installs uv, creates a Python 3.11 environment, installs pyproject.toml dependencies, validates the BotFather token, writes .env, creates start.bat, and adds a Start NexusTG desktop shortcut. Keep the console window open while NexusTG runs.

Linux / VPS installer

bash <(curl -sL "https://raw.githubusercontent.com/newfpv/NexusTG/main/install.sh")

The script installs Git/curl and Docker on apt-based systems, clones or pulls ~/NexusTG, lets you choose the app language, validates the BotFather token, writes .env, builds the image, and starts nexustg with Docker Compose.

cd ~/NexusTG
sudo docker compose ps
sudo docker compose logs -f

Manual Docker Compose

git clone https://github.com/newfpv/NexusTG.git
cd NexusTG
cp .env.example .env
nano .env

Minimum .env:

TG_BOT_TOKEN=1234567890:replace_with_real_token
LANG_FILE=language_EN.json
docker compose up -d --build
docker compose logs -f nexustg

Compose mounts ./data into /app/data, so configuration and sessions survive container replacement.

Manual native Python

git clone https://github.com/newfpv/NexusTG.git
cd NexusTG
cp .env.example .env

uv venv --python 3.11
uv pip install -r pyproject.toml
uv run main.py

Do not use the old commands pip install -r requirements.txt or python -m core.main: the repository has no requirements.txt and the entry point is the root main.py.

05 / onboarding

First-run setup

  1. Claim the control botOpen the BotFather-created bot and send /start. The first sender becomes the administrator.
  2. Enter Telegram API credentialsProvide the numeric API ID and the 32-character hexadecimal API hash from my.telegram.org.
  3. Add Gemini keysPaste one key or a comma-separated list. Multiple keys give the fallback system more capacity.
  4. Choose the timezoneUse an IANA name such as Europe/Minsk, Europe/London, or America/New_York.
  5. Optionally upload cookiesSend a .txt Netscape cookies file or choose Skip. It is saved as data/cookies.txt.
  6. Authorize the user accountEnter the phone number, use the inline number pad for Telegram's five-digit code, then enter the 2FA password if requested.

Where credentials come from

CredentialSourceStored in
TG_BOT_TOKEN@BotFather → /newbot.env
api_id / api_hashmy.telegram.org → API development toolscore_database.db
Gemini API keysGoogle AI Studiocore_database.db
Telegram sessionCreated after phone/code/2FA authorizationcore_database.db
Admin ownership is first-come on a fresh database

Do not expose a newly started control bot publicly before you claim it. A full reset clears the stored admin ID; the next person to send /start can become admin.

06 / control panel

Using the control bot

The main menu appears only after setup is complete and the userbot is connected. It displays the current time in the configured timezone and gathers buttons registered by every loaded module.

MY CHATS

Per-chat controls

Lists up to 30 recent private dialogs, excluding Telegram service chat 777000. Pick a contact to configure AI Twin, Voice, Media Downloader, Fake Activity, and profile information for that chat.

MODULE MENUS

Global behavior

AI Twin, AI Command, Voice, YouTube Summary, Text Structurer, downloads, shopping, fact checking, Message Saver, Custom Saver, and profile tools add their own controls.

SETTINGS

System configuration

Edit Gemini keys, model fallback order, timezone, AI cooldown status, AI connectivity test, shared YouTube cookies, or perform a full reset.

ONE MESSAGE UI

Clean navigation

The bot normally edits the existing menu message. If it cannot, it sends a new one and stores that message ID for later screens.

Three-state per-chat settings

Voice and Media Downloader per-chat toggles cycle through Global → On → Off. Global means the chat follows the module's global setting; On and Off override it. AI Twin uses the same inheritance idea for human typing and smart reading.

07 / quick reference

Default commands

CommandUseDefault access
.ai questionStream a context-aware Gemini answer; replying to a tracked answer continues without repeating .aiYou only
.fact claimSearch-backed fact check with a verdict and supporting detailsYou only
.textReply to voice, video note, video, or audio to transcribe itYou only
.fix textRewrite the command message into clean structured textYou; module off by default
.fixReply to text/caption/quote/voice/audio/video note and structure itYou; module off by default
.fix 5Merge and structure up to the previous five eligible messages; maximum 20You; module off by default
.sum URLStream a summary of the first YouTube link in the message or replied messageYou
.dlReply to a supported TikTok or Instagram Reel link and download itYou
.shop itemsTurn free-form shopping text into a Telegram checklistYou and others by default
.saveReply to any message and forward it to the configured chat/topicYou; module off by default

Command prefixes are editable in the corresponding module menus. A command comparison is case-insensitive in several modules, but not all; keep the exact configured spelling to avoid surprises.

08 / AI service

Gemini keys, models, and fallbacks

All AI modules share one service layer. It tries each configured API key and each configured model, records temporary failures, and skips unavailable combinations until their cooldown expires.

Default model order

gemini-3.1-flash-lite-preview,
gemini-3-flash-preview,
gemini-2.5-flash,
gemini-2.5-flash-lite

Edit this comma-separated list under Settings → Models. Preview model availability can change; use Test AI after editing the list.

ConditionCooldownEffect
General key/model failure60 secondsSkips that combination temporarily
Server-side failure180 secondsAllows another key/model to take over
Authentication/permission failure1,800 secondsAvoids repeatedly calling a bad or blocked credential
Single Gemini request60-second timeoutFalls back or returns an empty/wait state

Search-enabled and ordinary requests have separate per-model cooldown records. Settings → Limits shows active bans with masked keys; Reset limits clears the local cooldown records but does not reset Google's real quota.

Context and cache rules

  • AI Twin reads up to 50 recent messages; Manual AI reads up to 30.
  • At most three context media files are downloaded and described in a single context pass.
  • Audio/video longer than 10 minutes is represented as a file marker instead of being transcribed for dialog context.
  • Media descriptions are cached for two days; YouTube context is cached for seven days.
  • YouTube context prefers RU, EN, UK, then BE subtitles; if none are available it uses up to 6,000 characters of description.

09 / module

AI Twin

AI Twin watches incoming messages in private human dialogs and can reply as your account. It is globally off by default, and each chat also starts inactive.

Activation rules

  • If global AI is off, a chat replies only when that chat is explicitly enabled.
  • If global AI is on, all eligible private chats participate unless an inactive chat is marked ignored.
  • Messages from bots, your own account, and Telegram service user 777000 are skipped.
  • A newer incoming message cancels an older pending reply for the same chat.
  • If you send a manual reply while AI is waiting, the pending AI task is cancelled.

Response pipeline

  1. 01
    Apply chat policy

    Checks global/chat activation, ignore state, sleep hours, inherited human settings, and search controls.

  2. 02
    Build context

    Collects up to 50 chronological messages, adds cached or generated media descriptions, reply context, and the global plus chat prompt.

  3. 03
    Generate

    Calls the Gemini fallback chain. Ordinary web links force Search for that request; YouTube links are processed through the YouTube context path.

  4. 04
    Simulate reading

    Waits the configured base delay, then optionally adds a smart delay based on text length or the newest media duration.

  5. 05
    Decide

    Questions are kept; non-questions can be ignored according to the configured percentage. A [LIKE] result becomes a reaction.

  6. 06
    Send naturally

    Splits lines into messages, simulates typing bursts, sometimes replies to the original, and has a 5% typo-then-correction path.

Global defaults

SettingDefaultMeaning
Global AIOffMaster automatic reply mode
Google SearchOnSearch grounding switch; regular links can still force it for that request
Before / after delay1–3 / 1–3 sRandom waits around response processing
Typing speed0.10 s/characterTyping duration, capped at 10 seconds per part
Human typingOn1.5–3.5 s typing bursts and 0.5–2.0 s pauses
Smart readingOn0.05 s per text character or media duration
Ignore chance10%Applied only to messages not recognized as questions
Reaction👍Used when the model emits [LIKE]
Sleep hoursOffSupports normal and overnight time ranges
Debug loggingOnLogs request flow and prompt previews; may expose sensitive context

Per-chat controls include activation, Search, exclusion from global AI, a supplemental prompt, before/after delay overrides, inherited/on/off human typing, inherited/on/off smart reading, ignore chance, and a button that skips the current smart media-reading wait.

10 / module

Manual AI command

.ai gives you explicit, streaming access to Gemini without enabling automatic replies. It builds context around the target message, supports a live photo/video attachment, formats Markdown into Telegram HTML, and edits the thinking message about every 0.8 seconds as output arrives.

Common patterns

.ai explain the last part of this conversation
.ai draft a concise reply

# Reply to a photo or message:
.ai analyze this

# Continue by replying to the generated answer:
What are the trade-offs?

The generated message ID is tracked in SQLite. A reply to that tracked answer can continue the conversation without the command prefix. This tracking is local and does not create a separate long-term AI thread object.

SettingDefaultNotes
Command.aiEditable
SearchOnUses the search-enabled Gemini request path
Allow othersOffWhen on, contacts can trigger a command in the chat
Debug outputOffPrints full prompt/output to process logs
Total command budget240 sContext collection and streaming have additional internal timeouts

11 / module

Voice Transcriber

Transcribes voice messages and video notes automatically in private chats, or transcribes voice, video note, video, and audio when the configured command is used as a reply. Bot dialogs are explicitly skipped.

Automatic mode

Auto my controls media sent by your own account; Auto other controls incoming media. Both default off and can be overridden per chat. Auto jobs are queued per chat, so several consecutive voice notes are processed in order. Results arriving close together can be appended into the previous transcription message.

Summary behavior

  • Summarize defaults on and adds an AI summary when duration is at least 60 seconds.
  • Summary only defaults off and outputs the summary instead of the transcript; it can be overridden per chat.
  • Long output is divided below Telegram's message limit into expandable blockquotes.
  • Transcription retries up to three times with a 60-second wait after overloaded responses.
  • Downloads are checked for zero-byte or incomplete files and retried after refreshing the Telegram message.
SettingDefault
Command.text
Auto my / auto otherOff / Off
Allow others to commandOff
Summarize ≥60 sOn
Summary onlyOff

12 / module

Text Structurer

Text Structurer rewrites rough text into a clean, readable message. It supports direct text, replies, Telegram reply quotes, voice/audio/video-note transcription, and chronological batches of earlier messages.

Modes

InputResult
.fix raw textThe command message is replaced by structured output
Reply .fix to your messageThe source message itself is edited; the trigger is removed
Reply .fix to another person's messageYour trigger message becomes the structured copy
Reply .fix extra instructionCombines the saved base prompt with the one-off instruction
Reply .fix to voice/audio/video noteTranscribes, structures, and deletes source media only after success
.fix 5Collects up to five eligible messages before the command, oldest to newest, and merges them
.fix 5 make it formalBatch mode plus a one-off modifier

Batch mode is capped at 20 messages and fetches up to 100 history items to find eligible text, captions, voice, audio, or video notes. Source messages are deleted only after the final AI edit succeeds. The module is off by default; the default command is .fix.

13 / module

YouTube Summary

.sum finds the first YouTube, youtu.be, or Shorts link in the command or replied message. yt-dlp fetches the title, duration, and subtitles; Gemini then streams a formatted summary back into the command message.

  • Enabled by default; command .sum.
  • Uses human or automatic subtitles in RU, EN, UK, then BE priority.
  • Falls back to the video description when subtitles are unavailable.
  • Caches context for seven days in youtube_cache.
  • Splits output when formatted content approaches 3,800 characters.
  • Debug mode prints the fetched YouTube context to stdout and is off by default.
  • The menu can clear the complete YouTube context cache.
.sum https://youtu.be/example

# Or reply to a message containing the link:
.sum

14 / module

Media Downloader

Downloads videos from TikTok links and Instagram Reel/Reels links with yt-dlp. Despite the shared cookies manager supporting YouTube cookies, this module's automatic URL matcher does not download arbitrary YouTube URLs.

Triggers

  • Auto my: automatically process supported links you send.
  • Auto other: automatically process supported links received from the other person.
  • Reply command: reply .dl to a supported URL. Other people can use it only when allowed.

All three switches default off globally and support Global/On/Off overrides per chat. Downloaded files are written temporarily under data/dl_*.mp4, uploaded as a reply to the URL, then removed.

Cookies manager

The module menu can upload, verify, and clear data/cookies.txt. Verification counts YouTube, Instagram, and TikTok cookie lines and considers session cookies or unexpired timestamps valid. Use Netscape-format cookies only and protect the file like a login credential.

15 / module

Smart Shopping

Smart Shopping turns unstructured items into Telegram's native checklist type. The AI returns a JSON list; NexusTG creates checklists in groups of up to 30 tasks, with permission for participants to check or add items. If native checklist creation fails, it sends Markdown checkboxes.

Ways to use it

.shop milk, two packs of pasta, apples and dish soap
  • Reply to an existing NexusTG shopping checklist to merge new items into a replacement list.
  • Add chat IDs or chat_id:topic_id pairs to Auto Chats for command-free processing in selected groups/topics.
  • Multiple auto destinations are comma-separated.
SettingDefault
ActiveOn
Command.shop
Allow othersOn
Delete original triggerOn
Auto chatsEmpty

16 / module

Fact Checker

.fact sends a claim through the search-enabled Gemini path, then displays a verdict and expandable details with link previews disabled. Details longer than about 3,000 characters are truncated to stay within Telegram limits.

.fact The claim to verify, with enough context to identify it

The module is enabled by default and the command is editable. It currently handles your outgoing text commands; unlike Manual AI, it has no Allow Others switch.

17 / module

Message Saver

Message Saver keeps a local cache of incoming private messages so deleted messages, edits, and self-destructing media can be copied to a private forum group. It is off by default and requires deliberate destination setup.

Consent, law, and sensitive data

This module can preserve content the sender expected to disappear, including view-once media. Use it only where lawful and appropriate, disclose recording/retention when required, and never expose the dump group or local cache.

Destination setup

  • Automatic: the userbot creates a supergroup, enables forum topics, adds the control bot, grants topic-management permissions, and stores the group ID.
  • Select existing: choose one of up to 15 groups from the first 100 dialogs; NexusTG tries to enable forum mode and add/promote the bot.
  • Manual: enter a group ID. Numeric forms are normalized toward Telegram's -100... supergroup format.

How saving works

  1. 01
    Cache incoming private messages

    Text and eligible media are indexed in saver_cache.sqlite; regular media up to 20 MB and TTL media up to 50 MB are downloaded by default.

  2. 02
    Apply scope

    An optional target-chat allowlist limits saving; a comma-separated user blacklist excludes specific senders.

  3. 03
    Create a person topic

    Each sender gets a forum topic named with profile name and ID. NexusTG posts a profile card, tries to attach the avatar, and pins it.

  4. 04
    Send evidence after a delay

    A queue waits a random 1–5 seconds by default, then sends deleted content, before/after edits, or TTL media.

  5. 05
    Clean up

    Consumed media is removed, orphan files are scanned every 12 hours, and a small random cleanup removes cache rows older than 180 days.

SettingDefaultFormat
ActiveOffToggle
Save deletedOnToggle
Save editedOnToggle
Save TTL/view-onceOnToggle
TargetsAll private chatsComma-separated chat IDs
BlacklistEmptyComma-separated user IDs
Send delay1–5 sTwo numbers
Media limits20 / 50 MBRegular / TTL

18 / module

Custom Saver

Custom Saver is an explicit forwarding shortcut. Configure a destination as chat_id or chat_id:topic_id, enable the module, then reply to any message with the trigger command. NexusTG deletes your command message and forwards the replied message to the target.

# Default trigger
.save

# Destination examples
-1001234567890
-1001234567890:42

Defaults: off, no destination, command .save. This module forwards through your user account and does not use Gemini.

19 / module

Fake Activity

From an individual chat menu, Fake Activity repeatedly sends a Telegram chat action for the number of minutes you enter. Starting another action in the same chat cancels the previous one; Stop sends the Cancel action.

typingupload photorecord videoupload videorecord audioupload audiorecord video noteupload video noteupload documentplayingchoose sticker

Actions are refreshed about every four seconds until the duration ends. Telegram clients may display actions differently, and long or deceptive activity can be disruptive; use it responsibly.

20 / module

Profile information

My Info shows the connected account's ID, full name, username, phone when visible, bio, Premium state, verification/scam/restriction state, and data-center ID. User Info adds contact, mutual-contact, deleted-account, and visibility state for the selected chat contact.

The module reads data already visible to the connected Telegram account. Hidden phone numbers remain unavailable; values depend on Telegram and Kurigram's current API objects.

21 / reference

Settings and defaults

System settings

ControlPurposeDefault
Gemini keysOne or comma-separated API keysEntered during setup
Model listComma-separated fallback priorityFour Gemini Flash variants
TimezoneMenu clock and setup validationEurope/London in a new DB
LimitsInspect/reset local per-key/model cooldownsNo bans
Test AITests every key/model combination with progress and StopManual action
YouTube cookiesUpload or delete shared data/cookies.txtMissing
Full resetStops userbot and clears admin, login, API, Gemini, and setup fieldsConfirmation required

Module defaults at a glance

ModuleInitially activePrimary default
AI TwinOffSearch on, human behavior on
Manual AICommand available.ai, Search on, others off
VoiceAuto off.text, summarize on
Text StructurerOff.fix, max batch 20
YouTube SummaryOn.sum, debug off
Media DownloaderAuto off.dl, others off
Smart ShoppingOn.shop, others on
Fact CheckerOn.fact
Message SaverOffDeleted/edit/TTL toggles prepared on
Custom SaverOff.save, target empty

22 / persistence

Files and data

PathContentsBack up?
.envBot token and selected language fileYes, securely
data/core_database.dbAdmin, Telegram API credentials/session, Gemini keys/models, global/chat/module settings, caches, AI command trackingYes, critical
data/saver_cache.sqliteMessage Saver index and sender-to-topic mappingYes if Saver is used
data/spy_cache/Message Saver media waiting for or supporting alertsOptional/sensitive
data/cookies.txtOptional site authentication cookies used by yt-dlpYes if hard to recreate
data/context_*Temporary context mediaNo
data/live_*Temporary current-message mediaNo
data/v_*, data/ts_fix_*, data/dl_*Temporary transcription/structuring/download filesNo

Main database tables

global_config, chat_config, ai_key_state, ignored_msgs, youtube_cache, media_memory_cache, and ai_cmd_tracker. The media-description cache is pruned daily for entries older than two days; YouTube entries are refreshed when older than seven days.

23 / recovery

Backup and restore

Docker deployment

cd ~/NexusTG
docker compose stop

tar -czf nexustg-backup-$(date +%F).tar.gz .env data

docker compose start

Stopping first gives SQLite a clean point-in-time copy. Store the archive encrypted or on a trusted offline volume.

Windows deployment

  1. Close the Start NexusTG console and confirm main.py is no longer running.
  2. Copy %USERPROFILE%\NexusTG\.env and the full %USERPROFILE%\NexusTG\data directory.
  3. Restart with the desktop shortcut.

Restore

  1. Stop NexusTG.
  2. Install or clone the desired code version.
  3. Place the saved .env and data/ back at the repository root.
  4. Start and inspect logs before enabling automation.
A backup is an account credential

Because the exported Telegram session is inside core_database.db, anyone who obtains a usable backup may be able to impersonate the connected account.

24 / lifecycle

Update, rollback, and removal

Linux / Docker update

cd ~/NexusTG
docker compose stop
tar -czf ../nexustg-before-update-$(date +%F).tar.gz .env data

git pull --ff-only
docker compose up -d --build
docker compose logs --tail=200 nexustg

Windows update

Back up .env and data/, close NexusTG, then rerun the installer. It performs git pull for an existing %USERPROFILE%\NexusTG checkout and rebuilds the environment/shortcut.

Pin or roll back to v2.2.1

git fetch --tags
git switch --detach v2.2.1

# Docker
docker compose up -d --build

A detached tag is useful for diagnosis but does not receive updates. To return to current development code:

git switch main
git pull --ff-only

Remove without losing data

cd ~/NexusTG
docker compose down

# Move .env and data/ to a secure backup before deleting the checkout.

Do not use docker compose down -v casually. The current Compose file uses a bind mount for ./data, but destructive volume flags are a poor habit and future layouts can change.

25 / safety

Security and privacy

  • Claim the settings bot immediately after first start and never share it as a public utility bot.
  • Restrict .env, data/, logs, backups, and Docker host access to the operator.
  • Use a dedicated Gemini project/key where practical; rotate any key accidentally shown in chat or logs.
  • Disable AI Twin debug after setup if prompt previews or message context should not appear in logs.
  • Leave Allow Others off unless you explicitly want contacts to consume your AI quota or run a command.
  • Start automatic modules off, enable one at a time, and test in a low-risk private chat.
  • Keep cookies.txt private; it can contain active website sessions.
  • Use Message Saver only with a retention policy and consent appropriate to your jurisdiction.
  • Review Telegram's Terms and flood limits; a userbot operates as your account, not as a sandboxed bot identity.

Full reset scope

The UI full reset clears the stored phone/session, Telegram API ID/hash, Gemini keys, admin/menu IDs, setup flag, and AI cooldown rows. It does not delete every module setting, chat override, saver database, cached media, cookies file, or .env. For a true clean start, stop the app and archive/remove the entire data/ directory plus recreate .env.

26 / diagnostics

Troubleshooting

The bot does not start
# Docker
docker compose ps
docker compose logs --tail=250 nexustg

# Native
uv run main.py

Check that .env exists, TG_BOT_TOKEN is valid, the selected LANG_FILE exists, and the data directory is writable.

The control bot stays on “connecting”

The main menu is withheld until the userbot is connected. Send /start, complete account authorization, and inspect logs for session, API ID/hash, or network errors. The health loop checks the userbot every 30 seconds and attempts a restart after three failed checks.

Another person became admin

On a fresh or fully reset database, the first /start sender is stored as admin. Stop the service, secure access to the bot, then perform a controlled reset or restore a known-good core_database.db.

Gemini returns no answer or shows cooldowns
  1. Open Settings → Test AI.
  2. Verify keys are comma-separated with no accidental text.
  3. Review Models and remove unavailable preview names.
  4. Open Limits to see local cooldowns.
  5. Reset local limits only after fixing the underlying key/quota issue.
YouTube summary cannot fetch context

Try a public video with subtitles, update yt-dlp by rebuilding/reinstalling, and upload a current Netscape cookies.txt in Settings. Private, age-restricted, regional, or bot-protected videos may still fail. Clear YouTube Summary cache after replacing cookies.

Instagram or TikTok download fails

Open Media Downloader → Cookie Manager, upload and verify cookies, then retry. The link must match a TikTok domain or instagram.com/reel/reels. Check logs for yt-dlp errors and rebuild so the image receives the latest yt-dlp.

Voice transcription creates an empty or zero-byte file

Current main retries checked downloads twice and refreshes the Telegram message between attempts. Update beyond v2.2.1, confirm disk space and write permissions for data/, and inspect Kurigram/MTProto errors in logs.

.fix does nothing

Text Structurer is off by default. Enable it in the control bot, confirm the command spelling, and ensure the trigger is sent by your own account. Batch mode needs eligible earlier messages; media mode supports voice, audio, and video notes.

AI Twin answers when it should not

Check both global AI and the chat's activation/ignore state. An inactive chat is not automatically excluded while global AI is on unless it is marked ignored. Also check sleep hours and remember that ordinary links force a Search-enabled request.

Message Saver receives nothing
  • Confirm the main Saver switch and the relevant deleted/edited/TTL toggle.
  • Verify dump group ID and that the control bot is a member with topic permissions.
  • Ensure the sender is not blacklisted and the chat is in Targets when an allowlist is set.
  • Check media size against the 20 MB regular / 50 MB TTL defaults.
  • Inspect data/saver_cache.sqlite permissions and Saver logs.
The database is locked

Stop duplicate NexusTG processes first. Both SQLite engines use a 30-second busy timeout and a single main connection pool, but two containers/processes sharing one data/ directory can still conflict. Make a backup, stop all copies, then start exactly one instance.

I need a completely clean setup
docker compose down
mv data data.backup
mkdir data

# Review or recreate .env, then:
docker compose up -d --build

This is more complete than the UI reset. Keep data.backup secure until the new setup is verified.

27 / extension API

Developing a module

At startup, NexusTG imports every non-underscore .py file in modules/. It detects known objects and hooks by name; there is no separate manifest or package registry in the current source.

HookPurpose
routerAiogram Router included in the settings bot dispatcher
register_userbot(app)Register Kurigram handlers for account events
register_userbot(app, bot)Same, with access to the control bot
get_main_menu_buttons()Add rows to the main menu
get_settings_buttons()Add module settings entry points
get_chat_menu_buttons(chat_id)Add per-chat controls
on_startup()Initialize module databases, workers, or other resources

Minimal module shape

from aiogram import Router
from aiogram.types import InlineKeyboardButton
from pyrogram import Client, filters

from core.utils import CoreAPI

router = Router()
MODULE_NAME = "example"

async def get_settings_buttons():
    return [[InlineKeyboardButton(
        text="Example",
        callback_data="example_main"
    )]]

def register_userbot(app: Client):
    @app.on_message(filters.me & filters.command("example", prefixes="."))
    async def example_handler(client, message):
        await message.edit("Example is active")

CoreAPI methods

get_global_config, update_global_config, get_chat_config, update_chat_config, get_module_cfg, update_module_cfg, get_chat_module_cfg, update_chat_module_cfg, session/reset helpers, and ignored-message tracking. Module settings are JSON nested inside the main global/chat rows; copy the outer dict before mutation so SQLAlchemy detects the change.

  • Keep handlers asynchronous and move blocking work into asyncio.to_thread.
  • Use unique handler groups and callback prefixes to prevent module conflicts.
  • Delete temporary media in finally blocks.
  • Escape user text before Telegram HTML formatting.
  • Make settings defaults explicit in the getter, not only in translation copy.
  • Restart NexusTG after adding or changing a module; loading happens only at process start.

28 / releases

Version status

VersionDateStatus
main / 2c39d492026-06-29Current source; post-v2.2.1 Text Structurer and Voice fixes
v2.2.12026-06-20Latest tagged release
v2.2.02026-04-16YouTube AI, handler refactoring, stability work
v2.1.12026-04-16Handler, AI formatting, SQLite/Kurigram improvements
v2.0.02026-04-13NexusTG / AI Twin 2.0 redesign

The repository's license file is the GNU Affero General Public License v3.0. Older README badges that called it MIT were incorrect.

29 / acknowledgements

Acknowledgements

Parts of NexusTG's methods and development approach were inspired by SpyBot, created by woxov.

Special thanks to woxov for creating SpyBot, publishing the project, and sharing ideas that helped inform parts of NexusTG's development. NexusTG is independently developed and maintained, while this acknowledgement records the inspiration and influence of that earlier work.

ready / controlled rollout

Start small, then automate

Install and finish authorization first. Test Gemini and one manual command. Back up .env and data/. Only then enable automatic replies, downloads, transcription, or retention for selected chats.