ReplyMarkup in php telegram bot - telegram

I have problem with my telegram bot.I want to make Keybaord for my bot. When I run my telegram api url from my browser it works:
https://api.telegram.org/mybottoken/sendmessage?chat_id=93119306&text=something&reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]], "one_time_keyboard":true};
but
When I want run to this url($sendto Variable) in my php file this not work.
my php code is:
<?php
define('BOT_TOKEN', '183690241:AAHgluc7D9g0DF_InurfBj2YdBgPE7fmymo');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
$array = array();
// read incoming info and grab the chatID
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$chatText = $update["message"]["text"];
// compose reply
$reply = sendMessage();
// send reply
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply."&reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]], "one_time_keyboard":true};
file_get_contents($sendto);
function sendMessage(){
global $chatID;
global $chatText;
if ($chatText =="/start") {
$message = "Salam - Roboate Megat Hastam";
}
elseif ($chatText =="Khoobi?") {
$message = "Merc - Shomaa khobi?";
}
elseif ($chatText =="Chand salete?") {
$message = "Be Tu Che!";
}
else
{
$message = "No Command";
}
return rawurlencode($message);
}
?>
please help where i made mistake.
thanks all guys.

Try this code:
var_dump($keyboard = json_encode($keyboard = [
'keyboard' => [
['Yes'],['No'],['Maybe'],
['1'],['2'],['3'],
] ,
'resize_keyboard' => true,
'one_time_keyboard' => true,
'selective' => true
]),true);
function sendKeyboard($chat_id, $keyboard) {
$text = "Merc - Shomaa khobi?";
file_get_contents(API_URL ."sendMessage?chat_id=".$chat_id."&reply_markup=".$keyboard."&text=".urlencode($text));
}
if($message == "/start"){
sendKeyboard($chat_id, $keyboard);
}

Related

dynamically populated cascading dropdown error

I found very useful article on the web
for contact form 7
<?php
function ajax_cf7_populate_values() {
// read the CSV file in the $makes_models_years array
$makes_models_years = array();
$uploads_folder = wp_upload_dir()['basedir'];
$file = fopen($uploads_folder.'\make_model_year.csv', 'r');
$firstline = true;
while (($line = fgetcsv($file)) !== FALSE) {
if ($firstline) {
$firstline = false;
continue;
}
$makes_models_years[$line[0]][$line[1]][] = $line[2];
}
fclose($file);
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'makes' => array_keys($makes_models_years),
'models' => array(),
'years' => array(),
'current_make' => false,
'current_model' => false
);
// collect the posted values from the submitted form
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
$year = key_exists('year', $_POST) ? $_POST['year'] : false;
// populate the $return_array with the necessary values
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = array_keys($makes_models_years[$make]);
if ($model) {
$return_array['current_model'] = $model;
$return_array['years'] = $makes_models_years[$make][$model];
if ($year) {
$return_array['current_year'] = $year;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
}
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
and some java
<script>
(function($) {
// create references to the 3 dropdown fields for later use.
var $makes_dd = $('[name="makes"]');
var $models_dd = $('[name="models"]');
var $years_dd = $('[name="years"]');
// run the populate_fields function, and additionally run it every time a value changes
populate_fields();
$('select').change(function() {
populate_fields();
});
function populate_fields() {
var data = {
// action needs to match the action hook part after wp_ajax_nopriv_ and wp_ajax_ in the server side script.
'action' : 'cf7_populate_values',
// pass all the currently selected values to the server side script.
'make' : $makes_dd.val(),
'model' : $models_dd.val(),
'year' : $years_dd.val()
};
// call the server side script, and on completion, update all dropdown lists with the received values.
$.post('/wp-admin/admin-ajax.php', data, function(response) {
all_values = response;
$makes_dd.html('').append($('<option>').text(' -- choose make -- '));
$models_dd.html('').append($('<option>').text(' -- choose model -- '));
$years_dd.html('').append($('<option>').text(' -- choose year -- '));
$.each(all_values.makes, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_make == this) {
$option.attr('selected','selected');
}
$makes_dd.append($option);
});
$.each(all_values.models, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_model == this) {
$option.attr('selected','selected');
}
$models_dd.append($option);
});
$.each(all_values.years, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_year == this) {
$option.attr('selected','selected');
}
$years_dd.append($option);
});
},'json');
}
})( jQuery );
</script>
but when i add it to me website nothing appear in the dropdowns. They are empty.
I tried to contact the blogger but there is no answer yet. Give me some advice
I copied the csv almost as the one in the post. So I think the function is mistaken... somewhere
I found the solution: in the article the file name is mistaken. It has to be "make_model_year.csv" !!!

wordpress wp_mail throws error: could not instantiate mail function

I have two forms in my website. Both were working fine. but suddenly now they are not working. Emails are not going from both the forms.
// This function gets called when user clicks on submit button
<script type="text/javascript">
var $ = jQuery;
function sendMessage(){
var name = $('[name="name"]').val();
var email = $('[name="email"]').val();
var phone = $('[name="phone"]').val();
var message = $('[name="message"]').val();
var filter = /^[7-9][0-9]{9}$/;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(name == '')
{
$('.name-error').show();
}
else
{
$('.name-error').hide();
}
if(email == '')
{
$('.email-error').show();
}
else
{
$('.email-error').hide();
}
if(phone == '')
{
$('.phone-error').show();
}
else
{
$('.phone-error').hide();
}
if(message == '')
{
$('.message-error').show();
}
else
{
$('.message-error').hide();
}
if(name != '' && email != '' && phone != '' && message != ''){
if(emailReg.test(email)){
if(filter.test(phone)){
var data = {
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
action: 'send_mails',
formdata: $("#contact").serialize()
};
var myRequest = jQuery.post(data.url, data, function(response){
console.log(response)
});
myRequest.done(function(){
$('#msg').html("<p class='msg' style='background-color:#dff0d8; border-color: #d6e9c6; color:#3c763d; padding:10px; border-radius:4px;'>The Email has been sent successfully!</p>").fadeIn('slow');
$('#msg').delay(5000).fadeOut('slow');
});
$("#contact").trigger("reset");
$('#msg').html("<p class='msg' style='background-color:#dff0d8; border-color: #d6e9c6; color:#3c763d; padding:10px; border-radius:4px;'>The Email has been sent successfully!</p>").fadeIn('slow');
$('#msg').delay(5000).fadeOut('slow');
}
else
{
alert("Provide valid mobile number");
}
}
else
{
alert("Provide valid Email Id");
}
}
else
{
// alert("Kindly enter all the details");
return false;
}
}
</script>
This is function from functions.php file.
function send_mails()
{
$formData = $_POST['formdata'];
$data = array();
parse_str($formData, $data);
$name = $data['name'];
$email = $data['email'];
$phone = $data['phone'];
$message = $data['message'];
$msg = "A new enquiry has been posted on the website\n";
$msg.= "Name: ".$name."\n";
$msg.= "Email: ".$email."\n";
$msg.= "Phone: ".$phone."\n";
$msg.= "Message: ".$message."\n";
$headers = array('Content-Type: text/html; charset=UTF-8');
//echo $msg;
$admin_email = get_option( 'admin_email' );
// print_r($admin_email);
$res = wp_mail('email',"Enquiry",$msg,$headers);
if($res)
{
echo "Mail has been sent";
}
else
{
echo "Could not send mail";
debug_wpmail($res);
}
die();
}
add_action('wp_ajax_send_mails', 'send_mails');
add_action('wp_ajax_nopriv_send_mails', 'send_mails');
debug_wpmail returns the error "Could not instantiate mail function". I did not find anything on google.
if ( ! function_exists('debug_wpmail') ) :
function debug_wpmail( $result = false ) {
if ( $result )
return;
global $ts_mail_errors, $phpmailer;
if ( ! isset($ts_mail_errors) )
$ts_mail_errors = array();
if ( isset($phpmailer) )
$ts_mail_errors[] = $phpmailer->ErrorInfo;
print_r('<pre>');
print_r($ts_mail_errors);
print_r('</pre>');
}
endif;
Can you modify this part :
From
$res = wp_mail('email',"Enquiry",$msg,$headers);
To
$res = wp_mail($admin_email,'Enquiry',$msg,$headers);
This happens due to your site haven't been configured with email service provider like Google/SendGrid or SMTP Or It just goes removed. Example configuration can be found below:

Upload image/video to facebook asynchronously using php sdk 4

I am trying to upload video/image to facebook albumb using php sdk 4 asynchronously.I googled and found that php asynchronous call be sent using fsockopen. However, it is not working for facebook request. I have two files, one for checking login and getting token. Then second file is called for uploading the file to facebook. Below is the code for first file:
// start session
session_start();
Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// init app with app id and secret
FacebookSession::setDefaultApplication('xxxxx', 'yyyy');
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://website.com/user/login/page/view/fb-share-php1' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
}catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb'] = $session;
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
//$session = new FacebookSession( $session->getToken() );
// graph api request for user data
//$request = new FacebookRequest( $session, 'GET', '/me' );
//$response = $request->execute();
backgroundPost('http://website.com/user/login/page/view/fb-share-php');
// get response
//$graphObject = $response->getGraphObject()->asArray();
// print profile data
//echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
}else {
// show login url
echo 'Login';
}
function backgroundPost($url){
$parts=parse_url($url);
//print_r($parts);exit;
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
echo "test";
return false;
} else {
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ". 0 ."\r\n";
$out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
// print_r($out);exit;
fwrite($fp, $out);
fclose($fp);
return true;
}
}
And second file is:
// start session
session_start();
Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
$session = $_SESSION['fb'] ;
file_put_contents('file.txt', serialize($session));
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'source' => '#/var/www/website-root/images/add_more.png',
'message' => 'User provided message'
)
))->execute()->getGraphObject();
file_put_contents('files.txt', serialize($session));
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
Finally, I figured out the way to achieve it. Now, I am using facebook javascript sdk with php sdk. Following is the process:
1)Get access token from javascript sdk(first file) and pass it to background along with the url of image/video. Code may be modified, if image/video is being uploaded through source.
2) php file(2nd file) containing function for executing backend-process(which is in third file) receives the posted data and and call the third file(in the form of url) and pass the data to it as well.
3) File(s) are uploaded to facebook through php sdk 4(third file)
Below is the code for first file containing javascript sdk code:
<script>
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function() {
FB.init({
appId : 'your app id',
xfbml : true,
version : 'v2.0'
});
FB.login(function(response){
console.log(response);
if (response.status === 'connected') {
var data = new Array();
alert('Logged into your app and Facebook.');
//type: 0 for photo and type:1 for video. Create data array dynamically for real word applications
data[0]= {url: 'http://url-of-video-file.mov',privacy : 'SELF', message: "title of video", type:1};
data[1]= {url: 'http://url-to-image-file.png',privacy : 'SELF', message: "photo caption", type:0};
$.ajax({
url: 'http://url-of-second-file/containing-code-for/backend-process',
data: {data: data, accessToken:response.authResponse.accessToken},
type: 'POST',
success:function(){
alert("photo uploaded");
}
});
},{scope:'email'});
}
</script>
Now code of second file which receives data and execute back-end process:
<?php
//session_start();
ignore_user_abort(true);
set_time_limit(0);
function backgroundPost($url){
$parts=parse_url($url);
//print_r($parts);exit;
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
echo "test";
return false;
} else {
$vars = $_POST;
$content = http_build_query($vars);
//file_put_contents('url.txt',$content);exit;
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ". strlen($content) ."\r\n";
//$out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
// print_r($out);exit;
fwrite($fp, $out);
fwrite($fp,$content);
fclose($fp);
return true;
}
}
backgroundPost('http://link-to-third-file/containing-code-for-facebook-upload');
Now code of third file, which will actually upload the files. Please note, video files need to be downloaded before it can be uploaded.
<?php
// start session
//session_start();
error_reporting(1);
ignore_user_abort(true);
set_time_limit(0);
#ini_set('display_errors', 1);
//include facebook library through autoload
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// init app with app id and secret
FacebookSession::setDefaultApplication('app_id','secret_key' );
$session = new FacebookSession( $_POST['accessToken'] );
foreach($_POST['data'] as $key => $data){
if($data['type'] == 1){
$ext = substr($data['url'],strrpos($data['url'],'.'));
$file = '/path/to/temp/location/for/saving/video/'.time().$ext;
if(file_put_contents($file,file_get_contents($data['url']))){
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/videos', array(
'source' => '#'.$file,
'title' => $data['message'],
'privacy' => json_encode(array('value' => $data['privacy'])),
'published' => true
)
))->execute()->getGraphObject()->asArray();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}else{
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'url' => $data['url'],
'message' => $data['message'],
'privacy' => json_encode(array('value' => $data['privacy'])),
'published' => true
)
))->execute()->getGraphObject()->asArray();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}
?>

can I stop all email sending from a wordpress site ?where to do this wp-includes/class-phpmailer.php?

howto close all email sending option in that word press config. should i use
wp-includes/class-phpmailer.php ? or where ?
if ($this->SingleTo === true && count($toArr) > 1) {
foreach ($toArr as $key => $val) {
$rt = #mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
// implement call back function if it exists
$isSent = ($rt == 1) ? 1 : 0;
$this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
}
}
will this do ?
Add the following code to wp-config.php, it will stop sending of all emails
function wp_mail()
{
//silence is golden!!
}

I can push notification to one device but fail to push in a loop

I code my push notification service as shown below. It will gain token stored in test_db and then send it. The problem is that I don't receive notification from all my device. But, if I send notification to one specific device and I uncomment **//if( $row['pushtoken']=='bfd53a383e0f65bc96b43f3547548ec13d4c46d61526d7b6be5d7ed581563e77')**, the device will receive a notification. It is very weird. Here is my code:
$link = mysql_connect('localhost', 'root', '111111');
if (!$link) {
error_log( "mysql_connect fail\n");
die('could not connect: ' . mysql_error());
}
else
{
$is_db_selected = mysql_select_db('test_db',$link);
if($is_db_selected)
{
$sql = "select * from pushtoken;";
error_log($sql);
$result = mysql_query($sql, $link);
if ($result)
{
echo "ready to push notification\n";
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'aps_dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 10, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT , $streamContext);
if (!$apns)
exit("Failed to connect: $error $errorString" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
ob_flush();
flush();
$payload['aps'] = array('alert' => 'xman give mortal 7 messages!!!', 'badge' => 1, 'sound' => 'default');
$payload = json_encode($payload);
while ($row = mysql_fetch_assoc($result))
{
***//if( $row['pushtoken']=='bfd53a383e0f65bc96b43f3547548ec13d4c46d61526d7b6be5d7ed581563e77')***
{
echo "push notification one by one\n";
$deviceToken = $row['pushtoken'];
$apnsMessage = chr(0) . pack("n", 32) . pack('H*', $deviceToken) .pack("n", strlen($payload)). $payload;
if(fwrite($apns, $apnsMessage,strlen($apnsMessage))==FALSE)
{
echo "can't write to socket!<br />";
}
ob_flush();
flush();
//fclose($apns);
echo "token is ".$deviceToken ."\n";
//break;
}
}
//socket_close($apns);
fclose($apns);
} else {
error_log ('error select pushtoken: ' . mysql_error() . "\n");
}
}
}
You may want to check that all of the tokens are valid. In the past I had an issue where if I had a dev token in my DB and tried to use the production push server all the messages that were sent after the message using the dev token would fail to be delivered.

Resources