LineBot -(4) 取得使用者資訊(Profile)

在 Message API 可以找到  ChannelAccessToken


Controller 取得使用者請求的資料 : 

伺服端會處理的事情 :

        public async Task<ActionResult> Post()
        {
            using (var ms = new MemoryStream())
            {
                await Request.Body.CopyToAsync(ms); //取得資料

                string postData = Encoding.UTF8.GetString(ms.ToArray()); //轉成字串資料

                StickyReceivedModel received = GetStickyReceivedModel(postData); //收集的資料轉成 model

                UserProfile profile = await GetUserProfile(received.UserId); //使用 userId 取得 profile 資料

                ReplayMessage(received,profile); //回傳訊息
            }

            return Ok();

        }

取得資料

using (var ms = new MemoryStream()) 
{
       await Request.Body.CopyToAsync(ms);
       string postData = Encoding.UTF8.GetString(ms.ToArray());
}

轉換成 Model

        private StickyReceivedModel GetStickyReceivedModel(string postData)
        {
            var receivedMessage = JsonConvert.DeserializeObject<LineReceivedMessage>(postData);

            return new StickyReceivedModel
            {
                UserId = receivedMessage.events[0].source.userId,
                Message = receivedMessage.events[0].message.text,
                ReplyToken = receivedMessage.events[0].replyToken
            };
        }

LineReceivedMessage

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

StickyReceivedModel

    public class StickyReceivedModel
    {
        public string UserId { get; set; }
        public string Message { get; set; }
        public string ReplyToken { get; set; }

使用 UserId 取得 Profile  

這邊可以直接參考 line 的文件 : 

https://developers.line.biz/en/reference/messaging-api/#get-profile

所以使用 Get  https://api.line.me/v2/bot/profile/{userId}  及傳入 ChannelAccessToken 即可

使用 HttpClinet 發出請求 : 

        HttpClient httpClient = new HttpClient()
        private async Task<UserProfile> GetUserProfile(string userId)
        {
            //GET https://api.line.me/v2/bot/profile/{userId}
            var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri($"https://api.line.me/v2/bot/profile/{userId}"),
                Headers = {
                    { "Authorization", $"Bearer {ChannelAccessToken}" },
                }
            };
            var result = await httpClient.SendAsync(httpRequestMessage);

            var content = await result.Content.ReadAsStringAsync();

            var profile = JsonConvert.DeserializeObject<UserProfile>(content);

            return profile;
        }

UserProfile

    public class UserProfile
    {
        public string displayName { get; set; }
        public string userId { get; set; }
        public string pictureUrl { get; set; }
        public string statusMessage { get; set; }
    }

回應訊息 (text) 

        private async void ReplayMessage(StickyReceivedModel received, UserProfile profile)
        {
            var replyMessage = new
            {
                replyToken = received.ReplyToken,
                messages = new object[] { new {
                        type = "text",
                        text = $"你的名字是{profile.displayName}"
                    }
                }
            };

            string s = JsonConvert.SerializeObject(replyMessage);
            byte[] bytes = Encoding.UTF8.GetBytes(s);
            ByteArrayContent byteContent = new ByteArrayContent(bytes);
            byteContent.Headers.Remove("Content-Type");
            byteContent.Headers.Add("Content-Type", "application/json");

            var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri("https://api.line.me/v2/bot/message/reply"),
                Headers = {
                    { "Authorization", $"Bearer {ChannelAccessToken}" },
                },
                Content = byteContent
            };

            await httpClient.SendAsync(httpRequestMessage);
        }

執行結果

print

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *