I will hold my hands up here and admit, I am not great at advertising my website on social media. When posting a new blog post it auto generates a link on some social media sites for me, but I rarely ever repost links especially for my older blog posts. Today I am hoping to fix this issue using my Raspberry Pi, Python and Twitter.
A while back I created a twitter bot using Python and automated it on a Raspberry Pi so that it would auto reply to tweets and tweet sensor readings. Then I used that Pi in a different project, and my Twitter bot (geektechstuff_a) went into hibernation for over a year.
At the beginning of the UK’s Covid-19 #stayathome I started to look at projects on my site and projects I had noted down to do (since December 2019 this list keeps growing). One of which was to bring the geektechstuff_a Twitter bot back, but in a new way. My amazing wife had the idea of using the bot to post links to the geektechstuff.com website, so I have taken a break from learning C++ and decide to implement her idea.
The files and code for this project (minus my Twitter keys) are available at: https://github.com/geektechdude/python_geektechstuff_link_tweeter
This project is made up of three files:
The Python file with the code to open links.csv, randomly choose a line and then Tweet it.
A CSV file containing a line for each link I want to share. These lines are made up of a description, URL and a hashtag I want use on the tweet.
My auth / secret keys for Twitter. These should be kept secret, so I place them in a separate file and have main.py import them.
#!/usr/bin/python3 # geektechstuff Python Link Tweeter # libraries to import import random from twython import Twython # auth file contains all the Twitter details for account from auth import ( consumer_key, consumer_secret, access_token, access_token_secret ) # setting up Twitter twitter = Twython( consumer_key, consumer_secret, access_token, access_token_secret ) def random_line(filename): lines = open(filename).read().splitlines() return random.choice(lines) def tweet_to_send(): tweet_to_send = random_line('path_to_file') tweet_to_send_str = str(tweet_to_send) twitter.update_status(status=tweet_to_send_str) return() tweet_to_send()
I wont post all of links.csv (it’ll fill most of this post with links), instead here is a screen shot:
Scheduling Tweets With Cron
I am using cron on my Raspberry Pi to schedule the tweets, so cron will run the program daily. To access cron use the command:
Cron expects the minute, hour, date of month, month, day of week and then the command to run.
0 9 * * * python3 /path_to_program/program.py
This will use Python3 to run program.py daily at 9am. I’ve not decided what time is best for the tweets yet and may tweak this.