A Simple Blog Post Tweeter
I continue on my journey to rebuild this blog’s traffic. One idea I had was to build a simple Python based blog post tweeter. I would select a blog post at random and then tweet it to my @neuralmarket Twitter account. I chose Python because of the Twython package. It made for a simple connection to my Twitter account and was easy to parse a text file.
The idea was this. I create a text file of all the blog posts I want to retweet - appended with a bit.ly link - and write a catchy tweet. I would then run the Python script to select at random a pre-written tweet from the text file. When I’m ready, I can cron job this script and run it once or twice a day. Over time I can add or delete pre-written tweets or try to optimize them for SEO.
I suggest that all my readers try this, it’s not hard and is simple to follow.
The Twitter Token
First you have to get a Twitter token. This allows you the Python script to post on your behalf and there are four bits of information you need. First visit dev.twitter.com and navigate to the application owner access token page. There you can learn on how to make a single application and generate the follow api values:
Access Token Secret
You’ll need these four items for the Python script below.
The text file
Next, create a simple text file (TXT extension) and put a single tweet per line. Make sure to add your blog post link. I use bit.ly to shorten my long URLs.
Here’s an example of my text file:
Autogenerate Blog Posts with .@Rapidminer http://bit.ly/1RRb0Hd A simple Stock Trend Following model in .@Rapidminer http://bit.ly/1UjDta0 What does Value really mean? For reals! http://bit.ly/1Y4PaaK What to expect from being a Sales Engineer at a Startup http://bit.ly/1Y4PR3A
Make sure to save this file in the same directory as your Python script. I keep all my scripts and files in a Dropbox folder so I can access it anywhere.
Now here’s the code. I’m going to “XXX” out my consumer and access keys, you’ll have to add your own from the first step above.
#!/usr/bin/env python import sys import os import random from twython import Twython, TwythonError CONSUMER_KEY = 'XXXXXXXXXXXXXXXXXXXXXX' CONSUMER_SECRET = 'XXXXXXXXXXXXXXXXXXXXXX' ACCESS_KEY = 'XXXXXXXXXXXXXXXXXXXXXX' ACCESS_SECRET = 'XXXXXXXXXXXXXXXXXXXXXX' #Use the following path structure for linux machine #f = open('/home/path/to/tweet.txt', 'r') #Use the following path structure for a windows machine f = open('C:\\path\\to\\tweet.txt', 'r') lines = f.readlines() f.close() post = random.choice(lines) api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) try: api.update_status(status="R2D2 says: " + post) except TwythonError as e: print e
It’s as simple as that. Just remember you need to install the Twython package and I wrote this script in Python v2.7. Any questions, just drop me a comment.Posted on 12/8/2016 #Twitter #Machine Learning