I saw a couple of days ago this tutorial on youtube.
It was very interesting, so I decided to make a own bot.
I used the code from the tutorial as a template:
<?php
$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;
$update = file_get_contents('php://input');
$updatearray = json_decode($update, TRUE);
$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];
if($text == 'hy'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
}
elseif($text == 'ciao'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}
The script worked if I execute the script manually. However when I use the webhook it doesn't work anymore. The tutorial said that $update = file_get_contents('php://input'); is the right way, to be used before $update = file_get_contents($website."/getupdates");. My question how can I use php://input to execute my script automatically? The script is on a server from "one.com" and the certificate is also from "one.com".
If you use selfsigned ssl you have to point to the ssl path ,,
use the ssh to run this command after filling it with your real data ,,
curl -F "url=https://example.com/myscript.php" -F "certificate=#/etc/apache2/ssl/apache.crt" https://api.telegram.org/bot<SECRETTOKEN>/setWebhook
After change to WebHook method, you need to put as follows, since now we are going to handle one message at time. For me works perfectly.
instead
$chatId = $updateArray["result"][0]["message"]["chat"]["id"];
to
$chatID = $update["message"]["chat"]["id"];
this is the answer for all of your problems.
follow this step after you got a secret token for your bot:
create file in your website https://yourdomain.com/secret-folder/index.php
create your php file like this :
<?php
$website = 'https://api.telegram.org/bot123456789:1234567890ABCDEF1234567890ABCDEF123/';
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (isset($update["message"])){
$chatID = $update["message"]["chat"]["id"];
$text = $update["message"]["text"];
if ( $text == '/start' ) {
// send welcome message
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=Welcome to my bot");
}else{
// send another message or do your logic (up to you)
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=some text here");
}
}
?>
Set Your Webhook from this bot #set_webhookbot
choose command or type ' ست وب هوک '
reply with your secret bot token ex: ' 123456789:1234567890ABCDEF1234567890ABCDEF123 '
reply with your webhook address 'https://yourdomain.com/secret-folder/index.php'
reply with /setwebhook
if you follow step by step its will work.
enjoy it !!
Sorry for digging up this old question so enthusiastically, I had exactly the same question as you.
I think actually the answer may be easier yet less satisfying as we hoped: I don't think it's possible to get a list of previous messages to the bot while using the webhook.
Namely: what this does, is run the PHP script directly as soon as the bot receives a message. Nothing is stored in an accessible database, hence no updateArray is returned.
I came across this example, which shows how php://input works. I guess the solution to display a list of messages would be, let the php script store the message in a database everytime a message is 'forwarded' via the webhook.
If anyone found something else: I'm very interested.
As per my understanding from your code snippet above, you need to use php://input within double quotes instead of single quotes. In php, we are having bing difference in this use case.
Related
So, I'm starting to understand a bit more of WhatsApp API and all the messages that my number received are sent to my server via Webhook. The text messages are fine, but I'm struggling with the media messages.
When the user sends an image for example, Facebook's Webhook only sends me the mime_type and the sha256 of the image.
Can anyone please guide me the steps of what I need to do?
Do I need to convert it to base64, and then write the file in my server? Do I need to use a specific function? Do I need to use another programming language that's not PHP?
I'm totally lost on this one.
The way to do this, as pointed out by #CBroe is to use the media endpoints.
Assuming message is the message from the Webhook
// Get the image information, including the download link
$image_url_handle = fopen("https://graph.facebook.com/v13.0/" . $message->id);
$image_url = "";
// Read all of the data before parsing
while (!feof($image_url_handle)) {
$image_url .= fread($image_url_handle);
}
// Close the stream
fclose(image_url_handle);
// Get the url from the image information
$image_url = json_decode($image_url)->url;
// Start a request to the download URL.
$image_stream = fopen($image_url);
Note: There is no error handling or frameworks, though this should work most of the time
I am trying to figure out how to call a google script via the api from php. Here is my script:
function doGet() {
return ContentService.createTextOutput("hello world!");
}
I can call it as a web app via it's URL but what I am trying to accomplish will require it be called via the API. Google's documentation is so confusing it's almost useless.
This seems like it would be such a simple task but I'm getting nowhere fast. Does anyone know where to find a simple step by step tutorial or can someone detail the steps required to accomplish this?
UPDATE: So, I've given up on the google API to access scripts. I can use all of the drive api calls but it seems it's not possible to call my own script via the API. Here is my ultimate goal:
A google script to zip files:
function doGet(e) {
var fileIds = [];
// hard code a couple of file id's just for simplicity now.
fileIds.push('0BzoYw0RgVVOvU0RqdTFrcGdSSzA');
fileIds.push('0BzoYw0RgVVOvNEJNcWpmSkNxNTA');
return ContentService.createTextOutput(zipping(fileIds));
}
function zipping(fileIds) {
var zipfilename = "sample2.zip";
var blobs = [];
var mimeInf = [];
var accesstoken = ScriptApp.getOAuthToken();
fileIds.forEach(function(e) {
try {
var file = DriveApp.getFileById(e);
var mime = file.getMimeType();
var name = file.getName();
} catch (er) {
return er
}
var blob;
blob = UrlFetchApp.fetch("https://www.googleapis.com/drive/v3/files/" + e + "?alt=media", {
method: "GET",
headers: {"Authorization": "Bearer " + accesstoken},
muteHttpExceptions: true
}).getBlob().setName(name);
blobs.push(blob);
});
var zip = Utilities.zip(blobs, zipfilename);
return DriveApp.createFile(zip).getId(); // return the file id of the new zip file.
}
Publish -> Deploy as web app...
Select "New"
Select "Me"
Select "Only Myself"
Click "Deploy" and authorize the access as requested.
Call the web app with curl from command line to test:
curl -L https://script.google.com/macros/u/0/s/### script id ###/exec
Get html containing the error: "Sorry, unable to open the file at this time."
Change permissions so anyone can execute the app.
Same error. Even entering the url in the browser as the same user gives the same error.
At this point I think I have to admit defeat and find a solution other than Google.
------------------ UPDATE 2 --------------------
Apparently the error:
"Sorry, unable to open the file at this time. Please check the address and try again."
I think this is some oddball problem with Google. The same script works in some accounts but not others. I see from searching the web, others randomly get this error and there is no definitive solution. If anyone knows one, please let me know.
----------------- UPDATE 3 --------------------
This error is an oddball problem with Google. Apparently a new script in some accounts will get this error until the next day. I have verified this several times so if this happens to you, wait a day and try executing it again. The good thing is that after Google finally is able to "open the file" you can make any changes you want, including additional script files to that project, and it updates instantly.
However, a new project will have to wait until the next day so pre create any you think you might want and a couple extra a day ahead of time.
How about this sample script? When you deploy Web Apps, please copy and paste the URL. And please use it to $url of the following script.
How to deploy Web Apps.
On the Script Editor
File
-> Manage Versions
-> Save New Version
Publish
-> Deploy as Web App
-> "Project version:" is latest one or create as New.
-> At "Execute the app as", select "your account"
-> At "Who has access to the app", select "Anyone, even anonymous"
-> Click "Deploy"
-> Copy "Current web app URL"
-> Click "OK"
Sample script :
<?php
$url = 'https://script.google.com/macros/s/#####/exec';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($curl);
echo $response;
curl_close($curl);
?>
Result :
hello world!
References :
Web Apps
cURL Functions
If I misunderstand your question, I'm sorry.
I am using Google Cloudshell platform to create an ssl-certified url for hosting a webhook. So I originally began using getupdates to find the chat_id and send the bot messages. The following code, meant to get the user's chat-id and then text him "text" , works fine.
<?php
$botToken = "insert bot token" ;
$website = "https://api.telegram.org/bot".$botToken ;
$update = file_get_contents($website."\getupdates");
$updateArray = json_decode($update, TRUE) ;
$chatId = $updateArray["result"][0]["message"]["chat"]["id"] ;
file_get_contents($website."/sendmessage?chat_id=".$chatId."&text=test") ;
?>
Then I set up a webhook using setwebhook and modified the above code.
<?php
$botToken = "insert bot token" ;
$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"] ;
file_get_contents($website."/sendmessage?chat_id=".$chatId."&text=test") ;
?>
In other words I changed the \getupdates with "php://input" . It did not work.
I suppose it is possible that google app engine does not automatically sign its ssl certificates and perhaps that's why the webhook does not work.
Any help will be appreciated.
EDIT : In response to the answers/comment below, I tried the getWebhookinfo approach and got
"url:"https://my_url.com" ,"has_custom_certificate":false, "pending_update_count":0, "max_connections":40
You can find out problem via following method:
Check getWebhookInfo method, make sure your webhook URL is correct, and no last_error_message field.
POST similar data to your server, here is some data you can use in curl -d JSON, just copy it and run on your own server.
At last, check your CDN config (if you had applied on that server), temporary disable flooding or any check.
I am desperately trying to make my form works.
But I am having issue with validating the recaptcha server side.
I have been looking around and going over my form a thousand times making tests, I know it doesn't pass the step of the recaptcha, but can't figure it out.
Here is my piece of code :
//variable :
$recaptcha = $_POST['g-recaptcha-response'];
//test captcha
if($recaptcha != '')
{
$secret = " MY KEY HERE";
$ip = $_SERVER['REMOTE_ADDR'];
$var = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$recaptcha."&remoteip=".$ip);
$array = json_decode($var,true);
//check if captcha ok then check fields empty
if($array['success'])
Please let me know if you can find anything wrong.
Thank you.
(indeed I removed my security key)
In my testing, I ran into two problems that you might be having.
The remoteip argument is optional. When I removed it, everything worked. Here's why: I was testing with both client and server machines on private IP's behind a firewall, so the $_SERVER['REMOTE_ADDR'] value on my server was 192.168.x.x. Google saw the public IP of my NAT firewall, so that is what siteverify tried to match against.
You can only check a given response once. If you try to check it again, it will always fail. So during testing you need to use a fresh one each time.
Also, you can simplify your PHP code a bit by using:
"...siteverify?secret=$secret&response=$recaptcha");
Try this:
$secret = "YOUR-SECRET-KEY";
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $_POST['g-recaptcha-response']);
$googleResponse = json_decode($verifyResponse);
if ($googleResponse->success)
{
$captchaVerified = true;
}
I am trying to create a Telegram Bot. I follow this video. my codes are working in localhost, but when I put them on server the result is different. this code just call getUpdates method of Telegram api.
Code :
<?php
$botToken = "146158152:AAHO**********-L3xF08RN7H0xK8E";
$website = "https://api.telegram.org/bot".$botToken;
$update = file_get_contents($website."/getUpdates");
var_dump($update);
?>
Localhost result :
string(616) "{"ok":true,"result":[{"update_id":35****293, "message":{"message_id":1,"from":{"id":95*****4,"first_name":"Mahmood","last_name":"Kohansal","username":"mahmoodkohansal"},"chat":{"id":95*****4,"first_name":"Mahmood","last_name":"Kohansal","username":"mahmoodkohansal","type":"private"},"date":1448737853,"text":"\/start"}},{"update_id":356676294, "message":{"message_id":2,"from":{"id":95*****4,"first_name":"Mahmood","last_name":"Kohansal","username":"mahmoodkohansal"},"chat":{"id":95881214,"first_name":"Mahmood","last_name":"Kohansal","username":"mahmoodkohansal","type":"private"},"date":1448737855,"text":"1"}}]}"
and Server result :
bool(false)
Sorry for my poor English.
If your code works in localhost, the first assumption would be that your server was not successful in establishing a connection to the bot api.
Perhaps you should put it in an if statement.
$token = "your token";
$website = "https://api.telegram.org/bot".$token;
if($updates = file_get_contents($website."/getUpdates"))
{
echo "Connection made";
}
else
{
echo "Fail";
}
Also can you make sure a webHook isn't set? getUpdates method does not return results if a webHook is set.
PHP file_get_contents method was the problem. I found the same problem with this method here, and use the solution to solve my problem.