LHL's Blog - Telegram Bot
type: channel
link: https://blog.lhl.one/tag/Telegram-Bot/
items: Typecho 插件 - TelegramNotice 评论与文章推送

Typecho 插件 - TelegramNotice 评论与文章推送
type: item
date: 2026-02-05T20:03:00+08:00
description: 鉴于很多Telegram推送插件不完善，于是做了这个插件。⚡ 功能✅ Telegram 机器人推送评论通知（支持多 Chat ID 群发、邮箱绑定、Telegram 回复评论、评论快捷审核）✅ Typecho 后台文章一键推送至Telegram🧩 截图 管理界面后台推送Bot 推送 移动端优化 💻 Github 地址🏗️ 整体架构插件主要由三个核心文件组成:Plugin.php - 插件主类,负责配置、评论监听和消息推送TelegramComment_Action.php - Action处理类,负责Webhook回调和管理接口push.php - 推送文章📋 核心实现流程1️⃣ 插件激活流程 (Plugin::activate)public static function activate(): string { Typecho\Plugin::factory('Widget_Feedback')->finishComment = __CLASS__ . '::onFinishComment'; Typecho\Plugin::factory('Widget_Comments_Edit')->finishComment = __CLASS__ . '::onFinishComment'; Utils\Helper::addAction('telegram-comment', 'TypechoPlugin\\TelegramNotice\\TelegramComment_Action'); try { $opt = Utils\Helper::options()->plugin('TelegramNotice'); $token = trim((string)($opt->botToken ?? '')); if ($token !== '') { self::ensureWebhookConfigured($token); } } catch (\Throwable $e) { // ignore } return _t('TelegramNotice 启用成功'); }关键动作:注册评论钩子 (finishComment),监听新评论和评论编辑注册自定义Action路由 /action/telegram-comment2️⃣ 评论推送流程 (Plugin::onFinishComment)public static function onFinishComment($comment) { $opt = Utils\Helper::options()->plugin('TelegramNotice'); $token = trim((string)($opt->botToken ?? '')); // ... 准备配置参数 // 1. 确保Webhook已配置 self::ensureWebhookConfigured($token); // 2. 渲染消息模板 $message = self::renderTemplate($tpl, $comment, $postTitle); // 3. 构建Inline Keyboard (审核按钮) $keyboard = [ 'inline_keyboard' => [ [ ['text' => '✅ 通过', 'callback_data' => "approve_{$comment->coid}"], ['text' => '🗑️ 标记垃圾', 'callback_data' => "spam_{$comment->coid}"], ['text' => '💬 回复', 'callback_data' => "reply_{$comment->coid}"], ] ] ]; // 4. 确定发送目标 // - 如果评论者邮箱有绑定chat_id -> 发给绑定的用户 // - 否则发给默认chat_id列表 $targetChatIds = self::resolveTargetChatIds($opt, $mail); // 5. 群发消息 foreach ($targetChatIds as $cid) { self::tgApi($token, 'sendMessage', [ 'chat_id' => $cid, 'text' => $message, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard) ]); } }推送逻辑:Webhook自动配置: 确保Telegram Webhook指向本站模板渲染: 替换 {title} {author} {text} 等变量Inline Keybo…