TelegramChannelService.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Database\Query\Builder;
  4. use Illuminate\Support\Facades\Crypt;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Storage;
  7. use Illuminate\Support\Facades\Log;
  8. use Illuminate\Support\Facades\Validator;
  9. use Illuminate\Validation\ValidationException;
  10. use RuntimeException;
  11. use Telegram\Bot\Api;
  12. use Telegram\Bot\Exceptions\TelegramResponseException;
  13. use Telegram\Bot\FileUpload\InputFile;
  14. class TelegramChannelService
  15. {
  16. public const LEGACY_FIELD = 'channel_message';
  17. public const VIEW = 'admin/telegramChannel/list';
  18. public const MANAGE = 'admin/telegramChannel/save';
  19. public const PUBLISH = 'admin/telegramChannel/publish';
  20. public function list(): array
  21. {
  22. return $this->joinedChannels()->orderBy('channels.id')
  23. ->get()
  24. ->map(fn ($row) => $this->present($row, (int) $row->default_channel_id === (int) $row->id))
  25. ->all();
  26. }
  27. public function detail(int $id): array
  28. {
  29. $row = $this->find($id);
  30. return $this->present($row, (int) $row->default_channel_id === $id, true);
  31. }
  32. public function save(#[\SensitiveParameter] array $input, bool $legacy = false): array
  33. {
  34. if (is_string($input['name'] ?? null)) {
  35. $input['name'] = trim($input['name']);
  36. if ($input['name'] === '') {
  37. $input['name'] = null;
  38. }
  39. }
  40. $hasMessage = array_intersect(['type', 'text', 'image', 'video', 'button'], array_keys($input)) !== [];
  41. $fields = Validator::make($input, [
  42. 'id' => $legacy ? 'prohibited' : 'sometimes|required|integer|min:1',
  43. 'name' => 'nullable|string|max:255',
  44. 'chatId' => 'required|string|max:64',
  45. 'bot_id' => 'sometimes|nullable|integer|min:1|prohibits:bot_token',
  46. 'bot_username' => ['nullable', 'string', 'max:64', 'regex:/^@?[a-z][a-z0-9_]*$/iD'],
  47. 'bot_token' => ['nullable', 'string', 'max:255', 'regex:/^[1-9][0-9]*:[a-z0-9_-]+$/iD'],
  48. 'enabled' => 'sometimes|required|boolean',
  49. 'type' => [($legacy || $hasMessage) ? 'required' : 'sometimes', 'string', 'in:text,image,video'],
  50. ], [], ['name' => '频道名称'])->validate();
  51. $target = self::normalizeTarget($fields['chatId']);
  52. if ($target === null) {
  53. throw ValidationException::withMessages(['chatId' => '请输入频道用户名或负数频道 ID']);
  54. }
  55. $message = isset($fields['type']) ? self::message($input) : null;
  56. $row = isset($fields['id']) && !$legacy ? $this->find((int) $fields['id']) : null;
  57. if ($legacy) {
  58. $row = $this->joinedChannels()->where(fn (Builder $query) => $query
  59. ->where('channels.target', $target)->orWhere('channels.telegram_chat_id', $target))->first();
  60. }
  61. $newToken = $fields['bot_token'] ?? null;
  62. $botId = array_key_exists('bot_id', $fields) ? $fields['bot_id'] : $row?->bot_id;
  63. $selectedBot = $botId === null ? null : $this->findBot((int) $botId);
  64. $bot = $newToken === null ? [] : $this->validateBot($fields['bot_username'] ?? null, $newToken);
  65. if ($newToken === null && isset($fields['bot_username'])
  66. && strcasecmp(ltrim($fields['bot_username'], '@'), $selectedBot->bot_username ?? '') !== 0) {
  67. throw ValidationException::withMessages(['bot_username' => '请从机器人管理中选择机器人']);
  68. }
  69. $targetUnchanged = $row !== null && in_array($target, [$row->target, $row->telegram_chat_id], true);
  70. $unbound = !$legacy && $botId === null && $newToken === null;
  71. $bindingUnchanged = (int) $botId === (int) $row?->bot_id && $newToken === null;
  72. if ($targetUnchanged && ($bindingUnchanged || $unbound)) {
  73. $identity = ['target' => $row->target, 'telegram_chat_id' => $row->telegram_chat_id, 'title' => $row->name];
  74. } elseif ($unbound) {
  75. $identity = ['target' => $target, 'telegram_chat_id' => str_starts_with($target, '-') ? $target : null, 'title' => ltrim($target, '@')];
  76. } else {
  77. $identity = $this->resolve($target, $newToken ?? $this->storedToken($selectedBot));
  78. }
  79. return DB::transaction(function () use ($fields, $identity, $message, $legacy, $row, $bot, $selectedBot) {
  80. $default = $this->settings()->lockForUpdate()->first();
  81. $channels = DB::table('telegram_channels');
  82. $existing = $row === null ? null : (clone $channels)->where('id', $row->id)->first();
  83. if ($row !== null && ($existing === null || $existing->target !== $row->target
  84. || $existing->telegram_chat_id !== $row->telegram_chat_id || $existing->bot_id !== $row->bot_id)) {
  85. throw ValidationException::withMessages(['id' => '频道已变更,请刷新后重试']);
  86. }
  87. $match = (clone $channels)->where(function (Builder $query) use ($identity) {
  88. $query->where('target', $identity['target']);
  89. if ($identity['telegram_chat_id'] !== null) {
  90. $query->orWhere('telegram_chat_id', $identity['telegram_chat_id']);
  91. }
  92. })->get();
  93. if ($legacy && $row === null && $match->count() === 1) {
  94. $existing = $match->first();
  95. if ($existing->bot_id !== null && $bot === [] && !array_key_exists('bot_id', $fields)) {
  96. throw ValidationException::withMessages(['chatId' => '请使用已保存的频道标识,或通过频道管理按 ID 编辑']);
  97. }
  98. }
  99. if ($match->contains(fn ($channel) => (int) $channel->id !== (int) $existing?->id)) {
  100. throw ValidationException::withMessages(['chatId' => '该频道已存在']);
  101. }
  102. if ($selectedBot !== null && $this->findBot((int) $selectedBot->id)->bot_token !== $selectedBot->bot_token) {
  103. throw ValidationException::withMessages(['bot_id' => '机器人配置已更新,请刷新后重试']);
  104. }
  105. $binding = $selectedBot?->id;
  106. if ($bot !== []) {
  107. $registered = DB::table('telegram_bots')->where('bot_username', $bot['bot_username'])->first();
  108. if ($registered !== null && $this->storedToken($registered) !== $this->storedToken((object) $bot)) {
  109. throw ValidationException::withMessages(['bot_token' => '请在机器人管理中更新已有机器人的 Token']);
  110. }
  111. $binding = $registered?->id ?? DB::table('telegram_bots')->insertGetId($bot + [
  112. 'created_at' => now(), 'updated_at' => now(),
  113. ]);
  114. }
  115. $enabled = (bool) ($fields['enabled'] ?? $existing?->enabled ?? true);
  116. $values = [
  117. 'name' => $fields['name'] ?? $existing?->name ?? $identity['title'],
  118. 'target' => $identity['target'],
  119. 'telegram_chat_id' => $identity['telegram_chat_id'],
  120. 'enabled' => $enabled,
  121. 'message' => $message === null
  122. ? ($existing?->message ?? 'null')
  123. : json_encode($message, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  124. 'bot_id' => $binding,
  125. 'updated_at' => now(),
  126. ];
  127. if ($existing === null) {
  128. $firstLegacy = $legacy && !$channels->exists();
  129. $id = (int) $channels->insertGetId($values + ['created_at' => now()]);
  130. if ($firstLegacy && $enabled) {
  131. $this->settings()->update(['default_channel_id' => $id]);
  132. }
  133. } else {
  134. $id = (int) $existing->id;
  135. $channels->where('id', $id)->update($values);
  136. if (!$enabled && (int) $default->default_channel_id === $id) {
  137. $this->settings()->update(['default_channel_id' => null]);
  138. }
  139. }
  140. return $this->detail($id);
  141. }, 3);
  142. }
  143. public function delete(int $id): void
  144. {
  145. DB::transaction(function () use ($id) {
  146. $default = $this->settings()->lockForUpdate()->first();
  147. $this->find($id);
  148. if ((int) $default->default_channel_id === $id) {
  149. $this->settings()->update(['default_channel_id' => null]);
  150. }
  151. DB::table('telegram_channels')->where('id', $id)->delete();
  152. }, 3);
  153. }
  154. public function legacyMessage(): ?array
  155. {
  156. $row = $this->defaultChannel();
  157. return $row === null ? null : ['chatId' => ltrim($row->target, '@')] + $this->storedMessage($row);
  158. }
  159. public function roomNoticeTarget(): ?string
  160. {
  161. $row = $this->defaultChannel();
  162. return $row === null ? null : ($row->telegram_chat_id ?? $row->target);
  163. }
  164. public function publish(int $id, bool $pin): array
  165. {
  166. $row = $this->find($id);
  167. return $this->publishContent($row, $this->storedMessage($row), $pin);
  168. }
  169. public function publishMessage(int $id, array $message, bool $pin, string $target): array
  170. {
  171. $row = $this->find($id);
  172. if ($row->bot_id === null) {
  173. throw ValidationException::withMessages(['channel_id' => '请先为频道绑定机器人']);
  174. }
  175. if (($row->telegram_chat_id ?? $row->target) !== $target) {
  176. throw ValidationException::withMessages(['channel_id' => '频道标识已变更,请重新创建发送记录']);
  177. }
  178. return $this->publishContent($row, $message, $pin);
  179. }
  180. private function publishContent(object $row, array $message, bool $pin): array
  181. {
  182. $channel = $this->present($row, false) + $message;
  183. if (!$channel['enabled']) {
  184. throw ValidationException::withMessages(['id' => '请先启用频道']);
  185. }
  186. if ($channel['type'] === null) {
  187. throw ValidationException::withMessages(['type' => '请先保存要发布的消息']);
  188. }
  189. $params = ['chat_id' => $channel['telegram_chat_id'] ?? $channel['chatId']];
  190. if ($channel['button'] !== []) {
  191. $params['reply_markup'] = json_encode(['inline_keyboard' => $channel['button']], JSON_THROW_ON_ERROR);
  192. }
  193. try {
  194. $telegram = $this->telegram($this->storedToken($row));
  195. $response = $this->send($telegram, $channel, $params);
  196. } catch (TelegramResponseException $exception) {
  197. if (($exception->getHttpStatusCode() ?? 500) < 500) {
  198. return ['sent' => false, 'pinned' => null, 'message_id' => null, 'error' => 'Telegram 拒绝发布,请检查机器人发帖权限、频道和消息内容'];
  199. }
  200. return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
  201. } catch (\Exception) {
  202. return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
  203. }
  204. $messageId = $response['message_id'] ?? null;
  205. if (isset($response['body_error'])) {
  206. return ['sent' => null, 'pinned' => null, 'message_id' => $messageId, 'error' => $response['body_error']];
  207. }
  208. if ($messageId === null) {
  209. return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
  210. }
  211. $pinned = null;
  212. $error = null;
  213. if ($pin) {
  214. try {
  215. $pinned = $telegram->pinChatMessage(['chat_id' => $params['chat_id'], 'message_id' => $messageId]);
  216. if (!$pinned) {
  217. $error = '消息已发布,置顶未成功';
  218. }
  219. } catch (\Exception) {
  220. $pinned = false;
  221. $error = '消息已发布,请在频道中检查置顶状态';
  222. }
  223. }
  224. return ['sent' => true, 'pinned' => $pinned, 'message_id' => $messageId, 'error' => $error];
  225. }
  226. private function send(Api $telegram, array $channel, array $params): array
  227. {
  228. if ($channel['type'] === 'text') {
  229. return $telegram->post('sendMessage', $params + ['text' => $channel['text']])->getResult() ?: [];
  230. }
  231. $text = $channel['text'];
  232. $separateBody = mb_strlen($text) > 1024;
  233. $response = $this->sendMedia($telegram, $channel, $params + ['caption' => $separateBody ? '' : $text]);
  234. if ($separateBody && isset($response['message_id'])) {
  235. try {
  236. $body = $telegram->post('sendMessage', [
  237. 'chat_id' => $params['chat_id'],
  238. 'text' => $text,
  239. ])->getResult();
  240. if (isset($body['message_id'])) {
  241. return $response;
  242. }
  243. } catch (\Exception) {
  244. // The media was already sent. Do not retry the entire message.
  245. }
  246. $response['body_error'] = '媒体已发送,正文发送结果未确认,请在 Telegram 中核对';
  247. }
  248. return $response;
  249. }
  250. private function sendMedia(Api $telegram, array $channel, array $params): array
  251. {
  252. $image = $channel['type'] === 'image';
  253. $media = $channel[$channel['type']];
  254. $field = $image ? 'photo' : 'video';
  255. // Only read files produced by the admin upload endpoints on the configured public disk.
  256. $disk = Storage::disk('public');
  257. $prefix = rtrim($disk->url(''), '/') . '/';
  258. $path = str_starts_with($media, $prefix) ? substr($media, strlen($prefix)) : '';
  259. if (preg_match('~\A(?:images|videos)/[a-f0-9]{32}\.(?:jpg|jpeg|png|webp|mp4|mov|avi|webm)\z~i', $path) && $disk->exists($path)) {
  260. $stream = $disk->readStream($path);
  261. if (!is_resource($stream)) {
  262. throw new RuntimeException('Unable to read uploaded media');
  263. }
  264. try {
  265. $params[$field] = InputFile::create($stream, basename($path));
  266. $response = $image ? $telegram->sendPhoto($params) : $telegram->sendVideo($params);
  267. return ['message_id' => $response->get('message_id')];
  268. } finally {
  269. if (is_resource($stream)) {
  270. fclose($stream);
  271. }
  272. }
  273. }
  274. // Telegram fetches external media directly.
  275. return $telegram->post($image ? 'sendPhoto' : 'sendVideo', $params + [$field => $media])->getResult() ?: [];
  276. }
  277. public function bots(): array
  278. {
  279. return DB::table('telegram_bots')->orderBy('bot_username')
  280. ->get(['id', 'bot_username', 'bot_name'])->all();
  281. }
  282. public function saveBot(#[\SensitiveParameter] array $input): array
  283. {
  284. $fields = Validator::make($input, [
  285. 'id' => 'sometimes|required|integer|min:1',
  286. 'bot_username' => ['nullable', 'string', 'max:64', 'regex:/^@?[a-z][a-z0-9_]*$/iD'],
  287. 'bot_token' => ['required', 'string', 'max:255', 'regex:/^[1-9][0-9]*:[a-z0-9_-]+$/iD'],
  288. ])->validate();
  289. $id = isset($fields['id']) ? (int) $fields['id'] : null;
  290. $row = $id === null ? null : $this->findBot($id);
  291. $bot = $this->validateBot($fields['bot_username'] ?? $row?->bot_username, $fields['bot_token']);
  292. if ($row !== null && strcasecmp($row->bot_username, $bot['bot_username']) !== 0) {
  293. throw ValidationException::withMessages(['bot_username' => '请使用此机器人的 Token,更换机器人请新增后再绑定']);
  294. }
  295. return DB::transaction(function () use ($id, $row, $bot) {
  296. $this->settings()->lockForUpdate()->first();
  297. $bots = DB::table('telegram_bots');
  298. $duplicate = (clone $bots)->where('bot_username', $bot['bot_username'])->value('id');
  299. if ($duplicate !== null && (int) $duplicate !== $id) {
  300. throw ValidationException::withMessages(['bot_username' => '该机器人已存在']);
  301. }
  302. $values = $bot + ['updated_at' => now()];
  303. if ($id === null) {
  304. $id = (int) $bots->insertGetId($values + ['created_at' => now()]);
  305. } else {
  306. if ($this->findBot($id)->bot_token !== $row->bot_token) {
  307. throw ValidationException::withMessages(['id' => '机器人已更新,请刷新后重试']);
  308. }
  309. $bots->where('id', $id)->update($values);
  310. }
  311. return ['id' => $id, 'bot_username' => $bot['bot_username'], 'bot_name' => $bot['bot_name']];
  312. }, 3);
  313. }
  314. public function deleteBot(int $id): void
  315. {
  316. DB::transaction(function () use ($id) {
  317. $this->settings()->lockForUpdate()->first();
  318. $this->findBot($id);
  319. if (DB::table('telegram_channels')->where('bot_id', $id)->exists()) {
  320. throw ValidationException::withMessages(['id' => '机器人仍绑定频道,请先在频道中解除绑定']);
  321. }
  322. DB::table('telegram_bots')->where('id', $id)->delete();
  323. }, 3);
  324. }
  325. public function privateMenu(int $id, string $language): array
  326. {
  327. return $this->privateMenus($id)[$language] ?? ['reply' => '', 'buttons' => [], 'type' => 'text', 'image' => '', 'video' => ''];
  328. }
  329. public function privateMenus(int $id): array
  330. {
  331. $menus = json_decode($this->findBot($id)->private_menus ?? '{}', true);
  332. foreach ($menus as &$menu) {
  333. $menu += ['type' => 'text', 'image' => '', 'video' => ''];
  334. }
  335. return $menus;
  336. }
  337. public function savePrivateMenu(int $id, string $language, array $input): array
  338. {
  339. return $this->savePrivateMenus($id, [$language => $input])[$language];
  340. }
  341. public function savePrivateMenus(int $id, array $input): array
  342. {
  343. $menus = [];
  344. foreach ($input as $language => $menu) {
  345. $menus[$language] = $this->validatePrivateMenu($menu);
  346. }
  347. DB::transaction(function () use ($id, $menus) {
  348. $bot = DB::table('telegram_bots')->where('id', $id)->lockForUpdate()->first()
  349. ?? throw ValidationException::withMessages(['id' => '机器人不存在']);
  350. $existing = json_decode($bot->private_menus ?? '{}', true);
  351. DB::table('telegram_bots')->where('id', $id)->update([
  352. 'private_menus' => json_encode(array_replace($existing, $menus), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  353. 'updated_at' => now(),
  354. ]);
  355. }, 3);
  356. return $menus;
  357. }
  358. private function validatePrivateMenu(array $input): array
  359. {
  360. $menu = Validator::make($input, [
  361. 'buttons' => 'present|array|list|max:20',
  362. 'buttons.*' => 'required|array|list',
  363. 'buttons.*.*' => 'required|string|max:128',
  364. ])->validate();
  365. $content = self::message([
  366. 'type' => $input['type'] ?? 'text',
  367. 'text' => $input['reply'] ?? null,
  368. 'image' => $input['image'] ?? null,
  369. 'video' => $input['video'] ?? null,
  370. ]);
  371. $menu += [
  372. 'type' => $content['type'],
  373. 'reply' => $content['text'],
  374. 'image' => $content['type'] === 'image' ? $content['image'] : '',
  375. 'video' => $content['type'] === 'video' ? $content['video'] : '',
  376. ];
  377. return $menu;
  378. }
  379. public function registerPrivateWebhook(int $id): array
  380. {
  381. $bot = $this->findBot($id);
  382. $token = $this->storedToken($bot);
  383. if ($token === config('services.telegram.token')) {
  384. return ['system_bot' => true];
  385. }
  386. $secret = $bot->webhook_secret;
  387. if ($secret === null) {
  388. DB::table('telegram_bots')->where('id', $id)->whereNull('webhook_secret')
  389. ->update(['webhook_secret' => bin2hex(random_bytes(32))]);
  390. $bot = $this->findBot($id);
  391. $secret = $bot->webhook_secret;
  392. }
  393. $webhookUrl = rtrim((string) config('app.url'), '/') . '/api/telegramBot/' . $id . '/webhook';
  394. try {
  395. $telegram = $this->telegram($token);
  396. $existingUrl = (string) $telegram->getWebhookInfo()->get('url');
  397. } catch (\Exception) {
  398. throw ValidationException::withMessages(['id' => '无法读取 Telegram 接入状态,请检查 Bot Token']);
  399. }
  400. if ($existingUrl !== '' && $existingUrl !== $webhookUrl) {
  401. throw ValidationException::withMessages(['id' => '机器人已接入其他 Webhook,请确认停用原接入后重试']);
  402. }
  403. try {
  404. $registered = $telegram->setWebhook([
  405. 'url' => $webhookUrl,
  406. 'secret_token' => $secret,
  407. 'allowed_updates' => ['message'],
  408. ]);
  409. } catch (\Exception) {
  410. $registered = false;
  411. }
  412. if (!$registered) {
  413. throw ValidationException::withMessages(['id' => '无法接入 Telegram,请检查 Bot Token 和站点 HTTPS 配置']);
  414. }
  415. return ['system_bot' => false];
  416. }
  417. public function handlePrivateWebhook(int $id, string $secret, array $update): void
  418. {
  419. $bot = DB::table('telegram_bots')->where('id', $id)->first();
  420. abort_unless($bot?->webhook_secret && hash_equals($bot->webhook_secret, $secret), 404);
  421. if (is_int($update['update_id'] ?? null)) {
  422. rescue(fn () => Log::channel('telegram_webhook')->info('Telegram 收到更新', ['bot_id' => $id, 'update' => $update]));
  423. }
  424. $message = $update['message'] ?? [];
  425. $chatId = $message['chat']['id'] ?? null;
  426. if (($message['chat']['type'] ?? null) !== 'private' || !is_int($chatId)
  427. || !is_string($message['text'] ?? null) || !preg_match('/^\/start(?:\s|$)/D', $message['text'])) {
  428. return;
  429. }
  430. $language = strtolower(substr((string) ($message['from']['language_code'] ?? ''), 0, 2));
  431. $menu = $this->configuredPrivateMenu($bot, $language);
  432. if ($menu === null) {
  433. return;
  434. }
  435. try {
  436. $this->sendPrivateMenu($this->telegram($this->storedToken($bot)), $chatId, $menu);
  437. } catch (\Exception) {
  438. Log::warning('Telegram 私聊菜单发送失败', ['bot_id' => $id]);
  439. abort(503);
  440. }
  441. }
  442. public function sendSystemPrivateMenu($chatId, string $language): bool
  443. {
  444. $token = config('services.telegram.token');
  445. if (!$token) {
  446. return false;
  447. }
  448. foreach (DB::table('telegram_bots')->whereNotNull('private_menus')->cursor() as $bot) {
  449. if ($token === $this->storedToken($bot) && ($menu = $this->configuredPrivateMenu($bot, $language)) !== null) {
  450. $this->sendPrivateMenu($this->telegram(null), $chatId, $menu);
  451. return true;
  452. }
  453. }
  454. return false;
  455. }
  456. private function configuredPrivateMenu(object $bot, string $language): ?array
  457. {
  458. $menus = json_decode($bot->private_menus ?? '{}', true);
  459. return $menus[$language] ?? $menus['en'] ?? $menus['zh'] ?? ($menus['vi'] ?? null);
  460. }
  461. private function sendPrivateMenu(Api $telegram, $chatId, array $menu): void
  462. {
  463. $keyboard = $menu['buttons'] === []
  464. ? ['remove_keyboard' => true]
  465. : ['keyboard' => $menu['buttons'], 'resize_keyboard' => true];
  466. $response = $this->send($telegram, ['text' => $menu['reply']] + $menu + ['type' => 'text'], [
  467. 'chat_id' => $chatId,
  468. 'reply_markup' => json_encode($keyboard, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  469. ]);
  470. if (isset($response['body_error'])) {
  471. Log::warning('Telegram 私聊菜单正文发送结果未确认', ['message_id' => $response['message_id']]);
  472. }
  473. }
  474. private function findBot(int $id): object
  475. {
  476. return DB::table('telegram_bots')->where('id', $id)->first()
  477. ?? throw ValidationException::withMessages(['bot_id' => '机器人不存在']);
  478. }
  479. private function validateBot(?string $username, #[\SensitiveParameter] string $token): array
  480. {
  481. try {
  482. $bot = $this->telegram($token)->getMe();
  483. } catch (\Exception) {
  484. throw ValidationException::withMessages(['bot_token' => '无法验证 Bot Token,请检查 Token 或 Telegram 连接']);
  485. }
  486. $actualUsername = $bot->get('username');
  487. if (!$bot->get('is_bot') || !is_string($actualUsername) || $actualUsername === '') {
  488. throw ValidationException::withMessages(['bot_token' => 'Bot Token 未返回有效的机器人账号']);
  489. }
  490. if ($username !== null && strcasecmp(ltrim($username, '@'), $actualUsername) !== 0) {
  491. throw ValidationException::withMessages(['bot_username' => '机器人用户名和 Bot Token 不匹配']);
  492. }
  493. return [
  494. 'bot_username' => strtolower($actualUsername),
  495. 'bot_name' => mb_substr((string) $bot->get('first_name'), 0, 255),
  496. 'bot_token' => Crypt::encryptString($token),
  497. ];
  498. }
  499. private function storedToken(?object $row): ?string
  500. {
  501. return $row?->bot_token === null ? null : Crypt::decryptString($row->bot_token);
  502. }
  503. protected function telegram(#[\SensitiveParameter] ?string $token): Api
  504. {
  505. return $token === null ? app(Api::class) : new Api($token);
  506. }
  507. private function resolve(string $target, #[\SensitiveParameter] ?string $token): array
  508. {
  509. if ($token === null && !config('services.telegram.token')) {
  510. throw ValidationException::withMessages(['bot_id' => '系统机器人尚未配置,请选择已添加的机器人']);
  511. }
  512. try {
  513. $chat = $this->telegram($token)->getChat(['chat_id' => $target]);
  514. } catch (\Exception) {
  515. $bot = $token === null ? '系统机器人' : '所选机器人';
  516. throw ValidationException::withMessages(['chatId' => "无法读取频道,请检查频道标识,并确认{$bot}已加入目标频道"]);
  517. }
  518. $id = (string) $chat->get('id');
  519. if ($chat->get('type') !== 'channel' || !preg_match('/^-[1-9]\d{1,19}$/D', $id)) {
  520. throw ValidationException::withMessages(['chatId' => '请输入 Telegram 频道,群组和私聊无法使用']);
  521. }
  522. $username = $chat->get('username');
  523. return [
  524. 'target' => $username ? self::normalizeTarget($username) ?? $id : $id,
  525. 'telegram_chat_id' => $id,
  526. 'title' => mb_substr((string) ($chat->get('title') ?: $target), 0, 255),
  527. ];
  528. }
  529. public static function legacyChannel(mixed $value): ?array
  530. {
  531. if (!is_array($value) || ($target = self::normalizeTarget($value['chatId'] ?? null)) === null) {
  532. return null;
  533. }
  534. $value['type'] ??= !empty($value['video']) ? 'video' : (!empty($value['image']) ? 'image' : 'text');
  535. try {
  536. $message = self::message($value);
  537. } catch (ValidationException) {
  538. return null;
  539. }
  540. return [
  541. 'name' => ltrim($target, '@'),
  542. 'target' => $target,
  543. 'telegram_chat_id' => str_starts_with($target, '-') ? $target : null,
  544. 'enabled' => true,
  545. 'message' => json_encode($message, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  546. ];
  547. }
  548. private static function normalizeTarget(mixed $value): ?string
  549. {
  550. if (!is_string($value)) {
  551. return null;
  552. }
  553. $value = trim($value);
  554. if (preg_match('/^-[1-9]\d{1,19}$/D', $value)) {
  555. return $value;
  556. }
  557. return preg_match('/^@?[a-z][a-z0-9_]{3,31}$/iD', $value) ? '@' . strtolower(ltrim($value, '@')) : null;
  558. }
  559. public static function message(array $input): array
  560. {
  561. $data = Validator::make($input, [
  562. 'type' => 'required|in:text,image,video',
  563. 'text' => 'nullable|required_if:type,text|string|max:4096',
  564. 'image' => 'nullable|required_if:type,image|string|max:2048|url:http,https',
  565. 'video' => 'nullable|required_if:type,video|string|max:2048|url:http,https',
  566. 'button' => 'sometimes|array|list',
  567. 'button.*' => 'required|array|list',
  568. 'button.*.*' => 'required|array',
  569. 'button.*.*.text' => 'required|string',
  570. 'button.*.*.url' => 'required|string|url:http,https,tg',
  571. ])->validate();
  572. foreach (['image', 'video'] as $field) {
  573. $url = $data[$field] ?? '';
  574. $host = rtrim(strtolower(trim(parse_url($url, PHP_URL_HOST) ?? '', '[]')), '.');
  575. if ($url !== '' && (
  576. parse_url($url, PHP_URL_USER) !== null
  577. || $host === 'localhost'
  578. || str_ends_with($host, '.localhost')
  579. || (filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_GLOBAL_RANGE))
  580. || str_contains(strtolower(rawurldecode(parse_url($url, PHP_URL_PATH) ?? '')), '/_ignition/')
  581. )) {
  582. throw ValidationException::withMessages([$field => '媒体地址须可公开访问']);
  583. }
  584. }
  585. return [
  586. 'type' => $data['type'],
  587. 'text' => $data['text'] ?? '',
  588. 'image' => $data['image'] ?? '',
  589. 'video' => $data['video'] ?? '',
  590. 'button' => array_map(fn ($row) => array_map(
  591. fn ($button) => ['text' => $button['text'], 'url' => $button['url']],
  592. $row,
  593. ), $data['button'] ?? []),
  594. ];
  595. }
  596. private function settings(): Builder
  597. {
  598. return DB::table('telegram_channel_settings')->where('id', 1);
  599. }
  600. private function defaultChannel(): ?object
  601. {
  602. return $this->joinedChannels()->where('channels.enabled', true)
  603. ->whereColumn('channels.id', 'settings.default_channel_id')->first();
  604. }
  605. private function find(int $id): object
  606. {
  607. return $this->joinedChannels()->where('channels.id', $id)->first()
  608. ?? throw ValidationException::withMessages(['id' => '频道不存在']);
  609. }
  610. private function joinedChannels(): Builder
  611. {
  612. return DB::table('telegram_channels as channels')
  613. ->crossJoin('telegram_channel_settings as settings')
  614. ->leftJoin('telegram_bots as bots', 'bots.id', '=', 'channels.bot_id')
  615. ->select('channels.id', 'channels.name', 'channels.target', 'channels.telegram_chat_id', 'channels.enabled', 'channels.message', 'channels.bot_id', 'settings.default_channel_id', 'bots.bot_username', 'bots.bot_name', 'bots.bot_token')
  616. ->where('settings.id', 1);
  617. }
  618. private function present(object $row, bool $default, bool $withMessage = false): array
  619. {
  620. $data = [
  621. 'id' => (int) $row->id,
  622. 'name' => $row->name,
  623. 'chatId' => $row->target,
  624. 'telegram_chat_id' => $row->telegram_chat_id,
  625. 'bot_id' => $row->bot_id === null ? null : (int) $row->bot_id,
  626. 'bot_username' => $row->bot_username,
  627. 'bot_name' => $row->bot_name,
  628. 'has_bot_token' => $row->bot_token !== null,
  629. 'enabled' => (bool) $row->enabled,
  630. 'is_default' => $default,
  631. ];
  632. return $withMessage ? $data + $this->storedMessage($row) : $data;
  633. }
  634. private function storedMessage(object $row): array
  635. {
  636. return json_decode($row->message, true) ?? [
  637. 'type' => null,
  638. 'text' => '',
  639. 'image' => '',
  640. 'video' => '',
  641. 'button' => [],
  642. ];
  643. }
  644. }