Telegram Bot PHP Warning while opening a stream - php

I get a negative response from the file_get_contents as follows
Telegram Bot PHP: Warning: file_get_contents failed to open stream: 400 Bad Request
Code in Context
ini_set("error_reporting", E_ALL);
$botToken = "249706675:AAGGJtFStHf6zbuQfbAClcGzzlFz75xqFKA";
$website = "https://api.telegram.org/bot".$botToken;
$update = file_get_contents("php://input");
$updateArray = json_decode($update, TRUE);
$chatId = $updateArray["result"][0]["message"]["chat"]["id"];
$message = $updateArray["message"]["text"];
switch($message) {
case "/hello":
sendMessage($chatId, "Hello!");
break;
case "/wtf":
sendMessage($chatId, "I'm personal bot of #TCGroup!");
break;
default:
sendMessage($chatId, "Default");
}
function sendMessage($chatId, $message) {
$url = $GLOBALS["website"]."/sendmessage?chat_id=".$chatId."&text=".urlencode($message);
file_get_contents($url);
}

Try camelCasing your sendMessage in the url. And use cURL extension instead of file_get_contents, as it's more efficent.

Related

Telegram Bot PHP won't work (Running Apache on Xampp)

I am building a bot for Telegram that basically the user will be able to run a command and it will return some text. I am running Apache servers on Xampp. I already tested capturing some Arrays from user and I can capture it.
Not sure if maybe I have to run it on SSL Web Servers? or is there a function that I can use instead with Apache?
<?php
ini_set('error_reporting', E_ALL);
$botToken = "";
$website = "https://api.telegram.org/bot".$botToken;
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
switch($message) {
case "/test":
sendMessage($chatId, "test");
break;
case "/hi":
sendMessage($chatId, "hey there!");
break;
default:
sendMessage($chatId, "default");
}
function sendMessage ($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage? chat_id=".$chatId."&text=".urlencode($message);
file_get_contents($url);
}
?>
These are the errors I get:
Notice: Use of undefined constant website - assumed 'website' in C:\xampp\htdocs\Socializers_bot\index.php on line 29
Warning: file_get_contents(https://api.telegram.org/bot/sendMessage?chat_id=&text=default): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\xampp\htdocs\Socializers_bot\index.php on line 30

i made a button but i can not answer to button in the inline keybord

When I click on inline keyboard, I can not get no answer our .Help me please? This is my code:
if ($data == "1") {
$message = 's';
$url = 'https://api.telegram.org/bot'.$token.'/sendMessage?chat_id='.$user_id.'&text='.$message;
$update = file_get_contents($url);
$url = 'https://api.telegram.org/bot'.$token.'/answerCallbackQuery?chat_id='.$user_id .'&callback_query_id='.$chat_id_in;
$update = file_get_contents($url);
}
$error = error_get_last();
echo "HTTP request failed. Error was: " . $error['message'];
You will see HTTP status code. Something like this :
HTTP request failed! HTTP/1.1 404 Not Found
I advise you not to use file_get_content and use CURL (guzzle or other)

Telegram webhook php bot doesn't answer

I'm trying to set up a telegram bot with a webhook. I can get it to work with getUpdates, but I want it to work with a webhook.
My site (that hosts the bot php script) has the SSL certificate working (I get the green lock in the address bar):
I set up the webhook with
https://api.telegram.org/bot<token>/setwebhook?url=https://www.example.com/bot/bot.php
And I got: {"ok":true,"result":true,"description":"Webhook was set"}
(I don't know if this matters, but I have given rwx rights to both the folder and the script)
The php bot: (https://www.example.com/bot/bot.php)
<?php
$botToken = <token>;
$website = "https://api.telegram.org/bot".$botToken;
#$update = url_get_contents('php://input');
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
switch($message) {
case "/test":
sendMessage($chatId, "test");
break;
case "/hi":
sendMessage($chatId, "hi there!");
break;
default:
sendMessage($chatId, "default");
}
function sendMessage ($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
url_get_contents($url);
}
function url_get_contents($Url) {
if(!function_exists('curl_init')) {
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
?>
But when I write anything to the bot I receive no answers...
Any ideas why?
Thanks
In your question it's not clear the script location. Seeing your code, it seems that you try to load a request through url_get_contents to retrieve telegram server response. This is the correct method if your bot works without webhook. Otherwise, after setting webhook, you have to process incoming requests.
I.e., if you set webhook to https://example.com/mywebhook.php, in your https://example.com/mywebhook.php script you have to write something like this:
<?php
$request = file_get_contents( 'php://input' );
# ↑↑↑↑
$request = json_decode( $request, TRUE );
if( !$request )
{
// Some Error output (request is not valid JSON)
}
elseif( !isset($request['update_id']) || !isset($request['message']) )
{
// Some Error output (request has not message)
}
else
{
$chatId = $request['message']['chat']['id'];
$message = $request['message']['text'];
switch( $message )
{
// Process your message here
}
}

Using readability parser API to fetch image url from web page

Here I found readability which parse the data from web page and give information of interest.
But I could not understand how to use it.
https://www.readability.com/developers/api/parser
Request: GET /api/content/v1/parser?url=http://blog.readability.com/2011/02/step-up-be-heard-readability-ideas/&token=1b830931777ac7c2ac954e9f0d67df437175e66e
It gives json response.
I am working on PHP, how to make above request for particular url like http://google.com?
UPDATE1:
<?php
define('TOKEN', "1b830931777ac7c2ac954e9f0d67df437175e66e");
define('API_URL', "https://www.readability.com/api/content/v1/parser?url=%s&token=%s");
function get_image($url) {
// sanitize it so we don't break our api url
$encodedUrl = urlencode($url);
//$TOKEN = '1b830931777ac7c2ac954e9f0d67df437175e66e';
//Also tried with $API_URL = 'http://blog.readability.com/2011/02/step-up-be-heard-readability-ideas'; with no luck
// build our url
$url = sprintf(API_URL, $encodedUrl, TOKEN); //Also tried with $TOKEN
// call the api
$response = file_get_contents($url);
if( $response ) {
return false;
}
$json = json_decode($response);
if(!isset($json['lead_image_url'])) {
return false;
}
return $json['lead_image_url'];
}
echo get_image('http://nextbigwhat.com/');
?>
Any issue with code? gives error - >
Warning: file_get_contents(https://www.readability.com/api/content/v1/parser?url=http%3A%2F%2Fnextbigwhat.com&token=1b830931777ac7c2ac954e9f0d67df437175e66e): failed to open stream: HTTP request failed! HTTP/1.1 403 FORBIDDEN in F:\wamp\www\inviteold\test2.php on line 14
Perhaps something like this:
define('TOKEN', "your_token_here");
define('API_URL', "https://www.readability.com/api/content/v1/parser?url=%s&token=%s");
function get_image($url) {
// sanitize it so we don't break our api url
$encodedUrl = urlencode($url);
// build our url
$url = sprintf(API_URL, $encodedUrl, $token);
// call the api
$response = file_get_contents($url);
if( $response ) {
return false;
}
$json = json_decode($response);
if(!isset($json['lead_image_url'])) {
return false;
}
return $json['lead_image_url'];
}
The code is not tested so you might need to adjust it.

PHP CURL Error after changing only url

For some reason my CURL isnt working now, all i did was change the url (as before i was using this to call info from the need for speed world servers) and it worked flawlessly, now I am trying to use it with IMDBAPI and it gives me an error.
url i type in:
http://localhost/movie.php?title=The Green Mile
Code:
<?php
$title = $_GET['title'];
//optional comment out or delete
error_reporting(E_ALL);
// The POST URL and parameters
$request = 'http://www.imdbapi.com/?t='.$title.'&r=XML';
// Get the curl session object
$session = curl_init($request);
// Set the POST options.
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Do the POST and then close the session
$response = curl_exec($session);
curl_close($session);
// Get HTTP Status code from the response
$status_code = array();
preg_match('/\d\d\d/', $response, $status_code);
// Check for errors
switch( $status_code[0] ) {
case 200:
// Success
break;
case 503:
die('Service unavailable. An internal problem prevented us from returning data to you.');
break;
case 403:
die('Forbidden. You do not have permission to access this resource, or are over your rate limit.');
break;
case 400:
// You may want to fall through here and read the specific XML error
die('Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.');
break;
default:
die('Your call returned an unexpected HTTP status of:' . $status_code[0]);
}
// Get the XML from the response, bypassing the header
if (!($xml = strstr($response, '<?xml'))) {
$xml = null;
}
// Output the XML
$movieInfo = simplexml_load_string($xml);
$movieTitle = $movieInfo->movie['title'];
echo "Title: $movieTitle <br />";
?>
Error:
Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.
I am a noob to CURL so any help is appreciated.
You should urlencode() the $title.
http://www.imdbapi.com/?t=The%20Green%20Mile&r=XML
This one works fine for me. Try to rawurlencode that title
$title = rawurlencode($title);
As Shi said,you need encode the values:
$title = rawurlencode($_GET["title"]);
You can get the http code of your request with:
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

Categories