Facebook chat using graph API - facebook

I'm using graph API in order to use Facebook chat.
I'm using the http://restfb.com/ framework.
The issue is that with the following code I can read all conversations and messages.
public void initClient()
{
m_facebookClient = new DefaultFacebookClient(MY_ACCESS_TOKEN, MY_APP_SECRET);
}
public void readPage()
{
Page page = m_facebookClient.fetchObject("352179081632935", Page.class);
System.out.println("Page likes = " + page.getLikes());
Connection<Conversation> conversations = m_facebookClient.fetchConnection("me/conversations", Conversation.class);
for(List<Conversation> conversationPage : conversations) {
for(Conversation conversation : conversationPage) {
System.out.println(conversation);
System.out.println(conversation.getUnreadCount());
Message lastMessage = null;
for (Message message : conversation.getMessages())
{
System.out.println("Message text = " + message.getMessage());
System.out.println("Message unread = " + message.getUnread());
System.out.println("Message from = " + message.getFrom().getName());
System.out.println("Message to = " + message.getTo().get(0).getName());
System.out.println("Message unseen = " + message.getUnseen());
lastMessage = message;
}
}
}
I would like to know how to send reply messages or new messages using this framework or Graph API?
Thank you,
Moshe

First of all, there is no me/conversations endpoint for users. Conversations are only available for Pages so it would be /{page-id}/conversations: https://developers.facebook.com/docs/graph-api/reference/v2.2/page/conversations
The Facebook docs explain in detail how it works, including some example code. I suggest using one of the official SDKs instead (JS SDK, PHP SDK, ...).
The Chat API (which is what you would want to use) is deprecated: https://developers.facebook.com/docs/chat/
Meaning, it is not possible anymore to use the Facebook chat in your App.

I found the way yo solve it by replying based on the conversation id.
For example:
m_facebookClient.publish("t_mid.1420120490471:36257b35667389d257/messages", FacebookType.class, Parameter.with("message", "RestFB test"));
t_mid.1420120490471:36257b35667389d257 - is the conversation id

Related

How to get other user's mention timeline of twitter with twitter4j api?

I'm struggling to get other user's mention timeline with twitter4j api. I could figure out that it's possible only to get other user's UserTimeline. It seems that there is no way to get other user's mention timeline
(I found that here - lookup "Interface TimelinesResources")
Is there way to get other user's mention timeline ???
You can get the MentionsTimeline using getMentionsTimeline() method of TimelineResources as a link you mentioned with some limitations of number of tweets returned.
Find below example of the example which will give you MentionsTimeline.
Twitter twitter = new TwitterFactory().getInstance();
try {
User user = twitter.verifyCredentials();
List<Status> statuses = twitter.getMentionsTimeline();
System.out.println("Showing #" + user.getScreenName() + "'s mentions.");
for (Status status : statuses) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get timeline: " + te.getMessage());
System.exit(-1);
}
You can use getUserTimeline() method of Twitter class.
References:
1. http://twitter4j.org/javadoc/twitter4j/Twitter.html
2. http://twitter4j.org/javadoc/twitter4j/Status.html
The Twitter API doesn't have an endpoint for viewing other users mentions (the statuses/mentions_timeline API returns only the mentions of the authenticated user).
You should use the search API, using as the query string the #screen_name of the user you want to get the mentions. Please note that the Twitter Search API may not return all mentions for a given user (it says that "the Search API is focused on relevance and not completeness").
So, using Twitter4j, you can get #NASA mentions using the following
Twitter twitter = new TwitterFactory().getInstance();
try {
Query query = new Query("#NASA");
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
}
} while ((query = result.nextQuery()) != null);
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
}

Send notification through facebook application using rest fb api

I am trying to send notification to facebook users via facebook application using restfb api. When tried to publish such notification, it shows an exception
"com.restfb.exception.FacebookGraphException: Received Facebook error response of type
GraphMethodException: Unsupported post request".
Below is my code:
FacebookType = facebookAppAccessToken.publish("user_id/notification?access_token=app_access_token"),
FacebookType.class, Parameter.with("template","send_notification"),
Parameter.with("href,"sample_link"));
Please help me resolving this. Thanks in advance
public void sendNotification(String externalUserId, String message) {
AccessToken appAccessToken = new DefaultFacebookClient()
.obtainAppAccessToken(APP_KEY, APP_SECRET);
FacebookClient facebookClient = new DefaultFacebookClient(
appAccessToken.getAccessToken());
try {
facebookClient.publish(externalUserId
+ "/notifications", FacebookType.class,
Parameter.with("template", message));
} catch (FacebookOAuthException e) {
if (e.getErrorCode() == 200) {
//Not an app user
} else if (e.getErrorCode() == 100) {
//Message cannot be longer than 180 characters
}
}
}
Handle error codes appropriately. And you can add href and ref as per your requirement.
Here are Details of parameters.

How to retrieve a particular Facebook post using post_id

In my application, there is a case where I want to retrieve the content (message) of a particular Facebook post. I am able to get the postid id for that particular post, but I am not able to get the content associated with that id. I could not find any FQL query to get the post message with post_id or a Graph API URL.
I have this URL to get the all posts, ../100005002784039/posts?fields=id,name,message, but I want only a particular message of the post while passing the post id.
How can I achieve this?
Thanks to sahil, my URL is like this:
https://graph.facebook.com/"+PostId()+"?access_token=Token);
Code
URL fbmsg = new URL("https://graph.facebook.com/"+trace.getFbPostId()+"?access_token="+TOKEN+"");
URLConnection yc = fbmsg.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
String s = "";
while ( (inputLine = in.readLine()) != null)
System.out.println(inputLine);
Log.d(TAG, "getPostId trace getFbPostId " + inputLine);
s = s + inputLine + "n";
Log.d(TAG, "getPostId trace getFbPostId " + s);
in.close();
System.out.println(s);
Simply make the following query to the API-
/POST_ID

How to post images to facebook via windows phone?

In my application image has to post to Facebook,mail.Sorry i am new to windows phone.i don't have a idea.please help me.what i can do first.
If you want to share a status you can use your facebook account on your phone using Share link task (with this method you can only post on your wall) http://msdn.microsoft.com/en-us/library/hh394027%28v=vs.92%29.aspx
To post (pictures, messages or others) on every wall you have access you need some things :
First you need to create a facebook application using this link :
Facebook developers
After that you need to identify yourself using a WebBrowser control with the link related to your application. The application requests authorization to perform certain actions such as posting. You need to detail the authorizations like this :
Dictionary<string, string> uriParams = new Dictionary<string, string>() {
{"client_id", "your app id"},
{"response_type", "token"},
{"scope", "user_about_me, offline_access, publish_stream"}, //The rights
{"redirect_uri", "http://www.facebook.com/connect/login_success.html"},
{"display", "touch"}
};
The Dictionary also contains the redirection uri to define if the operation was successful.
Finally you are authentified and receive an access token. Now you can use a WebRequest POST to post a message using this token :
WebRequest request = HttpWebRequest.Create("https://graph.facebook.com/" + the id of your wall + "/feed");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream((reqResult) =>
{
using (Stream strm = request.EndGetRequestStream(reqResult))
using (StreamWriter writer = new StreamWriter(strm))
{
writer.Write(client.AccessToken);
writer.Write("&message=" + HttpUtility.UrlEncode(status));
}
request.BeginGetResponse((result) =>
{
try
{
var response = request.EndGetResponse(result);
using (var rstrm = response.GetResponseStream())
{
var serializer = new DataContractJsonSerializer(typeof(FacebookPostResponse));
var postResponse = serializer.ReadObject(rstrm) as FacebookPostResponse;
callback(true, null);
}
}
catch (Exception ex)
{
callback(false, ex);
}
}, null);
}, null);
Here is how to post a message on a facebook page,
You should give the Facebook C# SDK a try
Facebook C# SDK
I have built this in once in an app of mine. They have plenty examples available which should be useful.

BlackBerry - Facebook extended permissions

I've just found a great sample of Facebook Connect on Blackberry by Eki Y. Baskoro,
The following is a short HOWTO on using Facebook Connect on Blackberry. I created a simple Facade encapsulating the Facebook REST API as well as added 'rough' MVC approach for screen navigation. I have tested on JDE 4.5 using 8320 simulator. This is still work in progress and all work is GPLed.
It works great for reading stuff.
NB Don't forget to get Facebook App Key and set it in TestBB class.
But now I want to post something on my wall. So I've add new method to FacebookFacade class using Stream.publish API:
/***
* Publishes message to the stream.
* #param message - message that will appear on the facebook stream
* #param targetId - The ID of the user, Page, group, or event where
* you are publishing the content.
*/
public void streamPublish(String message, String targetId)
{
Hashtable arguments = new Hashtable();
arguments.put("method", "stream.publish");
arguments.put("message", message);
arguments.put("target_id", targetId);
try {
JSONObject result = new JSONObject(
int new JSONTokener(sendRequest(arguments)));
int errorCode = result.getInt("error_code");
if (errorCode != 0) System.out.println("Error Code: "+errorCode);
} catch (Exception e) {
System.out.println(e);
}
}
/***
* Publishes message on current user wall.
* #param message - message that will appear on the facebook stream
*/
public void postOnTheWall(String message)
{
String targetId = String.valueOf(getLoggedInUserId());
streamPublish(message, targetId);
}
This will return Error code 200, "The user hasn't authorized the application to perform this action"
First I thought it's related with Facebook -> Application Settings -> Additional Permissions -> Publish recent activity (one line stories) to my wall but even checked, no difference...
Then I've found this post explains that issue related with extended permissions.
This in turn should be fixed by modifying url a little in LoginScreen class :
public LoginScreen(FacebookFacade facebookFacade) {
this.facebookFacade = facebookFacade;
StringBuffer data = new StringBuffer();
data.append("api_key=" + facebookFacade.getApplicationKey());
data.append("&connect_display=popup");
data.append("&v=1.0");
//revomed
//data.append("&next=http://www.facebook.com/connect/login_success.html");
//added
data.append("&next=http://www.facebook.com/connect/prompt_permissions.php?" +
"api_key="+facebookFacade.getApplicationKey()+"&display=popup&v=1.0"+
"&next=http://www.facebook.com/connect/login_success.html?"+
"xxRESULTTOKENxx&fbconnect=true" +
"&ext_perm=read_stream,publish_stream,offline_access");
data.append("&cancel_url=http://www.facebook.com/connect/login_failure.html");
data.append("&fbconnect=true");
data.append("&return_session=true");
(new FetchThread("http://m.facebook.com/login.php?"
+ data.toString())).start();
}
Unfortunately it's not working. Still Error Code 200 in return to stream.publish request...
Do you have any suggestions how to resolve this?
Thank you!
I have posted the updated API on my website (http://www.baskoro.web.id/facebook-connect-blackberry-HOWTO.html) and this should solve this issue. Please let me know otherwise.
Salam. Cheers!
Eki