Find Random Things to do when You are Bored (with Twitter & Python!!)

What is this about?

This article talks about how to build a bot, and integrate with the BoredAPI as well as Twitter (using Python).

What do we need

We need to create a Twitter developer account at developer.twitter.com/en. Then safely copy the consumer key, consumer secret, access token, and access token secret from the account dashboard.

Start coding

Install packages

We install the required packages using pip

pip install requests
pip install tweepy

Connect to Twitter

We put all our keys in a secrets.json file in the following format

{
    "consumer_key": "YOUR_CONSUMER_KEY",
    "consumer_secret": "YOUR_CONSUMER_SECRET",
    "access_token": "YOUR_ACCESS_TOKEN",
    "access_token_secret": "YOUR_ACCESS_TOKEN_SECRET"
}

In our code, first we import some libraries

import json
import tweepy
import requests

We open up the json file and read in our keys

with open("secrets.json","r") as file:
    secrets = json.load(file)

consumer_key = secrets["consumer_key"]
consumer_secret = secrets["consumer_secret"]
access_token = secrets["access_token"]
access_token_secret = secrets["access_token_secret"]

Next we create a Tweepy client with the following lines of code

client = tweepy.Client(
    consumer_key=consumer_key, consumer_secret=consumer_secret,
    access_token=access_token, access_token_secret=access_token_secret
)

Get a random activity from BoredAPI

We can very easily request the API for a random activity

activity = requests.get('https://www.boredapi.com/api/activity').json()['activity']

Construct the tweet and post

Using the tweepy client created earlier, we can post to twitter

tweet_text = "Cool Thing You Should Do Today" + "\n" + activity

# post the tweet using the Tweepy client
response = client.create_tweet(
    text=tweet_text
)

Example of a posted tweet

tweet screenshot

Conclusion

The account I created to post these tweets is here -> twitter.com/@new_to6

This is currently hosted on WayScript and is posting one tweet everyday.

If you have trouble with Tweepy, check out this page -> docs.tweepy.org/en/stable/examples.html

Warning: If you are pushing to GitHub, don't forget to add a .gitignore file and add secrets.json to it.

My GitHub repo can be found here. You can clone it and follow the README to get started.

Happy coding!