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.
Related
I can't log in my app using vtwsclib library function doLogin().
I would like retrieve some data from crm via the web services but I keep getting "login failed" message.
Beside that, I got no errors or warning from php.
My system is a xampp localhost, php -v 7.1.33.
Do I have to make some changes within the library code in addition of the code here below?
$url = 'urlofmyvtecrmaccess';the url to my crm access page.
$client = new Vtiger_WSClient($url);
$login = $client->doLogin('mycrmuser', 'mywebserviceaccesskey');
if (!$login)
echo 'Login Failed';
else
echo 'Login Successful';
Did you provide full url to the webservice file ?
Like http://yourcrm.com/webservice.php
You could find if there is any error in the api call using
$client->lastError() method
You can also debug inside doLogin() method to identifiy the error
Check the api response if it has any information of error
You must have to pass your encrypted password and for encryption, you have to use md5.
$encryptedPassword = md5('useraccesskey');
$login = $client->doLogin('mycrmuser', $encryptedPassword);
I'm trying to get the FB Messenger Bot API to work. I'm currently on the step where I'm trying to subscribe a webhook. I currently have a script of the following form:
#!/usr/bin/php
<?php
$challenge = $_REQUEST['hub_challenge'];
echo $challenge; # HERE!
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'token') {
echo $challenge;
}
?>
However when I try to "Verify and Save" the callback URL I get an error of the form:
The URL couldn't be validated. Response does not match challenge, expected value = '401537941', received=''
namely that my script is sending an empty string. However, if I change the line marked "HERE!" above to "echo 'cat' ", the error message is the same except "received='cat'" as expected. Thus, my script is being executed and is trying to send some content back to FB, but for some reason the $challenge variable is empty. Why could this be the case?
Thanks!
if($_GET['hub_verify_token'] === "validation_token"){
echo($_GET["hub_challenge"]);
} else {
echo("error");
}
There are probably extra string in your response as you are not exiting after printing challenge. Try your script in browser and inspect html to see if there is anything extra.
Use the following code as you would need to seperate verification code from your work webhook calls. Also verify token is not something you create from Facebook, its your own keyword
/* validate verify token needed for setting up web hook */
if (isset($_GET['hub_verify_token'])) {
if ($_GET['hub_verify_token'] === 'YOUR_SECRET_TOKEN') {
echo $_GET['hub_challenge'];
return;
} else {
echo 'Invalid Verify Token';
return;
}
}
So in this case your verify token is YOUR_SECRET_TOKEN, now when you are setting up web hook, Type YOUR_SECRET_TOKEN in the verification token.
I wrote recently a step by step guide with screen shots here.
In my PHP project I want to integrate SMS gateway.
I have integrated HSPSMS SMS gateway.
They have given one API for this,but unfortunately I am unable to call this in proper way. I have called API after user successfully registered to site for sending SMS to user regarding same to notify he had successfully registered. Currently I am sending SMS for same but API's can send response back for SMS delivery(Successfully SMS sent or not in a JSON format).
Here is a problem- I am unable to caught the return response of SMS gateway,so it causes the Response is showing on user/Web Page.
It is a problematic for user.
For calling SMS gateway I have used PHP Header function like:
header("Location:URL of SMS Gateway");
My Code as Bellow,
<?php
include("otherpages/connection.php");
if(isset($_POST['submit1'])) {
$mname=$_POST['mname'];
$cdate=$_POST['cdate'];
$maddress1=$_POST['maddress'];
$mschool=$_POST['mschool'];
$mkendra=$_POST['centrename'];
$mmobile=$_POST['mmobile'];
$user=$_POST['user'];
$pass=$_POST['pass'];
$approved="0";
$qr="insert into tempregistration values('','$cdate','$mname','$maddress1','$mschool','$mschool','$mkendra','$mmobile','$user','$pass','$approved')";
// Code for Registration SMS
$url = 'http://sms.hspsms.com/sendSMS?username=#USERNAME#&message=Dear User,You Have Succeffully Registered to ABC.com ,Thanks&sendername=HSPSMS&smstype=PROMO&numbers=9503808004&apikey=#APIKey#';
header("Location:$url");
?>
Please help me on same or guide where I am doing right or wrong?
Any help will be appreciable.
You're sending the user's browser to the API, what you want to do is have PHP make the request and then tell the user if it was successful or not.
You may be able to use get_file_contents, but curl will give you more control.
You should have a function that will send the request to the API and return a success/failure and then display a message to the user.
Something like this (untested):
if(isset($_POST['submit1'])) {
$mname=$_POST['mname'];
$cdate=$_POST['cdate'];
$maddress1=$_POST['maddress'];
$mschool=$_POST['mschool'];
$mkendra=$_POST['centrename'];
$mmobile=$_POST['mmobile'];
$user=$_POST['user'];
$pass=$_POST['pass'];
$approved="0";
$qr="insert into tempregistration values('',
'$cdate','$mname','$maddress1','$mschool',
'$mschool','$mkendra','$mmobile','$user','$pass','$approved')";
//update to encode parameters which contain spaces
$message = urlencode('Dear User, You have successfully registered ...');
// other parametes might also contain spaces ...
$username = urlencode('#USERNAME');
$sendername = urlencode('HSPSMS');
//etc
$url = 'http://sms.hspsms.com/sendSMS?username='.$username
.'&message='.$message
.'&sendername='.$sendername
.'&smstype=PROMO&numbers=9503808004&apikey=#APIKey#';
if ($result = do_api_call($url)){
echo "SMS API returned:<br>";
echo $result;//for debugging
}else {
echo "Failure"
}
}
...
function do_api_call($url){
//this is very simplistic code to get you going ...
//use curl instead for more control
return file_get_contents($url);
}
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.
I'm getting the "Configuration Failed" pop up after submitting my URL and Token in the WeChat sandbox environment. Could anyone suggest ways to debug or find a solution? Here are the details:
running a Heroku server and using the heroku generated URL.
pushed the sample code found in the documentation here
followed the youtube tutorial, copied the code and tried that as well.
<?php
$data[] = 'Test123';
$data[] = $_GET['timestamp'];
$data[] = $_GET['nonce'];
asort($data);
$strData = '';
$d = '';
$authString = '';
foreach($data as $d){
$authString .= $d;
}
//verify the signture
if(sha1($authString) == $_GET[signature]){
//check if the echostr
if(!empty($_GET['echostr'])){
echo $_GET['echostr'];
die();
}else{
//logic goes here
$return = '<xml>
<ToUserName><![CDATA['.$toUser.']]></ToUserName>
<FromUserName><![CDATA['.$fromUser.']]></FromUserName>
<CreateTime>'.time().'</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA['.$text.']]></Content>
<FuncFlag>0</FuncFlag>
</xml>';
echo $return;
}
}else{
die('You are not supposed to be here');
}
?>
checked the logs and found that its working fine but shows no activity when I submit the URL and token on WeChat sandbox.
have tried different variations of URL, from using the root URL to finishing with the php file ie xxxx/responder.php
Token submitted matches Token used in code.
Uploading raw php to the server, hijacked the heroku php hello world app with the documentation code or youtube code.
The code itself comes straight from the WeChat Docs or the Youtube Video. Please let me know if I could provide any additional information.
Any advice, tips or hints would be really appreciated.
Please check. The sandbox environment was broken for International. This should be resolved now. Please test again