Telegram API Bot - CallbackQuery response to the touch of a button - php

Actually the question is how to get an answer from the user at the click of a button?
What should be changed\rewritten in the code?
$access_token = '...';
$api = 'https://api.telegram.org/bot' . $access_token;
$output = json_decode(file_get_contents('php://input'), TRUE);
$message = $output['message']['text'];
$chat_id = $output['message']['chat']['id'];
if ($output['callback_query'] != null){
$data = $output['callback_query']['data'];
$data_id = $output['callback_query']['id'];
$chat = $output['callback_query']['message']['chat']['id'];
switch($data){
case "/123":
answerCallback($data_id, '123');
sendMessage($chat, "123", null);
break;
case "/plz":
answerCallback($data_id, 'plz');
sendMessage($chat, "plz", null);
break;
}
}
elseif ($message != null) {
switch($message) {
case '/test':
$inline_button1 = array("text"=>"123","callback_data"=>"/123");
$inline_button2 = array("text"=>"work plz","callback_data"=>'/plz');
$inline_keyboard = [[$inline_button1,$inline_button2]];
$keyboard=array("inline_keyboard"=>$inline_keyboard);
$replyMarkup = json_encode($keyboard);
sendMessage($chat_id, "ok", $replyMarkup);
break;
}
}
function sendMessage($chat_id, $message, $replyMarkup) {
file_get_contents($GLOBALS['api'] . '/sendMessage?chat_id=' . $chat_id . '&text=' . urlencode($message) . '&reply_markup=' . $replyMarkup);
}
function answerCallback($id, $text) {
file_get_contents($GLOBALS['api'] . '/answerCallbackQuery?callback_query_id='.$id.'&text='.$text);
}
This code only allows you to get a response from the message /test, and does not respond to button presses.
Uses webhook.

Have a look at your error log. You forgot to provide a value for $replyMarkup.
PHP Warning: Missing argument 3 for sendMessage()

Related

Google recaptcha missing-input-response

I have an error with the response of Google recaptcha.
Please, could you help me to find my error ?
function captcha(){
$secret = "...";
$response = $_POST['g-recaptcha-response'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$api_url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$remoteip;
$decode = json_decode(file_get_contents($api_url), true);
if ($decode['success'] == true) {
return $decode['success'];
}else{
$errorsCode = "";
foreach ($decode['error-codes'] as $key => $value) {
$errorsCode .= '<p><strong>' . $key.':</strong> '.$value.'</p>';
}
return $errorsCode;
}
}
I get always the same error : missing-input-response.
Thank you for your help !
EDIT : Solved with https://gist.github.com/jonathanstark/dfb30bdfb522318fc819 by Mrpink

Sending POST data from Symfony into Yii controller

I have Yii2 project. And there I also have api written by Symfony.
In Symfony part I have method in the class which send request to Yii controller.
$buzz = $this->container->get('buzz');
$buzz->getClient()->setVerifyHost(false);
$buzz->getClient()->setVerifyPeer(false);
$buzz->getClient()->setTimeOut(false);
$url = $this->container->getParameter('integra_sync_prices');
$sendResult = $buzz->post($url, array('authorization' => $this->container->getParameter('load_token')), array('products' =>
json_encode($productPrices)));
$resultJson = json_decode($sendResult->getContent(), true);
if (isset($resultJson['error']))
throw new \Exception('Site: '.$resultJson['error'], 500);
class IntegraController extends Controller{
public function actionIndex()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$headers = Yii::$app->request->getHeaders();
foreach ($headers as $key => $value) {
if(strtolower(trim($key)) == 'authorization') {
$token = trim($value[0]);
break;
}
}
$products = json_decode(Yii::$app->request->post('products'));
$post_products = Yii::$app->request->post('products');
if('111' == $token) {
if(isset($post_products) && $products) {
foreach ($products as $product) {
echo $product->price." = ".$product->productId."<br>";
Yii::$app->db->createCommand("UPDATE oc_product SET quantity = '" . (int)$product->quantity . "', price = '" . (float)$product->price . "' WHERE product_id = '" . (int)$product->productId . "'")->execute();
}
$json['success'] = 'complete';
} else {
$json['error'] = 'empty data';
}
} else {
$json['error'] = 'authorization error';
}
Yii::$app->controller->enableCsrfValidation = false;
echo json_encode($json);
}
I expect that data in my database will be updated by this controller. But there in nothing changes.
What do I do wrong? Maybe I should send some another headers? Thanks a lot )

PHP Telegram Bot (editMessageText & editReplyMarkup)

I am Kevin and these days I'm having problems with the functions editMessageText and editReplyMarkup. This is my code and I don't know where is the problem.
This is my code:
<?php
$botToken = "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$website = "https://api.telegram.org/bot".$botToken;
$FilejSon = file_get_contents("php://input");
$FilejSon = json_decode($FilejSon, TRUE);
$FirstName = $FilejSon["message"]["chat"]["first_name"];
$UserChatId = $FilejSon["message"]["chat"]["id"];
$Message = $FilejSon["message"]["text"];
$MessageID = $FilejSon["message"]["message_id"];
$CallBackID = $FilejSon["callback_query"]["from"]["id"];
$CallBackData = $FilejSon["callback_query"]["data"];
$what = ["callback_query"]["message"]["inline_message_id"];
$document = "http://media.giphy.com/media/109Ku3hdapZJle/giphy.gif"; //It's just a funny image
//Emoji
$phone = json_decode('"\uD83D\uDCF2"');
$list = json_decode('"\uD83D\uDCCB"');
$money = json_decode('"\uD83D\uDCB0"');
$postbox = json_decode('"\uD83D\uDCEE"');
$sos = json_decode('"\uD83C\uDD98"');
$link = json_decode('"\uD83D\uDD17"');
$jSonCodeKeyboard = '&reply_markup={"inline_keyboard":[[{"text":"1","url":"https://core.telegram.org/bots/api"}],[{"text":"2","url":"https://www.google.it"}],[{"text":"4","switch_inline_query_current_chat":"try"}],[{"text":"5","url":"https://www.google.it"},{"text":"'.$link.'%20Link%20'.$link.'","url":"http://botkevin.altervista.org/Bot/Nuovo_documento_di_testo.txt"}],[{"text":"6","callback_data":"Press"}]]}';
$jSonCodeKeyboard1 = '&reply_markup={"inline_keyboard":[[{"text":"Indietro","callback_data":"Ok"}]]}';
switch ($Message){
case '/start':
$msg = "Hello $GLOBALS[FirstName] $GLOBALS[MessageID] $GLOBALS[UserChatId] $GLOBALS[what].\n";
sendMessage($UserChatId, $msg, $jSonCodeKeyboard);
break;
case '/prova':
sendFile($UserChatId, $document);
break;
case '/prova1':
$msg = "worked $GLOBALS[MessageID]";
sendMessage($UserChatId, $msg, $jSonCodeKeyboard1);
break;
default:
if (callback($FilejSon)){
if ($CallBackData == "Press"){
sendMessage($CallBackID, "gg", $jSonCodeKeyboard1);
}
else if($CallBackData == "Ok")
{
$msg = "Edited";
Edit($CallBackID, $MessageID, $msg);
Edit1($CallBackID, $MessageID, $jSonCodeKeyboard1);
}
}
$msg = "Unrecognized command.";
sendMessage($UserChatId, $msg);
break;
}
function sendMessage($chat_id, $text, $LayoutKey){
if($LayoutKey==""){
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chat_id."&text=".urlencode($text);
file_get_contents($url);
}
else{
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chat_id."&text=".urlencode($text).$LayoutKey;
file_get_contents($url);
}
}
function sendFile($chat_id, $file){
$url = $GLOBALS[website]."/sendDocument?chat_id=".$chat_id."&document=".$file; //Gif,Pdf e Zip
file_get_contents($url);
}
function Edit($chat_id, $msgID, $text){
$url = $GLOBALS[website]."/editMessageText?chat_id=".$chat_id."&message_id=".$msgID."&text=".urlencode($text);
file_get_contents($url);
}
function Edit1($chat_id, $msgID, $LayoutKey){
$url = $GLOBALS[website]."/editMessageReplyMarkup?chat_id=".$chat_id."&message_id=".$msgID.$jSonCodeKeyboard1;
file_get_contents($url);
}
function callback($getUpdate){
return $getUpdate["callback_query"];
}?>
I've searched everywhere a solution but either were in another programming language or used a library and more, I'm not very good at php so i would like a basic thing like my code.
I would like to do that when I click on the inline keyboard of the first message that sends the bot by doing "/ start", clicking a button can modify the message and the inline keyboard without sending other messages clogging the chat.
(already checked https://core.telegram.org/bots/api)

telegram callback_data is null in update array

I'm trying to make responce to user press inline_button2, after inline_keyboard apper in chat and I click on inline_button2 I suppose object callback_data have data with "callback_data"=>'inline2' but callback_data is null
see screenshot
$access_token = '...';
$api = 'https://api.telegram.org/bot' . $access_token;
$content = file_get_contents("php://input");
$update = json_decode($content, TRUE);
$callback_query = $update['CallbackQuery'];
$callback_data = $callback_query['data'];
$message = $update["message"];
$text = $message["text"];
$chatId = $message["chat"]["id"];
if (!isset($chatId)) {exit;}
switch($callback_data){
case 'inline2':
sendMessage($chatId, "inline2 pressed",null);
break;
default:
sendMessage($chatId, var_export($callback_query,TRUE),null);
break;
}
switch($text) {
case 'inline':
$inline_button1 = array("text"=>"inline1","url"=>"http://google.com", "callback_data"=>'inline1');
$inline_button2 = array("text"=>"inline2","callback_data"=>'inline2');
$inline_keyboard = array(array($inline_button1,$inline_button2));
$keyboard=array("inline_keyboard"=>$inline_keyboard);
sendMessage($chatId, "назад",$keyboard);
break;
}
function sendMessage($chat_id, $message, $replyMarkup) {
$s='';
if (isset($replyMarkup)) {
$s=json_encode($replyMarkup);
}
file_get_contents($GLOBALS['api'] . '/sendMessage?parse_mode=HTML&chat_id=' . $chat_id . '&disable_web_page_preview=true&text=' . urlencode($message) .'&reply_markup='.$s);
}
You are accessing the callback_query wrongly and additionally you need to take the chatId from the callback_query object.
$callback_query = $update['callback_query'];
$callback_data = callback_query["data"];
$chatId = callback_query["message"]["chat"]["id"];
change this $callback_query = $update['CallbackQuery']; to $callback_query = $update['callbackquery'];
you also need to add the following for callbackquery
$message_id = ['callback_query']['message']['message_id']; //callbackquery message id
$chat_id = $callback_query['message']['chat']['id']; // callbackquery chat id
i hope this helps

having php fatal error Function name must be a string in C:\wamp\www\drupal-7.42\sites\all\modules\form_fun\form_fun.cake.inc on line 78

I am trying to send a curl request to moodle using drupal.But each tiem i run this code i get an error message that function name must be a string.I have tried everything but nothing is working.Can anybody please help me?
function form_fun_cake_submit(&$form, &$form_state) {
$serverUrl=' http://localhost/moodle/my/webservice/rest/server.php?wstoken=d90b5d90db13711d12df525366f15db1';
$functionName = 'core_user_create_users';
$user1 = new stdClass();
$user1->username = 'testusername1';
$user1->password = 'Uk3#0d5w';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'testemail1#moodle.com';
$user1->auth = 'manual';
$user1->idnumber = '';
$user1->lang = 'en';
$user1->timezone = 'Australia/Sydney';
$user1->mailformat = 0;
$user1->description = '';
$user1->city = '';
$user1->country = 'AU'; //list of abrevations is in yourmoodle/lang/en/countries
$preferencename1 = 'auth_forcepasswordchange';
$user1->preferences = array(
array('type' => $preferencename1, 'value' => 'true')
);
$users = array($user1);
$params = array('users' => $users);
/// REST CALL
$rest_format = 'json';
//$server_url = $domain_name . '/webservice/rest/server.php' . '?wstoken=' . $token . '&wsfunction=' . $function_name;
$server_url = 'localhost/moodle/my' . '/webservice/rest/server.php'. '?wstoken=' . '15bd45a3dab2958b7e8fc237b14f76cd' .'&wsfunction='. $functionName;
dpm($server_url);
require_once('curl.inc');
$curl = new curl;
$rest_format = ($rest_format == 'json') ? '&moodlewsrestformat=' . $rest_format : '';
$resp =$curl($server_url . $rest_format, $params); //This is my line no 78
dpm($rest_format);
$respRc = json_decode($resp, true);
dpm($resp);
echo '</br>************************** Server Response createUser()**************************</br></br>';
echo $server_url . '</br></br>';
var_dump($resp);
}
Line 78 replace $curl(...) with new curl(..), your object instancing is incorrect. What is telling the php log is that you are using a variable as function name aka $curl (nothing to do with $functionName wich might have generated an error later with curl not on compile if it was wrong).
$resp = new curl($server_url . $rest_format, $params);

Categories