LoginSignup
12
3

More than 1 year has passed since last update.

LINE BotのNode.js SDKでプロフィール取得のメモ #linedc

Last updated at Posted at 2021-08-27

userIdからプロフィールを取得したいってのをちょくちょく使うけど忘れるのでメモ

SDKのサンプルコード

client.getProfile()を利用します。

const profile = await client.getProfile(event.source.userId);
console.log(profile);
{
  userId: 'Ubxxxxxxxxxxxxxxxxxxxxxx',
  displayName: 'n0bisuke',
  pictureUrl: 'https://profile.line-scdn.net/ch/v2/p/xxxxxxxxxxxxxxxxxxxxxxxx/exist',
  statusMessage: 'こんにちは',
  language: 'ja'
}

コピペ用: リプライ

1時間でLINE BOTを作るハンズオンの記事から引用したコードです。

'use strict';

const express = require('express');
const line = require('@line/bot-sdk');
const PORT = process.env.PORT || 3000;

const config = {
    channelSecret: '作成したBOTのチャンネルシークレット',
    channelAccessToken: '作成したBOTのチャンネルアクセストークン'
};

const app = express();

app.get('/', (req, res) => res.send('Hello LINE BOT!(GET)')); //ブラウザ確認用(無くても問題ない)
app.post('/webhook', line.middleware(config), (req, res) => {
    console.log(req.body.events);
    Promise
      .all(req.body.events.map(handleEvent))
      .then((result) => res.json(result));
});

const client = new line.Client(config);

async function handleEvent(event) {

  let msg = ``;

  if (event.type !== 'message' || event.message.type !== 'text') {
    return Promise.resolve(null);
  }

  //☆ココがプロフ取得箇所
  const profile = await client.getProfile(event.source.userId);
  console.log(profile);
  msg = `${profile.displayName}さんこんにちは。 あなたのユーザーIDは${profile.userId}です。`

  return client.replyMessage(event.replyToken, {
    type: 'text',
    text: msg //実際に返信の言葉を入れる箇所
  });
}

app.listen(PORT);
console.log(`Server running at ${PORT}`);

コピペ用: プッシュメッセージ

友達全員にメッセージを送るシンプルな送信専用LINE BOTを作る【Node.js】 #linedcの記事から引用したコードです。

ただブロードキャストだと他の人にUserIdなど送るのはあまりよくないのでPushメッセージで自分だけに送信するようにしてます。

'use strict';

const line = require('@line/bot-sdk');

const config = {
    channelSecret: 'チャンネルシークレット',
    channelAccessToken: 'チャンネルアクセストークン'
};

const client = new line.Client(config);

let msg = ``;

//☆ココがプロフ取得箇所
const userId = `Ubxxxxxxxxxxxxxxxxxxxxxxxx`; //管理画面や他APIなどから取得しておく
const profile = await client.getProfile(userId);
console.log(profile);

msg = `${profile.displayName}さんこんにちは。あなたのユーザーIDは${profile.userId}です。`

const main = async () => {

    const messages = [{
        type: 'text',
        text: msg
    }];

    try {
        const res = await client.pushMessage(userId, messages);
        console.log(res);        
    } catch (error) {
        console.log(`エラー: ${error.statusMessage}`);
        console.log(error.originalError.response.data);
    }
}

main();

こんな感じに

スクリーンショット 2021-08-27 9.13.26.png

なります。

12
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
3