I am writing my telegram bot codes in PHP. I would like to split my inline keyboard into 2 or 3 columns. Here is my code:
foreach ($categories as $cat) {
$key[] = array(
array('text'=>$cat['name'],'callback_data'=>'sub-'.$cat['id'])
);
if ($k % 2 == 0) {
$keyoptions[] = $key;
$key = array();
}
$k++;
}
$telegram->SendMessage($userid, $keyoptions);
but my code doesn't work. Where is the problem and how can I solve my issue?
EDIT :
i just used this code
$keyoptions = array_chunk($keyoptions,3);
but still can't find the problem;
Telegram API: inline_keyboard: Array of Array of InlineKeyboardButton
Example:
keyboard: [
["uno :+1:"],["uno \ud83d\udc4d", "due"],["uno", "due","tre"]
]
I don't know what library you are using and what are those fields in your code, but this a working with native telegram API:
function inlineKeyboard($text, $chatID, $btnNames, $callBackDatas)
{
$inlineRow = array(); // this is array for each row of buttons
$i = 0;
foreach ($btnNames as $name) {
array_push($inlineRow, array("text" => $name, "callback_data" => $callBackDatas[$i]));
$i++;
}
/* if you need multiple rows then just create other inlineRow arrays
and push to this array below */
$inlineKeyboard = array($inlineRow);
$keyboard = array(
"inline_keyboard" => $inlineKeyboard
);
$postfields = array
(
'chat_id' => "$chatID",
'text' => $text,
'reply_markup' => json_encode($keyboard)
);
send('sendMessage', $postfields);
}
define('BaseURL', 'https://api.telegram.org/bot<TOKEN>');
function send($method, $datas)
{
$url = BaseURL . "/" . $method;
if (!$curld = curl_init()) {
exit;
}
curl_setopt($curld, CURLOPT_POST, true);
curl_setopt($curld, CURLOPT_POSTFIELDS, $datas);
curl_setopt($curld, CURLOPT_URL, $url);
curl_setopt($curld, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curld);
curl_close($curld);
return $output;
}
Related
SmartpaySPaymentRepository.php
i am new to laravel. i want to passe this value ($url->nodeValue) which is in the SmartpaySPaymentRepository.php sendPaymentToSmartpaySForPaymentToken function to SmartPaySController.php getQuotePayment($quoteId) function can someone help me to do this?
public function sendPaymentToSmartpaySForPaymentToken($xml, $authToken, $transactionId, $doPrepareUrl)
{
$fields = array(
'authToken' => $authToken,
'&requestXML' => $xml,
);
$fields_string = $xml;
foreach ($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init($doPrepareUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$response_from_smartpays = curl_exec($ch);
curl_close($ch);
$testString = $response_from_smartpays;//xml string
$dom = new \DOMDocument();
$dom->formatOutput = TRUE;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXml($testString);
$result = ($dom->getElementsByTagName('redirectURL'));
foreach ($result as $url){
return ($url->nodeValue);//want to passe this value to controller
}
}
SmartPaySController.php
public function getQuotePayment($quoteId)
{
$quote = $this->quoteRepo->getQuoteById($quoteId);
if($quote) {
$totalPrice = $quote->total_price;
if ($quote->amended_policy) {
$totalPrice = $quote->amend_price;
}
dd($url->nodeValue);//want to use $url->nodeValue here
$currency = CURRENCY_TYPE;
return $this->processSmartpaySPayment(PAYMENT_TYPE_QUOTE, $totalPrice, $currency, $quote->customer_id, $quoteId);
}else {
abort(404);
}
}
You can return them as an array in repository
$resultReturn = []
foreach ($result as $url){
$resultReturn[] = ($url->nodeValue);//want to passe this value to controller
}
return $resultReturn; // pass the array contiling all rsults in the loop
In the controller
$currency = CURRENCY_TYPE;
$results = $this->processSmartpaySPayment(PAYMENT_TYPE_QUOTE, $totalPrice, $currency, $quote->customer_id, $quoteId);
dd($results); //array of $url->nodeValue here
return $results;
From the Proxmox API, I am trying to get a list of nodes on which each VM is hosted in order to create the following array:
Array:
( [vm1] => node1 [vm2] => node2 [vm3] => node2 [vm4] => node2 )
My code:
<?php
$vmArray = array();
$multipleVmArray = array();
$nodeArray = array();
$multipleNodeArray = array();
if (empty($onlinenode)) {
echo "<br>All nodes are down.<br>";
}
else {
foreach ($servers as $server) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$onlinenode.'/api2/json/nodes/'.$server['node'].'/qemu');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $curlTimeOut);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Cookie: PVEAuthCookie=' .$cookie;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Node ' .$server['node']. ' is down (error : ' . curl_error($ch) . ').<br>';
}
else {
$arrays = json_decode($result, true);
$vmcount = count((array)$arrays['data']);
if ($vmcount == 0) {
echo 'Node ' .$server['node']. ' doesn\'t host vm.<br>';
}
else if ($vmcount == 1) {
array_push($vmArray,$arrays['data']['0']['name']);
array_push($nodeArray,$server['node']);
}
else {
$vmNames = array_column($arrays['data'], 'name');
array_push($multipleVmArray,$vmNames);
$nodeArrayFill = array_fill(0, $vmcount, $server['node']);
array_push($multipleNodeArray,$nodeArrayFill);
}
}
curl_close($ch);
}
}
$mergedVmArray = array_merge($vmArray,$multipleVmArray);
$mergedNodes = array_merge($nodeArray,$multipleNodeArray);
$combinedArrays = array_combine($mergedVmArray,$mergedNodes);
print_r($combinedArrays);
?>
But result is : Array ( [winxp] => pve1 [winxp4] => pve3 [Array] => Array ( [0] => pve2 [1] => pve2 ) )
(Pay no attention to the names of the VMs and nodes)
And I would like : Array ( [vm1] => node1 [vm2] => node2 [vm3] => node2 [vm4] => node2 )
I don't understand why the below code works but not when I implement on mine :
<?php
$vmArray = array();
$multipleVmArray = array();
$nodeArray = array();
$multipleNodeArray = array();
array_push($vmArray,"vm1");
array_push($multipleVmArray,"vm2", "vm3", "vm4");
array_push($nodeArray,"node1");
array_push($multipleNodeArray,"node2", "node2", "node2");
$mergedVmArray = array_merge($vmArray,$multipleVmArray);
$mergedNodes = array_merge($nodeArray,$multipleNodeArray);
$combinedArrays = array_combine($mergedVmArray,$mergedNodes);
print_r($combinedArrays);
?>
Any idea?
I have below code & I am generating tracking_id values manually & its working fine :
<?php
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => "1234",
];
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
Result :
{"response":[{"tracking_id":"1234",}],
Now i need to create tracking_id dynamically.... so i tried like below :
"tracking_id" => "$r = 'DOCC'. mt_rand(0000000001,9999999999); echo $r;",
I got below Result :
{"response":[{"tracking_id":" = 'DOCC'. mt_rand(0000000001,9999999999); echo ;","
But i should get some random number as tracking_id....
Means php code inside parameter is not working....
As your require 10 digit random number:
function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(1, 9);
}
return $result;
}
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'.randomNumber(10);//no need to echo, just assign it
];
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
Refactor your code:
$r = 'DOCC'. mt_rand(0000000001,9999999999);
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => $r,
];
Just replace $data array with the following.
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'. mt_rand(0000000001,9999999999),
];
I need to do a recursive loop on every result suggested by google up to a user-defined depth and save results in a multidimensional array, explored later on.
I want to get this result.
google
google app
google app store
google app store games
google app store games free
google maps
google maps directions
google maps directions driving
google maps directions driving canada
...
Currently, my recursive function returns replicated results from the second nesting.
google
google app
google app
google app store
google app store
google app
google app store
google app store
google app store
...
I think the problem comes from the array (parent results) that I pass as an argument to my function recursive_function() to each nested loops.
$child = recursive_function($parent[0][1], $depth, $inc+1);
Recursive function
// keywords at line or spaced
$keywords = explode("\n", trim("facebook"));
$result = recursive_function($keywords, 2);
function recursive_function($query, $depth, $inc = 1)
{
$urls = preg_filter('/^/', 'http://suggestqueries.google.com/complete/search?client=firefox&q=', array_map('urlencode', $query));
$parent = curl_multi_function($urls);
array_multisort($parent[0][1]);
if (count($parent[0][1]) === 0 || $inc >= $depth)
{
$out[] = $parent[0][1];
}
else
{
$child = recursive_function($parent[0][1], $depth, $inc+1);
$out[] = $child;
}
return $out;
}
Function curl
function curl_multi_function($data, $options = array())
{
// array of curl handles
$curly = array();
// data to be returned
$result = array();
// multi handle
$mh = curl_multi_init();
// loop through $data and create curl handles
// then add them to the multi-handle
foreach ($data as $id => $d)
{
$curly[$id] = curl_init();
$url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
curl_setopt($curly[$id], CURLOPT_URL, $url);
curl_setopt($curly[$id], CURLOPT_HEADER, 0);
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curly[$id], CURLOPT_SSL_VERIFYPEER, 0);
// post?
if (is_array($d))
{
if (!empty($d['post']))
{
curl_setopt($curly[$id], CURLOPT_POST, 1);
curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
}
}
// extra options?
if (!empty($options)) {
curl_setopt_array($curly[$id], $options);
}
curl_multi_add_handle($mh, $curly[$id]);
}
// execute the handles
$running = null;
do
{
curl_multi_exec($mh, $running);
}
while($running > 0);
// get content and remove handles
foreach($curly as $id => $c)
{
$result[$id] = curl_multi_getcontent($c);
// decode json result
$result[$id] = json_decode(utf8_encode($result[$id]));
curl_multi_remove_handle($mh, $c);
}
// all done
curl_multi_close($mh);
return $result;
}
Thank's
I've changed your recursive_function a little bit:
function recursive_function($query, $depth, $inc = 1)
{
$urls = preg_filter('/^/', 'http://suggestqueries.google.com/complete/search?client=firefox&q=', array_map('urlencode', $query));
$parent = curl_multi_function($urls);
foreach ($parent as $key => $value) {
array_multisort($value[1]);
$words = explode(' ', $value[0]);
$lastWord = end($words);
if (count($value[1]) === 0 || $inc >= $depth) {
$out[$lastWord] = [];
} else {
unset($value[1][0]);
$child = recursive_function($value[1], $depth, $inc+1);
$out[$lastWord] = $child;
}
}
return $out;
}
It generates an array like this:
[
google =>
[
app =>
[
store =>
[
games =>
[
free => []
]
]
]
...
]
]
Is that what you want?
I've been trying to get a PHP application to connect to Instapaper's Xauth services, but for the life of me I can't get it to work. I keep getting an "403: Invalid signature." error.
The error says that my signature base string wasn't what it expected, but when I compare the signature base string I construct with what they say they expect, they're exactly the same (sensitive information removed):
My signature base string:
POST&https%3A%2F%2Fwww.instapaper.com%2Fapi%2F1%2Foauth%2Faccess_token&oauth_callback%3DMy_URL%26oauth_consumer_key%3DCONSUMER_KEY%26oauth_nonce%3Dfe379af261aca07d890d2cfaa0f19ce0%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1461898452%26oauth_version%3D1.0%26x_auth_mode%3Dclient_auth%26x_auth_password%3DPASSWORD%26x_auth_username%3DEXAMPLE%2540gmail.com
What the error says it expects:
POST&https%3A%2F%2Fwww.instapaper.com%2Fapi%2F1%2Foauth%2Faccess_token&oauth_callback%3DMy_URL%26oauth_consumer_key%3DCONSUMER_KEY%26oauth_nonce%3Dfe379af261aca07d890d2cfaa0f19ce0%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1461898452%26oauth_version%3D1.0%26x_auth_mode%3Dclient_auth%26x_auth_password%3DPASSWORD%26x_auth_username%3DEXAMPLE%2540gmail.com
I pulled my php library from https://github.com/mheap/Instapaper-XAuth-PHP, but it's old so I've tried to modify it to work with the current Instapaper API. I believe I'm generating the signature string correctly and am following the instructions found here: https://dev.twitter.com/oauth/overview/creating-signatures and here: http://oauthbible.com/
I don't know what's wrong with the code, can someone please help?
class XAuth_Connection
{
private $_headers = array(
"oauth_signature_method" => "HMAC-SHA1",
"oauth_version" => "1.0",
"oauth_callback" => "MY_URL",
"oauth_consumer_key" => "",
"oauth_nonce" => "",
"oauth_timestamp" => ""
);
private $_params = array(
"x_auth_mode" => "client_auth",
"x_auth_username" => "",
"x_auth_password" => ""
);
private $_access_url = '';
public function __construct($key, $private, $access_url)
{
$this->_headers['oauth_consumer_key'] = $key;
$this->_headers['oauth_nonce'] = md5(uniqid(rand(), true));
$this->_headers['oauth_timestamp'] = time();
$this->_oauth_consumer_private = $private;
$this->_access_url = $access_url;
}
public function set_credentials($user, $password)
{
$this->_params['x_auth_username'] = $user;
$this->_params['x_auth_password'] = $password;
}
public function get_params_as_string()
{
ksort($this->_params);
$req = array();
foreach ($this->_params as $k => $v)
{
$req[] = $k ."=". $this->encode($v);
}
return implode("&", $req);
}
public function get_headers_as_string()
{
ksort($this->_headers);
$req = array();
foreach ($this->_headers as $k => $v)
{
$req[] = $k . "=" . $this->encode($v);
}
return implode("&", $req);
}
public function generate_signature()
{
//combine the parameters, encode, and sort them
$temp_params = array_merge($this->_params, $this->_headers);
$encoded_params = Array();
foreach($temp_params as $k => $v){
$encoded_params[$this->encode($k)] = $this->encode($v);
}
ksort($encoded_params);
//Build the param string
$param_base_string = "";
foreach($encoded_params as $k => $v){
$param_base_string .= $k .'='. $v . '&';
}
$param_base_string = rtrim($param_base_string, '&');
//create the signature base
$signature_base = 'POST&' . $this->encode($this->_access_url) .'&'. $this->encode($param_base_string);
$key = $this->encode($this->_oauth_consumer_private) . '&';
return base64_encode(hash_hmac("sha1",$signature_base, $key, true));
}
public function login()
{
$this->_headers['oauth_signature'] = $this->generate_signature();
ksort($this->_headers);
$header_str = 'OAuth ';
foreach ($this->_headers as $k => $v)
{
$header_str .= $k.'="'.$this->encode($v).'", ';
}
$header_str = rtrim($header_str, ', ');
$oauth_str = $this->get_params_as_string();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_access_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $oauth_str);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: " . $header_str));
$exec = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200)
{
return false;
}
parse_str($exec, $r);
return $r;
}
private function encode($s)
{
return ($s === false ? $s : str_replace('%7E','~',rawurlencode($s)));
}
}