How to get flickr random images for facebook messenger bot? - php

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');

Related

how do i integrate paynow zimbabwe api with a localhost system?

Can you please help me to integrate paynow zimbabwe gateway with my localhost system.I have tried to follow their documentation https://developers.paynow.co.zw/docs/quickstart.html but I failed. I want the user to be redirected to the paynow page to pay penalties.Also the result or status must be obtained in order to update the system database. Is it possible to link a localhost system to the paynow api or my system have to be live?. Thank you in advance
<?php
include "./includes/tables_header.php";
include "./includes/db.php";
require_once "./paynow/autoloader.php";
use Paynow\Payments\Paynow;
if(isset($_POST['Paynow']))
{
class Payow{
public function paynows($amount)
{
$siteurl="http://localhost/online_offenceTracking_system/payment1.php?";//substitute with your own return url
define('ps_error', 'Error');
define('ps_ok','Ok');
define('ps_created_but_not_paid','created but not paid');
define('ps_cancelled','cancelled');
define('ps_failed','failed');
define('ps_paid','paid');
define('ps_awaiting_delivery','awaiting delivery');
define('ps_delivered','delivered');
define('ps_awaiting_redirect','awaiting redirect');
define('site_url', $siteurl);
$int_key="###########";//get from paynow.co.zw
$int_id=#######;//get from paynow.co.zw, it should be an intenger
$paymentid="testID1234hs";
$url="https://www.paynow.co.zw/interface/initiatetransaction/?";
$reference=sha1(Paynow\Payments\Paynow::$app->user->identity->email);
$amount=6.25;
$returnurl="http://localhost/online_offenceTracking_system/payment1.php?r=credit/index"; //substitute with your own return urls
$resulturl="http://localhost/online_offenceTracking_system/payment1.php?r=credit/index"; //substitute with your own return urls
$authemail="acmwamuka#gmail.com";//This is the buyer's email address
$additionalinfo="Paying for canteen meals.";
$concat=$int_key.$int_id.$paymentid.$url.$reference.$returnurl.$resulturl.$authemail.$additionalinfo;
$concat=$concat.$int_key;
$values = array('resulturl' => $resulturl,
'returnurl' => $returnurl,
'reference' => $reference,
'amount' => $amount,
'id' => $int_id,
'additionalinfo' => $additionalinfo,
'authemail' => $authemail,
'authphone' => "07777777777",
'status' => 'Message'); //just a simple message
$fields_string = $this->CreateMsg($values,$int_key);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); //need fixing
$result = curl_exec($ch);
if($result)
{
$msg = $this->ParseMsg($result);
if ($msg["status"] == ps_error){
header("Location: $checkout_url");
exit;
}
else if ($msg["status"] == "Ok"){
$validateHash = $this->CreateHash($msg, $int_key);
if($validateHash != $msg["hash"]){
$error = "Paynow reply hashes do not match : " . $validateHash . " - " . $msg["hash"];
echo $error;
}
else
{
$theProcessUrl = $msg["browserurl"];
//echo $theProcessUrl;
//header("Location: ".$theProcessUrl);
Paynow\Payments\Paynow::$app->response->redirect($theProcessUrl);
$orders_array = array();
}
}
else {
//unknown status or one you dont want to handle locally
$error = "Invalid status from Paynow, cannot continue.";
}
}
else
{
$error = curl_error($ch);
echo $error;
}
//print_r($result);
//close connection
curl_close($ch);
}
public function ParseMsg($msg) {
$parts = explode("&",$msg);
$result = array();
foreach($parts as $i => $value) {
$bits = explode("=", $value, 2);
$result[$bits[0]] = urldecode($bits[1]);
}
return $result;
}
function CreateMsg($values, $MerchantKey){
$fields = array();
foreach($values as $key=>$value) {
$fields[$key] = urlencode($value);
}
$fields["hash"] = urlencode($this->CreateHash($values, $MerchantKey));
$fields_string = $this->UrlIfy($fields);
return $fields_string;
}
public function UrlIfy($fields) {
$delim = "";
$fields_string = "";
foreach($fields as $key=>$value) {
$fields_string .= $delim . $key . '=' . $value;
$delim = "&";
}
return $fields_string;
}
public function CreateHash($values, $MerchantKey){
$string = "";
foreach($values as $key=>$value) {
if( strtoupper($key) != "HASH" ){
$string .= $value;
}
}
$string .= $MerchantKey;
$hash = hash("sha512", $string);
return strtoupper($hash);
}
}}
?>
You can use a free service like ngrok to expose your localhost environment to the world wide web. Just make sure your returnurl and resulturl are using your ngrok address so that Paynow can callback your application.

Facebook OpenGraph 3.0 Post to FB Page with PHP

I'm not sure where I'm going wrong, but needing to post from my site to my Facebook Page.
~ fbautopost.php
require_once("Facebook/facebook.php");
class FacebookPost
{
var $consumer;
var $token;
var $method;
var $http_status;
var $last_api_call;
var $callback;
var $connection;
var $access_token;
function __construct($data)
{
$config = array();
$config['appId'] = $data['consumer_key'];
$config['secret'] = $data['consumer_secret'];
$pageID = $data['page_ID'];
$this->connection = new Facebook($config);
}
function share($title, $targetUrl, $imgUrl, $description, $access_token)
{
$this->connection->setAccessToken($access_token);
$params["access_token"] = $access_token;
if(!empty($title))
{
$params["message"] = $title;
$params["name"] = $title;
}
if(!empty($targetUrl))
{
$params["link"] = $targetUrl;
}
if(!empty($imgUrl))
{
$params["picture"] = $imgUrl;
}
if(!empty($description))
{
$params["description"] = $description;
}
// post to Facebook
try
{
$ret = $this->connection->api('/' .$pageID . '/feed/', 'post', $params);
}
catch(Exception $e)
{
$e->getMessage();
}
return true;
}
function getLoginUrl($params)
{
return $this->connection->getLoginUrl($params);
}
function getContent($url)
{
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_URL, $url);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ci, CURLOPT_HEADER, false);
curl_setopt( $ci, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ci);
curl_close ($ci);
return $response;
}
}
~ post.php
include('fbautopost.php');
$access_token = 'MY_ACCESS_TOKEN';
$facebookData = array();
$facebookData['consumer_key'] = 'MY_APP_ID';
$facebookData['consumer_secret'] = 'MY_SECRET_KEY';
$facebookData['page_ID'] = 'MY_PAGE_ID';
$title = 'Post Title';
$description = 'This is a test post';
$facebook = new FacebookPost($facebookData);
$facebook->share($title, $description, $access_token);
I haven't taken the app out of development, but as the admin I am not seeing any test posts posting on the page.
It's possible that I'm not getting the correct ACCESS TOKEN?? From the Graph Explorer, I am selecting my application, then getting a User Token with manage_page and publish_page permissions. I've also tried using a Page Token. Neither work. Is my code bad, or am I missing something else?
TIA
The issue was that I needed to require_once('Facebook/autoload.php'), not the Facebook.php that I had.

Telegram Bot sending a message without needing a ,message to trigger it

I am trying to let a Telegram bot send a message to a group without the need of a message by a user to trigger it. To be more specific i am trying to set up a birthday reminder where the bot querys a database, compares entries to the current date and broadcaststs a "Happy birthday" message in the group. As said i would like to do it via a cronjob that opens up the PHP script everyday and lets the bot broadcast it.
My problem is I checked all of Telegrams documentations and demo codes (https://core.telegram.org/bots/samples) but all of it are based on a User triggering the bot by sending a message.
My question is, if anyone was already able to implement a similar functionality and could aid me in extending my code? What might be worth mentioning is that the Bot is already integrated into the Group Chat and i have the chat id that would be needed for the bot to target the chat.
My code is as follows (i have to admit i copied it over from the demo examples):
<?php
define('BOT_TOKEN', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
function apiRequestWebhook($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;
}
$parameters["method"] = $method;
header("Content-Type: application/json");
echo json_encode($parameters);
return true;
}
function exec_curl_request($handle) {
$response = curl_exec($handle);
if ($response === false) {
$errno = curl_errno($handle);
$error = curl_error($handle);
error_log("Curl returned error $errno: $error\n");
curl_close($handle);
return false;
}
$http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
curl_close($handle);
if ($http_code >= 500) {
// do not wat to DDOS server if something goes wrong
sleep(10);
return false;
} else if ($http_code != 200) {
$response = json_decode($response, true);
error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n");
if ($http_code == 401) {
throw new Exception('Invalid access token provided');
}
return false;
} else {
$response = json_decode($response, true);
if (isset($response['description'])) {
error_log("Request was successfull: {$response['description']}\n");
}
$response = $response['result'];
}
return $response;
}
function apiRequest($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);
}
}
$url = API_URL.$method.'?'.http_build_query($parameters);
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
return exec_curl_request($handle);
}
function apiRequestJson($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;
}
$parameters["method"] = $method;
$handle = curl_init(API_URL);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters));
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
return exec_curl_request($handle);
}
function processMessage($message) {
// process incoming message
$message_id = $message['message_id'];
$chat_id = $message['chat']['id'];
if (isset($message['text'])) {
apiRequest("sendChatAction", array('chat_id' => $chat_id, "action" => "typing"));
// incoming text message
$text = $message['text'];
//Command for intializing the backend code for the birthday check (just to check its functionality but would prefer the code to run without a command)
if (strpos($text, "/geburtstagscheck") === 0) {
include 'skripte/start.php';
}
}}
define('WEBHOOK_URL', 'XXXXXXXXXXXXXX');
if (php_sapi_name() == 'cli') {
// if run from console, set or delete webhook
apiRequest('setWebhook', array('url' => isset($argv[1]) && $argv[1] == 'delete' ? '' : WEBHOOK_URL));
exit;
}
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (!$update) {
// receive wrong update, must not happen
exit;
}
if (isset($update["message"])) {
processMessage($update["message"]);
} ?>

How to develop user defined menu on wechat

here is my sample code. my developer mode is already enabled but there is no menu tabs options.
you can also add me on wechat so I can elaborate my problems in this matter, here is my wechat ID VinceZen. I badly need some help guys. Thank you in advance.
<?php
$data[] = '772134292672v';
$data[] = $_GET['timestamp'];
$data[] = $_GET['nonce'];
asort($data);
$strData = '';
$d = '';
$authString = '';
foreach($data as $d)
{
$authString .= $d;
}
//verify the signature
if(sha1($authString) == $_GET['signature'])
{
//check the echostr
if(!empty($_GET['echostr']))
{
echo $_GET['echostr'];
die();
}
else
{
//logic
//Getting access_token from customize menus
static function get_access_token($appid,$secret){
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$json=http_request_json($url);//here cannot use file_get_contents
$data=json_decode($json,true);
if($data['access_token']){
return $data['access_token'];
}else{
return "Error occurred while geting the access_token";
}
}
//Though URL request is https',cannot use file_get_contents.Using CURL while asking the JSON data
function http_request_json($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$return = "<xml>
<ToUserName><![CDATA['.$toUser.']]</ToUserName>
<FromUserName><![CDATA['.$fromUser.']]</FromUserName>
<CreateTime>'.time.'</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA['.text.']]</Content>
<FuncFlag>0</FuncFlag>
</xml>";
echo $return;
{
"button":[
{
"type":"click",
"name":"Daily Song",
"key":"V1001_TODAY_MUSIC"
},
{
"type":"click",
"name":" Artist Profile",
"key":"V1001_TODAY_SINGER"
},
{
"name":"Menu",
"sub_button":[
{
"type":"view",
"name":"Search",
"url":"http://www.soso.com/"
},
{
"type":"view",
"name":"Video",
"url":"http://v.qq.com/"
},
{
"type":"click",
"name":"Like us",
"key":"V1001_GOOD"
}]
}]
}
}
}
else
{
die('Access Denied');
}`enter code here`
?>

Facebook Authentication PHP & AJAX

I have a website that first uses the Facebook Javascript API to log a user in. However, when a user sends an xmlhttp request to one of my PHP scripts I would like to check again to see if that user is logged in via PHP (for securities sake).
I had a working system but after a site makeover there seems to be a bug. When I echo $html in the facebook.php script I get this error: {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException"}}.
/* request.js */
var postData = "id=" + id;
sendRequest('assets/php/believe.php',function(req) {
console.log(req.responseText);
},postData);
/* believe.php */
<?php
include("facebook.php");
$id = intval($_POST["id"]);
if($id == '') {
//Stuff
} else {
if($cookie) {
echo "hey";
}
}
?>
/* facebook.php */
<?php
define('YOUR_APP_ID', 'xxxxxx');
define('YOUR_APP_SECRET', 'xxxxxxxxxxxx');
function curl_get_contents($url){
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $url);
$html = curl_exec($curl);
curl_close($curl);
echo "$html";
return $html;
}
function get_facebook_cookie($app_id, $app_secret){
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value){
if ($key != 'sig'){
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $app_secret) != $args['sig']){
return null;
}
return $args;
}
$cookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);
$user = json_decode(curl_get_contents(
'https://graph.facebook.com/me?access_token=' .
$cookie['access_token']));
?>
I think your code is fine. User access token is expired. If user renews it, the code will work. Make sure you have a valid token in the cookie

Categories