Skip to content

Instantly share code, notes, and snippets.

@unnikked
Created January 5, 2016 22:02
Show Gist options
  • Save unnikked/5c92aa7fd42f6eac2ab1 to your computer and use it in GitHub Desktop.
Save unnikked/5c92aa7fd42f6eac2ab1 to your computer and use it in GitHub Desktop.
InlineDuckBot
<?php
require("./vendor/autoload.php");
define('BOT_TOKEN', 'token');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
function apiRequestWebhook($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
$parameters["method"] = $method;
header("Content-Type: application/json");
echo json_encode($parameters);
return true;
}
function exec_curl_request($handle) {
$response = curl_exec($handle);
if ($response === false) {
$errno = curl_errno($handle);
$error = curl_error($handle);
error_log("Curl returned error $errno: $error\n");
curl_close($handle);
return false;
}
$http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
curl_close($handle);
if ($http_code >= 500) {
// do not wat to DDOS server if something goes wrong
sleep(10);
return false;
} else if ($http_code != 200) {
$response = json_decode($response, true);
error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n");
if ($http_code == 401) {
throw new Exception('Invalid access token provided');
}
return false;
} else {
$response = json_decode($response, true);
if (isset($response['description'])) {
error_log("Request was successfull: {$response['description']}\n");
}
$response = $response['result'];
}
return $response;
}
function apiRequest($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
foreach ($parameters as $key => &$val) {
// encoding to JSON array parameters, for example reply_markup
if (!is_numeric($val) && !is_string($val)) {
$val = json_encode($val);
}
}
$url = API_URL.$method.'?'.http_build_query($parameters);
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
return exec_curl_request($handle);
}
function apiRequestJson($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
$parameters["method"] = $method;
$handle = curl_init(API_URL);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters));
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
return exec_curl_request($handle);
}
function processMessage($message) {
// process incoming message
$message_id = $message['message_id'];
$chat_id = $message['chat']['id'];
if (isset($message['text'])) {
// incoming text message
$text = $message['text'];
/*if (strpos($text, "/start") === 0) {
apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array(
'keyboard' => array(array('Hello', 'Hi')),
'one_time_keyboard' => true,
'resize_keyboard' => true)));
} else if ($text === "Hello" || $text === "Hi") {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you'));
} else if (strpos($text, "/stop") === 0) {
// stop now
} else {
apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => 'Cool'));
}*/
apiRequestJson("sendMessage", [
"chat_id" => $chat_id,
"text" => "This is only an inline bot.\nhttps://core.telegram.org/bots/inline"
]);
} else {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'I understand only text messages'));
}
}
define('WEBHOOK_URL', 'https://yoururl');
if (php_sapi_name() == 'cli') {
// if run from console, set or delete webhook
apiRequest('setWebhook', array('url' => isset($argv[1]) && $argv[1] == 'delete' ? '' : WEBHOOK_URL));
exit;
}
$content = file_get_contents("php://input");
error_log($content);
$update = json_decode($content, true);
if (!$update) {
// receive wrong update, must not happen
exit;
}
if (isset($update["message"])) {
processMessage($update["message"]);
} else if (isset($update["inline_query"])) {
$inlineQuery = $update["inline_query"];
$queryId = $inlineQuery["id"];
$queryText = $inlineQuery["query"];
if (isset($queryText) && $queryText !== "") {
apiRequestJson("answerInlineQuery", [
"inline_query_id" => $queryId,
"results" => queryDuckDuckGo($queryText),
"cache_time" => 86400,
]);
} else {
apiRequestJson("answerInlineQuery", [
"inline_query_id" => $queryId,
"results" => [
[
"type" => "article",
"id" => "0",
"title" => "Unnikked Blog",
"message_text" => "I'm the author of this bot, please visit my blog for more https://unnikked.ga",
],
]
]);
}
}
use Symfony\Component\DomCrawler\Crawler;
function queryDuckDuckGo($query) {
$content = file_get_contents('https://duckduckgo.com/html/?q=' . urlencode($query));
if(!$content) return [[
"type" => "article",
"id" => "0",
"title" => "Service unavailable",
"message_text" => "Service unavailable",
]];
$crawler = new Crawler($content);
$results = $crawler->filter(".links_main .large");
foreach ($results as $result) {
$titles[] = trim($result->textContent);
}
$results = $crawler->filter(".links_main .snippet");
foreach ($results as $result) {
$snippets[] = trim($result->textContent);
}
$results = $crawler->filter(".links_main .url");
foreach ($results as $result) {
$urls[] = trim($result->textContent);
}
foreach (range(0, count($titles) - 1) as $i) {
$collection[] = [
"type" => "article",
"id" => "$i",
"title" => "$titles[$i]",
"message_text" => "$titles[$i]\n$snippets[$i]\n$urls[$i]",
];
}
return $collection;
}
@xavianaxw
Copy link

Hi

I read your article from unnikked.ga about Understanding Telegram Inline Bots.

Currently I've set up a standard sendMessage respond that will reply with the user's name - Hello Aaron. What I'm trying to do now is setting up and inline bot for which i have run /setinline along with the placeholder text.

When trying to run the Bot inline using @JustWeeItBot i do see my placeholder text which I'm assuming that the setup for Inline Bot is done correctly.

Could you point me in the right direction? I have included a link to my codes below.
https://github.com/xavianaxw/telegram-bot-justweeit/blob/master/index.php

Your help is much appreciated!

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