Quantcast
Channel: okahiro | Okahiro's Gadget Lab
Viewing all articles
Browse latest Browse all 40

ラズパイから自動で画像付きツイートをしてみた。(改)

$
0
0

cloud-709148_1280

今回は前回の記事で掲載したPythonコードを少しだけいじってみたので軽く紹介します。

前回記事:ラズパイから自動で画像付きツイートをしてみた。

あまり代わり映えしないのにわざわざ記事を立てるな!というお叱りの声もありそうですが、事前に謝っておきます。すみません。
一日一回定時に最新のブログ記事をツイートするというのが前回のコードの内容でした。ただ、折角新しい記事を公開したのにすぐにツイートされないというのもやきもきするので、15分に一回ブログをチェックして、更新されていればRaspberry Piから自動でツイートするようにしてみます。
以下がコードです。

#!/usr/bin/python
#coding: UTF-8
import os
import datetime
import settings
import lxml.html
import requests
from TwitterAPI import TwitterAPI

#Move to script file directory.
file_dir = os.path.abspath(os.path.dirname(__file__))
os.chdir(file_dir)

#Print current date and time.
d = datetime.datetime.today()
print(d)

#Read settings.py file.
api = TwitterAPI(settings.CONSUMER_KEY, settings.CONSUMER_SECRET, settings.ACCESS_TOKEN, settings.ACCESS_TOKEN_SECRET)

#Parse my blog site. Get the latest article's title and URLs.
target_url = 'http://www.okahiro.info/gd/'
target_html = requests.get(target_url).text
root = lxml.html.fromstring(target_html)
anchors = root.xpath('//a')
msg = anchors[6].text + anchors[6].attrib['href']
#print('msg:' + msg.encode('utf-8'))
images = root.xpath('//img')
img_url = images[0].attrib['src']

#Read last_post.txt
f = open('last_msg.txt', 'r')
last_msg = f.read()
#print('last_msg:' + last_msg)
f.close

#Download image.
def download(url):
    global file_name
    file_name = url.split("/")[-1]
    res = requests.get(url, stream = True)
    if res.status_code == 200:
        with open(file_name, 'wb') as file:
            for chunk in res.iter_content(chunk_size = 1024):
                file.write(chunk)

download(img_url)

#Upload image.
IMAGE_PATH =  file_dir + "/" + file_name
file = open(IMAGE_PATH, 'rb')
data = file.read()
r = api.request('media/upload', None, {'media' : data})
print('UPLOAD MEDIA SUCCESS' if r.status_code == 200 else 'UPLOAD MEDIA FAILURE')

#Remove uploaded local image file.
os.remove(IMAGE_PATH)

f = open('last_msg.txt', 'w')
#Force to Tweet, if time is about 8 o'clock. 
if d.hour == 8 and d.minute >= 0 and d.minute <=15:
    if r.status_code == 200:
        media_id = r.json()['media_id']
        r = api.request('statuses/update', {'status':msg, 'media_ids':media_id})
        print('status_code:' + str(r.status_code))
        print('UPDATE STATUS SUCCESS' if r.status_code == 200 else 'UPDATE STATUS FAILURE')
        f.write(msg.encode('utf-8'))
        f.close
else:
    #Tweet, if only article is updated. 
    if last_msg.decode('utf-8') == msg:
        print('POST IS NOT NEW. NO TWEET')
        f.write(last_msg)
        f.close
    else:
        if r.status_code == 200:
            media_id = r.json()['media_id']
            r = api.request('statuses/update', {'status':msg, 'media_ids':media_id})
            #r = api.request('statuses/update', {'status':msg})
            print('status_code:' + str(r.status_code))
            print('UPDATE STATUS SUCCESS' if r.status_code == 200 else 'UPDATE STATUS FAILURE')
            f.write(msg.encode('utf-8'))
            f.close

あまりエレガントではありませんね。自分でも恥ずかしいですが、もっと良いコードが書けるように反面教師としていただければ幸いです。

前回のツイート内容と新しいツイート内容を比較するために、前回のツイート内容を’last_msg.txt’という名前のテキストファイルに記録します。新規に作成する機能はないので、このファイル名で空のファイルで良いので作成しておいて下さい。

また、前回と同じくログファイルに標準出力を書き出していますが、15分に一回書き込まれるのでファイルが肥大化しそうですね…。それを避けたい場合は、74行目の’f.write(last_msg)’をコメントアウトするか削除して下さい。

このスクリプトの起動方法は前回記事を参考にしていただければと思います。ただし、cronの記載例だけ示します。これで15分に一回スクリプトが実行されます。

*/15 * * * * /usr/bin/python /home/pi/auto_tweet/auto_tweet_new.py >> /home/pi/auto_tweet/log.txt 2>&1

なお上記のスクリプトでは、たとえ記事が更新されていなくても朝8時頃には強制的に最新の記事についてツイートするようになっています。

以上簡単ですが、今日のところはこの辺で。☕️


Viewing all articles
Browse latest Browse all 40

Trending Articles