I am creating a telegram bot with php. I need to let user insert data step by step when they run the command /order. I do an example:
User: /order
Bot: I will help you to make an order
Bot: Insert the name
User: Ciccio (he has typed the name)
Bot: Ok, now insert your surname
User: Pasticcio (he has typed the surname)
and so on...
I thought I was in the correct way to reach my purpose... but not... something does not work... Here my code:
elseif(strcmp($text, "/order") === 0) <-Here the command
{
$response =
"I will help you.\n"
."\n"
."Insert your name:";
$parameters = ['chat_id' => $chatId, "text" => $response, "parse_mode" => "Markdown"];
$parameters["method"] = "sendMessage";
echo json_encode($parameters);
$action_parameters = ['chat_id' => $chatId, "action" => "typing"];
$action_parameters["method"] = "sendChatAction";
echo json_encode($action_parameters);
$parameters2 = array('chat_id' => $chatId, "text" => "good! Now insert the surname");
$parameters2["method"] = "sendMessage";
echo json_encode($parameters2);
}
the code stop after I visualize the first message... it is like after I do my first echo json_encode($parameters); no code is runned anymore...
How can I reach my purpose?
Thank you
Do you use JSON response when received Webhook updates?
If yes, you need to make a request instead of print it to HTTP Response Body and log user input to your own database.
for any message your bot receives, you check the step of the user in your bot and you will send the right function (so the right question).
to do this you have to store users' steps. Please read my answer to this question.
Related
This telegram bot tries to ban a predetermined user IDs each time added to a group. IDs are listed in a file. I'm using this telegram bot class and in webhook method.
$telegram = new Telegram($bot_id);
$chat_id = $telegram->ChatID();
$button = $telegram->text();
if ($button == "DoBan"){
$fn = fopen("ids.txt","r");
while(! feof($fn)) {
$result = fgets($fn);
$int_result = (int)$result;
$content = array('chat_id' => $chat_id, 'user_id' => "$int_result");
$telegram->kickChatMember($content);
}
fclose($fn);
$content2 = array('chat_id' => $chat_id, 'text' => "ban done! ");
$telegram->sendMessage($content2);
die();
}
But there is two problems here:
1. If IDs listed in our file haven't been banned before in the group bot is added to, the bot can't ban any of them. the point is if you ban IDs manually in any other group and perform a banning by bot there one time you can ban those IDs in any other group after that.
2. When bot receives the "DoBan" after it finishes the banning it get stuck in a some kind of loop and prints "ban done!" over and over like it's doing the banning all over again.
UPDATE:
Based on further researches there are two reasons for the two expressed problems
For the first problem: If your bot hasn't seen the user ID before it cannot ban it. So the bot has to see the user first somewhere, either by starting the bot or seeing that user inside the same group with bot
For the second problem: In case of an unsuccessful request telegram bot API thinks something is wrong with your server and requests again every few seconds so you have to add header("HTTP/1.1 200 OK"); to your script or do the increment on update_id
So this is the updated code
$telegram = new Telegram($bot_id);
header("HTTP/1.1 200 OK");
http_response_code(200);
$chat_id = $telegram->ChatID();
$result = $telegram->getData();
$text = $result['message'] ['text'];
$update = $result ['update_id'];
$result ['update_id'] = ++$update;
if ($button == "DoBan"){
$fn = fopen("ids.txt","r");
while(! feof($fn)) {
$result = fgets($fn);
$int_result = (int)$result;
$content = array('chat_id' => $chat_id, 'user_id' => "$int_result");
$telegram->kickChatMember($content);
}
fclose($fn);
$content2 = array('chat_id' => $chat_id, 'text' => "ban done! ");
$telegram->sendMessage($content2);
die();
}
So I need to know how should I exactly increase the update_id or what is the proper way to add header("HTTP/1.1 200 OK");becasue the problems still exist.
Based on further researches there are two reasons for the two expressed problems
for the first problem: If your bot hasn't seen the user ID before it cannot ban it. So the bot has to see the user first somewhere, either by starting the bot or seeing that user inside the same group with bot
for the second problem: In case of an unsuccessful request telegram bot API thinks something is wrong with your server and requests again every few seconds so you have to add header("HTTP/1.1 200 OK"); to your script or do the increment on update_id
I hope you can help me with an issue with phone call dialings using Plivo PHP (new SDK 4.0). First I will indicate what I want to achieve:
- A client on my website wants to talk with an agent of main, so he introduces his telephone number in a form, choose an agent, and finally when submit, the website connect both of them dialing (this works). But then, (here begin my problems), I can't retrieve the call details (status, duration, initial and end dates of the call, etc...) for invoicing the client according to some of these details.
Edited 2018/02/23:
Ramya, the 600 error has dissapeared and everything seems to be ok as I see in the Plivo debug log. Below are my new codes (I think better done thanks to your instructions), and then, I show you the Plivo debud log (perhaps it's better you can see it inside my account, call made Feb 23, 2018 18:33:15), and finally I see my server debug error log is empty!.
The main problem is that dialstatus.php file, although seems to receive the parameters, I don't know how to access them because dialstatus.php does not execute showing the data in my monitor (in my code for example, this line never shows in the monitor screen:)
echo "Status = $estado, Aleg UUID = $aleg, Bleg UUID = $bleg";
So even though it receives the parameters, I can not access them to manipulate them, print them on the screen, do ifs with them, etc. May it be perhaps a permission problem with the files? (These php files have 6,4,4 permissions on my server, the same as the others).
Thank you!
Code 1: makecall.php
require 'vendor/autoload.php';
use Plivo\RestClient;
$client = new RestClient("**********", "**************************");
$telefono_cliente = "34*******";
$telefono_experto = "34*********";
$duracion = 50;
try {
$response = $client->calls->create(
"3491111111",
[$telefono_experto],
"https://www.ejemplo.com/llamar/response.php?telf=$telefono_cliente",
'POST',
[
'time_limit' => $duracion,
]
);
$id = $response->requestUuid;
echo "<br>Este es el requestUuid: " . $id . "<br><br>";
}
catch (PlivoRestException $ex) {
print_r($ex);
}
?>
Code 2: response.php
require 'vendor/autoload.php';
use Plivo\XML\Response;
$resp = new Response();
$params = array(
'callerId' => '3491111111',
'action' => "https://www.ejemplo.com/llamar/dialstatus.php",
'method' => "POST",
'redirect' => "false"
);
$body3 = 'Desde ejemplo un cliente desea hablar con usted.';
$params3 = array(
'language' => "es-ES", # Language used to read out the text.
'voice' => "WOMAN" # The tone to be used for reading out the text.
);
$resp->addSpeak($body3,$params3);
$dial = $resp->addDial($params);
//$number = "34**********";
$number = $_GET['telf'];
$dial->addNumber($number);
Header('Content-type: text/xml');
echo($resp->toXML());
/*
Output:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Speak language="es-ES" voice="WOMAN">Desde ejemplo un cliente desea hablar con usted.</Speak>
<Dial redirect="false" method="POST" action="http://www.ejemplo.com/llamar/dialstatus.php" callerId="3491111111">
<Number>34********</Number>
</Dial>
</Response>
*/
?>
Code 3: dialstatus.php
// Print the Dial Details
$estado = $_REQUEST['DialStatus'];
$aleg = $_REQUEST['DialALegUUID'];
$bleg = $_REQUEST['DialBLegUUID'];
echo "Status = $estado, Aleg UUID = $aleg, Bleg UUID = $bleg";
?>
Plivo Sales Engineer here.
Redirect = true is used only when you want to continue the call by returning another XML in your action URL. For you use case, you don't have to use this parameter. Even if the Redirect is set to false, Plivo will make a request to the action URL with a list of parameters. I looked into your account (here) and I can see this request getting sent with DialStatus, ALegUUID, BLegUUID along with other parameters.
Dial Action URL is the best place to know the DialStatus and DialHangupCause.
You can find the call duration and billing amount in Hangup URL request as well. This Hangup URL can be configured in your first API call (to the expert). By default, hangup URL is set to Answer URL.
Please raise a support ticket with us for further assistance.
Okay so here goes i am using a rest api called strichliste
i am creating a user credit payment system
i am trying to grab a users balance by username problems is
my restapi i can only get the blanace via its userid
I have created a bit of php that grabs all the current users and the corresponding id and balance using this below
function getbal(){
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://example.io:8081/user/'
)
);
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
print_r($resp);
}
this is the resulting respinse i get after using this in my main php script
<? getbal(); ?>
result --- #
{
"overallCount":3,
"limit":null,
"offset":null,"entries":[
{"id":1,
"name":"admin",
"balance":0,
"lastTransaction":null
},
{"id":2,
"name":"pghost",
"balance":0,
"lastTransaction":null
},
{"id":3,
"name":"sanctum",
"balance":0,
"lastTransaction":null
}
]
}
as you can see there are only currently 3 users but this will grow everyday so the script needs to adapt to growing numbers of users
inside my php script i have a var with the currently logged in use so example
$user = "sanctum";
i want a php script that will use the output fro gatbal(); and only output the line for the given user in this case sanctum
i want it to output the line in jsondecode for the specific user
{"id":3,"name":"sanctum","balance":0,"lastTransaction":null}
can anyone help
$user = "sanctum";
$userlist = getbal();
function findUser($u, $l){
if(!empty($l['entries'])){
foreach($l['entries'] as $key=>$val){
if($val['name']==$user){
return $val;
}
}
}
}
This way, once you have the list, and the user, you can just invoke findUser() by plugging in the userlist, and the user.
$userData = findUser($user, $userlist);
However, I would suggest finding a way to get the server to return only the user you are looking for, instead of the whole list, and then finding based on username. But thats another discussion for another time.
$mob_num=$_POST["mobileNumber"];
$sms_mes=$_POST["smsMessage"];
$lin_api = "http://abcd.com/SendSms.aspx?username=demo&password=demo123&to=$mob_num&from=TIWCOM&message=$sms_mes";
$get_mid = file_get_contents($lin_api);
echo " $get_mid ";
In the above code, I collect mobileNumber & smsMessage from a html form page and put it into $lin_api and try to send the $lin_api to abcd.com's server by file_get_contents
If I directly paste:
http://sitename/SendSms.aspx?username=demo&password=demo123&to=9876543210&from=TIWCOM&message=Testing SMS
(with '9876543210' as mobile number and 'Testing SMS' as message) in the link bar, it works. It sends SMS and returns a messageid code. But, if I use above code, I get some peculiar error message like:
Invalid Details (Username, Password, From, To or Message)
or
BAD Request. HTTP Error 400. The request is badly formed
Why? Please help. Thanks in advance.
Try:
$lin_api = "http://abcd.com/SendSms.aspx?" .
http_build_query(array('username' => 'demo',
'password' => 'demo123',
'to' => $mob_num,
'from' => 'TIWCOM',
'message' => "$sms_mes (by tiw.com)"));
I used php server side to connect with clickatell messages service , i used the soap api technique to make the connection . it is working .but in my code , i can send just one message at the same time , here is the code :
function actionSendSMS(){
$msgModel = new Messages();
$settModel = new Settings();
$setRows = $settModel->findAll();
$usr=$setRows[0]->clickatell_usr;
$pwdRows = $settModel->findAll();
$pwd=$pwdRows[0]->clickatell_pwd;
$api_idRows = $settModel->findAll();
$api_id=$api_idRows[0]->clickatell_api_id;
$msgModel->findAllBySql("select * from messages where is_sent=0 and
send_date=".date("m/d/Y"));
$client = new SoapClient("http://api.clickatell.com/soap/webservice.php?WSDL");
$params = array('api_id' => $api_id,'user'=> $usr,'password'=> $pwd);
$result = $client->auth($params['api_id'],$params['user'],$params['password']);
$sessionID = substr($result,3);
$callback=6;
// echo $result."<br/>";
// echo $sessionID;
$params2 = array('session_id'=>$sessionID, 'api_id' => $api_id,'user'=>
$usr,'password'=>$pwd,
'to'=>array('962xxxxxxx'), 'from'=>"thetester",'text'=>'this is a sample test
message','callback'=>$callback);
$result2 = $client->sendmsg($params2['session_id'],
$params['api_id'],$params['user'],$params['password'],
$params2['to'],$params2['from'],$params2['text'],$params2['callback']);
print_r( $result2)."<br/>";
$apimsgid= substr($result2[0],4);
$rowsx=Messages::model()->findAllBySql("select * from messages where is_sent=0 and
send_date='".date("m/d/Y")."'");
for($i=0;$i<count($rowsx);$i++)
{
$rowsx[$i]->clickatell_id=$apimsgid;
$rowsx[$i]->save();
}
//echo $apimsgid."<br/>";
if (substr($result2[0], 0,3)==='ERR' && (!(substr($result2[0], 0,2)==='ID'
) ))
{
echo 'Connot Routing Message';
}
.... now you see that this code will send one message at the same time , forget about the id , its for personal purpose , now this service i have to modify it , to send multiple messages at the same time , and i will give every message an unique ID , so now my problem is : is there any one knows if there is a service to send multiple sms at the same time ;
as in my code i fill the information for one message ,but i need a service to send multiple sms , does any body can give me a link to this service , i made many searches but there is no answer i have found
Try startbatch command to send multiple messages at the same time (it also supports personalized). However, it is not based soap, it is based http api.
Have you tried
$params2 = array('session_id'=>$sessionID, 'api_id' => $api_id,'user'=> $usr,'password'=>$pwd, 'to'=>array('962xxxxxxx', '962xxxxxxx', '962xxxxxxx'), 'from'=>"thetester",'text'=...
or
$params2 = array('session_id'=>$sessionID, 'api_id' => $api_id,'user'=> $usr,'password'=>$pwd, 'to'=>array('962xxxxxxx,962xxxxxxx,962xxxxxxx'), 'from'=>"thetester",'text'=...