[C#][ASP.net] 我們來聊聊Facebook Message Bot 如何實作 (二)
接續上一篇 [C#][ASP.net] 我們來聊聊Facebook Message Bot 如何實作 (一) 我們來繼續聊聊如何接受,發送,驗證 關於facebook message bot 的相關操作。
1. 首先我們要去驗證上一篇文章的粉絲專頁存取權杖 是否成功綁定可被使用
看一下他所寫的簡單地說,開始接收前必須我們要先這樣呼叫一次驗證一下粉絲專頁存取權杖是否能夠使用,呼叫格式為 https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=<token>,我們開一頁webhookStart.aspx 並且我們模擬一下呼叫是否驗證成功。
var page_token ="<FANPAGE_TOKEN>";
var uri = "https://graph.facebook.com/v2.6/me/subscribed_apps";
string parameters = "access_token=" + page_token;
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string result = wc.UploadString(uri, parameters);
Response.Write(result);
}
看起來成功再來就是接收端
2.接收端 看一下官方的 code
這邊我們繼續做webhook.aspx 讓他可以接受到使用者的訊息,當有人跟你的粉絲團說話時候你就會接收到facebook 根你的webhook說話,這時候我們程式碼先把它完整地紀錄下來,臉書傳來的格式如下
{
"object":"page",
"entry":[
{
"id":"199785103378748",
"time":1466156804347,
"messaging":[
{
"sender":{
"id":"1119921418064388"
},
"recipient":{
"id":"199785103378748"
},
"timestamp":1466156804269,
"message":{
"mid":"mid.1466156804033:80a0d15902ea73c095",
"seq":220,
"text":"hi"
}
}
]
}
]
}
所以我建立一個model 去對應
public class Sender
{
public string id { get; set; }
}
public class Recipient
{
public string id { get; set; }
}
public class Message
{
public string mid { get; set; }
public int seq { get; set; }
public string text { get; set; }
}
public class Messaging
{
public Sender sender { get; set; }
public Recipient recipient { get; set; }
public long timestamp { get; set; }
public Message message { get; set; }
}
public class Entry
{
public string id { get; set; }
public long time { get; set; }
public List<Messaging> messaging { get; set; }
}
public class ReceiveBotModel
{
public string @object { get; set; }
public List<Entry> entry { get; set; }
}
然後我們就來撰寫接收的code,繼續實作在webhook.aspx
//接收程式
//用來暫存的資料夾,當然你不用這樣存下來,這是我拿來測試用的
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "tmp_msg");
var sr = new StreamReader(Request.InputStream);
string content = sr.ReadToEnd();
//收到馬上把原始檔做一下紀錄
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "tmp_msg\\" + DateTime.Now.ToString("yyyyMMddHHmmsss") + "-origin.js", content);
try
{
var mcs = JsonConvert.DeserializeObject<ReceiveBotModel>(content);
//紀錄一下呼叫者 id 跟他的訊息
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "tmp_msg\\" + DateTime.Now.ToString("yyyyMMddHHmmsss") + "-chatinfo.js",
mcs.entry[0].messaging[0].sender.id+":" + mcs.entry[0].messaging[0].message.text);
//傳送訊息
//SendTextToUser(mcs.entry[0].messaging[0].sender.id);
}
catch (Exception exx)
{
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "tmp_msg\\" + DateTime.Now.ToString("yyyyMMddHHmmsss") + "-error.js",
exx.Message);
}
然後基本上用你的身分去跟粉絲團說話應該你就會收到訊息了,請注意,你必須要是粉絲團的管理員才會生效
3.傳送端,看一下facebook 的 code :
落落長,基本上這邊我測試很久,因為都常常出現404 bad request ,這邊我就把我try 很久的code 提供一下免得大家跟我一樣走了很大冤枉路
首先我們先得建立傳送的model
public class SendModel
{
public recipient recipient { get; set; }
public message message { get; set; }
}
public class recipient
{
public string id { get; set; }
}
public class message
{
public string text { get; set; }
}
接下來就是傳送的code 了
//傳送的code
private void SendTextToUser(string userId)
{
var d = new SendModel();
d.message = new message { text = "Hi,你好現在是下班時間,請稍後再傳。" };
d.recipient = new recipient { id = userId };
var path = "https://graph.facebook.com/v2.6/me/messages?access_token=" + FANPAGE_TOKEN;
var request = (HttpWebRequest)WebRequest.Create(path);
// request.ContentType = "application/x-www-form-urlencoded";
request.ContentType = "application/json";
request.Method = "POST";
//request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(JsonConvert.SerializeObject(d));
streamWriter.Flush();
streamWriter.Close();
}
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string result = reader.ReadToEnd();
Response.Write(result);
}
}
}
}
接下來就是看你的創意了
參考文件:
http://huli.logdown.com/posts/709641-teaching-facebook-messenger-api
http://sls.weco.net/node/25752
source code:
https://github.com/donma/FacebookBotCSharpSample
標籤:
ASP.net
,
C#
,
Facebook
,
Javascript
,
Node.js
-- Yesterday I wrote down the code. I bet I could be your hero. I am a mighty little programmer. 如果這篇文章有幫助到您,簡單留個言,或是幫我按個讚,讓我有寫下去的動力...