PHP Telegram Bot (editMessageText & editReplyMarkup) - php

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)

Related

Simple Telegram Bot but it doesn't respond to commands (PHP)

I'm fairly new to all of this, but I have created a simple telegram bot to test their functionality. I have set the webhook and I'm using ngrok for the "host". However when I type a command the bot just doesn't do anything.
Does anyone know how to fix this?
Here is the index.php file:
<?php
require('token.php');
require('config.php');
try{
$ngrokUrl = "ngrok url";
$bot = new TelegramBot($token);
$jH = new jsonHandler($token);
var_dump($bot->setWebhook($ngrokUrl));
$webhookJson = $jH->getWebhookJson();
$chatId = $jH->getChatId($webhookJson);
$msg = $jH->getText($webhookJson) !== "" ? $jH->getText($webhookJson) : "";
switch($msg){
default:{
if ($msg[0] == '/')
$bot->sendMessage($chatId, 'The command does not exist');
break;
}
case '/test':{
$msg = 'test test';
$bot->sendMessage($chatId, $msg);
break;
}
case '/help':{
$msg = 'Help!';
$bot->sendMessage($chatId, $msg);
break;
}
}
}catch(ErrorException $e){
echo $e->getMessage();
}
?>
And the config.php file:
<?php
function fetchApi($url){
$req = curl_init($url);
$resp = curl_exec($req);
if($resp == false){
$error = curl_error($req);
curl_close($req);
throw new ErrorException($error);
}
else{
curl_close($req);
//return $resp;
}
}
class TelegramBot{
protected $tUrl;
function __construct($token){
$this->tUrl = "https://api.telegram.org/bot".$token;
}
function setUrl($method){
return $this->tUrl."/".$method;
}
function sendMessage($chatId, $msg){
$data = [
'chat_id' => $chatId,
'&text' => $msg
];
$url = $this->setUrl("sendMessage?".http_build_query($data));
fetchApi($url);
file_get_contents($url);
}
class jsonHandler extends TelegramBot{
function getWebhookJson(){
$json = file_get_contents("php://input");
return json_decode($json, true);
}
function getChatId($jsonDecoded){
return $jsonDecoded["message"]["chat"]["id"];
}
function getText($jsonDecoded){
return $jsonDecoded["message"]["text"];
}
}
?>

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

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()

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

How to format output data from PHP form in separate text file?

I've created a PHP form that outputs the form data entries into a separate text file. The problem with the output is that it's plain text with no line breaks or spaces between entries. I would like to know how I can format the output data so that it is more legible (possibly using a table or just simple line breaks).
I asked my professor for a solution and he referred me to this page. I'm sure this is what I am looking for but I have trouble forming it for my needs. What do I need to change from the code on that page in order for it to work for me? I've tried adding and subtracting code but that resulted in syntax errors.
Here's the PHP form code:
<?php
// define variables and set to empty values
$nameErr = '';
$emailErr = '';
$commentErr = '';
$likesErr = '';
$howErr = '';
$rateErr = '';
$name = '';
$email = '';
$comment = '';
$likes = '';
$how = '';
$rate = '';
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
if (empty($_POST["comment"])) {
$commentErr = "Comments are required";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["likes"])) {
$likesErr = "Things you liked is required";
} else {
$likes = test_input($_POST["likes"]);
}
if (empty($_POST["how"])) {
$howErr = "How you got to our site is required";
} else {
$how = test_input($_POST["how"]);
}
if (empty($_POST["rate"])) {
$rateErr = "Rating our site is required";
} else {
$rate = test_input($_POST["rate"]);
}
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function file_write($data, $feedback){
if(is_string($data)){
return file_put_contents($feedback, $data, FILE_APPEND | LOCK_EX);//this appends the new data to the file and locks it while doing so to prevent multiple access to thje file at the same time.
}//return an error message if the data isnt a string
}
$data = $name.$email.$comment.$likes.$how.$rate.
'';
file_write($data, 'feedback.php')
?>
EDIT 1:
This is the section that I believe is causing the issues since there are two file_write:
function file_write($data, $feedback){
if(is_string($data)){
return file_put_contents($feedback, $data, FILE_APPEND | LOCK_EX);
}//return an error message if the data isnt a string
}
$data = $name.PHP_EOL.$email.PHP_EOL.$comment.PHP_EOL.$likes.PHP_EOL.$how.PHP_EOL.$rate.‌PHP_EOL.
file_write($data, 'feedback.php');
For the sake of this answer, I am assuming that file_write is a function that you've included somewhere. AFAIK file_write isn't a standard PHP function for writing to a file.
Your data is written to the file as a single line with no spaces because you haven't specified any spaces or line breaks.
If you want line breaks in-between each of the fields, do the following:
$data = $name.PHP_EOL.$email.PHP_EOL.$comment.PHP_EOL.$likes.PHP_EOL.$how.PHP_EOL.$rate;
file_write($data, 'feedback.php');
It is best to use PHP_EOL for adding line breaks. It is cross-platform -- PHP will automatically choose the correct newline character(s) for whichever platform your code is running on.
Try "\n" or you can also try "\r\n"
So you can following this code:
function file_write($data, $feedback){
if(is_string($data)){
return file_put_contents($feedback, $data.'\n\n', FILE_APPEND | LOCK_EX);
}//return an error message if the data isnt a string
}
$data = $name.'\n'.$email.'\n'.$comment.'\n'.$likes.'\n'.$how.'\n'.$rate;
first comment. Keep the FILE_APPEND flag as it will keep an on-going storage.
Second. In the future, if you want to analyze your data having it separated with newlines will be a pain to parse. I suggest exporting comma delimited with newlines only for new entries. You can then easily parse or import (as a csv) into Excel.
$data = $name.','.$email.','.$comment.','.$likes.','.$how.','.$rate.PHP_EOL;
file_write($data, 'feedback.php');
However, you may run into an issue where somebody puts a comma in your web form. How do you account for that? You could enclose each item in the row with quotes. You can do that one yourself! good luck.
You can use the PHP_EOL constant so that line endings appropriate to the server will be output, in which case your code would look like
$data = $_POST['name'] . PHP_EOL;
$data .= $_POST['email'] . PHP_EOL;
$data .= $_POST['comment'] . PHP_EOL;
$data .= $_POST['likes'] . PHP_EOL;
$data .= $_POST['how'] . PHP_EOL;
$data .= $_POST['rate'] . PHP_EOL;
OR try this one
$data = $_POST['name'] . "\r\n";
IF this not helps you try this as well
$data = sprintf("%s\n%s\n%s\n",$_POST['name'],$_POST['email'], $_POST['comment'],$_POST['how'],$_POST['rate']);
file_put_contents($file, $data, FILE_APPEND);
You may try this :
<?php
// define variables and set to empty values
$nameErr = '';
$emailErr = '';
$commentErr = '';
$likesErr = '';
$howErr = '';
$rateErr = '';
$name = '';
$email = '';
$comment = '';
$likes = '';
$how = '';
$rate = '';
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
if (empty($_POST["comment"])) {
$commentErr = "Comments are required";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["likes"])) {
$likesErr = "Things you liked is required";
} else {
$likes = test_input($_POST["likes"]);
}
if (empty($_POST["how"])) {
$howErr = "How you got to our site is required";
} else {
$how = test_input($_POST["how"]);
}
if (empty($_POST["rate"])) {
$rateErr = "Rating our site is required";
} else {
$rate = test_input($_POST["rate"]);
}
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function file_write($data, $feedback){
if(is_string($data)){
return file_put_contents($feedback, $data, FILE_APPEND | LOCK_EX);//this appends the new data to the file and locks it while doing so to prevent multiple access to thje file at the same time.
}//return an error message if the data isnt a string
}
$data = $name.PHP_EOL;
$data .= $email.PHP_EOL;
$data .= $comment.PHP_EOL;
$data .= $likes.PHP_EOL;
$data .= $how.PHP_EOL;
$data .= $rate.PHP_EOL;
file_write($data, 'feedback.php')
?>
Hope any of this help you

CakePHP- Accessing mail using IMAP

Re-visiting this problem specified in my previous question, I tried and tried, also with different accounts (I tried gmail, as well as outlook), but the problem still persists. The error I get is the following if I try to access my google account
Error: Unable to get imap_thread after 4 retries. 'Can't open mailbox {imap.gmail.com:993/ssl/imap/tls/novalidate-cert}INBOX: invalid remote specification'
if I try accessing email on my outlook account, the error is the same :
Error: Unable to get imap_thread after 4 retries. 'Can't open mailbox {outlook.office365.com:993/ssl/imap/tls/novalidate-cert}INBOX: invalid remote specification'
My setup is as follows :
public $emailTicket = array(
'datasource' => 'ImapSource',
'server' => 'outlook.office365.com',
'connect' => 'imap/tls/novalidate-cert',
'username' => 'my email here',
'password' => 'my password here',
'port' => '993', //incoming port
'ssl' => true,
'encoding' => 'UTF-8',
'error_handler' => 'php',
'auto_mark_as' => array(
'Seen',
// 'Answered',
// 'Flagged',
// 'Deleted',
// 'Draft',
),
);
I am working on a local machine, does anyone know if this might be the problem or not? Has anyone ever tried this and worked for him/her? I am open to all input!
I can't seem to find what's wrong here, I've been at this for about 2days now, so if anyone can help, I appreciate it!
Also here's the link for the plugin i'm using, by Nicolas Ramy..
You can use the following implemented code to fulfill your requirements:
public function generate_email_response_pdf()
{
$this->layout = false;
$this->autoRender = false;
$username = EMP_SMTP_MAIL_FROM;
$password = EMP_SMTP_MAIL_PASSWORD;
$imap = imap_open('{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX', $username, $password);
$emails = imap_search($imap, 'ALL');
if(!empty($emails))
{
//put the newest emails on top
rsort($emails);
foreach($emails as $email_number)
{
$flag = 0;
$mail_data = array();
$file_name = array();
$output = array();
$savefilename = null;
$filename = null;
$overview = imap_fetch_overview($imap, $email_number, 0);
//initialize the subject index with -000, considering not receving this will not be received in
//subject line of email
$output['subject'] = '-000x';
if(isset($overview[0] -> subject))
{
$output['subject'] = $overview[0] -> subject;
}
$structure = imap_fetchstructure($imap, $email_number);
if(property_exists($structure, 'parts'))
{
$flag = 1;
$flattened_parts = $this->flatten_parts($structure->parts);
foreach($flattened_parts as $part_number => $part)
{
switch($part->type)
{
case 0:
//the HTML or plain text part of the email
if((isset($part->subtype)=='HTML')&&(isset($part->disposition)=='ATTACHMENT'))
{
$part_number = 1.2;
}
else if(isset($part->subtype)=='HTML')
{
$part_number = $part_number;
}
else
{
$part_number = $part_number;
}
$message = $this->get_part($imap, $email_number, $part_number, $part->encoding);
//now do something with the message, e.g. render it
break;
case 1:
// multi-part headers, can ignore
break;
case 2:
// attached message headers, can ignore
break;
case 3: // application
case 4: // audio
case 5: // image
case 6: // video
case 7: // other
break;
}
if(isset($part->disposition))
{
$filename = $this->get_filename_from_part($part);
if($filename)
{
// it's an attachment
$attachment = $this->get_part($imap, $email_number, $part_number, $part->encoding);
$file_info = pathinfo($filename);
$savefilename = RESPONSE_ATTACHMENT_PREFIX.$file_info['filename'].'_'.$this->_getRandId(4).'.'.$file_info['extension'];
$file_name[] = $savefilename;
$attachment_file_name = $this->save_attachment($attachment, $savefilename, $directory_path);
//imap_fetchbody($imap, $email_number, 2); //This marks message as read
}
else
{
// don't know what it is
}
}
}
}
else
{
$encoding = $structure->encoding;
$message = imap_fetchbody($imap, $email_number, 1.2);
//echo $message; die;
if($message == "")
{
$message = imap_body($imap, $email_number);
if($encoding == 3)
{
$message = base64_decode($message);
}
else if($encoding == 4)
{
$message = quoted_printable_decode($message);
}
}
}
$header = imap_headerinfo($imap, $email_number);
$from_email = $header->from[0]->mailbox."#".$header->from[0]->host;
$to_email = $header->to[0]->mailbox."#".$header->to[0]->host;
$reply_to_email = $header->reply_to[0]->mailbox."#".$header->reply_to[0]->host;
$cc_email = array();
if(isset($header->cc))
{
foreach($header->cc as $ccmail)
{
$cc_email[] = $ccmail->mailbox.'#'.$ccmail->host;
}
$cc_email = implode(", ", $cc_email);
}
$output['to'] = $to_email;
$output['from'] = $from_email;
$output['reply_to'] = $reply_to_email;
$output['cc'] = $cc_email;
$formatted_date = date('D, d M Y h:i A', strtotime($overview[0] -> date));
$output['date'] = $formatted_date;
$output['message'] = $message;
$output['flag'] = $flag;
$mail_data['Attachment'] = $file_name;
$mail_data['Data'] = $output;
$this->set('response_data', $mail_data);
$mail_content = null;
if(!empty($mail_data))
{
$this->viewPath = 'Elements/default';
$mail_content = $this->render('pdf_content');
}
$header = null;
$footer = null;
$html = preg_replace(array('/[^\r\n\t\x20-\x7E\xA0-\xFF]*/'), '', $mail_content);
$pdfFile = $this->_generateWkPdf($html, $directory_path, $new_file_name, $header, $footer);
$image_type = EXT_JPG;
$response_files_array = $this->_generateImagesFromPdf($directory_path.$pdfFile, $directory_path, $new_file_name, $image_type);
}
}
imap_close($imap);
}

Categories