TelegramBot.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. /**
  3. * Telegram Bot
  4. *
  5. * @author mybsdc <[email protected]>
  6. * @date 2020/2/3
  7. * @time 15:23
  8. */
  9. namespace Luolongfei\Libs\MessageServices;
  10. use GuzzleHttp\Client;
  11. use Luolongfei\Libs\Log;
  12. use Luolongfei\Libs\Connector\MessageGateway;
  13. class TelegramBot extends MessageGateway
  14. {
  15. const TIMEOUT = 33;
  16. /**
  17. * @var string chat_id
  18. */
  19. protected $chatID;
  20. /**
  21. * @var string 机器人令牌
  22. */
  23. protected $token;
  24. /**
  25. * @var string Telegram 主机地址
  26. */
  27. protected $host;
  28. /**
  29. * @var Client
  30. */
  31. protected $client;
  32. public function __construct()
  33. {
  34. $this->chatID = config('message.telegram.chat_id');
  35. $this->token = config('message.telegram.token');
  36. $this->host = $this->getTelegramHost();
  37. $this->client = new Client([
  38. 'headers' => [
  39. 'Content-Type' => 'application/x-www-form-urlencoded'
  40. ],
  41. 'cookies' => false,
  42. 'timeout' => self::TIMEOUT,
  43. 'verify' => config('verify_ssl'),
  44. 'debug' => config('debug'),
  45. 'proxy' => config('message.telegram.proxy'),
  46. ]);
  47. }
  48. /**
  49. * 获取 Telegram 主机地址
  50. *
  51. * @return string
  52. */
  53. private function getTelegramHost()
  54. {
  55. $host = (string)config('message.telegram.host');
  56. if (preg_match('/^(?:https?:\/\/)?(?P<host>[^\/?\n]+)/iu', $host, $m)) {
  57. return $m['host'];
  58. }
  59. return 'api.telegram.org';
  60. }
  61. /**
  62. * 生成域名状态 MarkDown 完整文本
  63. *
  64. * @param string $username
  65. * @param array $domainStatus
  66. *
  67. * @return string
  68. */
  69. public function genDomainStatusFullMarkDownText(string $username, array $domainStatus)
  70. {
  71. $markDownText = sprintf(lang('100102'), $username);
  72. $markDownText .= $this->genDomainStatusMarkDownText($domainStatus);
  73. $markDownText .= $this->getMarkDownFooter();
  74. return $markDownText;
  75. }
  76. /**
  77. * 获取 MarkDown 页脚
  78. *
  79. * @return string
  80. */
  81. public function getMarkDownFooter()
  82. {
  83. $footer = '';
  84. $footer .= lang('100103');
  85. return $footer;
  86. }
  87. /**
  88. * 生成域名状态 MarkDown 文本
  89. *
  90. * @param array $domainStatus
  91. *
  92. * @return string
  93. */
  94. public function genDomainStatusMarkDownText(array $domainStatus)
  95. {
  96. if (empty($domainStatus)) {
  97. return lang('100105');
  98. }
  99. $domainStatusMarkDownText = '';
  100. foreach ($domainStatus as $domain => $daysLeft) {
  101. $domainStatusMarkDownText .= sprintf(lang('100106'), $domain, $domain, $daysLeft);
  102. }
  103. $domainStatusMarkDownText = rtrim(rtrim($domainStatusMarkDownText, ' '), ",,\n") . lang('100107');
  104. return $domainStatusMarkDownText;
  105. }
  106. /**
  107. * 生成域名续期结果 MarkDown 文本
  108. *
  109. * @param string $username
  110. * @param array $renewalSuccessArr
  111. * @param array $renewalFailuresArr
  112. * @param array $domainStatus
  113. *
  114. * @return string
  115. */
  116. public function genDomainRenewalResultsMarkDownText(string $username, array $renewalSuccessArr, array $renewalFailuresArr, array $domainStatus)
  117. {
  118. $text = sprintf(lang('100108'), $username);
  119. if ($renewalSuccessArr) {
  120. $text .= lang('100109');
  121. $text .= $this->genDomainsMarkDownText($renewalSuccessArr);
  122. }
  123. if ($renewalFailuresArr) {
  124. $text .= lang('100110');
  125. $text .= $this->genDomainsMarkDownText($renewalFailuresArr);
  126. }
  127. $text .= lang('100111');
  128. $text .= $this->genDomainStatusMarkDownText($domainStatus);
  129. $text .= $this->getMarkDownFooter();
  130. return $text;
  131. }
  132. /**
  133. * 生成域名 MarkDown 文本
  134. *
  135. * @param array $domains
  136. *
  137. * @return string
  138. */
  139. public function genDomainsMarkDownText(array $domains)
  140. {
  141. $domainsMarkDownText = '';
  142. foreach ($domains as $domain) {
  143. $domainsMarkDownText .= sprintf("[%s](http://%s) ", $domain, $domain);
  144. }
  145. $domainsMarkDownText = trim($domainsMarkDownText, ' ') . "\n";
  146. return $domainsMarkDownText;
  147. }
  148. /**
  149. * 获取 MarkDown 表格映射的原始数组
  150. *
  151. * @param string $markDownTable
  152. *
  153. * @return array
  154. */
  155. public function getMarkDownRawArr(string $markDownTable)
  156. {
  157. $rawArr = [];
  158. $markDownTableArr = preg_split("/(?:\n|\r\n)+/", $markDownTable);
  159. foreach ($markDownTableArr as $row) {
  160. $row = (string)preg_replace('/^\s+|\s+$|\s+|(?<=\|)\s+|\s+(?=\|)/', '', $row);
  161. if ($row === '') {
  162. continue;
  163. }
  164. $rowArr = explode('|', trim($row, '|'));
  165. $rawArr[] = $rowArr;
  166. }
  167. return $rawArr;
  168. }
  169. /**
  170. * 送信
  171. *
  172. * @param string $content 支持 markdown 语法,但记得对非标记部分进行转义
  173. * @param string $subject
  174. * @param integer $type
  175. * @param array $data
  176. * @param string|null $recipient 可单独指定 chat_id 参数
  177. * @param mixed ...$params
  178. *
  179. * @desc
  180. * 注意对 markdown 标记占用的字符进行转义,否则无法正确发送,根据官方说明,以下字符如果不想被 Telegram Bot 识别为 markdown 标记,
  181. * 应转义后传入,官方说明如下:
  182. * In all other places characters '_‘, ’*‘, ’[‘, ’]‘, ’(‘, ’)‘, ’~‘, ’`‘, ’>‘, ’#‘, ’+‘, ’-‘, ’=‘, ’|‘,
  183. * ’{‘, ’}‘, ’.‘, ’!‘ must be escaped with the preceding character ’\'.
  184. * 如果不转义则电报返回 400 错误
  185. *
  186. * 官方markdown语法示例:
  187. * *bold \*text*
  188. * _italic \*text_
  189. * __underline__
  190. * ~strikethrough~
  191. * *bold _italic bold ~italic bold strikethrough~ __underline italic bold___ bold*
  192. * [inline URL](http://www.example.com/)
  193. * [inline mention of a user](tg://user?id=123456789)
  194. * `inline fixed-width code`
  195. * ```
  196. * pre-formatted fixed-width code block
  197. * ```
  198. * ```python
  199. * pre-formatted fixed-width code block written in the Python programming language
  200. * ```
  201. * 需要注意的是,普通 markdown 语法中加粗字体使用的是“**正文**”的形式,但是 Telegram Bot 中是“*加粗我*”的形式
  202. * 更多相关信息请参考官网:https://core.telegram.org/bots/api#sendmessage
  203. * 另外我干掉了“_”、“~”、“-”、“.”和“>”关键字,分别对应斜体、删除线、无序列表、有序列表和引用符号,因为这几个比较容易在正常文本里出现,而
  204. * 我又不想每次都手动转义传入,故做了自动转义处理,况且 telegram 大多不支持
  205. *
  206. * 由于 telegram bot 的 markdown 语法不支持表格(https://core.telegram.org/bots/api#markdownv2-style),故表格部分由我自行解析
  207. * 为字符形式的表格,坐等 telegram bot 支持表格
  208. *
  209. * @return bool
  210. */
  211. public function send(string $content, string $subject = '', int $type = 1, array $data = [], ?string $recipient = null, ...$params)
  212. {
  213. $this->check($content, $data);
  214. $commonFooter = '';
  215. if ($type === 1 || $type === 4) {
  216. $this->setCommonFooter($commonFooter, "\n", false);
  217. } else if ($type === 2) {
  218. $this->setCommonFooter($commonFooter, "\n", false);
  219. $content = $this->genDomainRenewalResultsMarkDownText($data['username'], $data['renewalSuccessArr'], $data['renewalFailuresArr'], $data['domainStatusArr']);
  220. } else if ($type === 3) {
  221. $this->setCommonFooter($commonFooter);
  222. $content = $this->genDomainStatusFullMarkDownText($data['username'], $data['domainStatusArr']);
  223. } else {
  224. throw new \Exception(lang('100003'));
  225. }
  226. $content .= $commonFooter;
  227. $isMarkdown = true;
  228. // 使用可变参数控制 telegram 送信类型,一般不会用到
  229. if ($params && isset($params[1]) && $params[0] === 'TG') {
  230. $isMarkdown = $params[1];
  231. }
  232. if ($subject !== '') {
  233. $content = $subject . "\n\n" . $content;
  234. }
  235. if ($isMarkdown) {
  236. // 这几个比较容易在正常文本里出现,而我不想每次都手动转义传入,所以直接干掉了
  237. $content = preg_replace('/([.>~_{}|`!+=#-])/u', '\\\\$1', $content);
  238. // 转义非链接格式的 [] 以及 ()
  239. $content = preg_replace_callback_array(
  240. [
  241. '/(?<!\\\\)\[(?P<brackets>.*?)(?!\]\()(?<!\\\\)\]/' => function ($match) {
  242. return '\\[' . $match['brackets'] . '\\]';
  243. },
  244. '/(?<!\\\\)(?<!\])\((?P<parentheses>.*?)(?<!\\\\)\)/' => function ($match) {
  245. return '\\(' . $match['parentheses'] . '\\)';
  246. }
  247. ],
  248. $content
  249. );
  250. }
  251. try {
  252. $resp = $this->client->post(
  253. sprintf('https://%s/bot%s/sendMessage', $this->host, $this->token),
  254. [
  255. 'form_params' => [
  256. 'chat_id' => $recipient ?: $this->chatID,
  257. 'text' => $content, // Text of the message to be sent, 1-4096 characters after entities parsing
  258. 'parse_mode' => $isMarkdown ? 'MarkdownV2' : 'HTML',
  259. 'disable_web_page_preview' => true,
  260. 'disable_notification' => false
  261. ],
  262. ]
  263. );
  264. $resp = json_decode((string)$resp->getBody(), true);
  265. return $resp['ok'] ?? false;
  266. } catch (\Exception $e) {
  267. system_log(sprintf(lang('100112'), $e->getMessage()));
  268. return false;
  269. }
  270. }
  271. }