My chat bot is working great but I am having trouble debugging the Welcome message functionality because it only shows up when a conversation is initiated (although i'm pretty sure it's not working having tried it on a colleagues phone). How do I reset my chat so it sees me as a new user interacting with it?
This is my welcome PHP Script at the moment
<?php
function webhook() {
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'MYTOKEN') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$welcomejson = welcomemessage();
welcomesend($json);
function message() {
$json = '{
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[
{
"message":{
"text":"Welcome to My BOT!"
}
}
]
}';
return $json;
}
function send($json) {
$url = 'https://graph.facebook.com/v2.6/MYPAGEID/thread_settings?access_token=MYTOKEN';
//Initiate cURL.
$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
}
Try this:
Open Facebook in a desktop browser and go to the page linked to your messenger bot
Press "Message"
Inside the message popup/discussion choose "Options" (cog icon)
Select "Delete Conversation..." and say "Delete Conversation" in the confirmation prompt
Select "Message" again
Select "Get Started"
Step 4. really deletes the chat history you are having with the page/app so beware.
On desktop, delete the conversation and message the page again.
This will allow you to see the "Get Started" button again, allowing you to test it and your welcome message's functionality.
If you're trying to test the "Messenger Greeting", it's a lot more complicated. See below.
On Desktop the "Messenger Greeting" still will not show up after deleting the conversation. Only the "get started" button reappears. I believe this is a bug that I will be opening up a ticket for most likely.
You can get a similar experience on mobile by deleting the conversation, uninstalling, and reinstalling Messenger, but once again that does not display the Messenger greeting, it only shows the get started button.
Not being able to see the Messenger Greeting again is an issue for developers who are picky about the line-by-line formatting of the Messenger greeting, or who simply need to see it again for a demo of the messenger bot once the greeting has already been seen.
Thankfully, although EXTREMELY painful, there's a workaround. Basically have to re-setup your bot.
Create a new page
NEVER OPEN A MESSAGE WITH THE PAGE/BOT UNTIL STEP 17
Click settings, Messenger, and set your messenger greeting, and press save.
Since that doesn't actually save the toggled setting for some reason, select a different thing from messenger in the sidebar
Reselect Messenger
Turn on the greeting (the message should have saved properly, just not the toggle for whether its on or off)
Change to a different thing in sidebar
Re-select Messenger and double check that the messenger greeting is enabled
Create a new app
Add Messenger as a product
Select the page and copy the page access token
Put the page access token where it is needed in your code
Run your code
Connect to the webhook url with your verify token and all the boxes checked
After webhook connection is successful, subscribe it to your new page
Run your curl command to enable the 'get started' button and your welcome message that will happen after the button is pressed
Open a message with your page, and the Messenger greeting and get started button should appear. YOU GET ONE CHANCE AND THEN YOU'LL HAVE TO REPEAT ALL OF THESE STEPS TO SEE THE GREETING AGAIN.
I believe the toggle on messenger greeting not saving right is also a bug, and I may open a ticket for it.
There is a way to get the welcome screen in Messenger on iOS (at least as of Apr 28th), although it's super annoying. Basically, in addition to deleting the convo, you have to reinstall the app on your phone.
Go to the paged linked to your bot in facebook on desktop
Archive the conversation
Open Messenger on your phone and delete the conversion by swiping right on the cell in the conversation list
Delete Messenger from your phone
Reinstall Messenger from the App Store
Related
I am working on a Messenger chatbot in development mode and have made some progress dealing with messages and quick replies but can't find the way to detect the Postback payload event sent by Facebook after the user press the "Get Started Button"
I have set the Get Started button postback and put the payload string by sending a POST request to the Messenger Profile API which returned "success", and had also set the "messaging_postbacks" event to my webhook.
However when the button is clicked the event is not detected by the webhook.
This is part of my code:
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
//this handles the message text properly
$message = $input['entry'][0]['messaging'][0]['message']['text'];
//this deals correctly with quick reply payload
$quickreply = $input['entry'][0]['messaging'][0]['message']['quick_reply']['payload'];
I have tried separately and unsuccessfully each one of this lines of code to get the postback input triggered by the get started button:
$getstarted = $input['entry'][0]['messaging'][0]['get_started']['payload'];
$getstarted = $input['entry'][0]['messaging'][0]['message']['get_started']['payload'];
$getstarted = $input['entry'][0]['messaging'][0]['postback']['payload'];
$getstarted = $input['entry'][0]['messaging'][0]['message']['postback']['payload'];
I will appreciate any suggestions :)
The way to retrieve the value of the get_started button was among the ones I had tried, specifically:
$input['entry'][0]['messaging'][0]['postback']['payload']
The issue had to do with a separate part of my code in the cURL thats sends the POST request.
It said:
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
And needed to say:
if(!empty($input['entry'][0]['messaging'][0]['postback'])){
$result = curl_exec($ch);
The get_started button sends a postback to the webhook so the first script wasn't initiating the cUrl because there was no 'message' in the $input variable but a 'postback' property
A good video resource that dealt the same issue: https://www.youtube.com/watch?v=JQkmznEfVDo
I am trying to figure out how to call a google script via the api from php. Here is my script:
function doGet() {
return ContentService.createTextOutput("hello world!");
}
I can call it as a web app via it's URL but what I am trying to accomplish will require it be called via the API. Google's documentation is so confusing it's almost useless.
This seems like it would be such a simple task but I'm getting nowhere fast. Does anyone know where to find a simple step by step tutorial or can someone detail the steps required to accomplish this?
UPDATE: So, I've given up on the google API to access scripts. I can use all of the drive api calls but it seems it's not possible to call my own script via the API. Here is my ultimate goal:
A google script to zip files:
function doGet(e) {
var fileIds = [];
// hard code a couple of file id's just for simplicity now.
fileIds.push('0BzoYw0RgVVOvU0RqdTFrcGdSSzA');
fileIds.push('0BzoYw0RgVVOvNEJNcWpmSkNxNTA');
return ContentService.createTextOutput(zipping(fileIds));
}
function zipping(fileIds) {
var zipfilename = "sample2.zip";
var blobs = [];
var mimeInf = [];
var accesstoken = ScriptApp.getOAuthToken();
fileIds.forEach(function(e) {
try {
var file = DriveApp.getFileById(e);
var mime = file.getMimeType();
var name = file.getName();
} catch (er) {
return er
}
var blob;
blob = UrlFetchApp.fetch("https://www.googleapis.com/drive/v3/files/" + e + "?alt=media", {
method: "GET",
headers: {"Authorization": "Bearer " + accesstoken},
muteHttpExceptions: true
}).getBlob().setName(name);
blobs.push(blob);
});
var zip = Utilities.zip(blobs, zipfilename);
return DriveApp.createFile(zip).getId(); // return the file id of the new zip file.
}
Publish -> Deploy as web app...
Select "New"
Select "Me"
Select "Only Myself"
Click "Deploy" and authorize the access as requested.
Call the web app with curl from command line to test:
curl -L https://script.google.com/macros/u/0/s/### script id ###/exec
Get html containing the error: "Sorry, unable to open the file at this time."
Change permissions so anyone can execute the app.
Same error. Even entering the url in the browser as the same user gives the same error.
At this point I think I have to admit defeat and find a solution other than Google.
------------------ UPDATE 2 --------------------
Apparently the error:
"Sorry, unable to open the file at this time. Please check the address and try again."
I think this is some oddball problem with Google. The same script works in some accounts but not others. I see from searching the web, others randomly get this error and there is no definitive solution. If anyone knows one, please let me know.
----------------- UPDATE 3 --------------------
This error is an oddball problem with Google. Apparently a new script in some accounts will get this error until the next day. I have verified this several times so if this happens to you, wait a day and try executing it again. The good thing is that after Google finally is able to "open the file" you can make any changes you want, including additional script files to that project, and it updates instantly.
However, a new project will have to wait until the next day so pre create any you think you might want and a couple extra a day ahead of time.
How about this sample script? When you deploy Web Apps, please copy and paste the URL. And please use it to $url of the following script.
How to deploy Web Apps.
On the Script Editor
File
-> Manage Versions
-> Save New Version
Publish
-> Deploy as Web App
-> "Project version:" is latest one or create as New.
-> At "Execute the app as", select "your account"
-> At "Who has access to the app", select "Anyone, even anonymous"
-> Click "Deploy"
-> Copy "Current web app URL"
-> Click "OK"
Sample script :
<?php
$url = 'https://script.google.com/macros/s/#####/exec';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($curl);
echo $response;
curl_close($curl);
?>
Result :
hello world!
References :
Web Apps
cURL Functions
If I misunderstand your question, I'm sorry.
I have setup a webhook in Podio for an item.update in hook_update_item.php file. What I want to do if an item has been updated, I want to open a link preferably in a new tab, here is the code that I have:
<?php
require ("../podio/PodioAPI.php");
Podio::setup(Client ID, Client Secret);
Podio::authenticate_with_app(App ID, App Token);
switch ($_POST['type']) {
case 'hook.verify':
// Validate the webhook
PodioHook::validate($_POST['hook_id'], array('code' => $_POST['code']));
case 'item.update':
// Do something. item_id is available in $_POST['item_id']
if ($_POST['item_id'] == '238777597'){
//open new link here
$ch = curl_init('http://www.google.com.ph');
curl_exec($ch);
}
}
?>
Podio webhook has already been validated so I am assuming when webhook is firing it goes to the 'item.update'. But so far no luck on bringing up a new tab of google page. Appreciate any tips and suggestions!
I'm assuming that your code is running on a server somewhere. You could write a webpage that asks the server every n seconds/minutes if there are any new tabs that it should open. Your server receives the request, looks to see if there are any tabs to open and sends them in an array to the webpage. From there in javascript you can open the new tabs. Your browser might block them thought if you don't change the pop-up settings.
There might be a better way to do this using push notifications, but it is a start.
I've done a lot of searching and I've found outdated tutorials that don't work...
I have a site made with PHP and when I submit a particular form in my admin area, I want to publish to my Facebook "fan page"
There is no RSS available, so do you have any example to directly post to the Facebook fan page (not user wall) using php sdk?
Thank you!
Finally, after a lot of tests, it worked, without the PHP SDK. This is the step by step guide:
1. Get permissions and the page token
Go to https://developers.facebook.com/tools/explorer/ and select your app from the first drop down menu, in the left.
Click on the button "Get access token", and in the "Select Permissions" window, click in "Extended Permissions" and check manage_pages and publish_stream, and click in "Get Access Token" blue button.
You may be asked in this step to grant permissions to your app to access to your Facebook account, accept.
Next, click at the end of the text field next to the "GET" drop down, and replace the numbers for: me/accounts, and click in the blue button next to this text field.
You'll get the tokens for all your pages, including your app page. Find your page name in the list, will look like this: "name": "Your page name"
When you located your page, copy the access token for the page (will be really long), that can look like this: "access_token": "XXXXXXXX". Also copy the id of the page: "id": "XXXXX".
That's all for this step, we can start coding now.
2. Post to your page wall via PHP
First, for this script, you'll need a server supporting curl.
We start the PHP document defining the page access token and the page id that we've get in the 1st step:
<?php
$page_access_token = 'XXXXXXX';
$page_id = 'YYYYYYYY';
After that, we create an array with the info to post to our page wall:
$data['picture'] = "http://www.example.com/image.jpg";
$data['link'] = "http://www.example.com/";
$data['message'] = "Your message";
$data['caption'] = "Caption";
$data['description'] = "Description";
You can of course, use any other post parameter described in https://developers.facebook.com/docs/reference/api/post/ and if you don't need one or many of the parameters above you can simply delete it.
Ok, At this point we add to the array the access token:
$data['access_token'] = $page_access_token;
And we set our post URL, to post in our page:
$post_url = 'https://graph.facebook.com/'.$page_id.'/feed';
And the last step, we'll use a curl to post our message in our page wall:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
?>
After that, we can save our PHP document, and try to execute it. The post may appear in our Facebook page.
Hope this code helps to other people with the same problem!
You can test tokens using
Facebook Access Token Debugger
Working solution for API v.2.5
Get code for app_id as parameter of response_uri
https://www.facebook.com/dialog/oauth?client_id=".$app_id."&redirect_uri=".$response_uri."&response_type=code&scope=manage_pages,publish_pages
Get access_token based on code, app_id and app_secret as result of response_uri
https://graph.facebook.com/oauth/access_token?grant_type=authorization_code&client_id=".$app_id."&client_secret=".$app_secret."&code=".$code."&redirect_uri=".$response_uri
Get never expiring page_access_token for page_id based on access_token
https://graph.facebook.com/v2.5/".$page_id."?fields=access_token&access_token=".$access_token
As an addition to nmarti answer. Valid for API v.2.4.
If you don't want to go Facebook API console, rather do API calls, there are some instructions.
First of all, you have to have Facebook user, being admin on the page you want to post, also you have to create Facebook App in order to proceed.
Do login request, to get user token:
https://www.facebook.com/dialog/oauth?client_id=%app-id%&redirect_uri=%your-site-url%&response_type=token&scope=manage_pages,publish_pages
In response, you should get %user-token%, save it, you will need in the next step.
Read More
Ask for long lived token:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=%app-id%&client_secret=%app-secret%&fb_exchange_token=%user-token%
Now you will have %long-lived-token%, required to get long lived page token.
Read More
Now, get a list of your Facebook Pages,
https://graph.facebook.com/v2.4/%page-admin-user-id%/accounts/?access_token=%long-lived-token%
Find in the list your Page, and a page token, now you can continue with posting to page using nmarti example.
Also Facebook says:
The resulting page access token will not have any expiry time.
Read More
Here is the resource you are looking for. Scroll down to Page Login and read from there.
You have to get an access token for your page and then use that token when posting. This is assuming that you want your post to appear "from the page". IE - posting as if you were the page.
the actual call to the graph api to create a post object, and how to do it, can be found at this url from the facebook documentation.
I am working on a site that currently uses a basic authentication dialog box login system, that is the type of dialog that you get if you go here: http://www.dur.ac.uk/vm.boatclub/password/index.php
I did not set this system up and am not in a position to easily/quickly work around it, but it DOES work. The issue however is that the dialog box is not very helpful in telling you what login information you have to use (that is which username and password combination), and so I would like to replace it with a form. I had been thinking that this wasn't possible but I wanted to ask in order to find out.
Is it possible to set up an HTML form that sends the data to the server such that it accepts it in the same way that it would using this dialog box? Alternatively is it possible to set up a PHP script that would take normal form data and process it somehow passing it to the server such that it logs in?
Edit: After being told that this is basic authentication I went around and have managed to find a way that works and keeps the user persistently logged in. However, this does not work in internet explorer. The solution was simply to redirect the user to:
http://username:password#www.dur.ac.uk/vm.boatclub/password/index.php
But Internet Explorer removed it due to phishing uses about 3 years ago. Is there a way to use javascript to get the browser to access the site in this way? Or will I have to simply change my UI?
After a fair bit of research I found a way that works in both Chrome and IE, that is all that I've tested it in, but the logic of the code does not suggest it should break anywhere. It is based upon this article:
http://www.peej.co.uk/articles/http-auth-with-html-forms.html
Which is rather in depth but the crux of it is this - on the form submit you make an AJAX request into the basic authenticated folder. AJAX requests can accept username and password information for basic auth, and once the browser has authed once it's authorised in that realm, i.e. it will stay logged in. The previous article does it in pure javascript, so to add something other than simply explaining the link here's a (hopefully fairly transparent) implementation using jQuery:
$(document).ready(function()
{
$('#loginForm').submit(function()
{
var username = $('#usernameInput').val();
var password = $('#passwordInput').val();
$.ajax(
{
'password' : password,
'username' : username,
'url' : 'http://www.website.com/basic-auth-file.php',
'type' : 'GET',
'success' : function(){ window.location = 'http://www.website.com/basic-auth-file.php'; },
'error' : function(){ alert('Bad Login Details');},
}
);
return false;
});
});
This achieved what I wanted, and is relatively simple to understand, however I would implore anyone who wanted this to go out and didn't know about basic auth to go out and do the research!
You can replace it with a form. http://www.dur.ac.uk/vm.boatclub/password/index.php uses basic access authentication.
basic access authentication
What you could do is perform basic authentication via curl
<?php
// HTTP authentication
$url = "http://www.dur.ac.uk/vm.boatclub/password/index.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword");
$result = curl_exec($ch);
curl_close($ch);
//echo $result;
?>
Option 1
Proxy everything just echo'ing $result
Option 2
Read headers from $result and if status code != 200 then wrong login information has been entered. User should enter form again. If status code == 200 right credentials have been entered and you should do http basic authentication by sending headers.
header("Authorization: Basic " . base64_encode($username . ":" . $password);
You should not echo any data($result) before sending header else you will get an error
Some quick links:
http://phpsec.org/projects/guide/2.html