v2board/app/Services/TelegramService.php

86 lines
2.3 KiB
PHP
Raw Normal View History

2020-05-17 15:23:39 +08:00
<?php
namespace App\Services;
2020-07-31 15:22:27 +08:00
use App\Jobs\SendTelegramJob;
2020-08-02 15:05:27 +08:00
use App\Models\User;
2020-05-17 15:23:39 +08:00
use \Curl\Curl;
2021-12-17 13:35:54 +08:00
use Illuminate\Mail\Markdown;
2020-05-17 15:23:39 +08:00
class TelegramService {
protected $api;
2020-05-19 16:32:35 +08:00
public function __construct($token = '')
2020-05-17 15:23:39 +08:00
{
2020-07-05 19:24:25 +08:00
$this->api = 'https://api.telegram.org/bot' . config('v2board.telegram_bot_token', $token) . '/';
2020-05-17 15:23:39 +08:00
}
public function sendMessage(int $chatId, string $text, string $parseMode = '')
{
2021-12-17 13:35:54 +08:00
if ($parseMode === 'markdown') {
2021-12-23 14:25:05 +08:00
$text = str_replace('_', '\_', $text);
2021-12-17 13:35:54 +08:00
}
2020-05-17 15:23:39 +08:00
$this->request('sendMessage', [
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => $parseMode
]);
}
public function approveChatJoinRequest(int $chatId, int $userId)
{
$this->request('approveChatJoinRequest', [
'chat_id' => $chatId,
'user_id' => $userId
]);
}
public function declineChatJoinRequest(int $chatId, int $userId)
{
$this->request('declineChatJoinRequest', [
'chat_id' => $chatId,
'user_id' => $userId
]);
}
2020-05-17 15:23:39 +08:00
public function getMe()
{
2020-05-19 16:32:35 +08:00
return $this->request('getMe');
2020-05-17 15:23:39 +08:00
}
public function setWebhook(string $url)
{
2020-05-19 16:32:35 +08:00
return $this->request('setWebhook', [
2020-05-17 15:23:39 +08:00
'url' => $url
]);
}
private function request(string $method, array $params = [])
{
$curl = new Curl();
2020-05-19 16:32:35 +08:00
$curl->get($this->api . $method . '?' . http_build_query($params));
$response = $curl->response;
2020-05-17 15:23:39 +08:00
$curl->close();
2021-08-07 18:00:33 +08:00
if (!isset($response->ok)) abort(500, '请求失败');
2020-05-19 16:32:35 +08:00
if (!$response->ok) {
abort(500, '来自TG的错误' . $response->description);
}
return $response;
2020-05-17 15:23:39 +08:00
}
2020-07-31 15:22:27 +08:00
2020-09-20 16:41:48 +08:00
public function sendMessageWithAdmin($message, $isStaff = false)
2020-07-31 15:22:27 +08:00
{
if (!config('v2board.telegram_bot_enable', 0)) return;
2020-09-20 16:41:48 +08:00
$users = User::where(function ($query) use ($isStaff) {
$query->where('is_admin', 1);
if ($isStaff) {
$query->orWhere('is_staff', 1);
}
2020-09-19 22:52:05 +08:00
})
2020-07-31 15:22:27 +08:00
->where('telegram_id', '!=', NULL)
->get();
foreach ($users as $user) {
SendTelegramJob::dispatch($user->telegram_id, $message);
}
}
2020-05-17 15:23:39 +08:00
}