Skip to content
[Twitter API,node]APIで返答を追加する
web-tips
2020-07-14

調べた結果だけをさくっと記述。

返答を付けたいTwitterの書込を取得する(例では指定ユーザ自身のタイムライン)

  async getUserTweet(userId?: string, userName?: string, count = 5) {
    const res = await this.twitter.get('statuses/user_timeline', {
      user_id: userId,
      screen_name: userName,
      count: count
    });
    const tweetList: SimpleTweet[] = (<any[]>res).map((tw) => {
      return {
        id_str: tw.id_str,
        id_long: tw.id,
        author: userName || "",
        text: tw.text,
        created_at: tw.created_at
      }
    })
    return tweetList;
  }
  async getUserTweet(userId?: string, userName?: string, count = 5) {
    const res = await this.twitter.get('statuses/user_timeline', {
      user_id: userId,
      screen_name: userName,
      count: count
    });
    const tweetList: SimpleTweet[] = (<any[]>res).map((tw) => {
      return {
        id_str: tw.id_str,
        id_long: tw.id,
        author: userName || "",
        text: tw.text,
        created_at: tw.created_at
      }
    })
    return tweetList;
  }

取得した書込のid_strを付けてTwitterに書込する

  async postReply(parent: string, message: string) {
    const res: Promise<void> = this.twitter.post('statuses/update', {
      in_reply_to_status_id: parent,  //  idはid_strをstringのままでよい
      status: message,
      auto_populate_reply_metadata: true  // 返答になるらしい
    });
    res.catch(e => {
      console.log(e);
    })
  }
  async postReply(parent: string, message: string) {
    const res: Promise<void> = this.twitter.post('statuses/update', {
      in_reply_to_status_id: parent,  //  idはid_strをstringのままでよい
      status: message,
      auto_populate_reply_metadata: true  // 返答になるらしい
    });
    res.catch(e => {
      console.log(e);
    })
  }

参照するidはid_strを使う。整数として取得するとjavascriptの精度上、id値が丸まって変わってしまう(だから元々id_strが取得出来る)。in_reply_to_status_id: parent はAPI仕様では型は指定されていないが、stringでよいみたい。