twitterから特定リストのtweetを取得してそれをGmailで定期的に送る。

twitter廃人から抜け出したい。

とはいえ有用な情報は得たい。ということでリストからtweetのまとめを作ってメールで受け取るようにする。

IFTTTで楽にやれるんじゃないのと思ったらリストから取得するようなことはできないようなのでRでやる。

tweetを取得する

まずはtwitterの特定のリストからtweetを取得する。

twitteRパッケージとか使いたいところだがうまくいかなかったのでRTwitterAPIを使う。

devtools::install_github("joyofdata/RTwitterAPI")
library(RTwitterAPI)

consumer_key <- "YOUR KEY"
consumer_secret <- "YOUR SECRET"
oauth_token <- "YOUR TOKEN"
oauth_token_secret <- "YOUR TOKEN SECRET"

params <- c(
  "oauth_consumer_key"     = consumer_key,
  "oauth_nonce"            = NA,
  "oauth_signature_method" = "HMAC-SHA1",
  "oauth_timestamp"        = NA,
  "oauth_token"            = oauth_token,
  "oauth_version"          = "1.0",
  "consumer_secret"        = consumer_secret,
  "oauth_token_secret"     = oauth_token_secret
)

url <- "https://api.twitter.com/1.1/lists/statuses.json"
query <- c(owner_screen_name="dichika", slug="R")
# print_result=TRUEにすると日本語の場合errorが出ることがある
result <- RTwitterAPI::twitter_api_call(url, query, params, print_result=FALSE)

tweetを整形して出力

取得したtweetを整形してcsvで出力する。

日時の変換の際、日本語ロケールだと月が“11月”とかになってPOSIXctへの変換に失敗するためロケールを一時的に変更する

JSONなのでjsonliteを使って簡単にdata.frameにしたいところだが、マルチバイト対応がいまいちなのでrjsonを使う。

listからdata.frameへの変換はdo.callとかReduceを用いるのが定石だが今回はdplyrパッケージのrbind_allを使った。

出力に関しては、1日単位で使い捨てなのでデータベースなどは使わない。

この一連のコードをcronで定期的に動かして出力していく。Windowsだったらタスクスケジューラとか使えばいい。

# POSIXctへの変更のためにlocaleを一時的に変更する
Sys.setlocale("LC_TIME", "en_US")
getTwInfo <- function(x){
  res <- data.frame(
    id=x$user$screen_name,
    name=x$user$name,
    text=x$text,
    tweetid=x$id_str,
    time=as.POSIXct(x$created_at, tz=Sys.timezone(), format="%a %b %d %X %z %Y"))
  return(res)
  }
library(rjson)
library(dplyr)
twdata <- rbind_all(lapply(fromJSON(result), getTwInfo))
# localeを戻す
Sys.setlocale("LC_TIME", "ja_JP")
write.table(twdata, "tweet_today.csv", append=TRUE, sep=",", row.names=FALSE)

GmailでHTMLメールを送る

上記コードでtweetがたまってくるので、以下を寝る前くらいのタイミングに動してHTMLメールで一日分のtweetを送る。

Gmailで送るにはmailRパッケージを使う。mailRパッケージの使い方はこちら。

https://github.com/rpremraj/mailR

注意するポイントとしてパスワードがある。 2段階認証にしてる場合はログイン時に用いるパスワードではなく、https://security.google.com/settings/security/apppasswords でアプリ用の固有のパスワードをを生成する必要がある。

library(dplyr)
# write.tableで列名が入っているのでその行を抜く。重複しているtweetも除く。
twdata <- read.csv("tweet_today.csv", as.is=TRUE) %>% filter(name!="name") %>% distinct(text)
file.remove("tweet_today.csv")
mail_body <- sprintf("<html>%s</html>",
                 paste(collapse="", 
                       sprintf("<blockquote>%s<p>%s (@%s)<p>%s</blockquote><HR>",
                               twdata$time, twdata$name, twdata$id, twdata$text))
                 )

install.packages("mailR")
library(mailR) # Java runtimeが無いと突然落ちるので注意
send.mail(from = "dichika<hoge@gmail.com>",
          to = "xxxxxxxxxxxxxxx@i.softbank.jp",
          subject="本日のtweet一覧",
          body = mail_body,
          encoding = "utf-8",
          html = TRUE,
          smtp = list(host.name = "smtp.gmail.com", 
                      port = 465, 
                      user.name = "hoge@gmail.com",
                      passwd = "xxxxxxxxxxxxxxx", # 2段階認証にしてる場合はhttps://security.google.com/settings/security/apppasswordsでPWを生成
                      ssl = TRUE),
          authenticate = TRUE,
          send = TRUE)