Created
September 19, 2024 11:32
-
-
Save eyupfidan/9bfc3ad0232642edac136916a5f7d854 to your computer and use it in GitHub Desktop.
Telegram Service For Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Services; | |
use GuzzleHttp\Client; | |
use GuzzleHttp\Exception\GuzzleException; | |
class TelegramServices | |
{ | |
protected Client $client; | |
protected string $botToken; | |
protected string $chatId; | |
public function __construct() | |
{ | |
$this->client = new Client(); | |
$this->botToken = env('TELEGRAM_BOT_TOKEN'); | |
$this->chatId = env('TELEGRAM_CHAT_ID'); | |
} | |
/** | |
* Send the message on Telegram | |
* | |
* @param string $message | |
* @param string|null $chatId | |
* @return mixed | |
*/ | |
public function sendMessage(string $message, ?string $chatId = null): mixed | |
{ | |
$chatId = $chatId ?? $this->chatId; | |
try { | |
$response = $this->client->post("https://api.telegram.org/bot{$this->botToken}/sendMessage", [ | |
'json' => [ | |
'chat_id' => $this->$chatId, | |
'text' => $message, | |
'parse_mode' => 'HTML', # HTML Support | |
], | |
]); | |
return json_decode($response->getBody(), true); | |
} catch (GuzzleException $e) { | |
return $e->getMessage(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment