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

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

Related

How to handle 500 errors from Google API

How can I handle google API errors? For example, the following script will get the screenshot from the website requested:
$api_response = file_get_contents("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" . $websiteURL . "&screenshot=true");
$result = json_decode($api_response, true);
$screenshot1 = $result['lighthouseResult']['audits']['final-screenshot']['details']['data'];
but if the domain doesn't exists google returns this error:
Failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error
How can I handle this error and create a custom error page for that?
My project is on Laravel 8.
You could do it with an if statement
if(($api_response = #file_get_contents("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" . $websiteURL . "&screenshot=true")) !== false) {
//success
$result = json_decode($api_response, true);
$screenshot1 = $result['lighthouseResult']['audits']['final-screenshot']['details']['data'];
}
else{
//do error stuff
}

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 Bot PHP Warning while opening a stream

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.

GET Request with params: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden

I am trying to use new features available with Steam API and I am having trouble, I think this is more of general issue than actual service related itself.
I keep getting:
failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
I am trying to send GET request with parameters using:
<?php
$url = "https://api.steampowered.com/ICSGOTournaments_730/GetTournamentItems/v1?key=".$_SESSION['steam_appid']."&event=9&steamid=".$_SESSION['steam_steamid']."&steamidkey=".$_SESSION['userAuthCode'];
$response = file_get_contents($url);
echo($response);
?>
I am 100% sure the parameters are correct I think it's something rather to do with my code than Steam itself.
When I try to use same code but different API call:
$url = "https://api.steampowered.com/ICSGOTournaments_730/GetTournamentLayout/v1?key=".$_SESSION['steam_appid']."&event=9";
That executes fine and returns data so it's something related to the other two parameters.
I am wondering is there any problem with the way I am building URL's?
Sessions file (3rd Party):
<?php
if (empty($_SESSION['steam_uptodate']) or empty($_SESSION['steam_personaname'])) {
require 'SteamConfig.php';
$url = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=".$steamauth['apikey']."&steamids=".$_SESSION['steamid']);
$content = json_decode($url, true);
$_SESSION['steam_appid'] = $steamauth['apikey'];
$_SESSION['steam_steamid'] = $content['response']['players'][0]['steamid'];
$_SESSION['steam_communityvisibilitystate'] = $content['response']['players'][0]['communityvisibilitystate'];
$_SESSION['steam_profilestate'] = $content['response']['players'][0]['profilestate'];
$_SESSION['steam_personaname'] = $content['response']['players'][0]['personaname'];
$_SESSION['steam_lastlogoff'] = $content['response']['players'][0]['lastlogoff'];
$_SESSION['steam_profileurl'] = $content['response']['players'][0]['profileurl'];
$_SESSION['steam_avatar'] = $content['response']['players'][0]['avatar'];
$_SESSION['steam_avatarmedium'] = $content['response']['players'][0]['avatarmedium'];
$_SESSION['steam_avatarfull'] = $content['response']['players'][0]['avatarfull'];
$_SESSION['steam_personastate'] = $content['response']['players'][0]['personastate'];
if (isset($content['response']['players'][0]['realname'])) {
$_SESSION['steam_realname'] = $content['response']['players'][0]['realname'];
} else {
$_SESSION['steam_realname'] = "Real name not given";
}
$_SESSION['steam_primaryclanid'] = $content['response']['players'][0]['primaryclanid'];
$_SESSION['steam_timecreated'] = $content['response']['players'][0]['timecreated'];
$_SESSION['steam_uptodate'] = time();
include 'mysql_connection.php';
$userAuth = getAuth();
if($userAuth != false){
$_SESSION['userAuthCode'] = $userAuth;
}
else{
$_SESSION['userAuthCode'] = "Unset";
}
}
$steamprofile['steamid'] = $_SESSION['steam_steamid'];
$steamprofile['communityvisibilitystate'] = $_SESSION['steam_communityvisibilitystate'];
$steamprofile['profilestate'] = $_SESSION['steam_profilestate'];
$steamprofile['personaname'] = $_SESSION['steam_personaname'];
$steamprofile['lastlogoff'] = $_SESSION['steam_lastlogoff'];
$steamprofile['profileurl'] = $_SESSION['steam_profileurl'];
$steamprofile['avatar'] = $_SESSION['steam_avatar'];
$steamprofile['avatarmedium'] = $_SESSION['steam_avatarmedium'];
$steamprofile['avatarfull'] = $_SESSION['steam_avatarfull'];
$steamprofile['personastate'] = $_SESSION['steam_personastate'];
$steamprofile['realname'] = $_SESSION['steam_realname'];
$steamprofile['primaryclanid'] = $_SESSION['steam_primaryclanid'];
$steamprofile['timecreated'] = $_SESSION['steam_timecreated'];
$steamprofile['uptodate'] = $_SESSION['steam_uptodate'];
?>
file_get_contents - for using https need use:
from php.net
When using SSL, Microsoft IIS will violate the protocol by closing the
connection without sending a close_notify indicator. PHP will report
this as "SSL: Fatal Protocol Error" when you reach the end of the
data. To work around this, the value of error_reporting should be
lowered to a level that does not include warnings. PHP can detect
buggy IIS server software when you open the stream using the https://
wrapper and will suppress the warning. When using fsockopen() to
create an ssl:// socket, the developer is responsible for detecting
and suppressing this warning.

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
}
}

Categories