2020-05-17 15:23:39 +08:00
|
|
|
|
<?php
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
|
|
|
|
|
use \Curl\Curl;
|
|
|
|
|
|
|
|
|
|
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 = '')
|
|
|
|
|
{
|
|
|
|
|
$this->request('sendMessage', [
|
|
|
|
|
'chat_id' => $chatId,
|
|
|
|
|
'text' => $text,
|
|
|
|
|
'parse_mode' => $parseMode
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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();
|
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
|
|
|
|
}
|
|
|
|
|
}
|