原理就是在新帖插入数据库后,通过调用 telegram bot 的 api 往 channel 发消息,具体步骤和代码如下:
-
创建一个电报 channel,直接在电报 App 上操作即可,就像微信建新群一样简单
-
创建一个电报 bot,并获取 bot 的 token,这个直接问 chatgpt:“如何开通 telegram bot 并获取 Bot_Token”,有详细步骤
-
将 bot 添加到 channel 并设为管理员,这个也直接问 chatgpt:“如何将 telegram bot 添加到 channel 并设为管理员”
-
bot 进 channel 后,在 channel 里发一条消息,然后用如下链接得到 channel 的 chatId:
https://api.telegram.org/bot${botToken}/getUpdates
然后在 https://gitee.com/Discuz/DiscuzX/blob/v3.5/upload/source/class/model/model_forum_thread.php#L219
添加如下代码:
if ( $this->param['pinvisible']===0 && $this->forum['fid']!=='5' ) {
try {
$msg = preg_replace('/\[[^\]]+\]/', '', $this->param['message']);
if (mb_strlen($msg, 'UTF-8') > 64) {
$msg = mb_substr($msg, 0, 64, 'UTF-8');
$msg .= '...';
}
$msg = str_replace(["\n", "\r\n"], " ", trim($msg));
$data = [
'chat_id' => $chatIdOfChannel,
'text' => "【新主题】
标题:{$this->param['subject']}
作者:{$this->member['username']}
内容:$msg
链接:https://shuzijumin.com/thread-{$this->tid}-1-1.html"
];
$ch = curl_init("https://api.telegram.org/bot{$botToken}/sendMessage");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_exec($ch);
curl_close($ch);
} catch (Exception $e) {}
}
在 https://gitee.com/Discuz/DiscuzX/blob/v3.5/upload/source/class/model/model_forum_post.php#L144
添加如下代码:
if ( $pinvisible===0 && $status===0 ) {
$threadInfo = C::t('forum_thread')->fetch_thread($this->thread['tid']);
try {
$msg = preg_replace('/\[[^\]]+\]/', '', $this->param['message']);
if (mb_strlen($msg, 'UTF-8') > 64) {
$msg = mb_substr($msg, 0, 64, 'UTF-8');
$msg .= '...';
}
$msg = str_replace(["\n", "\r\n"], " ", trim($msg));
$data = [
'chat_id' => $chatIdOfChannel,
'text' => "【新回帖】
原贴:{$threadInfo['subject']}
回复者:{$this->member['username']}
回复内容:$msg
链接:https://shuzijumin.com/forum.php?mod=redirect&goto=findpost&ptid={$this->thread['tid']}&pid={$this->pid}"
];
$ch = curl_init("https://api.telegram.org/bot{$botToken}/sendMessage");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_exec($ch);
curl_close($ch);
} catch (Exception $e) {}
}
这样每次发新主题或者回帖,电报 channel 都会有通知