update: telegram bot modularization

This commit is contained in:
tokumeikoi 2022-01-27 01:46:26 +08:00
parent 1790de63f6
commit 5bf1dd3426
12 changed files with 279 additions and 156 deletions

View File

@ -2,8 +2,10 @@
namespace App\Console; namespace App\Console;
use App\Utils\CacheKey;
use Illuminate\Console\Scheduling\Schedule; use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel; use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\Cache;
class Kernel extends ConsoleKernel class Kernel extends ConsoleKernel
{ {
@ -24,6 +26,7 @@ class Kernel extends ConsoleKernel
*/ */
protected function schedule(Schedule $schedule) protected function schedule(Schedule $schedule)
{ {
Cache::put(CacheKey::get('SCHEDULE_LAST_CHECK_AT', null), time());
// v2board // v2board
$schedule->command('v2board:statistics')->dailyAt('0:10'); $schedule->command('v2board:statistics')->dailyAt('0:10');
// check // check

View File

@ -0,0 +1,52 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Models\ServerShadowsocks;
use App\Models\ServerTrojan;
use App\Services\ServerService;
use App\Utils\CacheKey;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ServerGroup;
use App\Models\ServerV2ray;
use App\Models\Plan;
use App\Models\User;
use App\Models\Ticket;
use App\Models\Order;
use App\Models\StatOrder;
use App\Models\StatServer;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Laravel\Horizon\Contracts\MasterSupervisorRepository;
class SystemController extends Controller
{
public function getStatus()
{
return response([
'data' => [
'schedule' => $this->getScheduleStatus(),
'horizon' => $this->getHorizonStatus()
]
]);
}
protected function getScheduleStatus():bool
{
return (time() - 120) < Cache::get(CacheKey::get('SCHEDULE_LAST_CHECK_AT', null));
}
protected function getHorizonStatus():bool
{
if (! $masters = app(MasterSupervisorRepository::class)->all()) {
return false;
}
return collect($masters)->contains(function ($master) {
return $master->status === 'paused';
}) ? false : true;
}
}

View File

@ -5,18 +5,16 @@ namespace App\Http\Controllers\Guest;
use App\Services\TelegramService; use App\Services\TelegramService;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Models\User;
use App\Utils\Helper;
use App\Services\TicketService;
class TelegramController extends Controller class TelegramController extends Controller
{ {
protected $msg; protected $msg;
protected $commands = [];
public function __construct(Request $request) public function __construct(Request $request)
{ {
if ($request->input('access_token') !== md5(config('v2board.telegram_bot_token'))) { if ($request->input('access_token') !== md5(config('v2board.telegram_bot_token'))) {
abort(500, 'authentication failed'); abort(401);
} }
} }
@ -24,41 +22,34 @@ class TelegramController extends Controller
{ {
$this->msg = $this->getMessage($request->input()); $this->msg = $this->getMessage($request->input());
if (!$this->msg) return; if (!$this->msg) return;
$this->handle();
}
public function handle()
{
$msg = $this->msg;
try { try {
switch($this->msg->message_type) { foreach (glob(base_path('app//Plugins//Telegram//Commands') . '/*.php') as $file) {
case 'send': $command = basename($file, '.php');
$this->fromSend(); $class = '\\App\\Plugins\\Telegram\\Commands\\' . $command;
break; if (!class_exists($class)) continue;
case 'reply': $instance = new $class();
$this->fromReply(); if ($msg->message_type === 'message') {
break; if (!isset($instance->command)) continue;
if ($msg->command !== $instance->command) continue;
$instance->handle($msg);
return;
}
if ($msg->message_type === 'reply_message') {
if (!isset($instance->regex)) continue;
if (!preg_match($instance->regex, $msg->reply_text, $match)) continue;
$instance->handle($msg, $match);
return;
}
} }
} catch (\Exception $e) { } catch (\Exception $e) {
$telegramService = new TelegramService(); $telegramService = new TelegramService();
$telegramService->sendMessage($this->msg->chat_id, $e->getMessage()); $telegramService->sendMessage($msg->chat_id, $e->getMessage());
}
}
private function fromSend()
{
switch($this->msg->command) {
case '/bind': $this->bind();
break;
case '/traffic': $this->traffic();
break;
case '/getlatesturl': $this->getLatestUrl();
break;
case '/unbind': $this->unbind();
break;
default: $this->help();
}
}
private function fromReply()
{
// ticket
if (preg_match("/[#](.*)/", $this->msg->reply_text, $match)) {
$this->replayTicket($match[1]);
} }
} }
@ -66,136 +57,18 @@ class TelegramController extends Controller
{ {
if (!isset($data['message'])) return false; if (!isset($data['message'])) return false;
$obj = new \StdClass(); $obj = new \StdClass();
$obj->is_private = $data['message']['chat']['type'] === 'private' ? true : false;
if (!isset($data['message']['text'])) return false; if (!isset($data['message']['text'])) return false;
$text = explode(' ', $data['message']['text']); $text = explode(' ', $data['message']['text']);
$obj->command = $text[0]; $obj->command = $text[0];
$obj->args = array_slice($text, 1); $obj->args = array_slice($text, 1);
$obj->chat_id = $data['message']['chat']['id']; $obj->chat_id = $data['message']['chat']['id'];
$obj->message_id = $data['message']['message_id']; $obj->message_id = $data['message']['message_id'];
$obj->message_type = !isset($data['message']['reply_to_message']['text']) ? 'send' : 'reply'; $obj->message_type = !isset($data['message']['reply_to_message']['text']) ? 'message' : 'reply_message';
$obj->text = $data['message']['text']; $obj->text = $data['message']['text'];
$obj->is_private = $data['message']['chat']['type'] === 'private';
if ($obj->message_type === 'reply') { if ($obj->message_type === 'reply') {
$obj->reply_text = $data['message']['reply_to_message']['text']; $obj->reply_text = $data['message']['reply_to_message']['text'];
} }
return $obj; return $obj;
} }
private function bind()
{
$msg = $this->msg;
if (!$msg->is_private) return;
if (!isset($msg->args[0])) {
abort(500, '参数有误,请携带订阅地址发送');
}
$subscribeUrl = $msg->args[0];
$subscribeUrl = parse_url($subscribeUrl);
parse_str($subscribeUrl['query'], $query);
$token = $query['token'];
if (!$token) {
abort(500, '订阅地址无效');
}
$user = User::where('token', $token)->first();
if (!$user) {
abort(500, '用户不存在');
}
if ($user->telegram_id) {
abort(500, '该账号已经绑定了Telegram账号');
}
$user->telegram_id = $msg->chat_id;
if (!$user->save()) {
abort(500, '设置失败');
}
$telegramService = new TelegramService();
$telegramService->sendMessage($msg->chat_id, '绑定成功');
}
private function unbind()
{
$msg = $this->msg;
if (!$msg->is_private) return;
$user = User::where('telegram_id', $msg->chat_id)->first();
$telegramService = new TelegramService();
if (!$user) {
$this->help();
$telegramService->sendMessage($msg->chat_id, '没有查询到您的用户信息,请先绑定账号', 'markdown');
return;
}
$user->telegram_id = NULL;
if (!$user->save()) {
abort(500, '解绑失败');
}
$telegramService->sendMessage($msg->chat_id, '解绑成功', 'markdown');
}
private function help()
{
$msg = $this->msg;
if (!$msg->is_private) return;
$telegramService = new TelegramService();
$commands = [
'/bind 订阅地址 - 绑定你的' . config('v2board.app_name', 'V2Board') . '账号',
'/traffic - 查询流量信息',
'/getlatesturl - 获取最新的' . config('v2board.app_name', 'V2Board') . '网址',
'/unbind - 解除绑定'
];
$text = implode(PHP_EOL, $commands);
$telegramService->sendMessage($msg->chat_id, "你可以使用以下命令进行操作:\n\n$text", 'markdown');
}
private function traffic()
{
$msg = $this->msg;
if (!$msg->is_private) return;
$user = User::where('telegram_id', $msg->chat_id)->first();
$telegramService = new TelegramService();
if (!$user) {
$this->help();
$telegramService->sendMessage($msg->chat_id, '没有查询到您的用户信息,请先绑定账号', 'markdown');
return;
}
$transferEnable = Helper::trafficConvert($user->transfer_enable);
$up = Helper::trafficConvert($user->u);
$down = Helper::trafficConvert($user->d);
$remaining = Helper::trafficConvert($user->transfer_enable - ($user->u + $user->d));
$text = "🚥流量查询\n———————————————\n计划流量:`{$transferEnable}`\n已用上行:`{$up}`\n已用下行:`{$down}`\n剩余流量:`{$remaining}`";
$telegramService->sendMessage($msg->chat_id, $text, 'markdown');
}
private function getLatestUrl()
{
$msg = $this->msg;
$user = User::where('telegram_id', $msg->chat_id)->first();
$telegramService = new TelegramService();
$text = sprintf(
"%s的最新网址是%s",
config('v2board.app_name', 'V2Board'),
config('v2board.app_url')
);
$telegramService->sendMessage($msg->chat_id, $text, 'markdown');
}
private function replayTicket($ticketId)
{
$msg = $this->msg;
if (!$msg->is_private) return;
$user = User::where('telegram_id', $msg->chat_id)->first();
if (!$user) {
abort(500, '用户不存在');
}
$ticketService = new TicketService();
if (!$msg->text) return;
if ($user->is_admin || $user->is_staff) {
$ticketService->replyByAdmin(
$ticketId,
$msg->text,
$user->id
);
}
$telegramService = new TelegramService();
$telegramService->sendMessage($msg->chat_id, "#`{$ticketId}` 的工单已回复成功", 'markdown');
$telegramService->sendMessageWithAdmin("#`{$ticketId}` 的工单已由 {$user->email} 进行回复", true);
}
} }

View File

@ -110,6 +110,8 @@ class AdminRoute
$router->post('/payment/getPaymentForm', 'Admin\\PaymentController@getPaymentForm'); $router->post('/payment/getPaymentForm', 'Admin\\PaymentController@getPaymentForm');
$router->post('/payment/save', 'Admin\\PaymentController@save'); $router->post('/payment/save', 'Admin\\PaymentController@save');
$router->post('/payment/drop', 'Admin\\PaymentController@drop'); $router->post('/payment/drop', 'Admin\\PaymentController@drop');
// System
$router->get ('/system/getStatus', 'Admin\\SystemController@getStatus');
}); });
} }
} }

View File

@ -0,0 +1,38 @@
<?php
namespace App\Plugins\Telegram\Commands;
use App\Models\User;
use App\Plugins\Telegram\Telegram;
class Bind extends Telegram {
public $command = '/bind';
public $description = '将Telegram账号绑定到网站';
public function handle($message, $match = []) {
if (!$message->is_private) return;
if (!isset($message->args[0])) {
abort(500, '参数有误,请携带订阅地址发送');
}
$subscribeUrl = $message->args[0];
$subscribeUrl = parse_url($subscribeUrl);
parse_str($subscribeUrl['query'], $query);
$token = $query['token'];
if (!$token) {
abort(500, '订阅地址无效');
}
$user = User::where('token', $token)->first();
if (!$user) {
abort(500, '用户不存在');
}
if ($user->telegram_id) {
abort(500, '该账号已经绑定了Telegram账号');
}
$user->telegram_id = $message->chat_id;
if (!$user->save()) {
abort(500, '设置失败');
}
$telegramService = $this->telegramService;
$telegramService->sendMessage($message->chat_id, '绑定成功');
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Plugins\Telegram\Commands;
use App\Models\User;
use App\Plugins\Telegram\Telegram;
class GetLatestUrl extends Telegram {
public $command = '/getlatesturl';
public $description = '将Telegram账号绑定到网站';
public function handle($message, $match = []) {
$telegramService = $this->telegramService;
$text = sprintf(
"%s的最新网址是%s",
config('v2board.app_name', 'V2Board'),
config('v2board.app_url')
);
$telegramService->sendMessage($message->chat_id, $text, 'markdown');
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Plugins\Telegram\Commands;
use App\Plugins\Telegram\Telegram;
class Help extends Telegram {
public $command = '/help';
public $description = '获取帮助';
public function handle($message, $match = []) {
if (!$message->is_private) return;
$commands = [
'/bind 订阅地址 - 绑定你的' . config('v2board.app_name', 'V2Board') . '账号',
'/traffic - 查询流量信息',
'/getlatesturl - 获取最新的' . config('v2board.app_name', 'V2Board') . '网址',
'/unbind - 解除绑定'
];
$text = implode(PHP_EOL, $commands);
$this->telegramService->sendMessage($message->chat_id, "你可以使用以下命令进行操作:\n\n$text", 'markdown');
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Plugins\Telegram\Commands;
use App\Models\User;
use App\Plugins\Telegram\Telegram;
use App\Services\TicketService;
class ReplyTicket extends Telegram {
public $regex = '/[#](.*)/';
public $description = '获取帮助';
public function handle($message, $match = []) {
if (!$message->is_private) return;
$this->replayTicket($message, $match[1]);
}
private function replayTicket($msg, $ticketId)
{
$user = User::where('telegram_id', $msg->chat_id)->first();
if (!$user) {
abort(500, '用户不存在');
}
$ticketService = new TicketService();
if (!$msg->text) return;
if ($user->is_admin || $user->is_staff) {
$ticketService->replyByAdmin(
$ticketId,
$msg->text,
$user->id
);
}
$telegramService = $this->telegramService;
$telegramService->sendMessage($msg->chat_id, "#`{$ticketId}` 的工单已回复成功", 'markdown');
$telegramService->sendMessageWithAdmin("#`{$ticketId}` 的工单已由 {$user->email} 进行回复", true);
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Plugins\Telegram\Commands;
use App\Models\User;
use App\Plugins\Telegram\Telegram;
use App\Utils\Helper;
class Traffic extends Telegram {
public $command = '/traffic';
public $description = '查询流量信息';
public function handle($message, $match = []) {
$telegramService = $this->telegramService;
if (!$message->is_private) return;
$user = User::where('telegram_id', $message->chat_id)->first();
if (!$user) {
$help = new Help();
$help->handle($message);
$telegramService->sendMessage($message->chat_id, '没有查询到您的用户信息,请先绑定账号', 'markdown');
return;
}
$transferEnable = Helper::trafficConvert($user->transfer_enable);
$up = Helper::trafficConvert($user->u);
$down = Helper::trafficConvert($user->d);
$remaining = Helper::trafficConvert($user->transfer_enable - ($user->u + $user->d));
$text = "🚥流量查询\n———————————————\n计划流量:`{$transferEnable}`\n已用上行:`{$up}`\n已用下行:`{$down}`\n剩余流量:`{$remaining}`";
$telegramService->sendMessage($message->chat_id, $text, 'markdown');
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Plugins\Telegram\Commands;
use App\Models\User;
use App\Plugins\Telegram\Telegram;
class UnBind extends Telegram {
public $command = '/unbind';
public $description = '将Telegram账号从网站解绑';
public function handle($message, $match = []) {
if (!$message->is_private) return;
$user = User::where('telegram_id', $message->chat_id)->first();
$telegramService = $this->telegramService;
if (!$user) {
$help = new Help();
$help->handle($message);
$telegramService->sendMessage($message->chat_id, '没有查询到您的用户信息,请先绑定账号', 'markdown');
return;
}
$user->telegram_id = NULL;
if (!$user->save()) {
abort(500, '解绑失败');
}
$telegramService->sendMessage($message->chat_id, '解绑成功', 'markdown');
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace App\Plugins\Telegram;
use App\Services\TelegramService;
abstract class Telegram {
abstract protected function handle($message, $match);
public $telegramService;
public function __construct()
{
$this->telegramService = new TelegramService();
}
}

View File

@ -17,7 +17,8 @@ class CacheKey
'SERVER_SHADOWSOCKS_LAST_CHECK_AT' => 'ss节点最后检查时间', 'SERVER_SHADOWSOCKS_LAST_CHECK_AT' => 'ss节点最后检查时间',
'SERVER_SHADOWSOCKS_LAST_PUSH_AT' => 'ss节点最后推送时间', 'SERVER_SHADOWSOCKS_LAST_PUSH_AT' => 'ss节点最后推送时间',
'TEMP_TOKEN' => '临时令牌', 'TEMP_TOKEN' => '临时令牌',
'LAST_SEND_EMAIL_REMIND_TRAFFIC' => '最后发送流量邮件提醒' 'LAST_SEND_EMAIL_REMIND_TRAFFIC' => '最后发送流量邮件提醒',
'SCHEDULE_LAST_CHECK_AT' => '计划任务最后检查时间'
]; ];
public static function get(string $key, $uniqueValue) public static function get(string $key, $uniqueValue)