日記とか、工作記録とか

自分に書けることを何でも書いてゆきます。作った物、買ったもの、コンピュータ系の話題が多くなるかもしれません。

Raspberry pi 3 + Python = Twitter Botの起動(とりあえず投稿するところまで)

Raspberry piの良いところは常時起動しても電気代があまりかからないところです。Raspi 3になって消費電力はやや増えましたけれども、それでもスマホより少し少ないくらいなので、24時間稼働していても心が痛みません。

常時起動の良さを活かしてTwitterBotにしてみようということで、今回は起動部分を作ってみます。今回の作業はとっかかりのところだけですが、このくらいなら1時間ほどあればできるのでお手軽です。

Python Twitterモジュールのインストール

Twitterはユーザが凄く多いですから、自分で作らなくても配布されているものがたくさん見つかります。GitHubを探したらたくさんForkされているモジュールがあったので、これをお借りすることにしました。顔写真は作者さんなのでしょうか…… 熊……

github.com

インストールはsudo pipを使えば簡単です。

pi@pi3:~/twitter $ sudo pip install python-twitter
Collecting python-twitter
  Downloading python-twitter-3.1.tar.gz (80kB)
    100% |????????????????????????????????| 81kB 1.2MB/s
Collecting future (from python-twitter)
  Downloading future-0.15.2.tar.gz (1.6MB)
    100% |????????????????????????????????| 1.6MB 154kB/s
Requirement already satisfied (use --upgrade to upgrade): requests in /usr/lib/python2.7/dist-packages (from python-twitter)
Collecting requests-oauthlib (from python-twitter)
  Downloading requests_oauthlib-0.6.2-py2.py3-none-any.whl
Collecting oauthlib>=0.6.2 (from requests-oauthlib->python-twitter)
  Downloading oauthlib-1.1.2.tar.gz (111kB)
    100% |????????????????????????????????| 112kB 1.2MB/s
Building wheels for collected packages: python-twitter, future, oauthlib
  Running setup.py bdist_wheel for python-twitter ... done
  Stored in directory: /root/.cache/pip/wheels/22/1e/2e/506871fa7dc610616948e70812d5e2518cd89c13f757b98f6c
  Running setup.py bdist_wheel for future ... done
  Stored in directory: /root/.cache/pip/wheels/11/c5/d2/ad287de27d0f0d646f119dcffb921f4e63df128f28ab0a1bda
  Running setup.py bdist_wheel for oauthlib ... done
  Stored in directory: /root/.cache/pip/wheels/e6/be/43/e4a2ca8cb9c78fbd9b5b14b96cb7a5cc43f36bc11af5dfac5b
Successfully built python-twitter future oauthlib
Installing collected packages: future, oauthlib, requests-oauthlib, python-twitter
Successfully installed future-0.15.2 oauthlib-1.1.2 python-twitter-3.1 requests-oauthlib-0.6.2
You are using pip version 8.1.1, however version 8.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
pi@pi3:~/twitter $ pip install --upgrade pip
Collecting pip
  Downloading pip-8.1.2-py2.py3-none-any.whl (1.2MB)
    100% |????????????????????????????????| 1.2MB 201kB/s
Installing collected packages: pip
  Found existing installation: pip 8.1.1
    Uninstalling pip-8.1.1:
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 317, in run
    prefix=options.prefix_path,
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 726, in install
    requirement.uninstall(auto_confirm=True)
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 746, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/usr/lib/python2.7/shutil.py", line 303, in move
    os.unlink(src)
OSError: [Errno 13] 許可がありません: '/usr/bin/pip'
You are using pip version 8.1.1, however version 8.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
pi@pi3:~/twitter $ sudo pip install --upgrade pip
Collecting pip
  Downloading pip-8.1.2-py2.py3-none-any.whl (1.2MB)
    100% |????????????????????????????????| 1.2MB 201kB/s
Installing collected packages: pip
  Found existing installation: pip 8.1.1
    Uninstalling pip-8.1.1:
      Successfully uninstalled pip-8.1.1
Successfully installed pip-8.1.2
pi@pi3:~/twitter $

Exampleを入手するためにソースコードもclone

pipでインストールすると、exampleは含まれていません。exampleの入手や、今後の開発の目的でソースも入手しておきます。

pi@pi3:~/twitter $ git clone https://github.com/bear/python-twitter/
Cloning into 'python-twitter'...
remote: Counting objects: 2954, done.
remote: Total 2954 (delta 0), reused 0 (delta 0), pack-reused 2954
Receiving objects: 100% (2954/2954), 7.24 MiB | 1.36 MiB/s, done.
Resolving deltas: 100% (1873/1873), done.
Checking connectivity... done.
pi@pi3:~/twitter $

Twitterのアカウントに開発者登録する

さて、いまやろうとしていることは、既存のTwitter Botを利用者として使うということではなくて、自作の(とはいえソースのほとんどは借り物ですが)Botを動かそうということです。こういったときには、Twitter社に自分のプログラムを登録して、アクセス権をもらう必要があります。このため自分のTwitterアカウントを登録します。

dev.twitter.com

apps.twitter.com

私はこれまでTwitterアカウントに携帯電話の番号を登録していなかったのですが、開発者登録するときには必須となっていました。私のアカウントのうち、ほとんど使われていなかったWindVoice_enのほうにプログラムを登録しました。

twitter.com

開発者登録の方法は、上でソースをもらったbearさんのページに記載があるのでそれを参考にすればOKです。自分で作ろうとしているアプリケーションの名称、簡単な説明、アプリを登録しているURL(作成中の場合はとりあえず何でも埋めておけばいい(spaceholder)ようです)を記載すれば良いことになっています。

登録をすると、コンシューマーキー、コンシューマーシークレット、アクセストークン、アクセストークンシークレット、という4種類の鍵文字列がもらえます。これらは大事な情報なので他の人に知られてはいけません。パスワードに相当するものですね。以下の説明ではxで情報をつぶしてあります。

テストツイート

cloneしたソースコードのexample/tweet.pyがつぶやきを投稿するためのサンプルプログラムです。投稿したい文字列と一緒にアクセスキー4個を入力する必要があるのですが、長くて面倒なので、環境変数に登録してしまうことにしました。それができる機能がすでに織り込まれています。

pi@pi3:~/twitter/python-twitter/examples $ tail ~/.bashrc
fi

eval $(thefuck --alias)

# Env for Raspi3Bot
export TWEETUSERNAME=xxxxxxxxxxxxxxxxxxxxxxxxx
export TWEETPASSWORD=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
export TWEETACCESSKEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
export TWEETACCESSSECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

pi@pi3:~/twitter/python-twitter/examples $
pi@pi3:~/twitter/python-twitter/examples $ . ~/.bashrc

ホームディレクトリの.bascrcの末尾のところにこんな感じで4つの鍵を書いておきます(.bashrcはworld readableなので、アクセス権的に不安ですけど、このラズパイを使うのは私だけということで……)。これを記載したら、.bashrcを再読込させて、いよいよ投稿を試してみます。

pi@pi3:~/twitter/python-twitter/examples $ ./tweet.py "もう一度コメントに挑戦……"
WindVoice_en just posted: もう一度コメントに挑戦……
pi@pi3:~/twitter/python-twitter/examples $

念のため自分のタイムラインを確認すると確かに投稿されていました。

f:id:WindVoice:20160720115411p:plain

まとめ

とりあえず投稿するところまでいけましたが、目的はコマンドラインからつぶやくことではなくて、これで常時起動のBotを作ることでした。場当たり的ですがここからがアイディアの出し所ですね。過去の投稿と合わせればセンサーからの読み取り値をつぶやくなどはすぐできると思いますが、しかし公に知らせて楽しい物でもないかも…… どうしたものか少し考えます。

誰でもできるTwitter Botの作り方―人気キャラにつぶやかせる

誰でもできるTwitter Botの作り方―人気キャラにつぶやかせる