Created
November 23, 2019 05:45
-
-
Save theconsolelogger/a42160d4cefb5e4bd61fd1c56cb00845 to your computer and use it in GitHub Desktop.
A PHP class that can be used in a Laravel project to send response messages to the Telegram Bot API.
This file contains hidden or 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\Helpers; | |
use GuzzleHttp\Client; | |
class Telegram | |
{ | |
private $chat_id; | |
private $message_id; | |
private $api_key; | |
private $base_uri = 'https://api.telegram.org/'; | |
private $client; | |
public function __construct() | |
{ | |
if (!env('TELEGRAM_KEY')) | |
{ | |
throw new Exception('Telegram key not set. Please set TELEGRAM_KEY in .env file.'); | |
} | |
$this->api_key = urlencode(env('TELEGRAM_KEY')); | |
$this->client = new Client([ | |
'base_uri' => $this->base_uri, | |
'headers' => [ | |
'Content-type' => 'application/json' | |
] | |
]); | |
} | |
public function setChatId($id) | |
{ | |
$this->chat_id = $id; | |
return $this; | |
} | |
public function setMessageId($id) | |
{ | |
$this->message_id = $id; | |
return $this; | |
} | |
public function sendAnimation($image, $caption) | |
{ | |
return $this->send('/sendAnimation', [ | |
'chat_id' => $this->chat_id, | |
'animation' => $image, | |
'caption' => $caption.' - Powered by GIPHY', | |
'reply_to_message_id' => $this->message_id | |
]); | |
} | |
public function sendMessage($text) | |
{ | |
return $this->send('/sendMessage', [ | |
'chat_id' => $this->chat_id, | |
'text' => $text, | |
'reply_to_message_id' => $this->message_id | |
]); | |
} | |
public function sendPoll($question, $options) | |
{ | |
return $this->send('/sendPoll', [ | |
'chat_id' => $this->chat_id, | |
'question' => $question, | |
'options' => $options, | |
'reply_to_message_id' => $this->message_id | |
]); | |
} | |
public function sendLocation($location) | |
{ | |
return $this->send('/sendLocation', [ | |
'chat_id' => $this->chat_id, | |
'longitude' => $location['longitude'], | |
'latitude' => $location['latitude'], | |
'reply_to_message_id' => $this->message_id | |
]); | |
} | |
private function send($url, $json) | |
{ | |
if (!app()->environment('production')) | |
{ | |
return response($json, 200); | |
} | |
$this->client->post('bot'.$this->api_key.$url, [ | |
'json' => $json | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment