TelegramBot.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\Components;
  3. use App\Http\Models\EmailLog;
  4. use Log;
  5. use Telegram\Bot\Api;
  6. /**
  7. * Telegram操作类
  8. *
  9. * Class Telegram
  10. *
  11. * @package App\Components
  12. */
  13. class TelegramBot
  14. {
  15. public static function send($title, $content)
  16. {
  17. if (Helpers::systemConfig()['is_telegram']) {
  18. $telegram = new Api(Helpers::systemConfig()['telegram_token']);
  19. try {
  20. $response = $telegram->sendMessage([
  21. 'chat_id' => Helpers::systemConfig()['telegram_chatid'],
  22. 'text' => $content,
  23. 'parse_mode' => 'Markdown'
  24. ]);
  25. if ($response->getMessageId()) {
  26. self::addLog($title, $content);
  27. } else {
  28. self::addLog($title, $content, 0, 'Telegram消息推送失败');
  29. }
  30. } catch (\Exception $e) {
  31. Log::error('Telegram消息推送异常:' . $e);
  32. }
  33. } else {
  34. Log::error('消息推送失败:未启用或未正确配置Telegram');
  35. }
  36. }
  37. /**
  38. * 添加Telegram推送日志
  39. *
  40. * @param string $title 标题
  41. * @param string $content 内容
  42. * @param int $status 投递状态
  43. * @param string $error 投递失败时记录的异常信息
  44. *
  45. * @return int
  46. */
  47. private static function addLog($title, $content, $status = 1, $error = '')
  48. {
  49. $code = Helpers::makeEmailLogCode();
  50. $log = new EmailLog();
  51. $log->type = 4;
  52. $log->code = $code;
  53. $log->address = 'admin';
  54. $log->title = $title;
  55. $log->content = $content;
  56. $log->status = $status;
  57. $log->error = $error;
  58. return $log->save();
  59. }
  60. }