Skip to content

Instantly share code, notes, and snippets.

@itskenny0
Created October 18, 2016 12:43
Show Gist options
  • Save itskenny0/f819db7fc93e152b6115192944d622a2 to your computer and use it in GitHub Desktop.
Save itskenny0/f819db7fc93e152b6115192944d622a2 to your computer and use it in GitHub Desktop.
Tiny, incomplete, hacky Telegram bot API class
<?php
class Telegram {
const API_ROOT = "https://api.telegram.org/bot%KEY%/%METHOD%";
private $botkey;
private $methods = [
"getUpdates" => [
"meta" => [
"type" => "POST"
],
"fields" => [
"update_id" => true,
"message" => false,
"edited_message" => false,
"inline_query" => false,
"chosen_inline_result" => false,
"callback_query" => false
]
],
"sendMessage" => [
"meta" => [
"type" => "POST"
],
"fields" => [
"chat_id" => true,
"text" => true,
"parse_mode" => false,
"disable_web_page_preview" => false,
"disable_notification" => false,
"reply_to_message_id" => false,
"reply_markup" => false
]
],
"getMe" => [
"meta" => [
"type" => "POST"
],
"fields" => []
]
];
public function __construct($botkey) {
$this->botkey = $botkey;
}
public function __call($name, $args = array()) {
if(!isset($this->methods[$name])) throw new Exception("Call to non-existant function " . $name . ".");
$request = array();
$methods = $this->methods[$name]['fields'];
while(1) {
list($field, $required) = each($methods);
if(empty($field)) break;
if($required === true && empty($args)) throw new Exception("Missing argument $field for $name.");
if(empty($args)) break;
$request[$field] = array_shift($args);
}
$output = curl_exec($this->buildRequest($name, $request));
$output = json_decode($output);
return $output;
}
private function buildRequest($method, $args) {
$url = self::API_ROOT;
$url = str_replace("%KEY%", $this->botkey, $url);
$url = str_replace("%METHOD%", $method, $url);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($args));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
return $ch;
}
}
$test = new Telegram("botkeybotkeybotkeybotkey");
print_r($test->getUpdates());
print_r($test->sendMessage("6219499", "hello"));
print_r($test->getMe());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment