v2board/app/Http/Controllers/Guest/TelegramController.php

75 lines
2.6 KiB
PHP
Raw Normal View History

2020-05-17 15:23:39 +08:00
<?php
namespace App\Http\Controllers\Guest;
2020-05-20 15:51:32 +08:00
use App\Services\TelegramService;
2020-05-17 15:23:39 +08:00
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class TelegramController extends Controller
{
2020-05-20 16:11:18 +08:00
protected $msg;
2022-01-27 01:46:26 +08:00
protected $commands = [];
2020-05-20 16:11:18 +08:00
2020-05-17 15:23:39 +08:00
public function __construct(Request $request)
{
if ($request->input('access_token') !== md5(config('v2board.telegram_bot_token'))) {
2022-01-27 01:46:26 +08:00
abort(401);
2020-05-17 15:23:39 +08:00
}
}
public function webhook(Request $request)
{
2020-05-20 16:11:18 +08:00
$this->msg = $this->getMessage($request->input());
if (!$this->msg) return;
2022-01-27 01:46:26 +08:00
$this->handle();
}
public function handle()
{
$msg = $this->msg;
2020-05-20 15:51:32 +08:00
try {
2022-01-27 01:46:26 +08:00
foreach (glob(base_path('app//Plugins//Telegram//Commands') . '/*.php') as $file) {
$command = basename($file, '.php');
$class = '\\App\\Plugins\\Telegram\\Commands\\' . $command;
if (!class_exists($class)) continue;
$instance = new $class();
if ($msg->message_type === 'message') {
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;
}
2020-05-20 15:51:32 +08:00
}
} catch (\Exception $e) {
$telegramService = new TelegramService();
2022-01-27 01:46:26 +08:00
$telegramService->sendMessage($msg->chat_id, $e->getMessage());
2020-08-03 16:27:37 +08:00
}
}
2020-05-20 15:30:51 +08:00
private function getMessage(array $data)
{
2020-05-28 16:10:43 +08:00
if (!isset($data['message'])) return false;
2020-05-20 15:30:51 +08:00
$obj = new \StdClass();
2020-05-28 16:10:43 +08:00
if (!isset($data['message']['text'])) return false;
2020-05-20 15:30:51 +08:00
$text = explode(' ', $data['message']['text']);
2020-05-20 15:53:23 +08:00
$obj->command = $text[0];
$obj->args = array_slice($text, 1);
$obj->chat_id = $data['message']['chat']['id'];
$obj->message_id = $data['message']['message_id'];
2022-01-27 01:46:26 +08:00
$obj->message_type = !isset($data['message']['reply_to_message']['text']) ? 'message' : 'reply_message';
2020-08-03 16:27:37 +08:00
$obj->text = $data['message']['text'];
2022-01-27 01:46:26 +08:00
$obj->is_private = $data['message']['chat']['type'] === 'private';
2022-01-27 14:56:44 +08:00
if ($obj->message_type === 'reply_message') {
2020-08-03 16:27:37 +08:00
$obj->reply_text = $data['message']['reply_to_message']['text'];
}
2020-05-20 15:30:51 +08:00
return $obj;
}
2020-05-17 15:23:39 +08:00
}