| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- <?php
- namespace App\Repositories\Utils;
- use App\Repositories\ConfigRepoistory;
- use Hyperf\Guzzle\ClientFactory;
- use Psr\SimpleCache\CacheInterface;
- class TelegramRepository
- {
- /**
- * 缓存仓库
- * @var null|CacheInterface
- */
- private $cacheRepo = null;
- /**
- * http客户端仓库
- * @var null|\GuzzleHttp\Client
- */
- private $httpClient = null;
- private $configRepo = null;
- private $noticenterConfig = [];
- /**
- * 发送通用文本消息.
- * @param $content
- * @return bool
- * @throws \GuzzleHttp\Exception\GuzzleException
- */
- public function sendCommonText($content, $taskName = null)
- {
- $ntCofnig = $this->getNoticenterConfig();
- $uri = '/api/tg/send/common/text/message';
- $options = [
- 'query' => [
- 'AUTH-TOKEN' => $ntCofnig['token'],
- ],
- 'json' => [
- 'content' => $content,
- 'task_name' => $taskName,
- ],
- ];
- $ret = $this->getHttpClient()->post($uri, $options);
- $httpStatus = $ret->getStatusCode();
- $bodyRaw = $ret->getBody()->getContents();
- $result = [];
- if ($httpStatus == 200) {
- $arrResp = json_decode($bodyRaw, true);
- $result['code'] = $arrResp['code'];
- $result['message'] = $arrResp['message'];
- $result['data'] = $arrResp['data'];
- } else {
- logger('TelegramRepository-sendCommonText', ['http_status' => $httpStatus, 'body_raw' => $bodyRaw]);
- }
- return true;
- }
- /**
- * 获取消息中心配置.
- * @return array
- * @throws \Psr\SimpleCache\InvalidArgumentException
- */
- public function getNoticenterConfig()
- {
- if (empty($this->noticenterConfig)) {
- $baseUrl = $this->getConfigRepo()->get('tg_msg_server', 'sys', '');
- $token = $this->getConfigRepo()->get('tg_api_token', 'sys', '');
- $baseUrl = rtrim($baseUrl, '/'); // 干掉最后一个斜杆
- $this->noticenterConfig = [
- 'base_url' => $baseUrl,
- 'token' => $token,
- ];
- }
- return $this->noticenterConfig;
- }
- /**
- * @return \GuzzleHttp\Client|ClientFactory|null
- */
- private function getHttpClient()
- {
- if (!$this->httpClient instanceof ClientFactory) {
- $ntCofnig = $this->getNoticenterConfig();
- $baseUrl = rtrim($ntCofnig['base_url'], '/');
- $token = $ntCofnig['token'];
- $options = array(
- 'base_uri' => $baseUrl,
- 'timeout' => 15, // 超时,单位秒.
- 'verify' => false, // 是否校验SSL证书.
- 'http_errors' => false, // 如果跟随http异常头部是否中断.
- 'debug' => false, // 是否启用调试模式.
- 'allow_redirects' => false, // 不跟随301/302跳转.
- 'headers' => [
- 'AUTH-TOKEN' => $token,
- ],
- );
- $this->httpClient = make(ClientFactory::class)->create($options);
- }
- return $this->httpClient;
- }
- /**
- * @return ConfigRepoistory|mixed
- */
- private function getConfigRepo()
- {
- if (!$this->configRepo instanceof ConfigRepoistory) {
- $this->configRepo = make(ConfigRepoistory::class);
- }
- return $this->configRepo;
- }
- }
|