PHP Telegram Bot sends same message many times - php

I have a Telegram Bot which worked fine for a few months. About 3-4 weeks ago the Telegram Bot sends sometimes (!) the same messages a few times - not just one time!
I have already tried many things to fix that:
I save the update_id in the database. If the new update_id is higher than the saved one, the bot sends the message. If not, an error occurs. (Found out yesterday that every duplicate message has got a new (higher) update_id - so this method is useless)
I tried to add exit(); to every PHP Function - didn't work.
I checked the whole code, if there is a not closed loop. But everything is fine.
I added a ?limit=1 to the function, but also no chance.
Slowly I am at the end of my ideas. Maybe someone has got a good answer for that.
I have always the $update and the chat ID:
define('api', 'https://api.telegram.org/bot'.token.'/');
$data = file_get_contents("php://input");
$update = json_decode($data, true);
$cbid = $update["callback_query"]["from"]["id"];
My function looks like this:
function callback($up){
return $up["callback_query"];
}
function tg_send_message($id, $text) {
$params=[
'chat_id' => $id,
'text' => $text,
'parse_mode' => 'Markdown',
];
$ch = curl_init('https://api.telegram.org/bot'.token.'/sendMessage?limit=1');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3500);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 3500);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
}
If I want to send a message if someone clicks on the inline button Top 10:
if(callback($update) and $cbdata == "top_10"){
tg_send_message($cbid, "This is my message!");
}
Everything worked fine and is working now as well - the bot just sends sometime a message multiple times.
The extra messages have always a new update_id! And if there is a variable value from another API (like Bitcoin price), it is also changing. It's like you clicked 22 times on the button (but you just clicked once)
I am very thankful for every helpful answer! Thank you very much.
Best regards.
EDIT: I have also tried the following:
function tg_btn_click_send_message($id, $text) {
$response = $update["callback_query"];
$botUrl = "https://api.telegram.org/bot" . BOT_TOKEN . "/answerCallbackQuery";
$postFields = array('callback_query_id' => $callback_query_id, 'text' => $response);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $botUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$output = curl_exec($ch);
//send Text
header("Content-Type: application/json");
$parameters = array('chat_id' => $id, "text" => $text);
$parameters["method"] = "sendMessage";
echo json_encode($parameters);
}
Like suggested here: php telegram answercallbackquery sendmessage
But also not working.

If someone has the same problem, here the solution:
function tg_answer_callback_query($cbq_id) {
$params=[
'callback_query_id' => $cbq_id
];
$ch = curl_init('https://api.telegram.org/bot'.token.'/answerCallbackQuery');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3500);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 3500);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
}
Run this code at the end of if(callback($update)) (not after it!) and it works!

Related

google chat bot webhook not working in php

Google chatbot has a webhook where users can automate chat there is a small python script to make it work but I want to do the same using php. I am using curl to hit the post method
$apiUrl = 'https://chat.googleapis.com/v1/spaces/AAAAbvoeZ0w/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=h2OIcCLB6_f_XxhPX6lugnGizE88ZBBpJURFHtPfh_0%253D';
$ch = curl_init($apiUrl);
//$kid_userid = "IXM_".session('user_data')['userID'];
$data = '{"text": "All Mock Test are Free "}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
after hitting this code I am getting errors.
{
error: {
code: 400,
message: "Invalid request token h2OIcCLB6_f_XxhPX6lugnGizE88ZBBpJURFHtPfh_0%3D",
status: "INVALID_ARGUMENT"
}
}
but same code when I am running on python it is working perfectly. Any Help will be very helpful. Thanks for the help in advance and I tried my best to explain .Sorry If I have made any mistake.
This code works for me. I have it from another SO answer, maybe the issue is the missing CURLOPT_POST...
$uri = "https://chat.googleapis.com/v1/spaces/AAAAgcWhzwk/messages?key=MY_KEYI&token=MY_TOKEN";
$msg = '*Testing Curl PHP message to Google Chat*\n\n Description';
$params = '{"text": "'.$msg.'"}';
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
The above code which I have shared is correct actually I just added the new bot URI and it worked. THanks, everyone for your help.

Request-URI Too Long - SMS API

My problem is somehow peculiar. I have this bulksms api from my provider:
http://www.estoresms.com/smsapi.php?username=user&password=1234&sender=##sender##&recipient=##recipient##&m
essage=##message##&
then i wrapped it in PHP and passed it in cURL:
$api = "http://www.estoresms.com/smsapi.php?username=".$sms_user."&password=".$sms_pwd."&sender=".$sender_id."&recipient=".$numbers."&message=".$text."&";
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$send_it = curl_get_contents($api);
ordinarily, it worked fine, but when $recepient (phone numbers) are more than say 300, i get an error:
Request-URI Too Long
The requested URL's length exceeds the capacity limit for this server.
Additionally, a 414 Request-URI Too Long error was encountered while trying to use an ErrorDocument to handle the request.
But BulkSMS should be able to send to thousands of numbers at a time.
From my research, i found out that there's a limit to URL. I'm not the server owner. i working on a shared hosting plan. pls how can i get around this problem. I know there's a solution to it that would not mean buying my own server.
Thanks
Can you try to make the API use POST instead of GET. It would solve the issue.
Edit:
I'm not sure your API check POST, but try that:
$api = "http://www.estoresms.com/smsapi.php";
$data = array('username' => $sms_user, 'password' => $sms_pwd, 'sender' => $sender_id , 'recipient' => $numbers , 'message' => $text);
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$send_it = curl_get_contents($api);
Have a look at this code example (from bulksms.com).
http://developer.bulksms.com/eapi/code-samples/php/send_sms/
So then, i had to find a way around my own problem. if the API will not allow thousands of numbers at a time, then let's break it into chunks at the point of execution.
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$how_many = count(explode(',', $numbers));
if ($how_many > 250){
$swi = range(0, ceil($how_many/250)-1);
foreach ($swi as $sw){$numbers_a = implode(',', (array_slice(explode(',', $numbers), $sw*250, 250)));
$api = "http://www.estoresms.com/smsapi.php?username=".$sms_user."&password=".$sms_pwd."&sender=".$sender_id."&recipient=".$numbers_a."&message=".$text."&";
$send_it = curl_get_contents($api);
}
}
if ($how_many <= 250){
$api = "http://www.estoresms.com/smsapi.php?username=".$sms_user."&password=".$sms_pwd."&sender=".$sender_id."&recipient=".$numbers."&message=".$text."&";
$send_it = curl_get_contents($api);
}

Toggl Reporting API with PHP cURL

I am trying to access the Toggl Reporting API.
I tried following in PHP with cURL, which connects to the API but gives the following error message: 'This method may not be used.' Any light on why this is the case would be useful as I'm very new to webservices. I may be missing something obvious or totally going the wrong way about it, so apologies if this is the case.
<?php
$userAgent = 'xxx';//username
$token = 'xxx';//token
$returned_content = get_data('https://toggl.com/reports/api/v2/summary?&workspace_id=[workspaceid]&since=2013-05-19&until=2013-05-20&user_agent=[username here]');
print_r($returned_content);
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_USERPWD, $token.':api_token');
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>
Edit: I tried a different approach. If I run the following code, I no longer receive any error messages, so the code seems to be executing but I can't print the response to the screen. Is there something specific I need to do to view the output other than print_r?(Toggl API returns JSON). Thanks.
$json = curl%20-v%20-u%[myapitoken]:api_token%20https://toggl.com/reports/api/v2/weekly?workspace_id=[id]&wsid=282507&since=2012-08-19&until=2013-09-20&user_agent=[user].json;
print_r($json);
Edit: Finally resolved! Code is as follows:
$workspace_id = '[id here]';
$user_agent = '[user agent here]'; // no spaces
$api_token = '[token here]';
$report_url = 'https://toggl.com/reports/api/v2/weekly?user_agent='.$user_agent.'&since=2013-08-01&until=2013-09-01';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_USERPWD, $api_token . ':api_token');
curl_setopt($ch, CURLOPT_URL, $report_url . '&workspace_id=' . $workspace_id);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$result = curl_exec($ch);
$result = json_encode($result);
Hope this helps someone in the future!
As I understand, you are receiving this message because of CURLOPT_SSL_VERIFYPEER == FALSE.
Try to remove this string from the code:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
Maybe I wrong, but I think with this option you are receiving "HTTP 501 Not Implemented" error from the Toggl server, which contains exactly the same message, "This method may not be used."

Using curl to bring search results from external site

I have 2 sites, one main, one external. On the main site, I am using Lucene to search through it. The problem is, I am trying to also search through the external site.
The Form action for the external site:
<form action="https://secure.bcchf.ca/SuperheroPages/searchResults.cfm?Event=WOT" method="post" name="search_tribute" >
I've tried to use curl, but it only brings up the search form without actually doing the search (the field is empty as well).
<?php
$ch = curl_init("https://secure.bcchf.ca/SuperheroPages/searchResults.cfm?Event=WOT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, tname='hello');
$output = curl_exec($ch);
echo $output;
curl_close($ch);
?>
Any tips?
I don't have access to the form action since it's on an external site. All i have is a form that links to it when I submit it.
<?php
$ch = curl_init("https://secure.bcchf.ca/SuperheroPages/searchResults.cfm?Event=WOT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array("teamName" => "hello", "searchType" => "team"));
$output = curl_exec($ch);
echo $output;
curl_close($ch);
?>
Can you try this?
I'm pretty sure it's supposed to be teamName instead of tName
Most search engine use GET and not POST .. you can try
// asumption
$_POST['search'] = "hello";
// Return goole Search Result
echo curlGoogle($_POST['search']);
function curlGoogle($keyword) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/search?hl=en&q=' . urlencode($keyword) . '&btnG=Google+Search&meta=');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FILETIME, true);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Or if you want post then
curl_setopt($ch, CURLOPT_POSTFIELDS, array("search"=>"hello"));
Your php code is not valid syntax, it does not compile.
So if this is really what you have, your problem is that your file generates a fatal error.
That being said, this question is hard to answer since we don't know the site you want to grab your search results from.
Try modifying your line like this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "search=hello");
or alternatively
curl_setopt($ch, CURLOPT_POSTFIELDS, array("search" => "hello");
Maby it will work, however it may be that more post data is required or that the element name is not correct.
You have to look at the form or try making a request and look at it with chromes developer tools or firebug.
Also there are a number of ways for external sites to prevent what you are doing, altough evertything can be worked around somehow.
Assuming that is not the case, I hope i could help you.
Try just putting it into an array.
as that will be the variable the $_POST checks on the other side
and just checked your link, its teamName for the field
$fields = array("teamName"=>"julia");
Then..
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
So your complete code is...
<?php
$ch = curl_init("https://secure.bcchf.ca/SuperheroPages/searchResults.cfm?Event=WOT");
$fields = array("teamName"=>"julia");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$output = curl_exec($ch);
var_dump($output);
curl_close($ch);
?>

how to send xml file to server backend using php? [duplicate]

This question already has answers here:
How to properly send and receive XML using curl?
(2 answers)
Closed 9 years ago.
I have fetched data from server using this code, `$server = 'LOCALHOST:9000';
$headers = array(
"Content-type: text/xml"
,"Content-length: ".strlen($requestXML)
,"Connection: close"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch)){
print curl_error($ch);
echo " something went wrong..... try later";
}else{
echo " request accepted";
print $data;
curl_close($ch);
}`
Now I have to do reverse, how to send the data into server using php? curl method is the only way or is there any other method to do the same. Give me some example.
Sending/Receiving using cURL is the exact same thing. cURL is based on sending data to an given URL and possibly receiving a response. Let's take a simple example of getting a user and sending a user.
Getting a user would be
$data = array(
'user_id' => 1
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/getUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
getUser.php does nothing more than search for a user and return the data found.
$response would possibly contain data of the user, perhaps just a text-response containing the name. A serialized PHP array, an XML response with a full user profile.. etc.
Inserting/Sending data
$data = array(
'user_name' => 'Joshua',
'user_email' => 'my#email.com'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/addUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
addUser.php performs some validation of the fields and if validated inserts a user in the database
$response in this case does not contain the userdata (however: it's a possibility), but more likely the $response contains a result. An ok textresponse, a json/xml response or perhaps a '200 OK' header response
It's all basically the same. There is no difference in getting/sending data using cURL. It's all based on sending a request and in most cases do something with the outcome.

Categories