-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathTelegramChannelAdapter.php
More file actions
67 lines (57 loc) · 1.77 KB
/
TelegramChannelAdapter.php
File metadata and controls
67 lines (57 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
namespace Bow\Notifier\Adapters;
use Bow\Database\Barry\Model;
use Bow\Http\Client\HttpClient;
use Bow\Notifier\Contracts\ChannelAdapterInterface;
use Bow\Notifier\Notifier;
use Exception;
use InvalidArgumentException;
use RuntimeException;
class TelegramChannelAdapter implements ChannelAdapterInterface
{
/**
* @var string
*/
private ?string $botToken;
/**
* Constructor
*
* @throws InvalidArgumentException When Telegram bot token is missing
*/
public function __construct()
{
$this->botToken = config('messaging.telegram.bot_token');
}
/**
* Envoyer le message via Telegram
*
* @param Model $context
* @param Notifier $notifier
* @return void
* @throws Exception
*/
public function send(Model $context, Notifier $notifier): void
{
if (!method_exists($notifier, 'toTelegram')) {
return;
}
$data = $notifier->toTelegram($context);
if (!isset($data['chat_id']) || !isset($data['message'])) {
throw new InvalidArgumentException('The chat ID and message are required for Telegram');
}
if (!$this->botToken) {
throw new InvalidArgumentException('The Telegram bot token is required');
}
$client = new HttpClient();
$endpoint = "https://api.telegram.org/bot{$this->botToken}/sendMessage";
try {
$client->acceptJson()->post($endpoint, [
'chat_id' => $data['chat_id'],
'text' => $data['message'],
'parse_mode' => $data['parse_mode'] ?? 'HTML'
]);
} catch (Exception $e) {
throw new RuntimeException('Error while sending Telegram message: ' . $e->getMessage());
}
}
}