feat: bot

This commit is contained in:
hashbro
2026-08-15 23:05:51 +08:00
parent 9049fdccad
commit 376b442880
26 changed files with 944 additions and 352 deletions
@@ -5,14 +5,18 @@ namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Channel;
use App\Models\User;
use App\Services\TelegramNotifier;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
class AgentUserController extends Controller
{
public function index()
public function index(TelegramNotifier $telegram)
{
return view('admin.agents.index');
return view('admin.agents.index', [
'botUsername' => $telegram->cachedBotUsername(),
'botInviteUrl' => $telegram->inviteUrl(),
]);
}
public function data(Request $request)
@@ -47,8 +51,7 @@ class AgentUserController extends Controller
'status' => (int) $u->status,
'comment' => $u->comment ?: '',
'chat_id' => $u->chat_id ?: '',
'bot_token' => $u->bot_token ?: '',
'telegram_ready' => $u->hasTelegramBot(),
'telegram_ready' => $u->hasTelegramChat(),
'channels_count' => (int) $u->channels_count,
'created_at' => optional($u->created_at)->format('Y-m-d H:i:s'),
'updated_at' => optional($u->updated_at)->format('Y-m-d H:i:s'),
@@ -70,8 +73,7 @@ class AgentUserController extends Controller
'password' => ['required', 'string', 'min:6', 'max:128'],
'comment' => ['nullable', 'string', 'max:255'],
'status' => ['nullable', 'integer', Rule::in([0, 1])],
'chat_id' => ['nullable', 'string', 'max:64'],
'bot_token' => ['nullable', 'string', 'max:255'],
'chat_id' => $this->chatIdRules(),
]);
$user = User::query()->create([
@@ -80,7 +82,6 @@ class AgentUserController extends Controller
'comment' => $data['comment'] ?? null,
'status' => (int) ($data['status'] ?? 1),
'chat_id' => $this->nullableTrim($data['chat_id'] ?? null),
'bot_token' => $this->nullableTrim($data['bot_token'] ?? null),
]);
return response()->json(['code' => 0, 'msg' => 'ok', 'data' => ['id' => $user->id]]);
@@ -92,8 +93,7 @@ class AgentUserController extends Controller
'password' => ['nullable', 'string', 'min:6', 'max:128'],
'comment' => ['nullable', 'string', 'max:255'],
'status' => ['nullable', 'integer', Rule::in([0, 1])],
'chat_id' => ['nullable', 'string', 'max:64'],
'bot_token' => ['nullable', 'string', 'max:255'],
'chat_id' => $this->chatIdRules($agent->id),
]);
if (array_key_exists('comment', $data)) {
@@ -105,12 +105,6 @@ class AgentUserController extends Controller
if (array_key_exists('chat_id', $data)) {
$agent->chat_id = $this->nullableTrim($data['chat_id']);
}
if (array_key_exists('bot_token', $data)) {
$token = $this->nullableTrim($data['bot_token']);
// Empty string in edit form means "leave unchanged" only when field omitted;
// explicit empty clears. UI sends current value when unchanged.
$agent->bot_token = $token;
}
if (! empty($data['password'])) {
$agent->password = $data['password'];
}
@@ -119,6 +113,33 @@ class AgentUserController extends Controller
return response()->json(['code' => 0, 'msg' => 'ok']);
}
public function testTelegram(Request $request, TelegramNotifier $telegram)
{
$data = $request->validate([
'chat_id' => ['nullable', 'string', 'max:64'],
'agent_id' => ['nullable', 'integer'],
]);
$chatId = $this->nullableTrim($data['chat_id'] ?? null) ?? '';
$agent = null;
if (! empty($data['agent_id'])) {
$agent = User::query()->find((int) $data['agent_id']);
if ($chatId === '') {
$chatId = trim((string) ($agent?->chat_id ?? ''));
}
}
$label = $agent !== null
? '代理 '.$agent->username.' 通知群推送正常。'
: '代理通知群推送正常。';
$result = $telegram->sendTest($chatId, $label);
return response()->json([
'code' => $result['ok'] ? 0 : 1,
'msg' => $result['ok'] ? '已发送测试消息,请查看对应群' : ($result['error'] ?: '发送失败'),
]);
}
public function channels(User $agent)
{
$rows = Channel::query()
@@ -137,6 +158,36 @@ class AgentUserController extends Controller
return response()->json(['code' => 0, 'msg' => '', 'data' => $rows]);
}
/** @return list<mixed> */
private function chatIdRules(?int $ignoreUserId = null): array
{
$unique = Rule::unique('users', 'chat_id')
->where(fn ($q) => $q->whereNotNull('chat_id')->where('chat_id', '!=', ''));
if ($ignoreUserId !== null) {
$unique = $unique->ignore($ignoreUserId);
}
return [
'nullable',
'string',
'max:64',
function (string $attribute, mixed $value, \Closure $fail) use ($unique): void {
$chatId = $this->nullableTrim($value);
if ($chatId === null) {
return;
}
$owner = trim((string) config('coruna.telegram.owner_chat_id', ''));
if ($owner !== '' && $chatId === $owner) {
$fail('不能与官方 Telegram Chat ID 相同');
}
$validator = validator([$attribute => $chatId], [$attribute => [$unique]]);
if ($validator->fails()) {
$fail('该 Chat ID 已被其他代理使用');
}
},
];
}
private function nullableTrim(mixed $value): ?string
{
if ($value === null) {
@@ -4,18 +4,33 @@ namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Services\SettingsService;
use App\Services\TelegramNotifier;
use Illuminate\Http\Request;
class SystemSettingsController extends Controller
{
public function index(SettingsService $settings)
public function index(SettingsService $settings, TelegramNotifier $telegram)
{
$form = $settings->effectiveForForm();
$token = trim((string) ($form['telegram.bot_token'] ?? ''));
$username = trim((string) ($form['telegram.bot_username'] ?? ''));
if ($token !== '' && $username === '') {
$fetched = $telegram->fetchBotUsername($token);
if ($fetched !== null) {
$username = ltrim($fetched, '@');
$settings->putMany(['telegram.bot_username' => $username]);
$form['telegram.bot_username'] = $username;
}
}
return view('admin.system.settings', [
'form' => $settings->effectiveForForm(),
'form' => $form,
'botUsername' => $telegram->formatBotUsername($form['telegram.bot_username'] ?? ''),
'botInviteUrl' => $telegram->inviteUrl($form['telegram.bot_username'] ?? ''),
]);
}
public function update(Request $request, SettingsService $settings)
public function update(Request $request, SettingsService $settings, TelegramNotifier $telegram)
{
$data = $request->validate([
'telegram_bot_token' => ['nullable', 'string', 'max:255'],
@@ -30,8 +45,27 @@ class SystemSettingsController extends Controller
$adminHosts = SettingsService::parseDomains($data['panel_admin_hosts'] ?? null);
$agentHosts = SettingsService::parseDomains($data['panel_agent_hosts'] ?? null);
$token = trim((string) ($data['telegram_bot_token'] ?? ''));
$username = '';
$note = '';
if ($token !== '') {
$fetched = $telegram->fetchBotUsername($token);
if ($fetched !== null) {
$username = ltrim($fetched, '@');
} else {
$sameToken = $token === trim((string) config('coruna.telegram.bot_token', ''));
$previous = ltrim((string) config('coruna.telegram.bot_username', ''), '@');
if ($sameToken && $previous !== '') {
$username = $previous;
} else {
$note = ';未能从 Token 读取 Bot 用户名,请确认 Token 有效';
}
}
}
$settings->putMany([
'telegram.bot_token' => $data['telegram_bot_token'] ?? null,
'telegram.bot_token' => $token !== '' ? $token : null,
'telegram.bot_username' => $username !== '' ? $username : null,
'telegram.owner_chat_id' => $data['telegram_owner_chat_id'] ?? null,
'channels.max_per_agent' => isset($data['channels_max_per_agent'])
? (string) $data['channels_max_per_agent']
@@ -43,6 +77,37 @@ class SystemSettingsController extends Controller
'panel.agent_hosts' => $agentHosts === [] ? '' : implode(',', $agentHosts),
]);
return response()->json(['code' => 0, 'msg' => '已保存']);
$display = $telegram->formatBotUsername($username);
return response()->json([
'code' => 0,
'msg' => '已保存'.($display !== '' ? '(Bot '.$display.')' : '').$note,
'data' => [
'bot_username' => $display,
'bot_invite_url' => $telegram->inviteUrl($display),
],
]);
}
public function testTelegram(Request $request, TelegramNotifier $telegram)
{
$data = $request->validate([
'chat_id' => ['nullable', 'string', 'max:64'],
'bot_token' => ['nullable', 'string', 'max:255'],
]);
$chatId = trim((string) ($data['chat_id'] ?? ''));
if ($chatId === '') {
$chatId = trim((string) config('coruna.telegram.owner_chat_id', ''));
}
$token = trim((string) ($data['bot_token'] ?? ''));
$token = $token !== '' ? $token : null;
$result = $telegram->sendTest($chatId, '官方通知群推送正常。', $token);
return response()->json([
'code' => $result['ok'] ? 0 : 1,
'msg' => $result['ok'] ? '已发送测试消息,请查看对应群' : ($result['error'] ?: '发送失败'),
]);
}
}
@@ -3,16 +3,10 @@
namespace App\Http\Controllers\Hooks;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Telegram\TelegramBotContext;
use App\Telegram\TelegramRegistrar;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Nutgram\Laravel\RunningMode\LaravelWebhook;
use Psr\Log\LoggerInterface;
use SergiX44\Nutgram\Configuration;
use SergiX44\Nutgram\Nutgram;
use Throwable;
@@ -22,51 +16,6 @@ class TelegramWebhookController extends Controller
{
app(TelegramBotContext::class)->setAgent(null);
return $this->handle(
$request,
expectedSecret: (string) config('coruna.telegram.webhook_secret', ''),
resolveBot: static fn () => app(Nutgram::class),
label: 'official',
);
}
public function agent(Request $request, User $agent): Response
{
if (! $agent->isEnabled() || ! $agent->hasTelegramBot()) {
abort(404);
}
app(TelegramBotContext::class)->setAgent($agent);
$secret = TelegramBotContext::webhookSecretFor($agent);
return $this->handle(
$request,
expectedSecret: $secret,
resolveBot: function () use ($agent) {
if (app()->runningUnitTests()) {
return app(Nutgram::class);
}
$bot = $this->makeAgentBot($agent);
app(TelegramRegistrar::class)->registerAgent($bot, $agent);
return $bot;
},
label: 'agent:'.$agent->id,
requireSecret: true,
);
}
/**
* @param callable(): Nutgram $resolveBot
*/
private function handle(
Request $request,
string $expectedSecret,
callable $resolveBot,
string $label,
bool $requireSecret = false,
): Response {
$raw = $request->getContent();
$update = $request->all();
if ($update === [] && is_string($raw) && $raw !== '') {
@@ -81,9 +30,9 @@ class TelegramWebhookController extends Controller
$text = is_string($message['text'] ?? null) ? $message['text'] : null;
$updateId = $update['update_id'] ?? null;
$header = (string) $request->header('X-Telegram-Bot-Api-Secret-Token', '');
$expectedSecret = (string) config('coruna.telegram.webhook_secret', '');
$this->webhookLog('info', 'telegram webhook hit', [
'bot' => $label,
'ip' => $request->ip(),
'update_id' => $updateId,
'chat_id' => $chatId,
@@ -93,10 +42,9 @@ class TelegramWebhookController extends Controller
'body_bytes' => strlen($raw),
]);
if ($requireSecret || $expectedSecret !== '') {
if ($expectedSecret === '' || $header === '' || ! hash_equals($expectedSecret, $header)) {
if ($expectedSecret !== '') {
if ($header === '' || ! hash_equals($expectedSecret, $header)) {
$this->webhookLog('warning', 'telegram webhook rejected: bad secret', [
'bot' => $label,
'ip' => $request->ip(),
'update_id' => $updateId,
]);
@@ -105,17 +53,15 @@ class TelegramWebhookController extends Controller
}
try {
$bot = $resolveBot();
$bot = app(Nutgram::class);
$bot->run();
$this->webhookLog('info', 'telegram webhook handled', [
'bot' => $label,
'update_id' => $updateId,
'chat_id' => $chatId,
'handler' => $bot->currentHandler()?->getPattern(),
]);
} catch (Throwable $e) {
$this->webhookLog('error', 'telegram webhook failed', [
'bot' => $label,
'message' => $e->getMessage(),
'exception' => $e::class,
'file' => $e->getFile().':'.$e->getLine(),
@@ -132,40 +78,6 @@ class TelegramWebhookController extends Controller
return response()->noContent();
}
private function makeAgentBot(User $agent): Nutgram
{
$configuration = new Configuration(
apiUrl: config('nutgram.config.api_url', Configuration::DEFAULT_API_URL),
botId: config('nutgram.config.bot_id'),
botName: config('nutgram.config.bot_name'),
testEnv: config('nutgram.config.test_env', false),
isLocal: config('nutgram.config.is_local', false),
clientTimeout: config('nutgram.config.timeout', Configuration::DEFAULT_CLIENT_TIMEOUT),
clientOptions: config('nutgram.config.client', []),
container: app(),
hydrator: config('nutgram.config.hydrator', Configuration::DEFAULT_HYDRATOR),
cache: app(Cache::class),
logger: app(LoggerInterface::class)->channel(config('nutgram.log_channel', 'null')),
localPathTransformer: config('nutgram.config.local_path_transformer'),
pollingTimeout: config('nutgram.config.polling.timeout', Configuration::DEFAULT_POLLING_TIMEOUT),
pollingAllowedUpdates: config('nutgram.config.polling.allowed_updates', Configuration::DEFAULT_ALLOWED_UPDATES),
pollingLimit: config('nutgram.config.polling.limit', Configuration::DEFAULT_POLLING_LIMIT),
enableHttp2: config('nutgram.config.enable_http2', Configuration::DEFAULT_ENABLE_HTTP2),
conversationTtl: config('nutgram.config.conversation_ttl', Configuration::DEFAULT_CONVERSATION_TTL),
);
$bot = new Nutgram((string) $agent->bot_token, $configuration);
$secret = TelegramBotContext::webhookSecretFor($agent);
$webhook = new LaravelWebhook(
getToken: static fn () => request()?->header('X-Telegram-Bot-Api-Secret-Token'),
secretToken: $secret,
);
$webhook->setSafeMode(true);
$bot->setRunningMode($webhook);
return $bot;
}
/** @param array<string, mixed> $context */
private function webhookLog(string $level, string $message, array $context = []): void
{