botToken = $botToken ?? config('services.telegram.bot_token'); } /** * Send a message to a Telegram chat. * * @param string $chatId The chat ID to send the message to. * @param string $message The message text (supports Markdown). * @return bool True if the message was sent successfully. */ public function sendMessage(string $chatId, string $message): bool { if (empty($this->botToken)) { Log::error('TelegramService: No bot token configured.'); return false; } try { $url = $this->apiBase . $this->botToken . '/sendMessage'; $client = new \GuzzleHttp\Client(); $response = $client->post($url, [ 'json' => [ 'chat_id' => $chatId, 'text' => $message, 'parse_mode' => 'Markdown', ], 'timeout' => 10, ]); $data = json_decode($response->getBody()->getContents(), true); if ($data && ($data['ok'] ?? false)) { return true; } Log::error('TelegramService: API error', [ 'response' => $data, 'chat_id' => $chatId, ]); return false; } catch (\Exception $e) { Log::error('TelegramService: Failed to send message', [ 'error' => $e->getMessage(), 'chat_id' => $chatId, ]); return false; } } /** * Set a webhook for the bot. * * @param string $url The webhook URL. * @return bool True if the webhook was set successfully. */ public function setWebhook(string $url): bool { if (empty($this->botToken)) { Log::error('TelegramService: No bot token configured for webhook.'); return false; } try { $webhookUrl = $this->apiBase . $this->botToken . '/setWebhook'; $client = new \GuzzleHttp\Client(); $response = $client->post($webhookUrl, [ 'json' => [ 'url' => $url, 'allowed_updates' => ['message', 'callback_query'], ], 'timeout' => 10, ]); $data = json_decode($response->getBody()->getContents(), true); return $data && ($data['ok'] ?? false); } catch (\Exception $e) { Log::error('TelegramService: Failed to set webhook', [ 'error' => $e->getMessage(), ]); return false; } } /** * Get bot information. * * @return array|null Bot info or null on failure. */ public function getMe(): ?array { if (empty($this->botToken)) { return null; } try { $url = $this->apiBase . $this->botToken . '/getMe'; $client = new \GuzzleHttp\Client(); $response = $client->get($url, ['timeout' => 10]); $data = json_decode($response->getBody()->getContents(), true); if ($data && ($data['ok'] ?? false)) { return $data['result']; } return null; } catch (\Exception $e) { Log::error('TelegramService: Failed to get bot info', [ 'error' => $e->getMessage(), ]); return null; } } }