March 8, 2017

Post Raspberry Pi status on Twitter

Goal

Tweet RPi (and CHIP) status with temperature, external IP, etc.

Environment

  • Raspbian Jessie Lite
  • Python 2.7

Prepare Twitter Account

A Twitter account is needed to publish the status, and set it to private unless you want to make postings public.
  1. Register Twitter account
  2. Log on to Twitter with the account.
  3. Go to https://twitter.com/settings/account
  4. Change setting in Privacy and safety, Email notification, 
  5. Go to https://apps.twitter.com/
  6. Create New App and get following:
    • Consumer Key (API key)
    • Consumer Secret (API Secret)
    • Access Token
    • Access Token Secret
From your regular Twitter account, follow above account.

RPi Commands

I want to get status on RPi on external IP and temperature.  This can be extended to tweet other information as well, but for now, that's what I want to get.

Getting Temperature:
$ cat /sys/class/thermal/thermal_zone0/temp
and divide this number by 1000, and that's celcius.

Get External IP:
There is a service -- try open this URL: http://ip.jsontest.com/

Just wrap all of these into Python with twitter module.


Python Code

Install "tweepy" python module: $ sudo pip install tweepy

Here is a tweepy example -- insert appropriate values in places of "######":

import tweepy

class TwitterAPI:
    def __init__(self):
        consumer_key = "######"
        consumer_secret = "######"
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        access_token = "######"
        access_token_secret = "######"
        auth.set_access_token(access_token, access_token_secret)
        self.api = tweepy.API(auth)

    def tweet(self, message):
        self.api.update_status(status=message)

if __name__ == "__main__":
    twitter = TwitterAPI()
    twitter.tweet("TEST")

Add it to start/stop level and crontab.

Full code is available at: https://github.com/keithkim/tweet-sys



No comments: