I'm having problem in my telegram bot with this code
<?php
if ($_SERVER['HTTPS'] != "on") {
$url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
exit;
}
$botToken = "XXXX...";
$website = "https://api.telegram.org/bot".$botToken;
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
// get message_id
$messageId = $update["message"]["message_id"];
switch($message) {
case("action"):
sendMessage($chatId, "What should I do?");
break;
case("add"):
// add the 2nd parameter
editMessageText($chatId, $messageId, "should I add?");
break;
default:
sendMessage($chatId, "default");
}
function sendMessage($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage? chat_id=".$chatId."&text=".urlencode($message)."&reply_markup".$reply1;
file_get_contents($url);
}
function editMessageText($chatId, $messageId, $message) {
$url = $GLOBALS[website]."/editMessageText?chat_id=".$chatId."&message_id=".$messageId."&text=".urlencode($message);
file_get_contents($url);
}
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>
I tried to use this as a example and its not work if I use this its keep loading and after a minute the bot will spam me with the same amount of button i press with him
I already used above code but its not editing it incase its sending me the same message
You need to add break inside default
default:
sendMessage($chatId, "default");
break;
}
I capture this one I think it is also getting some error, you did not assign any value to variable $reply1, and also missing = mark after the &reply_markup
function sendMessage($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message)."&reply_markup".$reply1;
file_get_contents($url);
}
if you need to run for the testing use this
function sendMessage($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
file_get_contents($url);
}
If you need any help
Related
I am trying to get the post count of an instagram account, I have managed to do followers and following but cant get to get the post count right.
<?php
$username = 'instagram';
$response = #file_get_contents( "https://www.instagram.com/$username/?__a=1" );
if ( $response !== false ) {
$data = json_decode( $response, true );
if ( $data !== null ) {
$full_name = $data['graphql']['user']['full_name'];
$follower = $data['graphql']['user']['edge_followed_by']['count'];
$follows = $data['graphql']['user']['edge_follow']['count'];
echo "<p>{$full_name}</p> <p>{$follower} followers {$follows} following.</p>";
}
} else {
echo 'Username not found.';
}
?>
If anyone ever needs the answer, I managed to pull it through...
<?php
$username = 'instagram';
$response = #file_get_contents( "https://www.instagram.com/$username/?__a=1" );
if ( $response !== false ) {
$data = json_decode( $response, true );
if ( $data !== null ) {
$full_name = $data['graphql']['user']['full_name'];
$follower = $data['graphql']['user']['edge_followed_by']['count'];
$follows = $data['graphql']['user']['edge_follow']['count'];
$posts = $data['graphql']['user']['edge_owner_to_timeline_media']['count'];
echo "<h2><a href='https://www.instagram.com/{$username}'>{$full_name}</a></h2>
<p><span>{$posts} posts</span> <span>{$follower} followers</span> <span>{$follows} following</span></p>";
}
} else {
echo 'Username not found.';
}
?>
You can get many options by just going to
https://www.instagram.com/$username/?__a=1
and changing the $username to the account you need to see
I have a problem to creating a custom keyboard for my telegram bot.
Simply, it doesn't works and I don't know the reason...
This is my code:
<?
$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"];
$telegramusername = $update["message"]["from"]["username"];
$message_id = $update["message"]["message_id"];
$message_name = $update["message"]["chat"]["first_name"];
switch($message)
{
case "ciao":
funzioneCiao($chatId);
break;
case "youtube":
TastieraInline($chatId);
break;
default:
TastieraMenuPrincipale($chatId);
break;
}
function inviaMessaggio($chatId, $messaggio)
{
$url = "$GLOBALS[website]/sendMessage?chat_id=$chatId&parse_mode=HTML&text=".urlencode($messaggio);
file_get_contents($url);
}
function funzioneCiao($chatId)
{
$messaggio = "ciao";
inviaMessaggio($chatId, $messaggio);
}
function TastieraMenuPrincipale($chatId)
{
$messaggio = "ciaaaao";
$tastiera = '&reply_markup={"keyboard":[["Menu Principale"],["Developer"]]}';
$url = "$GLOBALS[website]"."/sendMessage?chat_id=".$chatId."&parse_mode=HTML&text=".$messaggio.$tastiera;
file_get_contents($url);
}
function TastieraInline($chatId)
{
$message = "Iscriviti subito";
$tastiera = '&reply_markup={"inline_keyboard":[[{"text":"SEGUIMI!","url":"http://www.youtube.com"}]]}';
$url = $GLOBALS[website].'/sendMessage?chat_id='.$chatId.'&parse_mod=HTML&text='.$message.$tastiera;
file_get_contents($url);
}
?>
Functions: "funzioneCiao($chatId);" and "inviaMessaggio($chatId, $messaggio)" works but,
"TastieraMenuPrincipale($chatId)" and "TastieraInLine($ChatId)" doesn't works.
I'm a beginner in PHP so I have a lot difficult...
Thank you.
I just tested the code, it works perfectly...
Why didn't you use CURL instead of file_get_contents(); ?!
just write this function into your code then call it after getting new updates :
function makeHTTPRequest($method, $types = []){
$url = 'https://api.telegram.org/bot'.$botToken.'/'.$method;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($types));
$res = curl_exec($ch);
if (curl_error($ch)){
var_dump(curl_error($ch));
} else {
return json_decode($res);
}
}
make sure CURL is activated on your hosting server!
I am not able to add grouplist in rest api by php code
<?php
// Input your info here:
$email = "********* "; // your account email
$password = "*****"; // your account password
$integratorKey = "********"; // your account integrator key, found on (Preferences -> API page)
$accountID = "********** ";
$debug = $_POST["debug"];
$debug = $_POST["debug"];
// construct the authentication header:
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (to retrieve baseUrl and accountId)
/////////////////////////////////////////////////////////////////////////////////////////////////
$url = "https://demo.docusign.net/restapi/v2/login_information";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-DocuSign-Authentication: $header"));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
echo "error calling logon webservice, status is:" . $status;
exit(-1);
}
$response = json_decode($json_response, true);
$accountId = $response["loginAccounts"][0]["accountId"];
$baseUrl = $response["loginAccounts"][0]["baseUrl"];
curl_close($curl);
//--- display results
if ($debug){
echo "<BR>accountId = " . $accountId . "<BR>baseUrl = " . $baseUrl . "<BR>";
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 2 - status retrieval using filters
/////////////////////////////////////////////////////////////////////////////////////////////////
echo "<BR>Sending new user update...<BR>";
$curl = curl_init($baseUrl . "/users");
if ($debug){
echo "URL is: " . $baseUrl . "/users" . "<BR>";
echo "Title: " . $_POST["title"]."<BR>";
echo "First Name: " . $_POST["firstName"]."<BR>";
echo "Middle Name: " .$_POST["middleName"]."<BR>";
echo "Last Name: " . $_POST["lastName"]."<BR>";
echo "User Name: " .$_POST["userName"]."<BR>";
echo "Password :" . $_POST["password"]."<BR>";
echo "Email: " .$_POST["email"]."<BR>";
echo "Check box:".$_POST['check_list']."<BR>";
}
$data = array("newUsers" => array
(
array
(
"lastName" => $_POST["lastName"],
"firstName" => $_POST["firstName"],
"password" => $_POST["password"],
"userName" => $_POST["userName"],
"email" => $_POST["email"],
"middleName" => $_POST["middleName"],
"title" => $_POST["title"],
"userSettings" => array
(
array
(
"name" => "canSendEnvelope",
"value" => "true"
)
),
"forgottenPasswordInfo" => array
(
"forgottenPasswordQuestion1" => $_POST["forgottenPasswordQuestion1"],
"forgottenPasswordAnswer1" => $_POST["forgottenPasswordAnswer1"]
),
"groupList" => array
(
"groupId" => $_POST["check_list"],
"groupName" => $_POST["check_list"],
"permissionProfileId" => $_POST["check_list"],
"groupType" => $_POST["check_list"]
)
)
)
);
$data_string = json_encode($data);
if ($debug) {
echo "<BR><BR>";
echo $data_string;
echo "<BR><BR>";
}
// build web request
$request_header = array(
'Accept: application/json',
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
"X-DocuSign-Authentication: $header" );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_header);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
//execute web request
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
echo "error calling webservice, status is:" . $status . "<BR>error text is --> ";
print_r($json_response); echo "<BR>";
exit(-1);
}
$response = json_decode($json_response, true);
//--- display results
if ($debug){
echo "Received " . $response . " end<BR>";
}
echo "New user created."
?>
Since groupList is an array property you need to specify each group node separately. The JSON that your PHP code produces should look like this:
"groupList": [
{
"groupId": "sample string 1",
"groupName": "sample string 2",
"permissionProfileId": "sample string 3",
"groupType": "sample string 4"
}
],
Setting target temperature throwing an error like below. I am using php curl to set the temperature. Any help is appreciated.
object(stdClass)#72 (2) {
["cmd"]=>
string(12) "REINIT_STATE"
["pod"]=>
string(5) "rts04"
}
Code:
echo "Setting target temperature...\n";
$success = $nest->setTargetTemperature(150,$device_serial_number);
var_dump($success);
//***********************//
public function setTargetTemperature($temperature, $serial_number) {
$serial_number = $this->getDefaultSerial($serial_number);
$temperature = $this->temperatureInCelsius($temperature, $serial_number);
echo $temperature;
$data = json_encode(array('target_change_pending' => TRUE, 'target_temperature' => $temperature));
return $this->doPOST("/v2/put/shared." . $serial_number, $data);
}
//************//
private function doPOST($url, $data_fields) {
return $this->doRequest('POST', $url, $data_fields);
}
private function doRequest($method, $url, $data_fields, $with_retry=TRUE) {
$ch = curl_init();
if ($url[0] == '/') {
$url = $this->transport_url . $url;
}
$headers = array('X-nl-protocol-version: ' . self::protocol_version);
if (isset($this->userid)) {
$headers[] = 'X-nl-user-id: ' . $this->userid;
$headers[] = 'Authorization: Basic ' . $this->access_token;
}
if (is_array($data_fields)) {
$data = array();
foreach($data_fields as $k => $v) {
$data[] = "$k=" . urlencode($v);
}
$data = implode('&', $data);
} else if (is_string($data_fields)) {
$data = $data_fields;
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, self::user_agent);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookie_file);
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$headers[] = 'Content-length: ' . strlen($data);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if (DEBUG) {
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
} else {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE); // for security this should always be set to true.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // for security this should always be set to 2.
curl_setopt($ch, CURLOPT_SSLVERSION, 1); // Nest servers now require TLSv1; won't work with SSLv2 or even SSLv3!
// Update cacert.pem (valid CA certificates list) from the cURL website once a month
$curl_cainfo = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'cacert.pem';
$last_month = time()-30*24*60*60;
if (!file_exists($curl_cainfo) || filemtime($curl_cainfo) < $last_month || filesize($curl_cainfo) < 100000) {
file_put_contents($curl_cainfo, file_get_contents('http://curl.haxx.se/ca/cacert.pem'));
}
if (file_exists($curl_cainfo) && filesize($curl_cainfo) > 100000) {
curl_setopt($ch, CURLOPT_CAINFO, $curl_cainfo);
}
}
$response = curl_exec($ch);
$info = curl_getinfo($ch);
if ($info['http_code'] == 401 || (!$response && curl_errno($ch) != 0)) {
if ($with_retry && $this->use_cache()) {
// Received 401, and was using cached data; let's try to re-login and retry.
#unlink($this->cookie_file);
#unlink($this->cache_file);
if ($info['http_code'] == 401) {
$this->login();
}
return $this->doRequest($method, $url, $data_fields, !$with_retry);
} else {
throw new RuntimeException("Error: HTTP request to $url returned an error: " . curl_error($ch), curl_errno($ch));
}
}
$json = json_decode($response);
if (!is_object($json) && ($method == 'GET' || $url == self::login_url)) {
if (strpos($response, "currently performing maintenance on your Nest account") !== FALSE) {
throw new RuntimeException("Error: Account is under maintenance; API temporarily unavailable.", NESTAPI_ERROR_UNDER_MAINTENANCE);
}
if (empty($response)) {
throw new RuntimeException("Error: Received empty response from request to $url.", NESTAPI_ERROR_EMPTY_RESPONSE);
}
throw new RuntimeException("Error: Response from request to $url is not valid JSON data. Response: " . str_replace(array("\n","\r"), '', $response), NESTAPI_ERROR_NOT_JSON_RESPONSE);
}
if ($info['http_code'] == 400) {
if (!is_object($json)) {
throw new RuntimeException("Error: HTTP 400 from request to $url. Response: " . str_replace(array("\n","\r"), '', $response), NESTAPI_ERROR_API_OTHER_ERROR);
}
throw new RuntimeException("Error: HTTP 400 from request to $url. JSON error: $json->error - $json->error_description", NESTAPI_ERROR_API_JSON_ERROR);
}
// No body returned; return a boolean value that confirms a 200 OK was returned.
if ($info['download_content_length'] == 0) {
return $info['http_code'] == 200;
}
return $json;
}
doPOST function called from setTargetTemperature. doRequest function called from doPOST.
For more reference see here https://github.com/gboudreau/nest-api
the easy things are:
Make sure the thermostat is in heat/cool mode, or cool mode.
Make sure the thermostat is not set to away.
Can you post the code block you are using to make the call?
There is a problem with my paypal Integration in live site.
For 90% of transactions, I didn't get any problem. Some times only I am facing this below problem.
Problem: After successful transaction, I am not getting Pay pal values like Transaction Id, Message etc. All values shows empty. It comes for 10% of transactions only. please tell me what may be the problem. Can't able to find out the reason
Thanks in Advance..
$paypal_email = '5345345345345f';
$cur_dir='http://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
$return_url = $cur_dir.'/paymentsucess.php';
$cancel_url = $cur_dir.'/payment-not-sucess.php';
$notify_url = $cur_dir.'/payments.php';
extract($_POST);
$item_name = $exam_name;
$item_amount = $amount;
$userid=$userid;
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
$querystring = "?business=".urlencode($paypal_email)."&";
$querystring .= "item_name=".urlencode($item_name)."&";
$querystring .= "amount=".urlencode($item_amount)."&";
//loop for posted values and append to querystring
foreach($_POST as $key => $value){
$value = urlencode(stripslashes($value));
$querystring .= "$key=$value&";
}
$querystring .= "return=".urlencode(stripslashes($return_url))."&";
$querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
$querystring .= "notify_url=".urlencode($notify_url);
header('location:https://www.paypal.com/cgi-bin/webscr'.$querystring);
exit();
}else{
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$value = preg_replace('/(.*[^%^0^D])(%0A) (.*)/i','${1}%0D%0A${3}',$value);// IPN fix
$req .= "&$key=$value";
}
$data['item_name'] = $_POST['item_name'];
$data['item_number'] = $_POST['item_number'];
$data['payment_status'] = $_POST['payment_status'];
$data['payment_amount'] = $_POST['mc_gross'];
$data['payment_currency'] = $_POST['mc_currency'];
$data['txn_id'] = $_POST['txn_id'];
$data['receiver_email'] = $_POST['receiver_email'];
$data['payer_email'] = $_POST['payer_email'];
$data['custom'] = $_POST['custom'];
$data['userid'] = $_POST['userid'];
// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
// Validate payment (Check unique txnid & correct price)
$valid_txnid = check_txnid($data['txn_id']);
$valid_price = check_price($data['payment_amount'], $data['item_number']);
// PAYMENT VALIDATED & VERIFIED!
if($valid_txnid && $valid_price){
$orderid = updatePayments($data);
if($orderid){
}else{
}
}else{
}
}else if (strcmp ($res, "INVALID") == 0) {
}
}
fclose ($fp);
}
}