[C#]Line-Bot Api PushMessage

Line在日前釋出了新的API文件,簡單來試試看PUSH吧

 

 

先上Line Developer看看Message API關於PushMessage的部分

https://devdocs.line.me/en/#push-message

大概可以了解我們必須要得到三個東西

1.webhook URL

2.Access Token

3.UID

以上不贅述…因為網路上已經有很多大神提供解決方案了

隨便開個WinForm來串吧,textBox依序填入UID,文字訊息,第三個textBox我讓它顯示JSON字串,簡單辨識一下是否正確

 private string SendRequest(Uri uri, byte[] jsonDataBytes, string contentType, string method, string authorization)
        {
            WebRequest req = WebRequest.Create(uri);
            req.ContentType = contentType;
            req.Method = method;
            req.ContentLength = jsonDataBytes.Length;
            req.Headers.Add("Authorization", authorization);

            var stream = req.GetRequestStream();
            stream.Write(jsonDataBytes, 0, jsonDataBytes.Length);
            stream.Close();

            WebResponse response = req.GetResponse();
            MessageBox.Show(((HttpWebResponse)response).StatusDescription);
            stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            string responseFromServer = reader.ReadToEnd();

            return responseFromServer;
        }

 我先弄個WebRequest出來,其中有一行req.Headers.Add("Authorization",authorization);

用意是因為Line-Bot API中提到Request headers需要有個認證

        private void button1_Click(object sender, EventArgs e)
        {
            string userId = UID.Text;
            string word = textvalue.Text;
            string mystr = "https://api.line.me/v2/bot/message/push";
            string apikey = "Bearer accessToekn";
            //JSON
            JObject obj = new JObject();
            obj.Add("to", userId);
            JArray msg = new JArray();
            JObject m1 = new JObject();
            m1.Add("type", "text");
            m1.Add("text", word);
            msg.Add(m1);                      
            obj.Add("messages", msg);
            string obj_S = JsonConvert.SerializeObject(obj);
            message_Json.Text = obj_S;
            //POST
             Uri myuri = new Uri(mystr);
             var data = Encoding.UTF8.GetBytes(obj_S);
            SendRequest(myuri,data,"application/json","POST",apikey);
        }

button的code大概就是建立個JSON物件,序列化後轉為Byte寫進Stream,再搭配其他參數一起送給SendRequest就好了

Line的Message JSON格式是 {"to":"UserID","messages":[{"type":"text","text":"test"}]},

其中message陣列至多可放五組,LINE API也支援多種PUSH格式

RUN完程式大概就這樣…

單純筆記,皆為非正規作法,旁門左道,胡搞瞎搞。