LINEBotでメンション情報が取れるようになった!
最近アップデートきた
Messaging APIアップデート(2021年1月)
テキストメッセージタイプの新プロパティ
以前は、グループチャットやトークルーム内のメンションの情報は取得できませんでした。今回、メッセージWebhookイベントオブジェクトのテキストメッセージタイプに追加された新プロパティを利用することで、メンションの情報を取得できるようになりました。新たに追加されたプロパティは以下のとおりです。
mention
:メンションの情報を含むオブジェクト。
mention.mentionees[]
:1個以上のメンション。
mention.mentionees[].index
:テキストの先頭を0とした、textプロパティ内のメンションの開始位置。
mention.mentionees[].length
:メンションの長さ。@exampleであれば、8が長さになります。
mention.mentionees[].userId
:メンションされたユーザーのユーザーID。
詳しくは、『Messaging APIリファレンス』の「テキスト」メッセージタイプを参照してください。
試してみる
nodejsで見てみる。
公式SDKのEcho-Botのサンプルを使う。
https://github.com/line/line-bot-sdk-nodejs/tree/next/examples/echo-bot
とりま、event.message
見てみよう。
function handleEvent(event) {
if (event.type !== 'message' || event.message.type !== 'text') {
// ignore non-text-message event
return Promise.resolve(null);
}
+ console.log(event.message);
// create a echoing text message
const echo = { type: 'text', text: event.message.text };
// use reply API
return client.replyMessage(event.replyToken, echo);
}
macuser@macbook:~/line-bot-sdk-nodejs/examples/echo-bot (next *)$ node index.js
listening on 3000
{
type: 'text',
id: '13424246938488',
text: '@みかんBot @R @りんごBot @カワウソちゃん ',
mention: { mentionees: [ [Object], [Object], [Object], [Object] ] }
}
おお、mentionees!
もっと見てみよう。
function handleEvent(event) {
if (event.type !== 'message' || event.message.type !== 'text') {
// ignore non-text-message event
return Promise.resolve(null);
}
+ console.log(event.message.mention.mentionees);
// create a echoing text message
const echo = { type: 'text', text: event.message.text };
// use reply API
return client.replyMessage(event.replyToken, echo);
}
macuser@macbook:~/line-bot-sdk-nodejs/examples/echo-bot (next *)$ node index.js
listening on 3000
[
{ index: 0, length: 7, userId: 'Ud99df1c3b2066eca8348547af0c8be9f' },
{ index: 8, length: 2, userId: 'U89c0a22ed4a897463bd950519e0f72ba' },
{ index: 11, length: 7, userId: 'U054f7d1ddf16b75f1a8df5c39d043c9b' },
{ index: 19, length: 8, userId: 'U272633bd8ac62da518bac7b7469cc420' }
]
おおお、よい!
ちょっと注意
情報の取得に同意してないユーザーのuserIdは取得できない。
macuser@macbook:~/line-bot-sdk-nodejs/examples/echo-bot (next *)$ node index.js
listening on 3000
[
{ index: 0, length: 7, userId: 'Ud99df1c3b2066eca8348547af0c8be9f' },
{ index: 8, length: 2, userId: 'U89c0a22ed4a897463bd950519e0f72ba' },
{ index: 11, length: 7, userId: 'U054f7d1ddf16b75f1a8df5c39d043c9b' },
{ index: 19, length: 16 }
]
詳細はこちら
https://developers.line.biz/ja/docs/messaging-api/user-consent/
最後に
メンションの情報を取得できるだけで大分幅が広がりそうですね〜
残念ながらbotからグループ、ルームメンバーへのメンションは出来ません。。。