This article was translated to English, and was originally published for deviceplus.jp.
Welcome to part 2 of tweeting on Raspberry Pi with “Twython.”
Like last time, we’ll be following along the Raspberry Pi Official Site Document. We’ll be covering posts with random character strings, posts with images, and linking up a streaming API.
We’ll be using the 2017-11-29 release of “Raspbian Stretch with desktop” OS version with a “Raspberry Pi2 Model B” for this article.
For part 1, check out →”Tweet on Raspberry Pi via Twython! (Part 1)”
“Tweet random messages” on page 7 uses a “random” Python module and introduces a program for posting random messages.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
01 import random 02 03 from twython import Twython 04 05 from auth import ( 06 07 consumer_key, 08 consumer_secret, 09 access_token, 10 access_token_secret 11 ) 12 13 14 twitter = Twython( 15 consumer_key, 16 consumer_secret, 17 access_token, 18 access_token_secret 19 20 ) 21 22 23 24 messages = [ 25 "Hello world", 26 "Hi there", 27 "What's up?", 28 "How's it going?", "Have you been here before?", "Get a hair cut!", ] message = random.choice(messages) twitter.update_status(status=message) print("Tweeted: %s" % message) |
We then saved the file under the name “random_tweet.py” in the “/home/pi” directory.
The module called “auth” on line 3 is “auth.py” that we created last time. This module collects “Consumer Key (API Key),” “Consumer Secret (API Secret),” “Access Toke,” and “Access Token Secret ” all in one place. Next, let’s prepare it in the same directory as “random_tweet.py.”
auth.py
1 2 3 4 |
01 consumer_key = 'ABCDEFGHIJKLKMNOPQRSTUVWXYZ' 02 consumer_secret = '1234567890ABCDEFGHIJKLMNOPQRSTUVXYZ' 03 access_token = 'ZYXWVUTSRQPONMLKJIHFEDCBA' 04 access_token_secret = '0987654321ZYXWVUTSRQPONMLKJIHFEDCBA' |
*Replace each value with what you obtained with Twitter Apps.
Lines 2-15 are the same as the Twitter post program (twitter.py) we made at the end of the previous article.
Add “import random” into the first line to be able to use random numbers. On lines 17 to 24, we stored six messages in an array;
The output comes out as 「How’s it going?」. That’s the fourth stored character string of “messages” variable (array).
If we look at the actual post, we can confirm that it’s posted as 「How’s it going?」. Although it’s a random post, if the same character string is repeatedly posted, then an error from Twitter is going to come up. When that happens, give it a little bit of time before reposting and try not to post the same character string (For example, including the time and character string). That should solve things.
“Tweet a picture” on the 8th page outlines how to post a tweet with an image.
Before starting a program, let’s prepare a suitable image first. This time, we’ll be adjusting the document and preparing 「image.png」 onto 「 /home/pi/Downloads/ 」.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from twython import Twython from auth import ( consumer_key, consumer_secret, access_token, access_token_secret ) twitter = Twython( consumer_key, consumer_secret, access_token, access_token_secret ) message = "Hello world - here's a picture!" with open('/home/pi/Downloads/raspberry.png', 'rb') as photo: twitter.update_status_with_media(status=message, media=photo) print("Tweeted: %s" % message) |
Lines 17-18 will be changed. Instead of 「update_status」, 「update_status_with_media」will be posted.
This is what it’ll look like. Somehow, it’s displaying some warning text.
Looking up why this is showing up, it looks like it’s currently not recommended to use the 「update_status_with_media」function.
Although it’s not recommended, it looks like we were able to safely post the tweet. Speaking of which, that got us a little interested in this method. Look at the Twython Official Site Manual; we rewrote the program!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from twython import Twython from auth import ( consumer_key, consumer_secret, access_token, access_token_secret twitter = Twython( consumer_key, consumer_secret, access_token, access_token_secret message = "Hello world - here's a picture!" photo = open('/home/pi/Downloads/raspberry.png','rb') response = twitter.upload_media(media=photo) twitter.update_status(status=message, media_ids=[response['media_id']] print("Tweeted: %s" % message) |
Looking at the manual’s 「Updating Status with Image」 section, we changed the section about posting tweets.
For the 「update_status」function, just as we tried out adding the parameters of an image, we were able to post without an error coming up! (The tweet is the same as in Fig. 4)
The last thing we’ll cover is 「Test the Twython Streamer」on page 9!
Instead of “Posting” a tweet, this time we’ll “Obtain” a tweet that’s already been posted.
Looking at the sample in the document, the somewhat customized program source is here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
from twython import TwythonStreamer from auth import ( consumer_key, consumer_secret, access_token, access_token_secret class MyStreamer(TwythonStreamer): def on_success(self, data): if 'text' in data: username = data['user']['screen_name'] tweet = data['text'] date = data['created_at'] print("%s @%s: %s" % (date,username, tweet)) print("----------") stream = MyStreamer( consumer_key, consumer_secret, access_token, access_token_secret stream.statuses.filter(track='#raspberrypi') |
First off, line 1’s import text is different. Up until now, all the sample programs have been input under the “Twython” class, but at this spot, it’s been altered to “TwythonStreamer.”
Streaming message types — Twitter Developers
“TwythonStreamer” is a type of class used for streaming API on Twitter.
Streaming message types — Twitter Developers
On lines 9-16, classes called “MyStreamer” are declared. This is for appointing actions when tweets are found.
On the program source above, aside from the body text of the tweet, the date, account name, and separator line are all customized for output.
On lines 18-24, I created an instance for a new “MyStreamer” class, and started tracking only tweets that contained “# raspberrypi”.
If you find the tweet, the output will look like this. Until you stop the program, it’ll continue obtaining these types of tweets. (It looks like it doesn’t differentiate between large or small characters)
Searching for tweets with「#raspberrypi」
Next let’s access Twitter and check out the search results.
You’ll get somewhat of a time log, but I think that roughly confirms that you can obtain in real time.
That wraps up our 2nd part explaining how to use “Twython.” You’ll now be able to post and search on Twitter with relative ease!
I think that “Twython” with Python as a base is easy to introduce to any electronics that use parts. I thought “Twython” would be a good way to bridge the internal processing through the API and the part that’s outputted in a visible form. By posting photos you’ve taken, or by taking action when there’s a tweet about a specific keyword, you can make a wide variety of things coupled with everything you’ve learned now!