初探 ASP.net Core 打造 LINE BOT

程式下載: https://drive.google.com/file/d/1rmz910QWqQxLa8XOMWrFG1fjSTPoTLFd/view?usp=sharing
本篇學會
– LOG的撰寫以及追蹤
– ngrok 讓本機可以debug webhook
– JSON 的基本運用
– LINE BOT初步瞭解(回應訊息)


準備篇

– Visual Studio 

– ngrok(localhost 對應到https public domain的服務)

下載連結:
https://ngrok.com/download

– LINE Developers 帳號(免費)

https://developers.line.biz/en/ “https://developers.line.biz/en/

開發步驟

–  新增asp.net Core web應用程式後按下一步


–  設定專案名稱LINEBOT,建立



–  選擇.NET Core → ASP.NET Core 3.1 →API→建立



–  首先安裝 *serilog.extensions.logging*



–  在Startup.cs加上  ILoggerFactory ,並設定檔名



–  在預設的WeatherForecastController.cs試著加上LOG



–  開啟程式後,到logs目錄下確定LOG正常



–  新增API控制器


–  修改route為 api/linebot ,程式如下

           // 記得using Microsoft.Extensions.Logging;
        readonly ILogger<LINEBOTController> _log;

        public LINEBOTController(ILogger<LINEBOTController> log)
        {
            _log = log;
        }
        [HttpPost]
        public async Task<IActionResult> Post(dynamic request
        {
            string x = Convert.ToString(request);
            _log.LogInformation(x);             
            return Ok(request);
        }



– 執行程式後,打開IIS Express,確認PORT號



– 打開命令提示字元,切換到ngrok目錄下



– 執行命令(記得Port號改成自己對應)
`!ngrok http 33766 -host-header=”localhost:33766″`



– 執行後,會取到一個https開頭網址,記下來後(不要關閉視窗)



– 進到LINE Developer網址,新增Provi![]



– 新增一個 Messaging API的Channel



– 設定名稱與描述、目錄、子目錄後勾選允許相關條款後按Create



– 最後同意使用資訊



– 建立完成後進到MessagingAPI頁籤



– 修改以下內容



– 允許加入群組或多人聊天室



– 停用加入好友訊息以及自動回應訊息,啟用webhook功能





– 加webhook URL輸入



– 輸入確定後按Verify

– 出現 307 Temporary Redirect



– Startup.cs中的 app.UseHttpsRedirection() 註解,重新開啟程式



– 重新驗證後成功!



– 從LOG看到LINE傳來的驗證訊息



## 回聲蟲

– 從開發者網站中的Messaging API得知如何做[回應reply](https://developers.line.biz/en/docs/messaging-api/sending-messages/#reply-messages)



– 安裝 NewtonSoft.Json



– 到LINE DEVELOPER中取得TOKEN複製



– 加上程式如下

    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; }
    }


– 修改POST函數如下

        public async Task<IActionResult> Post(dynamic request)
        {
            string x = Convert.ToString(request);
            _log.LogInformation(x);               
            var channelAccessToken = “你的TOKEN”;
            var receivedMessage = JsonConvert.DeserializeObject<LineReceivedMessage>(x); // 收到訊息解成物件
            string userid = receivedMessage.events[0].source.userId;  // 取得使用者ID
            string message = receivedMessage.events[0].message.text;  // 取得文字訊息
            var replyToken = receivedMessage.events[0].replyToken;  // 取得回應TOKEN
            var replyMessage = new
            {
                replyToken = replyToken,
                messages = new object[] { new {
                    type = “text”,
                    text = message
                }
                }
            };
            string s = JsonConvert.SerializeObject(replyMessage);  // 轉為JSON字串
            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);
            return Ok(request);
        }


– 結果



##參考資料:

LINE DEVELOPER API文件

[https://developers.line.biz/zh-hant/docs/messaging-api/](https://developers.line.biz/zh-hant/docs/messaging-api/ “https://developers.line.biz/zh-hant/docs/messaging-api/”)

作者: 林壽山

林壽山 目前任職於軟體公司研究開發部門主管,主要採用.net core/.net 5/6 開發,收銀機pos系統開發,第三方支付設計(綠界、馬來西亞epay/happypay、台新one碼),金流設計,行動支付設計(悠遊卡/一卡通),支付寶,微信,街口支付,信用卡機(聯合信用卡),擅長PHP網頁設計(CodeIgniter、Laravel)框架、Delphi程式設計、資料庫設計、C# WinForm/WebForm程式設計、ASP.net MVC、LINE串接、API串接設計