LoginSignup
7
7

More than 3 years have passed since last update.

Node.jsでTwitterを自動化する

Last updated at Posted at 2019-12-06

https://adventar.org/calendars/4650
OUCC(大阪大学コンピュータクラブ)のアドベントカレンダー12日目です。

Node.jsのtwitterモジュールでtwitterAPIを叩きました。
モジュールの更新が2017年で止まっており、一部機能が使えなくなっています。
先駆者の皆さんの記事のコードが動かないこともありました。

ツイートする

twitter APIを取得して、API key, API secret key, Access token, Access token secretを取得しました。これに関しても参照ページからほかの方の記事をご覧ください。

送信できる環境が整ったので、ひとまずtwitterモジュールからツイートしてみました。

//モジュールの読み込み
const twitter = require('twitter');

//ツイート内容
const text = 'test'

//上からAPI key, API secret key, Access token, Access token secret
const client = new twitter({
    consumer_key        : "-----------",
    consumer_secret     : "-----------",
    access_token_key    : "-----------",
    access_token_secret : "-----------"
});

client.post('statuses/update', {status: text}, function(error, tweet, response) {
  if (!error) {
    console.log(tweet);
  }
});

これでちゃんとツイートできました。定期的に実行すればbotが作れますね。

いいねを送信する

キーワードでツイートを検索して、いいねを送信していきます。
streamモジュールというものが以前は使えたらしいのですが、2019年春ごろから使えなくなっているようです。
モジュールの更新が2017年で止まっているので仕方ないですね。
そんなわけでstreamなしでやっていきます。

//モジュールの読み込み
const twitter = require('twitter');

//上からAPI key, API secret key, Access token, Access token secret
const client = new twitter({
    consumer_key        : "-----------",
    consumer_secret     : "-----------",
    access_token_key    : "-----------",
    access_token_secret : "-----------"
});

async function searchTweet(queryArg, nextResultsMaxIdArg = null) {
    client.get('search/tweets', { q: queryArg, count: 1, max_id: nextResultsMaxIdArg }, async (error, searchData, response) => {

      if (error) console.log(error);

      for (item in searchData.statuses) {
        const tweet = searchData.statuses[item];

      await client.post('https://api.twitter.com/1.1/friendships/create.json', {screen_name: tweet.user.screen_name}, () => {
        console.log(`\n${tweet.user.screen_name}さんをフォローしました。\n`);
      });

      //検索に失敗
      if (searchData.search_metadata == undefined) {
        console.log('no metadata');
      }

      else if (searchData.search_metadata.next_results) {
        let maxId = searchData.search_metadata.next_results.match(/\?max_id=(\d*)/);
        searchTweet(queryArg, maxId[1]);
      }
    }
  });
}

searchTweet('検索ワード');

postの内容を改変すればフォローもできます。

バージョン

Node.js : 12.13.1

モジュール

twitter : 6.13.1

参考ページ

twitterモジュール公式
https://www.npmjs.com/package/twitter

twitterAPIの解説
https://syncer.jp/Web/API/Twitter/REST_API/

bot作成の記事
https://yukimonkey.com/js-application/twitter-bot-2/

twitterモジュールの機能を一通り使った記事
https://tasoweb.hatenablog.com/entry/2018/06/01/002438

7
7
0

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