doge 2 дней назад
Родитель
Сommit
3019405dc1

+ 0 - 5
app/Http/Controllers/admin/TelegramChannel.php

@@ -87,11 +87,6 @@ class TelegramChannel extends Controller
         return $this->respond(fn () => $channels->save($request->all()));
     }
 
-    public function setDefault(Request $request, TelegramChannelService $channels): JsonResponse
-    {
-        return $this->respond(fn () => $channels->setDefault($this->id($request)));
-    }
-
     public function delete(Request $request, TelegramChannelService $channels): JsonResponse
     {
         return $this->respond(function () use ($request, $channels) {

+ 3 - 0
app/Services/TelegramChannelMessageService.php

@@ -31,6 +31,9 @@ class TelegramChannelMessageService
         if (!$channel['enabled']) {
             throw ValidationException::withMessages(['channel_id' => '请先启用频道']);
         }
+        if ($channel['bot_id'] === null) {
+            throw ValidationException::withMessages(['channel_id' => '请先为频道绑定机器人']);
+        }
         $scheduled = isset($fields['scheduled_at']) ? CarbonImmutable::parse($fields['scheduled_at'])->utc() : null;
         if ($scheduled !== null && $scheduled->lessThanOrEqualTo(now('UTC'))) {
             throw ValidationException::withMessages(['scheduled_at' => '定时发送时间必须晚于当前时间']);

+ 12 - 17
app/Services/TelegramChannelService.php

@@ -75,10 +75,15 @@ class TelegramChannelService
         }
 
         $targetUnchanged = $row !== null && in_array($target, [$row->target, $row->telegram_chat_id], true);
+        $unbound = !$legacy && $botId === null && $newToken === null;
         $bindingUnchanged = (int) $botId === (int) $row?->bot_id && $newToken === null;
-        $identity = $targetUnchanged && $bindingUnchanged
-            ? ['target' => $row->target, 'telegram_chat_id' => $row->telegram_chat_id, 'title' => $row->name]
-            : $this->resolve($target, $newToken ?? $this->storedToken($selectedBot));
+        if ($targetUnchanged && ($bindingUnchanged || $unbound)) {
+            $identity = ['target' => $row->target, 'telegram_chat_id' => $row->telegram_chat_id, 'title' => $row->name];
+        } elseif ($unbound) {
+            $identity = ['target' => $target, 'telegram_chat_id' => str_starts_with($target, '-') ? $target : null, 'title' => ltrim($target, '@')];
+        } else {
+            $identity = $this->resolve($target, $newToken ?? $this->storedToken($selectedBot));
+        }
 
         return DB::transaction(function () use ($fields, $identity, $message, $legacy, $row, $bot, $selectedBot) {
             $default = $this->settings()->lockForUpdate()->first();
@@ -149,19 +154,6 @@ class TelegramChannelService
         }, 3);
     }
 
-    public function setDefault(int $id): array
-    {
-        return DB::transaction(function () use ($id) {
-            $this->settings()->lockForUpdate()->first();
-            $row = $this->find($id);
-            if (!$row->enabled) {
-                throw ValidationException::withMessages(['id' => '请先启用频道']);
-            }
-            $this->settings()->update(['default_channel_id' => $id]);
-            return $this->detail($id);
-        }, 3);
-    }
-
     public function delete(int $id): void
     {
         DB::transaction(function () use ($id) {
@@ -195,6 +187,9 @@ class TelegramChannelService
     public function publishMessage(int $id, array $message, bool $pin, string $target): array
     {
         $row = $this->find($id);
+        if ($row->bot_id === null) {
+            throw ValidationException::withMessages(['channel_id' => '请先为频道绑定机器人']);
+        }
         if (($row->telegram_chat_id ?? $row->target) !== $target) {
             throw ValidationException::withMessages(['channel_id' => '频道标识已变更,请重新创建发送记录']);
         }
@@ -349,7 +344,7 @@ class TelegramChannelService
         $menu = Validator::make($input, [
             'reply' => 'required|string|max:4096',
             'buttons' => 'present|array|list|max:20',
-            'buttons.*' => 'required|array|list|max:8',
+            'buttons.*' => 'required|array|list',
             'buttons.*.*' => 'required|string|max:128',
         ])->validate();
 

+ 2 - 3
docs/前端交付/bot-28/后台/Telegram频道管理-前端接入.md

@@ -9,12 +9,11 @@
 | `GET /admin/telegramChannel/list` | 返回 `data.list` |
 | `GET /admin/telegramChannel/detail?id=12` | 返回频道详情 |
 | `POST /admin/telegramChannel/save` | 提交频道资料,返回详情 |
-| `POST /admin/telegramChannel/setDefault` | 提交 `{ "id": 12 }`,返回详情 |
 | `POST /admin/telegramChannel/delete` | 提交 `{ "id": 12 }`,返回 `[]` |
 
 读取权限为 `admin/telegramChannel/list`,修改权限为 `admin/telegramChannel/save`。
 
-保存示例为 `{"chatId":"@example_channel","name":"活动频道","bot_id":8,"enabled":true}`。编辑时加 `id`。频道标识可以用公开用户名或 `"-100…"`,选定的机器人要能读取该频道。名称可留空,新增时使用 Telegram 频道名称,编辑时保留原名称。传 `bot_id: null` 使用系统机器人,编辑时省略会保留原绑定。详情中的 `id` 是后台频道 ID,`telegram_chat_id` 是 Telegram 数字 ID 字符串,`is_default` 表示房间通知目标。
+保存示例为 `{"chatId":"@example_channel","name":"活动频道","bot_id":8,"enabled":true}`。编辑时加 `id`。频道标识可以用公开用户名或 `"-100…"`,选定的机器人要能读取该频道。频道名称可留空。新增时使用 Telegram 频道名称,未绑定机器人时使用频道标识。编辑时留空保留原名称。传 `bot_id: null` 表示不绑定机器人,编辑时省略会保留原绑定。详情中的 `id` 是后台频道 ID,`telegram_chat_id` 是 Telegram 数字 ID 字符串,未解析时可为 `null`。
 
 ## 频道消息
 
@@ -24,7 +23,7 @@
 | `POST /admin/telegramChannelMessage/create` | 新增立即或定时发送记录,返回该记录 |
 | `POST /admin/telegramChannelMessage/cancel` | 提交 `{ "id": 42 }`,仅待发送记录可取消 |
 
-读取权限为 `admin/telegramChannel/list`,新增和取消使用 `admin/telegramChannel/publish`。新增时从启用的频道中选择 `channel_id`。立即发送时省略 `scheduled_at`,定时时传带时区的 ISO 8601 时间。图片通过 `POST /admin/upload/uploadFile`(字段 `image`)上传,视频通过 `POST /admin/upload/uploadVideo`(字段 `file`)上传。用返回的 `data.path` 填入 `image` 或 `video`。
+读取权限为 `admin/telegramChannel/list`,新增和取消使用 `admin/telegramChannel/publish`。新增时从已启用且已绑定机器人的频道中选择 `channel_id`。立即发送时省略 `scheduled_at`,定时时传带时区的 ISO 8601 时间。图片通过 `POST /admin/upload/uploadFile`(字段 `image`)上传,视频通过 `POST /admin/upload/uploadVideo`(字段 `file`)上传。用返回的 `data.path` 填入 `image` 或 `video`。
 
 ```json
 {

+ 0 - 2
routes/admin.php

@@ -375,8 +375,6 @@ Route::middleware(['admin.jwt'])->group(function () {
             Route::get('/detail', [TelegramChannel::class, 'detail'])
                 ->defaults('permission_uri', TelegramChannelService::VIEW)->defaults('require_active_button', true);
             Route::post('/save', [TelegramChannel::class, 'save'])->defaults('require_active_button', true);
-            Route::post('/setDefault', [TelegramChannel::class, 'setDefault'])
-                ->defaults('permission_uri', TelegramChannelService::MANAGE)->defaults('require_active_button', true);
             Route::post('/delete', [TelegramChannel::class, 'delete'])
                 ->defaults('permission_uri', TelegramChannelService::MANAGE)->defaults('require_active_button', true);
             Route::post('/publish', [TelegramChannel::class, 'publish'])->defaults('require_active_button', true);

+ 28 - 27
tests/Integration/TelegramChannelTest.php

@@ -192,34 +192,30 @@ class TelegramChannelTest extends TestCase
         });
         DB::table('rooms')->insert(['room_id' => '123', 'game_name' => '游戏', 'rounds' => 3, 'base_score' => 10, 'participants' => 4]);
 
-        $this->telegramChannel(-1001000000001, 'first_channel');
         $first = $this->service->save($this->message('@first_channel', '一'));
-        $this->telegramChannel(-1001000000002, 'second_channel');
         $second = $this->service->save(['chatId' => '@second_channel']);
         $this->assertNull($second['type']);
         $request = $this->request(['id' => $second['id']]);
         $this->assertSame(-3, (new TelegramChannel())->publish($request, $this->service)->getData(true)['code']);
 
-        $this->service->setDefault($second['id']);
-        $this->assertSame('-1001000000002', ChannelService::createRoomNotice('123')['chat_id']);
+        DB::table('telegram_channel_settings')->where('id', 1)->update(['default_channel_id' => $second['id']]);
+        $this->assertSame('@second_channel', ChannelService::createRoomNotice('123')['chat_id']);
         $this->service->save($this->message('@second_channel', '二') + ['id' => $second['id'], 'enabled' => false]);
         $this->assertSame('一', $this->service->detail($first['id'])['text']);
         $this->assertSame('二', $this->service->detail($second['id'])['text']);
         $this->assertNull(ChannelService::createRoomNotice('123'));
 
-        $this->service->setDefault($first['id']);
+        DB::table('telegram_channel_settings')->where('id', 1)->update(['default_channel_id' => $first['id']]);
         $this->service->delete($first['id']);
         $this->assertNull(ChannelService::createRoomNotice('123'));
-        $this->assertCount(2, $this->requests);
+        $this->assertCount(0, $this->requests);
     }
 
     public function test_publishes_only_to_selected_channel_and_reports_pin_failure_separately(): void
     {
         $this->migrate();
-        $this->telegramChannel(-1001000000001, 'first_channel');
         $first = $this->service->save($this->message('@first_channel', '一'));
-        $this->service->setDefault($first['id']);
-        $this->telegramChannel(-1001000000002);
+        DB::table('telegram_channel_settings')->where('id', 1)->update(['default_channel_id' => $first['id']]);
         $second = $this->service->save($this->message('-1001000000002', '二'));
 
         $this->telegramResult(['message_id' => 37]);
@@ -229,12 +225,12 @@ class TelegramChannelTest extends TestCase
 
         $this->assertSame(0, $result['code']);
         $this->assertSame(['sent' => true, 'pinned' => false, 'message_id' => 37], array_intersect_key($result['data'], array_flip(['sent', 'pinned', 'message_id'])));
-        $this->assertCount(4, $this->requests);
-        parse_str((string) $this->requests[2]['request']->getBody(), $sent);
+        $this->assertCount(2, $this->requests);
+        parse_str((string) $this->requests[0]['request']->getBody(), $sent);
         $this->assertSame('-1001000000002', $sent['chat_id']);
         $this->assertSame('二', $sent['text']);
         $this->assertSame($second['button'], json_decode($sent['reply_markup'], true)['inline_keyboard']);
-        parse_str((string) $this->requests[3]['request']->getBody(), $pin);
+        parse_str((string) $this->requests[1]['request']->getBody(), $pin);
         $this->assertSame(['chat_id' => '-1001000000002', 'message_id' => '37'], $pin);
     }
 
@@ -289,19 +285,18 @@ class TelegramChannelTest extends TestCase
     public function test_blank_channel_name_defaults_on_create_and_is_preserved_on_edit(): void
     {
         $this->migrate();
-        $this->telegramChannel(-1001000000001, 'first_channel');
         $request = $this->request(['chatId' => '@first_channel', 'name' => '   ']);
         $controller = new TelegramChannel();
         $saved = $controller->save($request, $this->service)->getData(true);
         $this->assertSame(0, $saved['code']);
-        $this->assertSame('频道', $saved['data']['name']);
+        $this->assertSame('first_channel', $saved['data']['name']);
 
         $edit = ['id' => $saved['data']['id'], 'chatId' => '@first_channel'];
         $request = $this->request($edit + ['name' => '  后台自定义名称  ']);
         $this->assertSame('后台自定义名称', $controller->save($request, $this->service)->getData(true)['data']['name']);
         $request = $this->request($edit + ['name' => null]);
         $this->assertSame('后台自定义名称', $controller->save($request, $this->service)->getData(true)['data']['name']);
-        $this->assertCount(1, $this->requests);
+        $this->assertCount(0, $this->requests);
     }
 
     public function test_channel_tokens_are_encrypted_and_the_correct_bot_publishes_each_channel(): void
@@ -404,7 +399,8 @@ class TelegramChannelTest extends TestCase
         $this->telegramResult(['id' => 222, 'is_bot' => true, 'username' => 'second_bot']);
         $second = $this->service->saveBot(['bot_token' => '222:fixture_second']);
         $this->service->savePrivateMenu($first['id'], 'zh', ['reply' => '欢迎一', 'buttons' => [['联系客服']]]);
-        $this->service->savePrivateMenu($second['id'], 'zh', ['reply' => '欢迎二', 'buttons' => [['帮助']]]);
+        $buttons = [array_fill(0, 9, '帮助')];
+        $this->service->savePrivateMenu($second['id'], 'zh', ['reply' => '欢迎二', 'buttons' => $buttons]);
         $this->telegramResult(['url' => '']);
         $this->telegramResult(true);
         $this->service->registerPrivateWebhook($second['id']);
@@ -423,30 +419,35 @@ class TelegramChannelTest extends TestCase
         $this->assertSame('/bot222:fixture_second/sendMessage', $request->getUri()->getPath());
         parse_str((string) $request->getBody(), $sent);
         $this->assertSame('欢迎二', $sent['text']);
-        $this->assertSame([['帮助']], json_decode($sent['reply_markup'], true)['keyboard']);
+        $this->assertSame($buttons, json_decode($sent['reply_markup'], true)['keyboard']);
     }
 
-    public function test_system_bot_channel_and_scheduled_message_are_saved_independently(): void
+    public function test_unbound_channel_can_be_saved_and_scheduled_messages_require_a_bot(): void
     {
         $this->migrate();
-        $this->telegramChannel(-1001000000001, 'first_channel');
         $channel = $this->service->save(['chatId' => '@first_channel', 'bot_id' => null]);
         $this->assertNull($channel['bot_id']);
-        $this->assertSame('/bot1:fixture/getChat', $this->requests[0]['request']->getUri()->getPath());
+        $this->assertCount(0, $this->requests);
         $messages = new TelegramChannelMessageService($this->service);
         $input = ['channel_id' => $channel['id'], 'type' => 'text', 'text' => '定时消息',
             'scheduled_at' => now('UTC')->addHour()->toIso8601String()];
+        $request = $this->request($input);
+        $this->assertSame(-3, (new TelegramChannel())->createMessage($request, $messages)->getData(true)['code']);
+        $this->telegramResult(['id' => 111, 'is_bot' => true, 'username' => 'first_bot']);
+        $bot = $this->service->saveBot(['bot_token' => '111:fixture_first']);
+        $this->telegramChannel(-1001000000001, 'first_channel');
+        $this->service->save(['id' => $channel['id'], 'chatId' => '@first_channel', 'bot_id' => $bot['id']]);
         $record = $messages->create($input);
         $cancelled = $messages->create($input);
         $messages->cancel($cancelled['id']);
         $messages->dispatchDue();
         $this->assertSame('scheduled', $record['status']);
-        $this->assertCount(1, $this->requests);
+        $this->assertCount(2, $this->requests);
         DB::table('telegram_channel_messages')->update(['scheduled_at' => now('UTC')->subMinute()]);
         $this->telegramResult(['message_id' => 26]);
         $messages->dispatchDue();
         $messages->dispatchDue();
-        $this->assertCount(2, $this->requests);
+        $this->assertCount(3, $this->requests);
         $list = $messages->list(1);
         $this->assertSame(['cancelled', 'sent'], array_column($list['list'], 'status'));
         $this->assertSame(26, (int) $list['list'][1]['telegram_message_id']);
@@ -498,14 +499,14 @@ class TelegramChannelTest extends TestCase
     {
         $this->migrate();
         $this->app->register(FilesystemServiceProvider::class);
-        $this->telegramChannel(-1001000000001, 'first_channel');
+
         $media = 'https://files.example.test/photo.jpg';
         $channel = $this->service->save(['chatId' => '@first_channel', 'type' => 'image', 'image' => $media]);
         $this->telegramResult(['message_id' => 18]);
 
         $this->assertTrue($this->service->publish($channel['id'], false)['sent']);
-        $this->assertStringEndsWith('/sendPhoto', $this->requests[1]['request']->getUri()->getPath());
-        parse_str((string) $this->requests[1]['request']->getBody(), $sent);
+        $this->assertStringEndsWith('/sendPhoto', $this->requests[0]['request']->getUri()->getPath());
+        parse_str((string) $this->requests[0]['request']->getBody(), $sent);
         $this->assertSame($media, $sent['photo']);
     }
     public function test_admin_upload_is_sent_as_a_file_and_migration_can_be_retried(): void
@@ -516,11 +517,11 @@ class TelegramChannelTest extends TestCase
         $file = 'videos/' . bin2hex(random_bytes(16)) . '.mp4';
         $disk->put($file, 'test video');
         try {
-            $this->telegramChannel(-1001000000001, 'first_channel');
+
             $channel = $this->service->save([
                 'chatId' => '@first_channel', 'type' => 'video', 'video' => $disk->url($file),
             ]);
-            $this->service->setDefault($channel['id']);
+            DB::table('telegram_channel_settings')->where('id', 1)->update(['default_channel_id' => $channel['id']]);
             (require database_path('migrations/2026_11_13_150000_create_telegram_channels.php'))->up();
             $this->assertTrue($this->service->detail($channel['id'])['is_default']);
             $this->telegram->append(function ($request) {