[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ECKS4VW18SBMPPSX6S16Q4":3,"skill-same:01M7ECKS4VW18SBMPPSX6S16Q4":49},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M7ECKS4VW18SBMPPSX6S16Q4","telegram-user-session-reading",null,"jonahthan433\u002FCortexOS","jonahthan433","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211465495?v=4","01M7ECH9HPHGA89DCXHHJBTS3C","jonah.ai","01M7ECH9JCEM45DZMWPT7148S1",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002F.archive\u002Ftelegram-user-session-reading\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# telegram-user-session-reading\n\n# Telegram User-Session Reading\n\nClass of work: the user wants Hermes to **read or monitor the content of a\nTelegram channel\u002Fchat** — to summarize it, feed it into a briefing, or build\nsomething (e.g. a trading bot) off its posts. This is READ ingestion of a\nsource the user typically does NOT own.\n\n## READ THIS FIRST: try the public scraper before ANY user-session login\n\nIf the target channel is **public** (its `https:\u002F\u002Ft.me\u002F\u003Cchannel>` page loads,\nHTTP 200), you do NOT need a user session at all. Telegram exposes public\nchannel history at `https:\u002F\u002Ft.me\u002Fs\u002F\u003Cchannel>` with zero auth. Scrape that first\n— it sidesteps the entire login-code nightmare below. Use\n`scripts\u002Fscrape_channel.py \u003Cchannel> [count]`. Only fall back to a telethon\nuser session if the channel is **private** and the user can see it in their app.\n\nQuick public check: `curl -s -o \u002Fdev\u002Fnull -w \"%{http_code}\" https:\u002F\u002Ft.me\u002F\u003Cchannel>`\n→ `200` means the web page exists; then confirm `https:\u002F\u002Ft.me\u002Fs\u002F\u003Cchannel>`\nreturns post HTML (some channels disable the preview `\u002Fs\u002F` view).\n\n**Extracting structured fields from the scraped HTML is fiddly** — use\n`html.parser` (not regex) for message text, and beware that \"results table\"\nposts collapse to whitespace-tokens where the column order is header-row then\nvalue-row (the day number is NOT next to the word \"Day\"). See\n`references\u002Fparsing-public-channel-html.md` for the exact gotchas, working\nregexes, and the append-only JSONL de-dupe pattern — it saves many iterations.\n\n## ⚠️ Agent-relayed login codes are BURNED by Telegram — the user-session login usually CANNOT be completed by the agent\n\nThis is the single most important lesson. When a Telegram login code is **pasted\ninto any chat \u002F shared with anyone** — including legitimately handing it to\nHermes — Telegram's anti-phishing **invalidates that code and blocks the login**.\nThe user receives: *\"The code was entered correctly, but sign in was not\nallowed, because this code was previously shared by your account.\"* and a\nsecurity notice about a blocked login attempt.\n\nConsequences:\n- **The file-polling `login_wait.py` trick does NOT save you.** It fixes the\n  timing\u002FEOF problems, but the code is still one the user relayed through chat,\n  so Telegram still burns it. Every relayed code fails the same way.\n- This is a HARD Telegram security rule, not a bug to script around. A code is\n  only honored when typed **directly into the official Telegram client** on a\n  device the user controls — never one echoed into a chat with the agent.\n\nTherefore, for agent-driven setup:\n1. **Prefer the public scraper** (above) — no login needed. This is the\n   realistic path for \"monitor \u002F build a bot from channel X\".\n2. If a genuine user session is required and the channel is private, the user\n   must complete the login **themselves on a real device** (e.g. Telegram\n   Desktop) — the agent cannot relay the code for them.\n3. Do NOT burn multiple codes trying: each failed relay triggers another\n   security block and risks a flood-wait lockout on the number.\n\nWhen abandoning the user-session attempt, **clean up**: delete\n`~\u002F.hermes\u002Ftelegram_user.env` and any partial `~\u002F.hermes\u002F*.session` (they are\ncredentials), and pivot to the public scraper or user-forwards-posts approach.\n\n## Counting subscribers WITHOUT admin rights (channel growth metrics)\n\nA bot is usually NOT admin on the user's own channel (posting can still work\nvia a user session or `hermes send`). Consequences + working path:\n\n- **Bot API `getChat` omits `member_count` for non-admin bots.** If the bot is\n  not admin, don't chase admin rights just for a number — scrape the public\n  page instead.\n- **Public `https:\u002F\u002Ft.me\u002F\u003Cusername>` page HTML contains the exact subscriber\n  count** (in `tgme_page_extra`), zero auth:\n  ```python\n  html = urllib.request.urlopen(urllib.request.Request(\n      f\"https:\u002F\u002Ft.me\u002F{username}\", headers={\"User-Agent\": \"Mozilla\u002F5.0\"}), timeout=15\n  ).read().decode(\"utf-8\", \"replace\")\n  subs = int(re.search(r\"([\\d\\s,.]+)\\s*subscribers\", html).group(1)\n             .replace(\" \", \"\").replace(\",\", \"\").replace(\".\", \"\"))\n  ```\n  Returns the real count even with 4 subscribers; no login, no token.\n- **Metric pattern:** append daily `{\"date\": \"…\", \"subs\": N}` to an append-only\n  JSONL (e.g. `~\u002F.hermes\u002Fcortexcloud-posts\u002Fmetrics.json`), print today's value\n  with delta vs the previous day's entry. Baseline on first run is the honest\n  counter — never fabricate counts.\n- Per-post VIEW counts are NOT retrievable via bot API for historical posts\n  (no admin, no user session) — say so instead of inventing engagement numbers.\n\n## The critical distinction: bot token vs user session\n\nHermes' Telegram integration usually runs on a **bot token**\n(`TELEGRAM_BOT_TOKEN` in `~\u002F.hermes\u002F.env`). A bot **cannot**:\n- Join \u002F subscribe to a channel on the user's behalf (there is no\n  `joinChannel` API for bots).\n- Read arbitrary channels' history. A bot only sees messages in chats where a\n  channel admin explicitly added it, and even then history access is limited.\n\nSo \"subscribe me to @X\" or \"read @X for me\" is **not doable with the bot**.\nSay so plainly, then offer the two real options:\n1. **User joins the channel themselves** (5 seconds) — sufficient if Hermes\n   doesn't need to process the content.\n2. **Set up a telethon USER session** — required whenever Hermes must\n   programmatically read\u002Fmonitor the channel's content. This logs in AS the\n   user's account (api_id\u002Fapi_hash), which can read anything the user can see.\n\nFlag the power\u002Fscope tradeoff: a user session acts as the user's account. Scope\nyour scripts to **read-only** (iter_messages) for monitoring use cases, and\nstore credentials root-only.\n\n## Setup workflow (user session)\n\n1. **User gets API credentials from my.telegram.org** (only they can — tied to\n   their account, not the bot): https:\u002F\u002Fmy.telegram.org → API development tools\n   → create an app → copy `api_id` (number) and `api_hash` (string).\n\n2. **Store creds root-only** (per user rule: ask before storing sensitive\n   data). Write to e.g. `~\u002F.hermes\u002Ftelegram_user.env`, then `chmod 600`:\n   ```\n   TELEGRAM_API_ID=\u003Cid>\n   TELEGRAM_API_HASH=\u003Chash>\n   ```\n\n3. **Install telethon + python-dotenv into a venv.** On Debian, `python3 -m\n   venv` may produce a venv WITHOUT pip — use `uv`:\n   ```bash\n   uv pip install --python ~\u002F.hermes\u002Fgoogle-venv\u002Fbin\u002Fpython telethon python-dotenv\n   ```\n   (Reuse an existing venv, e.g. the google-venv, or make a dedicated one.)\n\n4. **One-time login creates the session file.** This needs the user's phone\n   number + the login code Telegram sends them. Do NOT use interactive\n   `input()`\u002FPTY — it fails with EOF and the code expires during the relay.\n   Use the file-polling login (`scripts\u002Flogin_wait.py`): run it in the\n   background, tell the user to check Telegram, then write their code to\n   `\u002Ftmp\u002Ftg_code` the instant they send it. See the login pitfalls below.\n\n5. **Read-only reader** uses `client.iter_messages(target, limit=N)` where\n   `target` is `@username` or a `https:\u002F\u002Ft.me\u002F...` URL. The session persists\n   after first login; subsequent reads are non-interactive.\n\nReady-to-use starter files:\n- `scripts\u002Fscrape_channel.py` — PUBLIC channel scraper (no auth). Try this\n  FIRST; uses `t.me\u002Fs\u002F\u003Cchannel>` + stdlib html.parser. Avoids the login-code\n  problem entirely.\n- `scripts\u002Fread_channel.py` — read-only recent-message fetcher.\n- `scripts\u002Flogin_wait.py` — RECOMMENDED session creator: no PTY\u002Fstdin, polls\n  `\u002Ftmp\u002Ftg_code` for the code (and `\u002Ftmp\u002Ftg_pw` for a 2FA password). Set phone\n  via `TG_PHONE` env.\n- `scripts\u002Flogin.py` — legacy interactive creator; prone to the EOF\u002Fexpiry\n  pitfalls below. Prefer `login_wait.py`.\n\n## Pitfalls\n\n- **Promising a bot can subscribe\u002Fread a channel.** It cannot. Check\n  `~\u002F.hermes\u002F.env` for `TELEGRAM_BOT_TOKEN` vs user-session creds first, and set\n  expectations before attempting anything.\n- **Interactive login EOF — PTY is NOT reliable.** telethon's default\n  `input('Please enter your phone...')` throws `EOFError: EOF when reading a\n  line` via heredoc\u002Fnon-PTY exec. But `pty=true` did NOT fix it either in\n  practice — the terminal's PTY did not feed typed stdin to `input()`, so it\n  still hit EOF. **Do not rely on PTY interactive input.** Use the\n  file-polling pattern instead (see `scripts\u002Flogin_wait.py`): the script calls\n  `send_code_request`, captures `phone_code_hash`, then polls a temp file (e.g.\n  `\u002Ftmp\u002Ftg_code`) for up to ~120s; the agent writes the code to that file the\n  instant the user sends it, and sign-in happens in the SAME process with the\n  fresh hash. Zero typing gap, zero PTY dependency.\n- **Login codes expire fast AND each request invalidates the previous.** The\n  #1 login failure here was `PhoneCodeExpiredError` \u002F `PhoneCodeInvalidError`\n  from a multi-turn relay: agent requests code in turn 1, user reads SMS and\n  replies in turn 3, agent signs in in turn 5 — by then the ~1-2 min window has\n  passed. Worse, every extra `send_code_request` you fire generates a NEW code\n  and INVALIDATES the prior one, so probing \"did the code send?\" repeatedly\n  burns codes. Rules: (a) request the code and sign in within ONE process\n  (send_code_request → sign_in with that run's `phone_code_hash`); (b) never\n  call `send_code_request` again \"to check\" — it kills the code the user is\n  about to give you; (c) use the file-polling script so the sign-in fires the\n  moment the code arrives, not a turn later.\n- **`sign_in` needs `phone_code_hash`.** A one-shot script that only does\n  `sign_in(phone, code)` fails with `ValueError: You also need to provide a\n  phone_code_hash`. Capture the hash from the `send_code_request` return value\n  in the same run and pass it: `sign_in(phone, code, phone_code_hash=r.phone_code_hash)`.\n- **2FA fallback.** If the account has two-step verification, `sign_in` after\n  the code raises a password error — catch it and call\n  `sign_in(password=\u003Cpw>)`. Have the login script accept an optional password\n  arg so you don't need a second round-trip.\n- **Missing python-dotenv.** If the login\u002Fread script uses `load_dotenv`,\n  install `python-dotenv` in the SAME interpreter. `No module named 'dotenv'`\n  means it landed in a different env — install with\n  `uv pip install --python \u003Cvenv>\u002Fbin\u002Fpython python-dotenv`.\n- **Session file is a credential.** `~\u002F.hermes\u002F*.session` grants account\n  access — keep it root-only, never commit or move it off-host.\n",{},"main","38b32c99e7ed0b8e215d638e92cfa452c1ec3079","skills\u002Fimported\u002F.archive\u002Ftelegram-user-session-reading","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS","https:\u002F\u002Fgithub.com\u002Fjonahthan433","AI Consultant","2026-10-24 05:13:39",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add jonahthan433\u002FCortexOS --skill telegram-user-session-reading",{"tool":35,"command":36},"bunx","bunx skills add jonahthan433\u002FCortexOS --skill telegram-user-session-reading",{"tool":38,"command":39},"pnpm","pnpm dlx skills add jonahthan433\u002FCortexOS --skill telegram-user-session-reading","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002F.archive\u002Ftelegram-user-session-reading\u002FSKILL.md",true,[43],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"skill.json","REFERENCE","参考文档",605,"https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002F.archive\u002Ftelegram-user-session-reading\u002Fskill.json",[50,56,62,68,74,80],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M7EDQZDQX3Q8Y7GCQX6KN9V7","opportunity-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fsales\u002Fopportunity-brief\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7EDQYA0V9Y99VKBREJJ3MRT","morning-intel","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fmorning-intel\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7EDQVX1JVY0B6PDHKKGM19G","decision-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fdecision-brief\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7EDQV1GENZAC2SZSD8KZ3GM","weekly-review","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fproductivity\u002Fweekly-review\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M7EDQT2KETJ1Y3CGVN9EKW2J","system-health","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fsystem-health\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M7EDQQN2JK3XPWMS1M4T0F3K","backup-restore","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fbackup-restore\u002FSKILL.md",[],[]]