mirror of
				https://github.com/v2board/v2board.git
				synced 2025-11-04 03:11:46 +08:00 
			
		
		
		
	
		
			
				
	
	
		
			65 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			65 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
<?php
 | 
						||
namespace App\Services;
 | 
						||
 | 
						||
use App\Jobs\SendTelegramJob;
 | 
						||
use App\Models\User;
 | 
						||
use \Curl\Curl;
 | 
						||
 | 
						||
class TelegramService {
 | 
						||
    protected $api;
 | 
						||
 | 
						||
    public function __construct($token = '')
 | 
						||
    {
 | 
						||
        $this->api = 'https://api.telegram.org/bot' . config('v2board.telegram_bot_token', $token) . '/';
 | 
						||
    }
 | 
						||
 | 
						||
    public function sendMessage(int $chatId, string $text, string $parseMode = '')
 | 
						||
    {
 | 
						||
        $this->request('sendMessage', [
 | 
						||
            'chat_id' => $chatId,
 | 
						||
            'text' => $text,
 | 
						||
            'parse_mode' => $parseMode
 | 
						||
        ]);
 | 
						||
    }
 | 
						||
 | 
						||
    public function getMe()
 | 
						||
    {
 | 
						||
        return $this->request('getMe');
 | 
						||
    }
 | 
						||
 | 
						||
    public function setWebhook(string $url)
 | 
						||
    {
 | 
						||
        return $this->request('setWebhook', [
 | 
						||
            'url' => $url
 | 
						||
        ]);
 | 
						||
    }
 | 
						||
 | 
						||
    private function request(string $method, array $params = [])
 | 
						||
    {
 | 
						||
        $curl = new Curl();
 | 
						||
        $curl->get($this->api . $method . '?' . http_build_query($params));
 | 
						||
        $response = $curl->response;
 | 
						||
        $curl->close();
 | 
						||
        if (!$response->ok) {
 | 
						||
            abort(500, '来自TG的错误:' . $response->description);
 | 
						||
        }
 | 
						||
        return $response;
 | 
						||
    }
 | 
						||
 | 
						||
    public function sendMessageWithAdmin($message, $isStaff = false)
 | 
						||
    {
 | 
						||
        if (!config('v2board.telegram_bot_enable', 0)) return;
 | 
						||
        $users = User::where(function ($query) use ($isStaff) {
 | 
						||
            $query->where('is_admin', 1);
 | 
						||
            if ($isStaff) {
 | 
						||
                $query->orWhere('is_staff', 1);
 | 
						||
            }
 | 
						||
        })
 | 
						||
            ->where('telegram_id', '!=', NULL)
 | 
						||
            ->get();
 | 
						||
        foreach ($users as $user) {
 | 
						||
            SendTelegramJob::dispatch($user->telegram_id, $message);
 | 
						||
        }
 | 
						||
    }
 | 
						||
}
 |