Skip to content

Instantly share code, notes, and snippets.

@kas-cor
Last active August 11, 2016 06:28
Show Gist options
  • Save kas-cor/1ee5d1a37857ef8f9a3ddf584a095cb5 to your computer and use it in GitHub Desktop.
Save kas-cor/1ee5d1a37857ef8f9a3ddf584a095cb5 to your computer and use it in GitHub Desktop.
Telegram sendMessage API
<?php
/**
* @author kas-cor <[email protected]>
* @link http://github.com/kas-cor repositories
*/
namespace cls;
class Telegram {
/**
* Access token API
* @var string
*/
private $token;
/**
* @param string $token Access token
*/
public function __construct($token) {
$this->token = $token;
}
/**
* Send message to chat id
* @param string $chat_id
* @param string $text
* @return string response json
*/
public function sendMessage($chat_id, $text) {
$message = urlencode(strip_tags(trim($this->convertToUtf8($text))));
$url = "https://api.telegram.org/bot" . $this->token . "/sendMessage?chat_id=" . $chat_id . "&text=" . $message;
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, "TelegramBot");
$json = curl_exec($curl_handle);
curl_close($curl_handle);
return $json;
}
/**
* Convert to utf-8, if win-1251
* @param type $text
* @return type
*/
private function convertToUtf8($text) {
if (!preg_match("//u", $text)) {
return iconv("windows-1251", "utf-8", $text);
} else {
return $text;
}
}
}
@kas-cor
Copy link
Author

kas-cor commented Jun 29, 2016

Useing

$telegram = New Telegram("token");
$chat_id = "123456789";
$text = "Test\nTest\nTest\nTest";
echo $telegram->sendMessage($chat_id, $text);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment