Skip to content

Instantly share code, notes, and snippets.

@ybagheri
Last active December 20, 2018 14:13
Show Gist options
  • Save ybagheri/33b3b2c7ea2cb4dd1f92e81aa0105d2a to your computer and use it in GitHub Desktop.
Save ybagheri/33b3b2c7ea2cb4dd1f92e81aa0105d2a to your computer and use it in GitHub Desktop.
Telegram inline bots answerInlineQuery Crawler
<?php
use Symfony\Component\DomCrawler\Crawler;
//.
//.
//.
if (isset($results->inline_query)) {
$inline_query = $results->inline_query;
$query_Id = $inline_query->id;
$query_Text = $inline_query->query;
if (isset($query_Text) && $query_Text !== "") {
makeHTTPRequest($token, "answerInlineQuery",[
"inline_query_id" => $query_Id,
"results" => json_encode(queryDuckDuckGo($query_Text)),
"cache_time" => 10,
]);
} else {
makeHTTPRequest($token, "answerInlineQuery",[
"inline_query_id" => $query_Id,
"results" => json_encode([
[
"type" => "article",
"id" => "0",
"title" => "my github",
"input_message_content" => ["message_text" => ""I'm the author of this bot, please visit my github page for https://github.com/ybagheri ",
"parse_mode" => "HTML"])
],
]
]);
}
}
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();
$crawler->addHtmlContent($content);
$crawler->filterXPath('//span[contains(@id, "article-")]')->evaluate('substring-after(@id, "-")');
$results = $crawler->filter(".links_main .result__title");
foreach ($results as $result) {
$titles[] = trim($result->textContent);
}
$results = $crawler->filter(".links_main .result__snippet");
foreach ($results as $result) {
$snippets[] = trim($result->textContent);
}
$results = $crawler->filter(".links_main .result__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;
}
function makeHTTPRequest($token, $method, $datas = [])
{
$url = "https://api.telegram.org/bot" . $token . "/" . $method;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datas));
$res = curl_exec($ch);
if (curl_error($ch)) {
var_dump(curl_error($ch));
} else {
return json_decode($res);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment