LoginSignup
17
15

More than 5 years have passed since last update.

Raspberry Pi で撮影した写真を tweet する bot

Last updated at Posted at 2014-06-19

結論

いろいろはまりましたが、作ってみると30行ちょいの小さなスクリプトでできることがわかりました。小さくすんでいるのは tmhOAuth と raspistill のおかげだと思います
作ったファイルは github にも置きました https://github.com/UedaTakeyuki/RaspiTweetBotWithPicture

きっかけ

Raspberry Pi でヒヨコの監視をしているこの人のツイートを見て衝撃を受け、同じものをつくって見ようと思ったのがきっかけです。同じようなIoTネタについてもっとややこしい構成で考えていたのですが、単にツイートで良かったんだと...

やること

  1. raspistill で撮影した写真をupdate_with_media でツイートするスクリプトを作る
  2. それを cron に設定する

準備

以下の準備が必要です
1. カメラモジュールの設定
2. httpd と php の準備(私は nginx の設定でハマりました)
3. tmhOAuth の準備

この実装のフォルダ構成説明

以下のフォルダ構成を前提とした実装になっております

/usr/share/nginx/www -- nginx のデフォルトのまま
/usr/share/nginx/www/lib/tmhOAuth -- tmhOAuth
/usr/share/nginx/www/lib/140617 -- スクリプト類

スクリプト

twwt.php

<?php
// 参考にした記事
// tbot開発物語: http://blog.okumin.com/archives/twitter-bot-2
// tmhOAuth: http://www.softel.co.jp/blogs/tech/archives/3295

error_reporting(-1);
//error_reporting(0);

require_once '/usr/share/nginx/www/libs/tmhOAuth/tmhOAuth.php'; //sudo apt-get install php5-curl 必要
require_once 'config.php'; // CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET を定義しておく

$image = "/usr/share/nginx/www/140617/test.jpg";
#
# 写真を test.jpg に撮影
$output=shell_exec("raspistill -hf -vf -w 1000 -h 1000 -t 1000 -o $image");
echo "Output = ".$output; // * failed to open vchiq instance と出た時は sudo chmod a+rw /dev/vchiq

# 「tmhOAuth」クラスのインスタンスを作成
$tmhOAuth = new tmhOAuth(array(
            'consumer_key'    => CONSUMER_KEY,
            'consumer_secret' => CONSUMER_SECRET,
            'token'      => ACCESS_TOKEN,
            'secret'     => ACCESS_TOKEN_SECRET));
$code = $tmhOAuth->request('POST', $tmhOAuth->url('1.1/statuses/update_with_media'),
    array(
        'media[]'  => "@{$image}",
        'status'   => "さつまいも水耕栽培 by 水草エアレーション"
    ),
    true,
    true
);
if ($code == 200) {
    echo("投稿しました");
} else {
    print_r($tmhOAuth->response['response']);
}
?>

tweet.sh
/usr/bin/php /usr/share/nginx/www/140617/tweet.php
crontab
# 10分毎にツイート
*/10 * * * * /usr/share/nginx/www/140617/tweet.sh

はまったポイント

  1. nginx の php の設定にハマりました
  2. ファイルやフォルダの権限設定
  3. 実行パス、コマンドライン実行、php で web から実行、cron で実行のそれらで cwd がややこしいです。全部、フルパスで書きました
  4. RasPi の起動直後など、/dev/vchiq に権限がないことがあります

感想

動き出すまではハマりましたが、raspistill と tmhOAuth のおかげで小さいスクリプトで出来ることがわかりました。

参考にした記事

twitter bot をつくったのは初めてだったのですが、以下の記事を参考にさせていただいたおかげですぐに理解できました
http://blog.okumin.com/archives/twitter-bot-2
http://www.softel.co.jp/blogs/tech/archives/3295

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