This is code of my bot in PHP, but it doesnt answer. What should I do? Here's the PHP error log :
[24-Sep-2018 09:06:29 UTC] PHP Warning: file_get_contents(https://api.telegram.org/bot694EMvJayx1zD-J3FPyKPfRlGka0 /sendMessage?chat_id=110***01&text=hellhAkbarixyzhMohammad Hosein): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
in /home/xcqcctmm/public_html/BOT/getnewsir.php on line 22
The code is :
<?php
$token = '692******1zD-J3FPyKPfRlGka0';
// read incoming info and grab the chatID
$json = file_get_contents('php://input');
$telegram = urldecode ($json);
$results = json_decode($telegram);
$message = $results->message;
$text = $message->text;
$chat = $message->chat;
$user_id = $chat->id;
$username = $chat->username;
$first_name = $chat->first_name;
//send reply
$answer = "hello".$user_id . "h" . $username . "h" . $first_name;
$url = 'https://api.telegram.org/bot'.$token.'/sendMessage?chat_id='. $user_id .'&text='.$answer;
file_get_contents($url);
?>
it doesn't work.
Telegram's API returns 400 Bad Request, which could be caused by any of the following:
FIRSTNAME_INVALID: The first name is invalid
LASTNAME_INVALID: The last name is invalid
PHONE_NUMBER_INVALID: The phone number is invalid
PHONE_CODE_HASH_EMPTY: phone_code_hash is missing
PHONE_CODE_EMPTY: phone_code is missing
PHONE_CODE_EXPIRED: The confirmation code has expired
API_ID_INVALID: The api_id/api_hash combination is invalid
PHONE_NUMBER_OCCUPIED: The phone number is already in use
PHONE_NUMBER_UNOCCUPIED: The phone number is not yet being used
USERS_TOO_FEW: Not enough users (to create a chat, for example)
USERS_TOO_MUCH: The maximum number of users has been exceeded (to create a chat, for example)
TYPE_CONSTRUCTOR_INVALID: The type constructor is invalid
FILE_PART_INVALID: The file part number is invalid
FILE_PARTS_INVALID: The number of file parts is invalid
FILE_PART_Х_MISSING: Part X (where X is a number) of the file is missing from storage
MD5_CHECKSUM_INVALID: The MD5 checksums do not match
PHOTO_INVALID_DIMENSIONS: The photo dimensions are invalid
FIELD_NAME_INVALID: The field with the name FIELD_NAME is invalid
FIELD_NAME_EMPTY: The field with the name FIELD_NAME is missing
MSG_WAIT_FAILED: A waiting call returned an error
Unfortunately, you have to debug which one causing the actual error.
Source
Related
Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// get the important data
$lati = $resp['lat'];
$longi = $resp['lon'];
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
return $data_arr;
}
The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:
[[DATE] America/New_York] PHP Notice: Undefined index: title in [...php] on line [...]
[[DATE] America/New_York] PHP Notice: Undefined variable: area in [...php] on line [...]
What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.
Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).
Would really appreciate any help with this, thank you!
Edit
This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.
The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.
// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
In full, with some abbreviation of the array building at the end for simplicity:
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return array($resp[0]['lat'], $resp[0]['lon']);
}
Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.
I am trying to get user's fan page post using the following code, but it's give me warning
Warning: file_get_contents(https://graph.facebook.com/782176371798916/posts): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
$page_posts = file_get_contents('https://graph.facebook.com/'.$page_id.'/posts');
$pageposts = json_decode($page_posts);
foreach ($pageposts["data"] as $fppost) {
echo $fppost['message'];
}
SO, how is the correct way to get user's fan page post?
The solution I found is by using the following code:
$pageposts = $facebook->api('/'.$page_id.'/posts', 'GET');
foreach ($pageposts["data"] as $fppost) {
echo $fppost['message'];
}
You didn't send the access_token parameter, just add it and it should work like charm:
$page_id = 'smashmag'; // Page ID or username
$token = '553435274702353|OaJc7d2WCoDv83AaR4JchNA_Jgw'; // Valid access token, I used app token here but you might want to use a user token .. up to you
$page_posts = file_get_contents('https://graph.facebook.com/'.$page_id.'/posts?fields=message&access_token='.$token); // > fields=message < since you want to get only 'message' property (make your call faster in milliseconds) you can remove it
$pageposts = json_decode($page_posts);
foreach ($pageposts->data as $fppost) {
if (property_exists($fppost, 'message')) { // Some posts doesn't have message property (like photos set posts), errors-free ;)
print $fppost->message.'</br>';
}
}
Using the example of CreateEnvelope sample code
I receive a message:
Guid should contain 32 digits with 4 dashes
(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
Using the method of guid() of SDK, which returns a string in the form {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
I receive a message:
The 'http://www.docusign.net/API/3.0:ID' element is invalid - The
value '0 'is invalid according to its datatype
What is the format for the recipient ID is valid?
In DocuSign, when you are adding recipients to your envelopes you need at least 3 pieces of data to uniquely identify each recipient. You need to set recipient name, email, and recipientId. (If you are using the Embedding feature then you need to set the CaptiveInfo as well for SOAP or the clientUserId if using REST)
The recipientId is user-defined, meaning you can set it to whatever you like- however it needs to be a non-negative number such as 1, 2, 1000, 2000. I believe the data type for the recipientId is string so you're not limited to just numbers either.
However, 0 is the one value that you can not set it to. So try changing the value of your recipientId to 1 or 2 or one or two or 1abc or 2def and see if that resolves your issue.
I use the following code:
$r = new Recipient();
$r->ID = '1';
$r->UserName = 'john';
$r->SignerName = 'John Doe';
$r->Email = 'john#example.com';
$r->Type = RecipientTypeCode::Signer;
$r->RoutingOrder = 1;
$r->RequireIDLookup = false;
$r->CaptiveInfo = new RecipientCaptiveInfo();
$r->CaptiveInfo->ClientUserId = '1';
...
And getting an error message:
Uncaught SoapFault exception: [soap:Client] 358101: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
If I use the following code:
$uid = $this->getUid();
$r->ID = $uid;
...
$r->CaptiveInfo->ClientUserId = $uid;
...
$this->getUid() using the method of guid() of SDK, which returns a string in the form {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
Getting an error message:
Uncaught SoapFault exception: [soap:Client] Validation error: The 'http://www.docusign.net/API/3.0:ID' element is invalid - The value '0' is invalid according to its datatype 'http://www.docusign.net/API/3.0:LocalId' - Value '0' was either too large or too small for PositiveInteger.
I have html sending a POST request that reaches php code to process the request...I'm getting a strange error saying theres a syntax error on line 1
Parse error: syntax error, unexpected T_FUNCTION in /home/content/31/9275231/html/subscribe.php on line 1
However I don't see any errors on line 1.
Here is the code (I hid my API key info)
<?php
function isValidEmail( $email = null )
{
return preg_match( "/^
[\d\w\/+!=#|$?%{^&}*`'~-]
[\d\w\/\.+!=#|$?%{^&}*`'~-]*#
[A-Z0-9]
[A-Z0-9.-]{1,61}
[A-Z0-9]\.
[A-Z]{2,6}$/ix", $email );
}
/* Check if email has been posted */
if ( !isset($_POST['email']) ) die();
/* Validate email */
if ( isValidEmail($_POST['email']) ) {
require_once('./MCAPI.class.php');
// **************************************************************** //
// Enter your API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('apikey');
// Enter your list's unique id from http://admin.mailchimp.com/lists/
// (click the "settings", the unique id is at the bottom of the page)
$list_id = 'list_unique_id';
// **************************************************************** //
if($api->listSubscribe($list_id, $_POST['email'], '') === true) {
echo 'successful';
}else{
echo 'Error: ' . $api->errorMessage;
}
}
else {
echo 'invalid_email';
}
One other peculiar thing: I notice that when I open this php code in textmate it looks fine, but when I open it in vim, all the code is displayed in one line with strange '^M' characters where new lines should be...any ideas?
The weird ^M characters are Windows/DOS line endings. Use this to replace them with Unix line endings:
:%s/^V^M/\r/g
More info here: http://grx.no/kb/2008/11/17/remove-windows-line-endings-in-vim/
Check the options in your text editor to see if you can make newlines as LFs instead of CRs (or both a CR followed by an LF). What's happening is your newlines are only CRs, whereas the PHP interpreter is looking for LFs for newlines, so it reads your code as one big line.
I am using the following code to retrieve an amount of Tweets from the Twitter API:
$cache_file = "cache/$username-twitter.cache";
$last = filemtime($cache_file);
$now = time();
$interval = $interval * 60; // ten minutes
// Check the cache file age
if ( !$last || (( $now - $last ) > $interval) ) {
// cache file doesn't exist, or is old, so refresh it
// Get the data from Twitter JSON API
//$json = #file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=" . $username . "&count=" . $count, "rb");
$twitterHandle = fopen("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$username&count=$count", "rb");
$json = stream_get_contents($twitterHandle);
fclose($twitterHandle);
if($json) {
// Decode JSON into array
$data = json_decode($json, true);
$data = serialize($data);
// Store the data in a cache
$cacheHandle = fopen($cache_file, 'w');
fwrite($cacheHandle, $data);
fclose($cacheHandle);
}
}
// read from the cache file with either new data or the old cache
$tweets = #unserialize(file_get_contents($cache_file));
return $tweets;
Of course $username and the other variables inside the fopen request are correct and it produces the correct URL because I get the error:
Warning: fopen(http://api.twitter.com/1/statuses/user_timeline.json?screen_name=Schodemeiss&count=5) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/ellexus1/public_html/settings.php on line 187
that ^^ error returns whenever I try and open my page.
Any ideas why this might be? Do I need to use OAuth to even just get my tweets!? Do I have to register my website as somewhere that might get posts?
I'm really not sure why this is happening. My host is JustHost.com, but I'm not sure if that makes any diffrence. All ideas are welcome!
Thanks.
Andrew
PS. This code lies inside a function where username, interval and count are passed in correctly, hence in the error code its created a well formed address.
Chances are you are getting rate-limited
400 Bad Request: The request was invalid. An accompanying error
message will explain why. This is the status code will be returned
during rate limiting.
150 requests per hour for non authenticated calls (Based on IP-addressing)
350 requests per hour for authenticated calls (Based on the authenticated users calls)
You have to authenticate to avoid these errors popping up.
And also please use cURL when dealing with twitter. I've used file_get_contents and fopen to call the twitter API, and found that it is very unreliable. You would get hit with that every now and then.
Replace the fopen with
$ch = curl_init("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$username&count=$count");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$it = curl_exec($ch); //content stored in $it
curl_close($ch);
This may help
Error codes
https://developer.twitter.com/en/docs/basics/response-codes.html
Error codes defination is given in above link