【本文】
指定したメンション付きツイートに自動リプライするTwitter用botのサンプル。node.jsで作成。
予め、Twitter DevelopersでAPI KeyやAccess Tokenを取得する必要がある。
課題としては、連続でbot攻撃されると、健気にひたすらリプライし続けるので、いずれサーバー落ちるかも。
なので、特定の相手や特定の文言のツイートが連続する場合は、リプライしないとかの処理も必要。
【設定ファイル】
[config.json]
- TwitterのDevelopersサイトから取得したAPI-KeyやAccess Tokenを設定
./config/coinfig.json{ "key_token":[ {"consumer_key":"xxx", "consumer_secret": "xxx", "access_token_key": "xxx", "access_token_secret": "xxx"} ], "tweet_info":[ {"tracking_twid": "@xxx"} ], "request_options": [ {"proxy": "http://proxy.xxx:[port]"} ] }
[msg.json]
- リプライやツイート用のメッセージ文言を設定
- 各自で拡張可能
./msg_setting/msg.json{ "Reply_meg":[ {"reply_normal": "xxx"} ] }
【スクリプト】
[main.js]
- botを呼び出す
main.jsvar tw_replyBot = require('./bot/twitter_replyBot.js');
[twitter_replyBot.js]
- bot本体
- 指定したメンション付きのツイートを常時監視
- ツイートした相手に対しリプライ
- 2018/9/10追加:proxy設定 ⇒ https://github.com/desmondmorris/node-twitter/tree/master/examples
./bot/twitter_replyBot.js/* Twitter bot: Reply automatically */ /* General Settings */ require('date-utils'); var twitter = require('twitter'); var request = require("request"); var fs = require('fs'); var json_config = JSON.parse(fs.readFileSync('./config/config.json', 'utf8')); var json_msg = JSON.parse(fs.readFileSync('./msg_setting/msg.json', 'utf8')); /* setting of bot with config file */ var bot = new twitter({ /* read by config.json */ consumer_key : json_config.key_token[0].consumer_key, consumer_secret : json_config.key_token[0].consumer_secret, access_token_key : json_config.key_token[0].access_token_key, access_token_secret : json_config.key_token[0].access_token_secret, request_options : { /* If you want to set proxy, use 'proxy: json_config.request_options[0].proxy' */ //proxy: json_config.request_options[0].proxy } }); /* Start tracking mention */ bot.stream( 'statuses/filter', { track : json_config.tweet_info[0].tracking_twid }, function( stream ) { stream.on( 'data', function( data ) { /* to read text in data */ var tweet = data.text; console.log(tweet); /* setting of text to reply */ var dateStr = new Date().toFormat("YYYY/MM/DD/ HH24:MI:SS"); /* Reply messages are called from message file */ //var textCreateTOReply = '@' + data.user.screen_name + ' ' + json_msg.Reply_meg[0].reply_normal + '\n\n' + dateStr; var textCreateTOReply = '@' + data.user.screen_name + ' ' + json_msg.Reply_meg[0].reply_normal; console.log( textCreateTOReply ); /* reply: using 'update' */ bot.post( 'statuses/update', { status: textCreateTOReply, in_reply_to_status_id: data.id_str }, function(error, data, response) { if (!error) { console.log("OK, Reply!") /* if you want to read filtering data, use 'console.log(data)'. */ //console.log(data); } } ) }); });
以上。
P.S.
Githubにもアップしておきました。
https://github.com/tomo-hata/twitter_bot
【参考文献】
API
構築方法やスクリプトとか
- "node.jsを使ってtwitter botを作ってみる" (from Qiita @iyuichi さん)
- オウム返し返信をしてくれるtwitterボットをnode.jsで作ってみた。 (from GitHubGist fddcddhdd さん)
※その他、似たようなスクリプトはたくさんあるので参考になります。