ilang-ai commited on
Commit ·
5c153bd
1
Parent(s): fa6f6d3
Tidy: drop vestigial device field + rewrite READMEs for the flagship
Browse files- chat.py/bot.py: remove the dead 'device' field left over from the old
node/device-onboarding contract; _parse and the AI handlers now return
(intent, reply) 2-tuples. py_compile clean, no behavior change (device was
always None and never acted on).
- README.md / README_CN.md: full rewrite for the antispam.bot flagship —
clean brand voice matching the landing page, 'engine behind antispam.bot'
positioning, a proper env-var config table, and accurate architecture.
All setup paths already use AI_API_KEY; HF front-matter preserved.
Files changed (4)
- README.md+59-56
- README_CN.md+60-57
- bot.py+8-8
- modules/chat.py+12-12
16 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171185 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315410 unmodified lines16516616716816917017117217317417517616 unmodified lines# 🛡️ TelegramGuard**AI group guardian that actually answers your questions.**Anti-spam. Vision. Chat. Zero config, free forever.[](LICENSE)[](https://ilang.ai)[](#host-your-own)**[English](README.md)** | **[中文](README_CN.md)**</div>---## Use It Now (Zero Setup)Add the official bot to your Telegram group. No install, no config, no cost.**[@iLangGuardBot](https://t.me/iLangGuardBot)**1. Open Telegram, search `@iLangGuardBot`2. Add it to your group3. Grant admin permissions (delete messages + ban users)4. Done. Spam protection is automatic.You can also DM the bot directly for AI chat.---## What It Does**Anti-Spam** — AI three-step analysis detects ads, scams, crypto spam, porn, political propaganda. Sees through Unicode tricks, emoji stuffing, homophone substitution. Catches repeat flooding (same message 3+ times) with zero AI cost. Bans and deletes all recent messages in parallel.**Vision** — Reads images and video thumbnails. Catches image spam. In chat mode, analyzes what's really happening in a photo, not just describing objects.**Chat** — @ the bot in any group or DM privately. Multilingual, auto-detects your language. Ask it anything and get a clear, useful answer — factual on sensitive topics, sensible boundaries on genuinely harmful ones.---## Host Your Own### Option 1: VPS (One Command)```bashcurl -sL https://raw.githubusercontent.com/ilang-ai/TelegramGuard/main/install.sh | sudo bash```The script handles everything: clone, dependencies, token setup, systemd service, auto-start.You need two things:- **Bot Token** — open Telegram → [@BotFather](https://t.me/BotFather) → `/newbot`- **AI API Key** — any OpenAI-compatible provider. Default targets [SiliconFlow](https://cloud.siliconflow.cn) (cheap, no VPN needed in China); OpenAI / DeepSeek / a local model work too. Override the endpoint with `AI_BASE_URL` and `AI_MODEL`.After install:```bashsystemctl status telegramguard # check statussystemctl restart telegramguard # restartjournalctl -u telegramguard -f # live logs```### Option 2: HuggingFace Space (Free, No Server)1. Fork this repo2. Create a [HuggingFace Space](https://huggingface.co/new-space) → Docker SDK → Blank3. GitHub repo Settings → Secrets → add `HF_TOKEN` (your HF write token)4. HF Space Settings → Secrets → add `BOT_TOKEN` + `AI_API_KEY`5. Push to GitHub triggers auto-deploy to HF### Option 3: Manual```bashgit clone https://github.com/ilang-ai/TelegramGuard.gitcd TelegramGuardpip install -r requirements.txtcp .env.example .env # fill in BOT_TOKEN + AI_API_KEY (defaults to SiliconFlow; edit AI_BASE_URL/AI_MODEL for another provider)set -a; source .env; set +a # load .env into the environmentpython bot.py```See [`.env.example`](.env.example) for every tunable (vision models, audio model, spam thresholds).---## Customize the AIThe bot's brain lives in `.ilang` files using [I-Lang Prompt Spec](https://ilang.ai):```prompts_demo/├── persona.ilang How it thinks + how it talks├── antispam.ilang What counts as spam└── vision.ilang How it reads images```Each file contains `::GENE` definitions that control behavior:```::GENE_IMMUTABLE{S002, T:RUTHLESS_RED_TEAM, A:FLATTER⇒FAIL, G:ALL, Θ:ALWAYS}# Show it a plan and it hunts the fatal flaw instead of praising.5 unmodified lines# Ads / scams / flooding → delete + strike, see through evasion.```Change the genes, change the bot. To customize: copy `prompts_demo/` to `prompts/`, edit. The bot loads `prompts/` first.**[Learn I-Lang Prompt Spec →](https://ilang.ai)**---## BotFather SetupAfter creating your bot, send to [@BotFather](https://t.me/BotFather):```/setjoingroups → Enable/setprivacy → Disable```---## Architecture```TelegramGuard/├── bot.py Core (group + private + events)├── config.py Env vars├── install.sh One-line VPS installer├── Dockerfile HF Space deployment├── modules/│ ├── ai_provider.py OpenAI-compatible AI layer (text · vision · audio)│ ├── chat.py Prompt orchestration (loads .ilang)10 unmodified lines<div align="center">Built with **[I-Lang Prompt Spec](https://ilang.ai)** — structured AI instructions using genetic code.[](https://github.com/ilang-ai/ilang-spec)[](https://ilang.ai)[](https://huggingface.co/i-Lang)MIT | [iLang Inc.](https://eastsoft.com) | [I-Lang Research](https://research.ilang.ai)</div>16 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311325 unmodified lines13813914014114214314414514614714814915015115215315415515615710 unmodified lines16816917017117217317417517617717817916 unmodified lines# 🛡️ TelegramGuard**The open-source engine behind [antispam.bot](https://antispam.bot)**The AI guardian that keeps your Telegram groups clean — and actually answers your questions.Zero config, free forever, self-hostable.[](LICENSE)[](https://ilang.ai)[](#self-host)**[English](README.md)** · **[中文](README_CN.md)** · **[antispam.bot](https://antispam.bot)**</div>---## Add it to your group (zero setup)Add the official bot — no install, no config, no cost.### → [@iLangGuardBot](https://t.me/iLangGuardBot)1. Search `@iLangGuardBot` on Telegram2. Add it to your group3. Give it admin — **delete messages** + **ban users**4. Done. Spam is cleaned automatically; @ it anytime with a question.You can also DM it directly for AI chat.---## What it does**🚫 Anti-Spam** — Catches ads, scams, crypto & gambling spam. Sees through Unicode lookalikes, full-width and zero-width tricks, emoji stuffing and slang. A zero-cost pre-filter kills the obvious stuff before it ever reaches the AI, and repeat-flooding is caught with no AI call at all.**👁️ Vision** — Reads images and video thumbnails to catch image-based ads and QR-code scams. In chat, it reads the story behind a photo, not just the pixels.**💬 Chat** — @ it in any group or DM it privately. Multilingual, auto-detects your language. Ask it anything and get a clear, useful answer — factual on sensitive topics, with sensible boundaries on genuinely harmful ones.---## Self-HostBring any **OpenAI-compatible** AI provider — [SiliconFlow](https://cloud.siliconflow.cn) (default), OpenAI, DeepSeek, or a local model. You need two things:- **Bot Token** — [@BotFather](https://t.me/BotFather) → `/newbot`- **AI API Key** — from your provider (default targets SiliconFlow)### Option 1 — VPS (one command)```bashcurl -sL https://raw.githubusercontent.com/ilang-ai/TelegramGuard/main/install.sh | sudo bash```Clones, installs dependencies, prompts for your two keys, and runs as a systemd service. Manage it with:```bashsystemctl status telegramguard # statussystemctl restart telegramguard # restartjournalctl -u telegramguard -f # live logs```### Option 2 — HuggingFace Space (free, no server)1. Fork this repo2. Create a [HuggingFace Space](https://huggingface.co/new-space) → Docker SDK → Blank3. GitHub repo → Settings → Secrets → add `HF_TOKEN` (your HF write token)4. HF Space → Settings → Secrets → add `BOT_TOKEN` + `AI_API_KEY`5. Push to GitHub — it auto-deploys to the Space### Option 3 — Manual```bashgit clone https://github.com/ilang-ai/TelegramGuard.gitcd TelegramGuardpip install -r requirements.txtcp .env.example .env # fill in BOT_TOKEN + AI_API_KEYset -a; source .env; set +a # load .env into the environmentpython bot.py```After creating your bot, send to [@BotFather](https://t.me/BotFather): `/setjoingroups → Enable` and `/setprivacy → Disable` (so it can see group messages).### ConfigurationEverything is set via environment variables — see [`.env.example`](.env.example):| Variable | Default | Purpose ||----------|---------|---------|| `BOT_TOKEN` | *(required)* | Telegram bot token || `AI_API_KEY` | *(required)* | OpenAI-compatible API key || `AI_BASE_URL` | `https://api.siliconflow.cn/v1` | Provider endpoint || `AI_MODEL` | `deepseek-ai/DeepSeek-V4-Flash` | Text model || `AI_VISION_MODELS` | `Qwen/Qwen3-VL-30B…` | Vision fallback chain (comma-separated) || `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | Voice-message model || `AI_IMAGE_MAX_WIDTH` | `600` | Downscale width before vision calls || `LEXICON_HARD_THRESHOLD` | `6` | Slang pre-filter strictness (higher = stricter) |---## Customize the AIThe bot's brain lives in plain `.ilang` files — [I-Lang Prompt Spec](https://ilang.ai), where each `::GENE` defines a behavior.```prompts_demo/├── persona.ilang how it thinks + how it talks├── antispam.ilang what counts as spam└── vision.ilang how it reads images``````::GENE_IMMUTABLE{S002, T:RUTHLESS_RED_TEAM, A:FLATTER⇒FAIL, G:ALL, Θ:ALWAYS}# Show it a plan and it hunts the fatal flaw instead of praising.5 unmodified lines# Ads / scams / flooding → delete + strike, see through evasion.```Change the genes, change the bot. To customize: copy `prompts_demo/` to `prompts/` (loaded first) and edit.**[Learn I-Lang Prompt Spec →](https://ilang.ai)**---## Architecture```TelegramGuard/├── bot.py Entry — handlers (group · private · events)├── config.py Env config├── install.sh One-command VPS installer├── Dockerfile Container build├── modules/│ ├── ai_provider.py OpenAI-compatible AI layer (text · vision · audio)│ ├── chat.py Prompt orchestration (loads .ilang)10 unmodified lines<div align="center">Built with **[I-Lang Prompt Spec](https://ilang.ai)** — structured AI instructions as genetic code.[](https://github.com/ilang-ai/ilang-spec)[](https://ilang.ai)[](https://huggingface.co/i-Lang)MIT · © [iLang Inc.](https://eastsoft.com) · [antispam.bot](https://antispam.bot) · [ilang.ai](https://ilang.ai)</div>
1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051062 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611 unmodified line# 🛡️ TelegramGuard**真正回答问题的AI群管机器人**反垃圾 · 看图识别 · 智能对话 · 零配置[](LICENSE)[](https://ilang.ai)[](#自己部署)**[English](README.md)** | **[中文](README_CN.md)**</div>---## 直接使用(零成本零配置)把官方机器人拉进你的电报群, 立刻开始工作。不需要安装, 不需要服务器, 不花一分钱。**[@iLangGuardBot](https://t.me/iLangGuardBot)**1. 打开电报, 搜索 `@iLangGuardBot`2. 把它加到你的群里3. 给管理员权限(删消息 + 封人)4. 完事。反垃圾全自动。也可以直接私聊机器人, 什么都能问。---## 它能做什么**反垃圾** — AI三步分析, 识别广告、诈骗、加密货币spam、色情、政治宣传。能看穿Unicode变体、emoji混淆、谐音替代等花招。相同消息刷屏3次自动判定, 零AI成本。封人+删除全部近期消息, 并行执行。**看图** — 识别图片和视频缩略图。拦截图片类垃圾信息。聊天模式下, 分析照片背后真正发生了什么, 不是干巴巴描述物体。**聊天** — 在群里@它或者私聊。自动检测语言, 用你的语言回复。什么都能问, 给你清晰实用的回答 — 敏感话题客观陈述, 真正有害的事守住边界。---## 自己部署### 方式一: VPS一键安装```bashcurl -sL https://raw.githubusercontent.com/ilang-ai/TelegramGuard/main/install.sh | sudo bash```一行命令搞定: 下载代码、装依赖、填token、创建系统服务、自动启动。你需要准备两样东西:- **Bot Token** — 打开电报 → 找 [@BotFather](https://t.me/BotFather) → 发 `/newbot`- **AI API Key** — 任意 OpenAI 兼容的服务。默认用 [硅基流动](https://cloud.siliconflow.cn)(便宜、国内直连不用梯子);OpenAI / DeepSeek / 本地模型也行。换服务用 `AI_BASE_URL` 和 `AI_MODEL` 覆盖。装完后管理:```bashsystemctl status telegramguard # 看状态systemctl restart telegramguard # 重启journalctl -u telegramguard -f # 看日志```### 方式二: HuggingFace Space(免费, 不需要服务器)1. Fork 这个仓库2. 创建 [HuggingFace Space](https://huggingface.co/new-space) → Docker SDK → Blank3. GitHub仓库 Settings → Secrets → 加 `HF_TOKEN`4. HF Space Settings → Secrets → 加 `BOT_TOKEN` + `AI_API_KEY`5. 推代码自动部署### 方式三: 手动```bashgit clone https://github.com/ilang-ai/TelegramGuard.gitcd TelegramGuardpip install -r requirements.txtcp .env.example .env # 填 BOT_TOKEN + AI_API_KEY(默认硅基流动;换服务改 AI_BASE_URL/AI_MODEL)set -a; source .env; set +a # 把 .env 加载进环境变量python bot.py```所有可调项(识图模型、语音模型、反垃圾阈值)见 [`.env.example`](.env.example)。---## 自定义AI人格机器人的大脑是三个 `.ilang` 文件, 使用 [I-Lang Prompt Spec](https://ilang.ai) 编写:```prompts_demo/├── persona.ilang 思维方式 + 说话方式├── antispam.ilang 什么算垃圾信息└── vision.ilang 怎么看图```每个文件里的 `::GENE` 定义一个行为:```::GENE_IMMUTABLE{S002, T:RUTHLESS_RED_TEAM, A:FLATTER⇒FAIL, G:ALL, Θ:ALWAYS}# 给它看方案, 它不夸你, 直接找致命漏洞::GENE_MUTABLE{P002, T:CONCISE, G:ALL, Θ:ALWAYS}# 2-3 句话。先给答案, 后补细节, 零废话。2 unmodified lines# 广告 / 诈骗 / 刷屏 → 删除 + 记过, 看穿规避手法。```改基因 = 改机器人。想自定义: 复制 `prompts_demo/` 到 `prompts/`, 然后编辑。机器人优先加载 `prompts/`。**[学习 I-Lang Prompt Spec →](https://ilang.ai)**---## BotFather 设置创建机器人后, 给 [@BotFather](https://t.me/BotFather) 发:```/setjoingroups → Enable(允许加群)/setprivacy → Disable(让机器人能看到群消息)```---## 项目结构```TelegramGuard/├── bot.py 核心逻辑├── config.py 环境变量配置├── install.sh 一键安装脚本├── Dockerfile HF Space部署├── modules/│ ├── ai_provider.py OpenAI兼容 AI 层(文本·识图·语音)│ ├── chat.py 提示词编排(加载.ilang)│ ├── prefilter.py 零成本垃圾预过滤 + 三路分诊│ ├── lexicon.py 黑话/规避归一化 + 打分│ ├── ilang_judge.py I-Lang 判定函数│ ├── admin.py 群管理│ ├── db.py SQLite共享连接 + 异步锁│ └── database.py 数据表└── prompts_demo/ AI人格定义(.ilang文件)```---<div align="center">基于 **[I-Lang Prompt Spec](https://ilang.ai)** 构建 — 用基因代码定义AI行为[](https://github.com/ilang-ai/ilang-spec)[](https://ilang.ai)[](https://huggingface.co/i-Lang)MIT | [iLang Inc.](https://eastsoft.com) | [I-Lang Research](https://research.ilang.ai)</div>1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191202 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641 unmodified line# 🛡️ TelegramGuard**[antispam.bot](https://antispam.bot) 背后的开源引擎**守护你电报群的 AI —— 自动清垃圾广告,还能真正回答问题。零配置、永久免费、可自托管。[](LICENSE)[](https://ilang.ai)[](#自己部署)**[English](README.md)** · **[中文](README_CN.md)** · **[antispam.bot](https://antispam.bot)**</div>---## 加进群就能用(零配置)把官方机器人拉进群 —— 不用安装、不用服务器、不花钱。### → [@iLangGuardBot](https://t.me/iLangGuardBot)1. 在电报搜 `@iLangGuardBot`2. 加到你的群里3. 给管理员权限 —— **删消息** + **封人**4. 完事。垃圾自动清理;随时 @ 它提问。也可以直接私聊它,什么都能问。---## 它能做什么**🚫 反垃圾** — 识别广告、诈骗、加密货币与赌博 spam。看穿 Unicode 变体、全角/零宽字符、emoji 混淆和黑话。零成本预过滤在消息碰到 AI 之前就干掉明显垃圾,刷屏更是完全不花 AI 调用就拦下。**👁️ 看图** — 识别图片和视频缩略图,拦截图片广告和二维码诈骗。聊天时读的是照片背后的故事,不是干巴巴描述像素。**💬 聊天** — 在群里 @ 它或私聊。自动检测语言,用你的语言回复。什么都能问,给你清晰实用的回答 —— 敏感话题客观陈述,真正有害的事守住边界。---## 自己部署用任意 **OpenAI 兼容**的 AI 服务 —— [硅基流动](https://cloud.siliconflow.cn)(默认)、OpenAI、DeepSeek 或本地模型。你需要两样:- **Bot Token** — [@BotFather](https://t.me/BotFather) → `/newbot`- **AI API Key** — 你的服务商(默认对接硅基流动)### 方式一:VPS 一键安装```bashcurl -sL https://raw.githubusercontent.com/ilang-ai/TelegramGuard/main/install.sh | sudo bash```自动下载、装依赖、填两个 key、创建 systemd 服务并启动。管理命令:```bashsystemctl status telegramguard # 看状态systemctl restart telegramguard # 重启journalctl -u telegramguard -f # 看日志```### 方式二:HuggingFace Space(免费,不用服务器)1. Fork 这个仓库2. 创建 [HuggingFace Space](https://huggingface.co/new-space) → Docker SDK → Blank3. GitHub 仓库 → Settings → Secrets → 加 `HF_TOKEN`(你的 HF write token)4. HF Space → Settings → Secrets → 加 `BOT_TOKEN` + `AI_API_KEY`5. 推代码到 GitHub,自动部署到 Space### 方式三:手动```bashgit clone https://github.com/ilang-ai/TelegramGuard.gitcd TelegramGuardpip install -r requirements.txtcp .env.example .env # 填 BOT_TOKEN + AI_API_KEYset -a; source .env; set +a # 把 .env 加载进环境变量python bot.py```创建机器人后,给 [@BotFather](https://t.me/BotFather) 发 `/setjoingroups → Enable` 和 `/setprivacy → Disable`(让它能看到群消息)。### 配置项全部通过环境变量设置 —— 见 [`.env.example`](.env.example):| 变量 | 默认值 | 作用 ||------|--------|------|| `BOT_TOKEN` | *(必填)* | 电报机器人 token || `AI_API_KEY` | *(必填)* | OpenAI 兼容的 API key || `AI_BASE_URL` | `https://api.siliconflow.cn/v1` | 服务端点 || `AI_MODEL` | `deepseek-ai/DeepSeek-V4-Flash` | 文本模型 || `AI_VISION_MODELS` | `Qwen/Qwen3-VL-30B…` | 识图模型容错链(逗号分隔) || `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | 语音模型 || `AI_IMAGE_MAX_WIDTH` | `600` | 识图前压缩宽度 || `LEXICON_HARD_THRESHOLD` | `6` | 黑话预过滤严格度(越高越严) |---## 自定义 AI 人格机器人的大脑是几个 `.ilang` 文件 —— [I-Lang Prompt Spec](https://ilang.ai),每个 `::GENE` 定义一个行为。```prompts_demo/├── persona.ilang 怎么思考 + 怎么说话├── antispam.ilang 什么算垃圾└── vision.ilang 怎么看图``````::GENE_IMMUTABLE{S002, T:RUTHLESS_RED_TEAM, A:FLATTER⇒FAIL, G:ALL, Θ:ALWAYS}# 给它看方案, 它不夸你, 直接找致命漏洞。::GENE_MUTABLE{P002, T:CONCISE, G:ALL, Θ:ALWAYS}# 2-3 句话。先给答案, 后补细节, 零废话。2 unmodified lines# 广告 / 诈骗 / 刷屏 → 删除 + 记过, 看穿规避手法。```改基因 = 改机器人。想自定义:复制 `prompts_demo/` 到 `prompts/`(优先加载)再编辑。**[学习 I-Lang Prompt Spec →](https://ilang.ai)**---## 项目结构```TelegramGuard/├── bot.py 入口 —— 处理器(群 · 私聊 · 事件)├── config.py 环境变量配置├── install.sh 一键 VPS 安装脚本├── Dockerfile 容器构建├── modules/│ ├── ai_provider.py OpenAI兼容 AI 层(文本 · 识图 · 语音)│ ├── chat.py 提示词编排(加载 .ilang)│ ├── prefilter.py 零成本垃圾预过滤 + 三路分诊│ ├── lexicon.py 黑话/规避归一化 + 打分│ ├── ilang_judge.py I-Lang 判定函数│ ├── admin.py 群管理│ ├── db.py SQLite 共享连接 + 异步锁│ └── database.py 数据表└── prompts_demo/ AI 人格定义(.ilang 文件)```---<div align="center">基于 **[I-Lang Prompt Spec](https://ilang.ai)** 构建 —— 用基因代码定义 AI 行为。[](https://github.com/ilang-ai/ilang-spec)[](https://ilang.ai)[](https://huggingface.co/i-Lang)MIT · © [iLang Inc.](https://eastsoft.com) · [antispam.bot](https://antispam.bot) · [ilang.ai](https://ilang.ai)</div>
73 unmodified lines747576777879808 unmodified lines89909192939495207 unmodified lines30330430530630730830931010 unmodified lines32132232332432532632732810 unmodified lines33934034134234334434534673 unmodified linesreturn " | ".join(parts)async def _handle_ai_result(intent, device, reply, msg, user_id, context):history = context.user_data.setdefault("history", [])await msg.reply_text(reply)history.append({"role": "assistant", "text": reply})8 unmodified linesconfig.ADMIN_USER_ID = update.effective_user.idif update.effective_chat.type == "private":context.user_data["history"] = []intent, device, reply = await ai_text("/start",history=None,context_info="NEW_SESSION:User just opened chat, greet briefly, say what you can do"207 unmodified linesuser_id = msg.from_user.idhistory = context.user_data.setdefault("history", [])history.append({"role": "user", "text": msg.text})intent, device, reply = await ai_text(msg.text, history, _ctx_info(context))await _handle_ai_result(intent, device, reply, msg, user_id, context)async def handle_private_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):10 unmodified linesexcept Exception:await msg.reply_text("Didn't receive that image. Try again?")returnintent, device, reply = await ai_vision(img_bytes, caption, history, _ctx_info(context))await _handle_ai_result(intent, device, reply, msg, user_id, context)async def handle_private_voice(update: Update, context: ContextTypes.DEFAULT_TYPE):10 unmodified linesexcept Exception:await msg.reply_text("Didn't catch that voice message. Try again or just type it out.")returnintent, device, reply = await ai_voice(audio_bytes, mime, history, _ctx_info(context))await _handle_ai_result(intent, device, reply, msg, user_id, context)# ==================== Events ====================73 unmodified lines747576777879808 unmodified lines89909192939495207 unmodified lines30330430530630730830931010 unmodified lines32132232332432532632732810 unmodified lines33934034134234334434534673 unmodified linesreturn " | ".join(parts)async def _handle_ai_result(intent, reply, msg, user_id, context):history = context.user_data.setdefault("history", [])await msg.reply_text(reply)history.append({"role": "assistant", "text": reply})8 unmodified linesconfig.ADMIN_USER_ID = update.effective_user.idif update.effective_chat.type == "private":context.user_data["history"] = []intent, reply = await ai_text("/start",history=None,context_info="NEW_SESSION:User just opened chat, greet briefly, say what you can do"207 unmodified linesuser_id = msg.from_user.idhistory = context.user_data.setdefault("history", [])history.append({"role": "user", "text": msg.text})intent, reply = await ai_text(msg.text, history, _ctx_info(context))await _handle_ai_result(intent, reply, msg, user_id, context)async def handle_private_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):10 unmodified linesexcept Exception:await msg.reply_text("Didn't receive that image. Try again?")returnintent, reply = await ai_vision(img_bytes, caption, history, _ctx_info(context))await _handle_ai_result(intent, reply, msg, user_id, context)async def handle_private_voice(update: Update, context: ContextTypes.DEFAULT_TYPE):10 unmodified linesexcept Exception:await msg.reply_text("Didn't catch that voice message. Try again or just type it out.")returnintent, reply = await ai_voice(audio_bytes, mime, history, _ctx_info(context))await _handle_ai_result(intent, reply, msg, user_id, context)# ==================== Events ====================
26 unmodified lines272829303132336 unmodified lines404142434445462 unmodified lines495051525354552 unmodified lines58596061626364656667686970717229 unmodified lines1021031041051061071081091101111121136 unmodified lines1201211221231241251267 unmodified lines13413513613713813914028 unmodified lines1691701711721731741759 unmodified lines18518618718818919019126 unmodified linesVISION_PROMPT = _load_prompt("vision.ilang")if not SYSTEM_PROMPT:SYSTEM_PROMPT = "You are TelegramGuard, a helpful AI assistant on Telegram. Reply concisely in the user's language. JSON format: {\"intent\": \"chat\", \"device\": null, \"reply\": \"your text\"}"logger.warning("Using fallback system prompt")GROUP_WELCOME = (6 unmodified linesdef _parse(raw):if not raw:return ("chat", None, "...")t = raw.strip()if t.startswith("```"):nl = t.find("\n")2 unmodified linest = t[:-3].strip()try:d = json.loads(t)return (d.get("intent", "chat"), d.get("device"), d.get("reply", t))except json.JSONDecodeError:passlast_brace = t.rfind("}")2 unmodified linesif start >= 0:try:d = json.loads(t[start:last_brace + 1])return (d.get("intent", "chat"), d.get("device"), d.get("reply", t))except json.JSONDecodeError:passlast_brace = t.rfind("}", 0, last_brace)for line in t.split("\n"):line = line.strip()if line and not line.startswith("{") and not line.startswith("taint") and not line.startswith("The "):return ("chat", None, line)return ("chat", None, "...")def _ctx(history, info):29 unmodified linesprompt = c + "\nuser: " + text if c else "user: " + textraw = await ai_provider.generate_text(prompt, system=SYSTEM_PROMPT)if not raw:return ("chat", None, _deflect())logger.info("AI raw[" + str(len(raw)) + "]: " + raw[:200])return _parse(raw)except Exception as e:logger.warning("AI text exception: " + str(e))return ("chat", None, _deflect())async def ai_vision(image_bytes, caption="", history=None, context_info=""):6 unmodified linesreturn _parse(raw)except Exception as e:logger.warning("AI vision: " + str(e))return ("chat", None, "Couldn't read that image. Try another one?")async def ai_voice(audio_bytes, mime_type="audio/ogg", history=None, context_info=""):7 unmodified linesreturn _parse(raw)except Exception as e:logger.warning("AI voice: " + str(e))return ("chat", None, "Didn't catch that. Try again or type it out.")async def ai_judge_group_message(text):28 unmodified linesraw = (raw or "").strip()if not raw:return _deflect()intent, device, reply = _parse(raw)if reply in ("...", ""):return _deflect()return reply9 unmodified linesraw = (raw or "").strip()if not raw:return _deflect()intent, device, reply = _parse(raw)if reply in ("...", ""):return _deflect()return reply26 unmodified lines272829303132336 unmodified lines404142434445462 unmodified lines495051525354552 unmodified lines58596061626364656667686970717229 unmodified lines1021031041051061071081091101111121136 unmodified lines1201211221231241251267 unmodified lines13413513613713813914028 unmodified lines1691701711721731741759 unmodified lines18518618718818919019126 unmodified linesVISION_PROMPT = _load_prompt("vision.ilang")if not SYSTEM_PROMPT:SYSTEM_PROMPT = "You are TelegramGuard, a helpful AI assistant on Telegram. Reply concisely in the user's language. JSON format: {\"intent\": \"chat\", \"reply\": \"your text\"}"logger.warning("Using fallback system prompt")GROUP_WELCOME = (6 unmodified linesdef _parse(raw):if not raw:return ("chat", "...")t = raw.strip()if t.startswith("```"):nl = t.find("\n")2 unmodified linest = t[:-3].strip()try:d = json.loads(t)return (d.get("intent", "chat"), d.get("reply", t))except json.JSONDecodeError:passlast_brace = t.rfind("}")2 unmodified linesif start >= 0:try:d = json.loads(t[start:last_brace + 1])return (d.get("intent", "chat"), d.get("reply", t))except json.JSONDecodeError:passlast_brace = t.rfind("}", 0, last_brace)for line in t.split("\n"):line = line.strip()if line and not line.startswith("{") and not line.startswith("taint") and not line.startswith("The "):return ("chat", line)return ("chat", "...")def _ctx(history, info):29 unmodified linesprompt = c + "\nuser: " + text if c else "user: " + textraw = await ai_provider.generate_text(prompt, system=SYSTEM_PROMPT)if not raw:return ("chat", _deflect())logger.info("AI raw[" + str(len(raw)) + "]: " + raw[:200])return _parse(raw)except Exception as e:logger.warning("AI text exception: " + str(e))return ("chat", _deflect())async def ai_vision(image_bytes, caption="", history=None, context_info=""):6 unmodified linesreturn _parse(raw)except Exception as e:logger.warning("AI vision: " + str(e))return ("chat", "Couldn't read that image. Try another one?")async def ai_voice(audio_bytes, mime_type="audio/ogg", history=None, context_info=""):7 unmodified linesreturn _parse(raw)except Exception as e:logger.warning("AI voice: " + str(e))return ("chat", "Didn't catch that. Try again or type it out.")async def ai_judge_group_message(text):28 unmodified linesraw = (raw or "").strip()if not raw:return _deflect()intent, reply = _parse(raw)if reply in ("...", ""):return _deflect()return reply9 unmodified linesraw = (raw or "").strip()if not raw:return _deflect()intent, reply = _parse(raw)if reply in ("...", ""):return _deflect()return reply
README.md+59-56
README_CN.md+60-57
bot.py+8-8
modules/chat.py+12-12