ブルーの趣味Log

日々の備忘録

pytrendsで取得したGoogle TrendsランキングをつぶやくTwitter botを作ってみる

ようやく帰ってきました。帰省中は全くブログを更新できず・・・
毎日食べて寝て2kgほど太ったのでこれからダイエットしないと。

Twitter botを作ってみる

Twitter botを作ってみます。もちろんPythonで。
運用はクラウドサービスを検討していましたが、よくよく考えてみたらraspberry piで良さそうです。

あ〜、zero w欲しいな〜

とりあえずライブラリをインストール

sudo pip install twitter

はい終了。

twitterbotpythonで作成

以下のサイトを参考にしました。
qiita.com

以下の情報をtwitter appから入手します。

Consumer Key(API Key)
Consumer Secret(API Secret)
Access Token
Access Token Secret

それでもってプログラムもたったこれだけ。

import twitter

auth = twitter.OAuth(consumer_key="xxxxx",
consumer_secret="xxxxx",
token="xxxxx",
token_secret="xxxxx")

t = twitter.Twitter(auth=auth)

status="Hello,World"
t.statuses.update(status=status) #Twitterに投稿

なんて簡単なんだ・・・

pytrendsと合体

pytrendsについては以下
www.blue-weblog.com
www.blue-weblog.com

合体!!

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import twitter
auth = twitter.OAuth(consumer_key="xxxxx",
consumer_secret="xxxxx",
token="xxxxx",
token_secret="xxxxx")

t = twitter.Twitter(auth=auth)

from pytrends.request import TrendReq
google_username = "xxxxx"
google_password = "xxxxx"
path = ""

pytrend = TrendReq(google_username, google_password, custom_useragent='My Pytrends Script', hl='utf-8', geo="jp")

trending_searches_df = pytrend.trending_searches()

data=""
for i in range(10):
    data+=str(i+1)+" "+trending_searches_df["title"][i]+"\n"

status= data
t.statuses.update(status=status)

そしてハマる・・・
raspberry piでpytrendをインストールしようとする以下のようなエラーが

Compile failed: command 'arm-linux-gnueabihf-gcc' failed with exit status 1
・・・
    ----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-MJfh_v/lxml/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-YRLNsB-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-MJfh_v/lxml/

何だこれ!
よくよく調べてみるとただライブラリが足りていないだけ。
ならそう書いてくれよ・・・
というわけで以下をインストールし、無事完了

sudo apt-get install libxslt1-dev 

twitterは文字数制限があるのでランキングは上位10位までを表示しています。

あとはCrontabで10分おきにつぶやくように設定して完了。
Cronは以前の監視カメラ作成の際にも使いました。
www.blue-weblog.com

完成したtwitterはこちらです。
※止めました

今日はここまで。

        • -

追記
同じ内容の連続投稿はダメらしい。
なのでランキングに変更がないと更新されなようです。