TelegramBot.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. <?php
  2. namespace App\Notification;
  3. use App\Util;
  4. use GuzzleHttp\Client;
  5. use Illuminate\Support\Facades\Request;
  6. use Longman\TelegramBot\Entities\Update;
  7. use Longman\TelegramBot\Exception\TelegramException;
  8. use Longman\TelegramBot\Telegram;
  9. class TelegramBot
  10. {
  11. const api_key='8489593650:AAEioF92HCRDd-mnDpTo-6imc_bdi1My1II';
  12. const username='@uswinBot';
  13. public $telegram;
  14. public function __construct(){
  15. try {
  16. $telegram = new Telegram(self::api_key, self::username);
  17. $mysql=['host' => env('DB_MYSQL_HOST', '127.0.0.1'),
  18. 'port' => env('DB_MYSQL_PORT', '3306'),
  19. 'database' => 'telegram',
  20. 'user' => env('DB_MYSQL_USERNAME'),
  21. 'password' => env('DB_MYSQL_PASSWORD'), ];
  22. $telegram->enableMySql($mysql);
  23. $this->telegram=$telegram;
  24. //// $result = $this->telegram->setWebhook("https://".$_SERVER["HTTP_HOST"]."/api/telehook");
  25. // $allowed_updates = [
  26. // Update::TYPE_MESSAGE,
  27. // Update::TYPE_CHANNEL_POST,
  28. // // etc.
  29. // ];
  30. // $this->telegram->handleGetUpdates(['allowed_updates' => $allowed_updates]);
  31. // if ($result->isOk()) {
  32. // echo $result->getDescription();
  33. // Util::WriteLog('telegram', $result->getDescription());
  34. // }
  35. }catch (TelegramException $e){
  36. Util::WriteLog('telegram','error:'.$e->getMessage());
  37. }
  38. }
  39. public function handle(){
  40. try {
  41. $update = json_decode(file_get_contents('php://input'), true);
  42. Util::WriteLog('telegram_update', json_encode($update, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
  43. return $this->telegram->handle();
  44. }catch (TelegramException $e){
  45. Util::WriteLog('telegram',$e);
  46. }
  47. }
  48. public function sendMsg($str){
  49. if(env('TELE_SENDOUT')){
  50. $url=env('TELE_SENDOUT');
  51. $client = new Client();
  52. $client->post( $url , [
  53. 'form_params' => ['str'=>$str], // 传递 POST 数据
  54. ]);
  55. return;
  56. }
  57. $str=substr($str,0,4000);
  58. try {
  59. \Longman\TelegramBot\Request::sendToActiveChats(
  60. 'sendMessage', // Callback function to execute (see Request.php methods)
  61. ['text' => $str], // Param to evaluate the request
  62. [
  63. 'groups' => true,
  64. 'supergroups' => true,
  65. 'channels' => false,
  66. 'users' => false,
  67. ]
  68. );
  69. }catch (\Exception $e){
  70. Util::WriteLog('telegram',$e->getMessage());
  71. }
  72. }
  73. /**
  74. * 定向发到「重要通知」群(.env:TELEGRAM_IMPORTANT_CHAT_IDS,逗号分隔多个 chat_id)。
  75. * 与 sendMsg 的 sendToActiveChats 不同:不依赖 telegram 库里的活跃会话表。
  76. */
  77. public function sendImportantMsg($str)
  78. {
  79. $str = substr((string) $str, 0, 4000);
  80. if ($str === '' || empty($this->telegram)) {
  81. return;
  82. }
  83. foreach ($this->importantChatIds() as $chatId) {
  84. try {
  85. \Longman\TelegramBot\Request::sendMessage([
  86. 'chat_id' => $chatId,
  87. 'text' => $str,
  88. ]);
  89. } catch (\Exception $e) {
  90. Util::WriteLog('telegram', 'important chat_id=' . $chatId . ' ' . $e->getMessage());
  91. }
  92. }
  93. }
  94. /** 老群广播 + 重要群各发一份(关键告警用) */
  95. public function sendMsgAndImportant($str)
  96. {
  97. $this->sendMsg($str);
  98. $this->sendImportantMsg($str);
  99. }
  100. public function sendProgramNotifyImportant($compName = '', $str = '', $contentArr = [])
  101. {
  102. $env = env('APP_ENV');
  103. $this->sendImportantMsg($env . " $compName 异常 ###\n [$str]\n" . json_encode($contentArr, JSON_PRETTY_PRINT));
  104. }
  105. /**
  106. * @return int[]
  107. */
  108. private function importantChatIds()
  109. {
  110. $raw = env('TELEGRAM_IMPORTANT_CHAT_IDS', '');
  111. if ($raw === null || $raw === '') {
  112. return [];
  113. }
  114. $parts = preg_split('/\s*,\s*/', (string) $raw, -1, PREG_SPLIT_NO_EMPTY);
  115. $ids = [];
  116. foreach ($parts as $p) {
  117. if (is_numeric($p)) {
  118. $ids[] = (int) $p;
  119. }
  120. }
  121. return $ids;
  122. }
  123. public function sendMsgWithEnv($str){
  124. if(is_array($str))$str=json_encode($str);
  125. $url=$_SERVER['REQUEST_SCHEME'].$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'].'?'.http_build_query(Request::all());
  126. $env = env('APP_ENV');//](".$url.")
  127. $str=$str."\n".'#### url:' . Request::getRequestUri() . "\n" .
  128. '#### params:' . json_encode(Request::all()) . "\n".(new \Exception())->getTraceAsString() ;
  129. $this->sendMsg($env .":". $str);
  130. }
  131. public function sendProgramNotify($compName="",$str="",$contentArr=[]){
  132. $env = env('APP_ENV');
  133. $this->sendMsg($env . " $compName 异常 ###\n [$str]\n".json_encode($contentArr,JSON_PRETTY_PRINT));
  134. }
  135. /**
  136. * @var TelegramBot
  137. */
  138. static private $_default=null;
  139. /**
  140. * @return TelegramBot
  141. */
  142. static public function getDefault(){
  143. if(!isset(self::$_default)||self::$_default==null)self::$_default=new TelegramBot();
  144. return self::$_default;
  145. }
  146. }