阅读facebook留言框

时间:2012-08-31 21:41:37

标签: c# .net c#-4.0 facebook-graph-api

我正在使用Facebook.dll i.s FacebookClient,主要是我想阅读Facebook用户邮箱我在db中保存了auth令牌。

  1. 从邮箱中选择邮件(全部),我可以提及开始日期和结束日期
  2. 保存db
  3. 中的所有邮件

    我用过

    dynamic result = objFacebookClient.Get("fql",
                         new { q = "SELECT message_id, author_id, body, created_time FROM message WHERE thread_id IN (SELECT thread_id FROM thread WHERE folder_id = 0)" });
    

    是否可以获得结果

    • 消息 - 消息内容
    • 发送发件人姓名和身份证件
    • 收件人 - 姓名和身份
    • 创建日期 - 消息创建日期

    代码在这里

    dynamic result = objFacebookClient.Get("fql",
       new { q = "SELECT message_id, author_id, body, created_time FROM message WHERE thread_id IN (SELECT thread_id FROM thread WHERE folder_id = 0)" });
    List<Model.FacebookUserMessageInfo> objFacebookMessageList = new List<Model.FacebookUserMessageInfo>();
    if (result != null)
    {
        Model.FacebookUserMessageInfo objFacebookMessage = null;
        var values = result.Values;
        var TotalResult = (((System.Collections.Generic.Dictionary<string, object>.ValueCollection)values).ToList()[0]);
        var TotalMessagesData = (JsonArray)TotalResult;
        if (TotalMessagesData != null)
        {
            foreach (var Messages in TotalMessagesData)
            {
                objFacebookMessage = new Model.FacebookUserMessageInfo();
                objFacebookMessage.MessageText = (((JsonObject)Messages)["body"]).ToString();
                objFacebookMessage.ActionUserID = Convert.ToInt64(((JsonObject)Messages)["author_id"]);
                if (objFacebookMessage.ActionUserID == CurrentUserId)
                {
                    objFacebookMessage.MessageType = Core.Enum.FacebookMessageType.Sent.ToString();
                }
                else
                {
                    objFacebookMessage.MessageType = Core.Enum.FacebookMessageType.Receive.ToString();
                }
                objFacebookMessage.FacebookUserId = FacebookUserId;
                var MessageSecond = (((JsonObject)Messages)["created_time"]).ToString();
                var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                objFacebookMessage.CreatedDate = dateTime.AddSeconds(double.Parse(MessageSecond));
                objFacebookMessageList.Add(objFacebookMessage);
            }
        }
    }
    

    提前致谢

2 个答案:

答案 0 :(得分:1)

我得到了我的解决方案

public class Facebook
{
    #region Private Properties

    private string ClientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
    private string ClientSecret = System.Configuration.ConfigurationManager.AppSettings["ClientSecret"];

    #endregion

    #region Public Methods

    public string GetLongLifeAccessToken(string ExistingToken)
    {
        try
        {
            string Data = string.Empty;
            string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=fb_exchange_token&fb_exchange_token={2} ",
                            ClientId, ClientSecret, ExistingToken);
            System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
            using (System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
                Data = sr.ReadToEnd();
                Data = HttpUtility.ParseQueryString(Data)["access_token"];
            }
            return Data;
        }
        catch (Exception ex)
        {

            throw new Exception(ex.Message);
        }

    }

    public List<Model.FacebookUserMessageInfo> ReadFacebookMailbox(string AuthToken, long? CurrentUserDefaultFacebookId, DateTime? LastProcessedDate, DateTime CurrentDate, int FacebookUserId)
    {
        try
        {

            FacebookClient objFacebookClient;
            List<Model.FacebookUserMessageInfo> objFacebookMessageList;
            objFacebookClient = new FacebookClient(AuthToken);
            try
            {
                objFacebookClient.Get("me");
            }
            catch (Exception ex)
            {
                throw new Exception(ErrorType.UnableToAuthorizFacebookUser.ToString());
            }
            TimeSpan t = LastProcessedDate.Value - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            int timestamp = (int)t.TotalSeconds;

            dynamic result = objFacebookClient.Get("fql",
               new { q = "SELECT message_id, author_id, viewer_id, body, created_time FROM message WHERE thread_id IN (SELECT thread_id FROM thread WHERE folder_id = 0) AND created_time >= " + timestamp.ToString() });
            objFacebookMessageList = new List<Model.FacebookUserMessageInfo>();
            if (result != null)
            {
                Model.FacebookUserMessageInfo objFacebookMessage = null;
                var values = result.Values;
                var TotalResult = (((System.Collections.Generic.Dictionary<string, object>.ValueCollection)values).ToList()[0]);
                var TotalMessagesData = (JsonArray)TotalResult;
                if (TotalMessagesData != null)
                {
                    foreach (var Messages in TotalMessagesData)
                    {
                        /*author_id =   The ID of the user who wrote this message.*/
                        /*viewer_id =   The ID of the user whose Inbox you are querying*/
                        objFacebookMessage = new Model.FacebookUserMessageInfo();
                        objFacebookMessage.MessageText = (((JsonObject)Messages)["body"]).ToString();
                        long author_id = Convert.ToInt64(((JsonObject)Messages)["author_id"]);
                        long viewer_id = Convert.ToInt64(((JsonObject)Messages)["viewer_id"]);
                        if (author_id == viewer_id)
                        {
                            objFacebookMessage.MessageType = Core.Enum.FacebookMessageType.Sent.ToString();
                        }
                        else
                        {
                            objFacebookMessage.MessageType = Core.Enum.FacebookMessageType.Receive.ToString();

                        }
                        objFacebookMessage.ActionUserID = author_id;
                        objFacebookMessage.FacebookUserId = FacebookUserId;
                        var MessageSecond = (((JsonObject)Messages)["created_time"]).ToString();
                        var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                        objFacebookMessage.CreatedDate = dateTime.AddSeconds(double.Parse(MessageSecond));
                        objFacebookMessageList.Add(objFacebookMessage);
                    }
                }

            }
            if (objFacebookMessageList.Count > 0)
            {
                objFacebookMessageList = objFacebookMessageList.Where(fm => fm.CreatedDate >= LastProcessedDate && fm.CreatedDate <= CurrentDate).ToList();

                objFacebookMessageList.ForEach(item =>
                {
                    var Auther = objFacebookClient.Get("https://graph.facebook.com/" + item.ActionUserID.ToString());
                    if (Auther != null)
                    {
                        item.ActionUserName = ((JsonObject)Auther)["name"].ToString();
                    }
                    else
                    {
                        item.ActionUserName = null;
                    }
                });

            }
            return objFacebookMessageList;



        }
        catch (Exception ex)
        {

            throw new Exception(ex.Message);
        }

    }

    #endregion
}

答案 1 :(得分:0)

如果我理解你想要的答案是:

您需要创建一个类 FacebookMes​​sage

class FacebookMessage
{
    public int SenderID { get; set; }
    public int AddresseeID { get; set; }
    public string SenderName { get; set; }
    public string AddresseeName { get; set; }
    public string Message { get; set; }

    public DateTime CreateDate { get; set; }

    public FacebookMessage()
    {
        SenderID = 0;
        AddresseeID = 0;
        SenderName = "";
        AddresseeName = "";
        Message = "";
    }
}

并使用此 FQL

dynamic result = objFacebookClient.Get("fql",
   new { q = "SELECT body, author_id, viewer_id, created_time FROM message WHERE thread_id IN (SELECT thread_id FROM thread WHERE folder_id = 0)" });

获取此信息并将其保存在 FacebookMes​​sage 中并为每条消息运行另一个查询:

    FacebookMessage faceMsg = null;
    var values = result.Values;
    var TotalResult = (((System.Collections.Generic.Dictionary<string, object>.ValueCollection)values).ToList()[0]);
    var TotalMessagesData = (JsonArray)TotalResult;
    if (TotalMessagesData != null)
    {
        foreach (var Messages in TotalMessagesData)
        {
            faceMsg= new FacebookMessage();
            faceMsg.Message = (((JsonObject)Messages)["body"]).ToString();
            faceMsg.SenderID = Convert.ToInt64(((JsonObject)Messages)["author_id"]);
            faceMsg.AddresseeID = Convert.ToInt64(((JsonObject)Messages)["viewer_id"]);
            var MessageSecond = (((JsonObject)Messages)["created_time"]).ToString();
            var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            faceMsg.CreatedDate = dateTime.AddSeconds(double.Parse(MessageSecond));

            result = objFacebookClient.Get("fql",
   new { q = "SELECT name FROM user WHERE uid = " + faceMsg.SenderID });

            var values = result.Values;
            faceMsg.SenderName = values.name; // Not tested, but should be something like that.

            result = objFacebookClient.Get("fql",
   new { q = "SELECT name FROM user WHERE uid = " + faceMsg.AddresseeID });

            var values = result.Values;
            faceMsg.AddresseeName= values.name; // Not tested, but should be something like that.

            faceMsgList.Add(objFacebookMessage);
        }
    }

建议将获取名称的查询拆分为不同的方法。