I try to made a telegram bot, but I've a problem when I send a photo.
This is my code:
I have this function:
function apiRequestImage($method, $parameters)
{
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
foreach ($parameters as $key => &$val) {
// encoding to JSON array parameters, for example reply_markup
if (!is_numeric($val) && !is_string($val)) {
$val = json_encode($val);
}
}
$urlpath = API_URL.$method.'?'.http_build_query($parameters);
$handle = curl_init($urlpath);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
}
and this to call it
function processMessage($message) {
// process incoming message
$message_id = $message['message_id'];
$chat_id = $message['chat']['id'];
$img = curl_file_create('test.png','image/png');
if (isset($message['text'])) {
// incoming text message
$text = $message['text'];
if (strpos($text, "/start") === 0) {
apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array(
'keyboard' => array(array('Hello', 'Hi','Bye')),
'one_time_keyboard' => true,
'resize_keyboard' => true)));
} else if ($text === "Hello" || $text === "Hi") {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you'));
} else if ($text === "Bye") {
apiRequestImage("sendPhoto", array('chat_id' => $chat_id, 'photo' => '#'.$img));
}else if (strpos($text, "/stop") === 0) {
// stop now
} else {
apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => 'Cool'));
}
} else {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'I understand only text messages'));
}
}
and call all
if (isset($update["message"])) {
processMessage($update["message"]);
}
The text run, but the photo no.
Can you help me?
The rest of code: http://pastebin.com/BKPxe2KC
Your code has multiple parts. I recommend that test part by part,
For example, your function has keyboard part and it seems not working(bad Telegram syntax), and it can prevent other parts(like photo sending). In my opinion it is better you first work on just on thing(for example sending photo) and when it did its job best then go on and add keyboard.(This is a working keyboard code https://stackoverflow.com/a/37948952/6478645.
Related
I have this php script:
<?php
class Curl_Class {
private $endpointUrl;
private $userName;
private $userKey;
public $token;
public $errorMsg = '';
private $defaults = array(
CURLOPT_HEADER => 0,
CURLOPT_HTTPHEADER => array('Expect:'),
// CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0
);
//constructor saves the values
function __construct($url, $name, $key) {
$this->endpointUrl=$url;
$this->userName=$name;
$this->userKey=$key;
$this->token=$key;
}
private function getChallenge() {
$curl_handler = curl_init();
$params = array("operation" => "getchallenge", "username" => $this->userName);
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "getChallenge failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$challengeToken = $jsonResponse["result"]["token"];
return $challengeToken;
}
function login() {
$curl_handler = curl_init();
$token = $this->getChallenge();
//create md5 string containing user access key from my preference menu
//and the challenge token obtained from get challenge result
$generatedKey = md5($token.$this->userKey);
$params = array("operation" => "login", "username" => $this->userName, "accessKey" => $generatedKey);
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "Login failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$sessionId = $jsonResponse["result"]["sessionName"];
//save session id
$this->token=$sessionId;
return true;
}
private function handleReturn($result, $name, $curl_handler) {
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if (!$jsonResponse) {
$this->errorMsg = "$name failed: ".$result."<br>";
return false;
}
if($jsonResponse["success"]==false) {
$this->errorMsg = "$name failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
return $jsonResponse["result"];
}
public function operation($name, $params, $type = "GET", $filepath = '') {
$params = array_merge(array("operation" => $name, "sessionName" => $this->token), $params);
if (strtolower($type) == "post") {
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
}
else {
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
}
if ($filepath != '' && strtolower($type) == "post") {
$element = $params['element'];
if (!empty($element)) {
$element = json_decode($element, true);
}
if (isset($element['filename'])) {
$filename = $element['filename'];
}
else {
$filename = pathinfo($filepath, PATHINFO_BASENAME);
}
$size = filesize($filepath);
$add_options = array(CURLOPT_HTTPHEADER => array("Content-Type: multipart/form-data"), CURLOPT_INFILESIZE => $size);
if (function_exists("mime_content_type")) {
$type = mime_content_type($filepath);
}
elseif (isset($element['filetype'])) {
$type = $element['filetype'];
}
else {
$type = '';
}
if (!function_exists('curl_file_create')) {
$add_params = array("filename" => "#$filepath;type=$type;filename=$filename");
}
else {
$cfile = curl_file_create($filepath, $type, $filename);
$add_params = array('filename' => $cfile);
}
$options += $add_options;
$options[CURLOPT_POSTFIELDS] = $params + $add_params;
}
$curl_handler = curl_init();
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
return $this->handleReturn($result, $name, $curl_handler);
}
}
?>
I'm learning programming so i'm in no way good at this.. I need to execute the function login() of this class from a url, giving in input the parameters (private $endpointUrl,private $userName,private $userKey) and receiving in output the $sessionId.
So, for example, i'll write in the url
https://webserver.com/Login.php? endpointUrl=1&username=2&userKey=3
and receiving in output the $sessionId.
Is it possible? How? Thanks!
Here's some example;
if(isset($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"])){
$x = new Curl_Class($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"]);
if($x->login()){
echo $x->token;
}
}
Better if serialize the GET input for security purposes. But in this example, just a simple call of login.
Since the login() method returning boolean, so from there we can know if the token created or not.
I am trying to save images from dropbox to my server. I have already done the code for that. I am also checking the HTTP status of the url before downloading the images with code. I am getting proper status but the issue is it always throws an error 401 even when i have put a condition to download images with status code 200 or 302. I am having the links of images in an excel file that i am reading with a laravel package. Please help me.
Image Download Function
public function ImportImagesProcess(Request $request)
{
$product_type = $request->get('product_type');
$category_id = $request->get('category_id');
$category_level = $request->get('category_level');
$filepath = $request->get('file_path');
$total_rows = $request->get('total_rows');
$start_index = $request->get('start_index');
$row_counter_break = $request->get('row_counter_break');
$data = Excel::load($filepath)->limit(false, ($start_index))->get();
$dataArr = $data->toArray();
$array = array_map('array_filter', $dataArr);
$array = array_filter($array);
if ($start_index > $total_rows) {
return response()->json([
'status' => 'complete',
'product_type' => $product_type,
'category_id' => $category_id,
'category_level' => $category_level,
'file_path' => $filepath,
'total_rows' => $total_rows,
'start_index' => 0,
'row_counter_break' => $row_counter_break,
]);
} else {
$rowCounter = 0;
foreach ($array as $value) {
$image_list = [];
if (!empty($value['image1'])) {
array_push($image_list, $value['image1']);
}
if (!empty($value['image2'])) {
array_push($image_list, $value['image2']);
}
if (!empty($value['image3'])) {
array_push($image_list, $value['image3']);
}
if (!empty($value['image4'])) {
array_push($image_list, $value['image4']);
}
if (!empty($value['image5'])) {
array_push($image_list, $value['image5']);
}
foreach ($image_list as $il) {
if ($rowCounter >= $row_counter_break)
break;
$status = self::CheckLinkStatus($il);
if ($status == 200) {
if (strpos($il, "?dl=0") !== false) {
$image_url = str_replace("?dl=0", "", $il);
$image_url = str_replace("www.dropbox.com", "content.dropboxapi.com", $il);
$info = pathinfo($image_url);
$contents = file_get_contents($image_url, true);
$file = $info['basename'];
file_put_contents(public_path('datauploads') . "/" . $file, $contents);
} else {
$img_status = self::CheckLinkStatus($il);
if ($img_status !== 404 && $img_status !== 401) {
$image_url = str_replace("www.dropbox.com", "content.dropboxapi.com", $il);
$info = pathinfo($image_url);
$contents = file_get_contents($image_url, true);
$file = $info['basename'];
file_put_contents(public_path('datauploads') . "/" . $file, $contents);
}
}
}
}
$rowCounter++;
}
return response()->json([
'status' => 'success',
'product_type' => $product_type,
'category_id' => $category_id,
'category_level' => $category_level,
'file_path' => $filepath,
'total_rows' => $total_rows,
'start_index' => $start_index,
'row_counter_break' => $row_counter_break,
]);
}
}
Image Status Check Function
public static function CheckLinkStatus($image)
{
$ch = curl_init($image);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $retcode;
}
Try this:
$ch = curl_init($image);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($httpCode != 404) //# if error code is not "404"
{
/* Your Function here. */
}
else
{
/* Handle 404 here. */
}
Try setting an array of http codes, like:
$httpCodes = [401,404];
And than just check:
if(!in_array(CheckLinkStatus($image),$httpCodes){
// YOur logic
} else {
// Handle 401 && 404
}
I am working on Opencart API (opencart v2.3) and I follow this link for documentation (Opencart ) . But there is no data on opencart APIs and how to use it, So I follow steps from other websites and using that code I receive this message when call login api, Success: API session successfully started!
But whenever I use another API for add product in cart or view cart or add order, I receive permission issue. I debug code and found that it required session app_id and when I check, it store only token, not app_id
I use following code which I found by googling.
common.php
<?php
function do_curl_request($url, $params=array()) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'E:\practice\oc2.3\tmp\apicookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'E:\practice\oc2.3\tmp\apicookie.txt');
$params_string = '';
if (is_array($params) && count($params)) {
foreach($params as $key=>$value) {
$params_string .= $key.'='.$value.'&';
}
rtrim($params_string, '&');
curl_setopt($ch,CURLOPT_POST, count($params));
curl_setopt($ch,CURLOPT_POSTFIELDS, $params_string);
}
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return $result;
}
login.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/login';
$fields = array(
'key' => 'FpafURRNAHgVcaUXZozahVdEOV7mtp1Q0ejvAMAIAfiZyVqIptqZ2uV9eQvT3PytlzELULH1vQwLKikFGBOm3yky1rTuFO6sEi0eBkH1y6WgpaNWIsB0ZMiRCCbGCBZZak2uR1CBg0TpOzcbevXWGStvoUsaKgl0B3OKRoHk6mRj7e6S63HJQzQksbbz0JfCuZsY9cvhY4ArQPzNf3XfrdgE3nTG5hYQCXaKPVqtS3R2Vqr4sazwjgXYajy7h6Dv',
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
if (isset($data->token)) {
$token = $data->token;
}
var_dump($data);
add_product.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/addproduct';
$fields = array(
'product_id' => '32',
'quantity' => '1',
'option[226]' => '15'
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
var_dump($data);
customer api
public function index() {
$this->load->language('api/customer');
// Delete past customer in case there is an error
unset($this->session->data['customer']);
$json = array();
if (!isset($this->session->data['api_id'])) {
$json['error']['warning'] = $this->language->get('error_permission');
} else {
// Add keys for missing post vars
$keys = array(
'customer_id',
'customer_group_id',
'firstname',
'lastname',
'email',
'telephone',
'fax'
);
foreach ($keys as $key) {
if (!isset($this->request->post[$key])) {
$this->request->post[$key] = '';
}
}
// Customer
if ($this->request->post['customer_id']) {
$this->load->model('account/customer');
$customer_info = $this->model_account_customer->getCustomer($this->request->post['customer_id']);
if (!$customer_info || !$this->customer->login($customer_info['email'], '', true)) {
$json['error']['warning'] = $this->language->get('error_customer');
}
}
if ((utf8_strlen(trim($this->request->post['firstname'])) < 1) || (utf8_strlen(trim($this->request->post['firstname'])) > 32)) {
$json['error']['firstname'] = $this->language->get('error_firstname');
}
if ((utf8_strlen(trim($this->request->post['lastname'])) < 1) || (utf8_strlen(trim($this->request->post['lastname'])) > 32)) {
$json['error']['lastname'] = $this->language->get('error_lastname');
}
if ((utf8_strlen($this->request->post['email']) > 96) || (!filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL))) {
$json['error']['email'] = $this->language->get('error_email');
}
if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
$json['error']['telephone'] = $this->language->get('error_telephone');
}
// Customer Group
if (is_array($this->config->get('config_customer_group_display')) && in_array($this->request->post['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$customer_group_id = $this->request->post['customer_group_id'];
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
// Custom field validation
$this->load->model('account/custom_field');
$custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);
foreach ($custom_fields as $custom_field) {
if (($custom_field['location'] == 'account') && $custom_field['required'] && empty($this->request->post['custom_field'][$custom_field['custom_field_id']])) {
$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
} elseif (($custom_field['location'] == 'account') && ($custom_field['type'] == 'text') && !empty($custom_field['validation']) && !filter_var($this->request->post['custom_field'][$custom_field['custom_field_id']], FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => $custom_field['validation'])))) {
$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
}
}
if (!$json) {
$this->session->data['customer'] = array(
'customer_id' => $this->request->post['customer_id'],
'customer_group_id' => $customer_group_id,
'firstname' => $this->request->post['firstname'],
'lastname' => $this->request->post['lastname'],
'email' => $this->request->post['email'],
'telephone' => $this->request->post['telephone'],
'fax' => $this->request->post['fax'],
'custom_field' => isset($this->request->post['custom_field']) ? $this->request->post['custom_field'] : array()
);
$json['success'] = $this->language->get('text_success');
}
}
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
Put the token right after your request URL will make it works.
Assume token returned by api/login is KYMmXA4Bcj8nL9WD3nl0oalaJOL1KSKo.
add_product.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/addproduct&token=KYMmXA4Bcj8nL9WD3nl0oalaJOL1KSKo';
$fields = array(
'product_id' => '32',
'quantity' => '1',
'option[226]' => '15'
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
var_dump($data);
Make sure server's IP address is added to the allowed IP addresses.
To check that, go to System → Users → API then edit the Default one.
Once there, click on IP Address tab and insert the server IP address.
To get the server IP address, you can use the following command line:
$ curl ipinfo.io/ip
I have a function which queries an api and outputs the response as an array. I can run this function once and then I can echo the array output.
But problem for me is, I can call this function once and have output. But I'd like to loop through these function parameters and call it for multiple usernames. Example:
<?php
require("./include/function.php");
$Player=fetchCharacterDescriptions("Senaxx", "2");
echo "<tr>";
echo "<th class=\"col-md-3\">" . $Player[0]['username'] . "</th>";
foreach ( $Player as $var )
{
echo "<th class=\"col-md-3\">",$var['class']," ",$var['light'],"</th>";
}
echo "</tr>";
echo "</thead>";
echo "</table>";
?>
And this call's the function fetchCharacterDescriptions in function.php which is:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$hash = array(
'3159615086' => 'Glimmer',
'1415355184' => 'Crucible Marks',
'1415355173' => 'Vanguard Marks',
'898834093' => 'Exo',
'3887404748' => 'Human',
'2803282938' => 'Awoken',
'3111576190' => 'Male',
'2204441813' => 'Female',
'671679327' => 'Hunter',
'3655393761' => 'Titan',
'2271682572' => 'Warlock',
'3871980777' => 'New Monarchy',
'529303302' => 'Cryptarch',
'2161005788' => 'Iron Banner',
'452808717' => 'Queen',
'3233510749' => 'Vanguard',
'1357277120' => 'Crucible',
'2778795080' => 'Dead Orbit',
'1424722124' => 'Future War Cult',
'2033897742' => 'Weekly Vanguard Marks',
'2033897755' => 'Weekly Crucible Marks',
);
function translate($x)
{
global $hash;
return array_key_exists($x, $hash) ? $hash[$x] : null;
}
//BungieURL
function callBungie($uri)
{
$apiKey = '145c4aff30864167ac4548c02c050679';
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-API-Key: ' . $apiKey
));
if (!$result = json_decode(curl_exec($ch) , true))
{
$result = false;
}
curl_close($ch);
return $result;
}
//Request Player
function fetchPlayer($username, $platform)
{
$result = false;
$uri = 'http://www.bungie.net/Platform/Destiny/SearchDestinyPlayer/' . $platform . '/' . $username;
$json = callBungie($uri);
if (isset($json['Response'][0]['membershipId']))
{
$result = array(
'membershipId' => $json['Response'][0]['membershipId'],
'membershipType' => $platform
);
}
return $result;
}
//Request characters
function fetchCharacters($username, $platform)
{
$result = array();
if($player = fetchPlayer($username, $platform)) {
$uri = 'http://bungie.net/Platform/Destiny/'.$player['membershipType'].'/Account/'.$player['membershipId'].'?ignorecase=true';
if( $json = callBungie($uri) ) {
foreach ($json['Response']['data']['characters'] as $character) {
$result[] = $character;
}
}
}
return $result;
}
//Request character descriptions
function fetchCharacterDescriptions($username, $platform)
{
$character_descriptions = array();
if($characters = fetchCharacters($username, $platform)) {
foreach ($characters as $character) {
$class = translate($character['characterBase']['classHash']);
$emblem = $character['emblemPath'];
$backgroundpath = $character['emblemPath'];
$level = $character['characterLevel'];
$character_id = $character['characterBase']['characterId'];
$light = $character['characterBase']['stats']['STAT_LIGHT']['value'];
$username = $username;
$character_descriptions[] = array(
'class'=> $class,
'emblem'=> $emblem,
'backgroundpath'=>$backgroundpath,
'character_id' => $character_id,
'characterlevel' => $level,
'light' => $light,
'username' => $username
);
}
return $character_descriptions;
}
return false;
}
?>
So my function call is: fetchCharacterDescriptions("Senaxx", "2"); and i'd like to add more players to this (from an array or something) So i can request the stats for multiple usernames.
You just have to loop over the players an perform fetchCharacterDescriptions for each of them.
$players = array(
"Senaxx" => "2",
"SomeoneElse" => "2",
);
foreach ($players as $playerName => $platformId) {
$Player = fetchCharacterDescriptions($playerName, $platformId);
// do your other stuff
}
Keep in mind that your webpage will load veeery slow because every call to fetchCharacterDescriptions() executes 2 curl requests. Also - if the API is down, your site effectivly is as well (or blank at least).
You are probably better off fetching the data beforehand (in certain intervalls) and storing it into a database/csv file or something.
I wan't my bot to receive images if user asks for it.
But I really not sure how to make it possible.
I've created special page on my web site, where I get images by request.
But, my bot isn't working.
I've created flickr account, created special page, the connected my bot's code with flickr page code.
So, the question is, how to make my bot search pictures in flickr and then provide them to user?
Here is code for bot page:
include 'flickr.php';
$row = "My access token";
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$row;
$ch = curl_init($url);
if($message == "image'.$set.'")
{
$load_images = $hasil;
$image = file_get_contents($load_images);
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"attachment":{
"type":"image",
"payload":{
"url":"'.$image.'"
}
}
}
}';
};
$json_enc = $jsonData;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_enc);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
And here is my flickr code.
I think that the mistake is somewhere here, but I can't see it.
require_once 'webhook.php';
class flickr
{
var $api;
function __construct($api) {
$this->api = $api;
}
function flickr_photos_search($search,$count_image,$size)
{
$params = array(
'api_key' => $this->api,
'method' => 'flickr.photos.search',
'text' => $search,
'format' => 'rest',
'per_page' => $count_image,
'page' => 1,);
$xml = $this->create_url($params);
if(#$rsp = simplexml_load_file($xml))
{
if (count($rsp)<>0)
{
foreach($rsp->photos->children() as $photo)
{
if ($photo->getName()=='photo')
{
$farm=$photo->attributes()->farm;
$server=$photo->attributes()->server;
$id=$photo->attributes()->id;
$secret=$photo->attributes()->secret;
if ($size=='Med')
{
$sz="";
}
else
{
$sz = "_".$size;
}
$gbr[]='<img src="https://farm'.$farm.'.staticflickr.com/'.$server.'/'.$id.'_'.$secret.$sz.'.jpg'.'" /> ';
}
}
}
else
{
die("No images found!");
}
}else
{
die("wrong parameter");
}
return $gbr;
}
function create_url($params)
{
$encoded_params = array();
foreach ($params as $k => $v){
$encoded_params[] = urlencode($k).'='.urlencode($v);
}
$url = "https://api.flickr.com/services/rest/?".implode('&', $encoded_params);
return $url;
}
}
if(isset($_REQUEST[$set]))
{
$search=$_REQUEST[$set];
$result= 30;
$size = 'm';
$flickr = new flickr('My flickr secret code');
$gbr = $flickr->flickr_photos_search($search,$result,$size);
foreach($gbr as $hasil)
{
echo $hasil.' ';
}
}
There is a problem:
$load_images = $hasil;
$image = file_get_contents($load_images);
"payload":{
"url":"'.$image.'"
}
From documentation - Payload image is just URL of that image
You can use my API (https://github.com/Fritak/messenger-platform) for that, really easy to use:
// Send an image (file).
$bot->sendImage($userToSendMessage, 'http://placehold.it/150x150');