Telegram group context assistant using grammY + GramJS + HydraDB + LLM (Anthropic/OpenAI/Gemini).
Input:
- Telegram group history and live messages
- Mention queries like
@your_bot summarize this thread
Output:
- Bot replies in the group
- Persistent logs in SQLite (
messagestable) - Optional dashboard view of logs and stats
- Seeder ingests old group messages to HydraDB
- Bot stores new group messages in HydraDB + SQLite
- On mention, bot recalls context from HydraDB
- Bot sends context + question to configured LLM and replies
- Intent classifier (
question/action/help) - Query rewriter (Gemini structured output)
- Hydra multi-query retrieval (
fullRecall+recallPreferences) - Rerank + extraction (issues/action items/entities/dates)
- Final response with evidence lines
- Optional safe action proposal +
/confirm yes
If agent stages fail, bot falls back to single-pass retrieve + answer.
- Stateful chat memory via grammY session per chat/user
- Richer Hydra metadata at ingest (
author,timestamp,message_type,group_id,reply_to, etc.) - Conversation-state memory ingest using
user_assistant_pairs+infer=true - Multi-query retrieval diagnostics with broader recall
- Structured extraction fields:
- issues
- action_items
- entities
- dates
- Action proposal via Gemini function-calling + allowlist execution
- Output sanitizer to remove markdown formatting markers before Telegram reply
- Node.js 18+
- npm
- Telegram bot token (BotFather)
- Telegram API ID/HASH (my.telegram.org)
- GramJS session string (personal account session)
- HydraDB API key + tenant id
- One LLM API key
npm install
cp .env.example .envFill .env.
Required:
TELEGRAM_BOT_TOKENTELEGRAM_API_IDTELEGRAM_API_HASHGRAMJS_SESSIONHYDRA_TENANT_IDSQLITE_DB_PATHHYDRADB_API_KEY(orHYDRA_DB_API_KEY)LLM_PROVIDER(anthropic,openai,gemini)- Provider key for chosen LLM
Important optional:
BOT_DEBUG=1verbose runtime logsAGENT_PIPELINE_ENABLED=1enable 2-stage agent pathSEED_MESSAGE_LIMIT=5000per group seed capSEED_TARGET_GROUP_ID=seed only one group idSEED_TARGET_GROUP_NAME=seed only one exact group title (lowercase compare)HYDRA_WRITE_SCOPE=group|globalHYDRA_RECALL_SCOPE=group|global|group_plus_globalGLOBAL_SUB_TENANT_ID=global-knowledgeHYDRA_MAX_RECALL_RESULTS=25HYDRA_RECALL_BREADTH_RESULTS=40HYDRA_USE_METADATA_FILTERS=0HYDRA_VERIFY_PROCESSING_ON_SEED=1HYDRA_VERIFY_POLL_INTERVAL_MS=3000HYDRA_VERIFY_MAX_WAIT_MS=300000AGENT_GEMINI_MODEL=gemini-2.5-flashPORT=3000
Isolated per-group memory:
HYDRA_WRITE_SCOPE=group
HYDRA_RECALL_SCOPE=groupGlobal shared memory across groups:
HYDRA_WRITE_SCOPE=global
HYDRA_RECALL_SCOPE=global
GLOBAL_SUB_TENANT_ID=global-knowledgeBest balance (group-first + global fallback):
HYDRA_WRITE_SCOPE=group
HYDRA_RECALL_SCOPE=group_plus_global
GLOBAL_SUB_TENANT_ID=global-knowledge- Open Telegram ->
@BotFather - Run
/newbot - Create bot and copy token
- Put token in
.env
Recommended for group bots:
- BotFather ->
/setprivacy-> select bot -> Disable
- Visit
https://my.telegram.org - Log in with your phone number
- Open API development tools
- Create app if needed
- Copy
api_idandapi_hash
Generate with:
node bot/auth-session.jsPrompts shown:
- Phone number
- Telegram code
- 2FA password (if enabled)
Copy printed session string into .env as GRAMJS_SESSION.
Sanity check:
node -e "require('dotenv').config(); const s=(process.env.GRAMJS_SESSION||'').replace(/\s+/g,''); console.log('session_len=',s.length,'prefix=',s.slice(0,6),'suffix=',s.slice(-6));"- Open
https://app.hydradb.com/keys - Sign up or log in
- Create/copy your API key (for
HYDRADB_API_KEY) - Go to Tenant and click Create Tenant
- Select Standard Tenant
- Add tenant ID, description, and keys (optional)
- Click Create
- Set values in
.env:HYDRADB_API_KEY=...HYDRA_TENANT_ID=<your_tenant_id>
Choose one provider:
Anthropic:
LLM_PROVIDER=anthropicANTHROPIC_API_KEY=...ANTHROPIC_MODEL=claude-sonnet-4-20250514
OpenAI:
LLM_PROVIDER=openaiOPENAI_API_KEY=...OPENAI_MODEL=gpt-5.4-mini
Gemini:
LLM_PROVIDER=geminiGEMINI_API_KEY=...GEMINI_MODEL=gemini-2.5-flash- Optional retry tuning:
GEMINI_MAX_RETRIES=2GEMINI_RETRY_BASE_MS=1500
npm run dev
# or
npm run botExpected output (examples):
[bot] Hydra scopes: write=..., recall=..., global=...[bot] Agent pipeline enabled: yes|no[seed] ...(auto-seed runs at startup)[bot] Starting long polling as @your_bot
List groups first:
npm run seed:list-groupsDry run:
npm run seed:dryReal seed:
npm run seedForce reseed:
SEED_FORCE=1 npm run seedPowerShell:
$env:SEED_FORCE="1"; npm run seednpm run dashboardOpen: http://localhost:3000
npm run phase1:test
npm run phase2:testEnable Hydra in phase1:
PHASE1_HYDRA_TEST=1 npm run phase1:testOverride phase2 prompt/context:
PHASE2_CONTEXT="Alice: release Friday" PHASE2_QUESTION="When is release?" npm run phase2:testnode bot/auth-session.jsnpm run lint
npm testMention usage:
@your_bot what did we decide about deployment?@your_bot list issues and action items from recent discussion@your_bot pin the latest summary
Slash commands:
/helpor/examples/issues-> last extracted issues/actions-> last extracted action items/status-> provider/pipeline/scope/pending action/followup <question>-> multi-turn follow-up/confirm yes-> confirm pending safe action
Allowlisted actions currently supported:
summarize_threadpin_summary(requires bot permission)schedule_reminder(preview message; no scheduler integration yet)moderation_action(preview/safe-mode response)
Actions are not auto-executed. User confirmation is required via /confirm yes.
Bot replies are normalized to plain Telegram text:
- strips markdown fences and markers (
**,*, backticks, headings) - keeps readable bullet points and evidence lines
- avoids raw formatting artifacts in final messages
Set:
BOT_DEBUG=1Adds logs such as:
- incoming message metadata
- mention detection
- pipeline stage signals
- recall chunk counts
- reply sent / fallback events
Set:
HYDRA_VERIFY_PROCESSING_ON_SEED=1
HYDRA_VERIFY_POLL_INTERVAL_MS=3000
HYDRA_VERIFY_MAX_WAIT_MS=300000This waits until seeded source IDs are ready/failed in Hydra before finishing group seed.
Input:
@your_bot what did we decide for deployment?
Expected:
- contextual answer
- evidence footer lines with source IDs/scores
- SQLite row with
is_bot_reply=1
Input:
@your_bot extract issues and action items from latest task messages- then
/issuesor/actions
Expected:
- extracted lists in clean text
Input:
@your_bot pin the latest summary/confirm yes
Expected:
- action preview/proposal then confirmed action response
Missing Hydra API key
- Set
HYDRADB_API_KEYorHYDRA_DB_API_KEY
GRAMJS session is not authorized
- Re-run
node bot/auth-session.js - Replace
GRAMJS_SESSION
- Seeder says
.seeded exists ... Skipping seeding
- Use
SEED_FORCE=1 npm run seed
- Bot not responding in group
- Add bot to group
- Disable bot privacy in BotFather
- Mention bot username explicitly
- Dashboard says DB not found
- Start bot once so SQLite file is created
- Check
SQLITE_DB_PATH
phase2:testfails withfetch failed
- Check internet access / firewall
- Verify
GEMINI_API_KEYand provider/model settings
- Configure
.env - Generate GramJS session
- Run
npm run seed:list-groups - Set
SEED_TARGET_GROUP_ID - Run
npm run seed:dry - Run
npm run seed - Run
npm run bot - Mention bot in Telegram group
- Run
npm run dashboard - Validate new commands:
/status,/issues,/actions,/followup ...