先在 Line Develop 裡面創建一個機器人
使用 Messaging API :
https://developers.line.me/en/docs/messaging-api/overview/
在這裡,Line Bot 使用 Json來傳遞資訊 :
https://developers.line.me/en/docs/messaging-api/reference/
故伺服器只是負責接收資料,轉成 Model,組出回傳訊息的 Json,然後利用 WebClinet 將資料丟到 Line 的伺服器處理,回傳訊息給使用者。
1.接收資料
在 Web Api 使用 Request.Content.ReadAsStringAsync().Result 取得資料
string postData = Request.Content.ReadAsStringAsync().Result;
2.轉成 Model
取得資料後,可以利用 JsonConvert 將資料轉換成 Model
var receivedMessage = JsonConvert.DeserializeObject<LineReceivedMessage>(postData);
目前可能會用到的資訊
string userid = receivedMessage.events[0].source.userId; //使用者 ID string message = receivedMessage.events[0].message.text; //文字訊息 var replyToken = receivedMessage.events[0].replyToken; //回傳的 token
Model 樣式 (部分功能而已,並不完整)
public class LineReceivedMessage { public List<Event> events; public LineReceivedMessage() { events = new List<Event>(); } } public class Event { public string type { get; set; } public Source source { get; set; } public EventMessage message { get; set; } public string replyToken { get; set; } public Event() { source = new Source(); message = new EventMessage(); } } public class Source { public string userId { get; set; } } public class EventMessage { public string id { get; set; } public string type { get; set; } public string text { get; set; } }
3.回傳的資料,這邊直接使用匿名型別處理,然後才轉成 Json
var replyMessage = new { replyToken = replyToken, messages = new object[] { new { type = "text", text = message } } };
將資料轉成 Json 然後用 WebClient 傳給 Line Bot 的伺服器處理 :
string s = JsonConvert.SerializeObject(replyMessage); byte[] bytes = Encoding.UTF8.GetBytes(s);
4.使用 WebClient 發送訊息
WebClient webClient = new WebClient(); webClient.Headers.Clear(); webClient.Headers.Add("Content-Type", "application/json"); webClient.Headers.Add("Authorization", "Bearer " + channelAccessToken); webClient.UploadData("https://api.line.me/v2/bot/message/reply", bytes);
功能完成後,使用者說啥,他就會回復相同訊息(限文字) :
完整程式碼 :
public void PostReplyMessage(){ var channelAccessToken = "{Cannel Access Token}"; var postData = Request.Content.ReadAsStringAsync().Result; var receivedMessage = JsonConvert.DeserializeObject<LineReceivedMessage>(postData); string userid = receivedMessage.events[0].source.userId; string message = receivedMessage.events[0].message.text; var replyToken = receivedMessage.events[0].replyToken; var replyMessage = new { replyToken = replyToken, messages = new object[] { new { type = "text", text = message } } }; string s = JsonConvert.SerializeObject(replyMessage); byte[] bytes = Encoding.UTF8.GetBytes(s); WebClient webClient = new WebClient(); webClient.Headers.Clear(); webClient.Headers.Add("Content-Type", "application/json"); webClient.Headers.Add("Authorization", "Bearer " + channelAccessToken); webClient.UploadData("https://api.line.me/v2/bot/message/reply", bytes); }