前提

這是我上週所開發的流浪動物領養聊天機器人得到大家的一些建議.

裡面有個建議是希望能夠新增好友的時候能夠增加”歡迎訊息”. 於是開始實作.

相關問題與解決方式

如何在新增朋友的時候發送預設簡訊

目標:

想要再新增你的機器人的時候,能夠發送一些簡單的介紹.

遇到困難:

其實根據 Line API Spec (Receive Operations) 應該要能直接收到透過 content.From 來查詢誰發的好友需求才是.

不過不清楚的官方文件是這樣說沒錯啦,實際上去跑的時候.

  • content 沒資料 (ID, From, To)
  • OpContent (透過 ontent.OperationContent() 拿的)一樣都沒資料 (ID, From, To)

在不斷地來來回回,總算找到可能是放在 result.RawContent .令人驚訝的是竟然是放在 result.RawContent.Param[0]

Root cause:

Line Server 無法回傳正確的值,在 content 底下關於 from, toid 都是空白. 根據Line Document 應該要有.

{"result":[
  {
    "from":"u2ddf2eb3c959e561f6c9fa2ea732e7eb8",
    "fromChannel":1341301815,
    "to":["u0cc15697597f61dd8b01cea8b027050e"],
    "toChannel":1441301333,
    "eventType":"138311609000106303",
    "id":"ABCDEF-12345678901",
    "content": {
      "location":null,
      "id":"325708",
      "contentType":1,
      "from":"uff2aec188e58752ee1fb0f9507c6529a",
      "createdTime":1332394961610,
      "to":["u0a556cffd4da0dd89c94fb36e36e1cdc"],
      "toType":1,
      "contentMetadata":null,
      "text":"Hello, BOT API Server!"
    }
  },
  ...
]}

但是我拿到

{
  "result": [
    {
      "content": {
        "params": [
          "XXX",
          null,
          null
        ],
        "message": null,
        "reqSeq": 0,
        "revision": 932,
        "opType": 4
      },
      "createdTime": 1462860363348,
      "eventType": "138311609100106403",
      "from": "XXX",
      "fromChannel": 1341301815,
      "id": "SOME_ID",
      "to": [
        "MSGID"
      ],
      "toChannel": 1462189304
    }
  ]
}

content 底下的東西都是空白的,這就是為什麼沒有資料的原因.

全部問題已經發給 Line Bot Go SDK issue #2

先透過一些方式來避開,以下是全部相關程式碼.

程式碼:

func callbackHandler(w http.ResponseWriter, r *http.Request) {
   received, err := bot.ParseRequest(r)
	if err != nil {
		if err == linebot.ErrInvalidSignature {
			w.WriteHeader(400)
		} else {
			w.WriteHeader(500)
		}
		return
	}
	for _, result := range received.Results {
		content := result.Content()

		//Add with new friend.
		if content != nil && content.IsOperation && content.OpType == OpTypeAddedAsFriend {
		
			out := fmt.Sprintf("(Welcom MSG)歡迎訊息..")
			//result.RawContent.Params[0] is who send your bot friend added operation, otherwise you cannot get in content or operation content.
			_, err = bot.SendText([]string{result.RawContent.Params[0]}, out)
			if err != nil {
				log.Println(err)
			}
			log.Println("New friend add event.")
		}
  }
}

相關資料


Evan

Attitude is everything