Introduction: Python Based Twitter Bot

This is a tutorial to create a simple, python based twitter bot. I will have code examples as well as an in-depth tutorial in how you can create and launch this bot. This is something that someone with python experience can absolutely do in a single day - maybe even an hour or two. I will be using Tweepy primarily.

Step 1: Step 1: Setup

This will be a windows only tutorial, as it's what I work with.

What you'll need:

  • Python - I personally recommend grabbing the latest version of python - python 3.6.4. Other python distributions may work with this in some ways but it's a good idea to just grab the latest version for the purpose of this tutorial.
  • Tweepy - Tweepy is the core framework you'll use for this bot, meaning it's super important and necessary. To download Tweepy, you'll need to use pip. If you're using the latest version of python, pop open your computer's terminal and type in "pip install tweepy". If you're having trouble with pip, head here.
  • Twitter account - well, obviously! You may be asking if you need to create a different type of account. The standard twitter account works.

Step 2: Step 2: Getting the Magic Numbers

The numbers you need

Twitter issues special numbers pertaining to the use of its API. If we want to create a bot, these numbers will be necessary.

  1. Create a twitter account.
  2. Visit Twitter app management.
  3. Create a new app.
  4. Click permissions and enable read and write.
  5. Click Keys and Access Tokens.
  6. Click "create my access token."
  7. Write Consumer Key, Consumer Secret, Access Token(Corresponds to Access Key - INCLUDE THE DASH), and Access Token Secret(corresponds to Access_Secret in the code) on a word document or on notepad for later. You'll need them.

Step 3: Step 3: Connecting to Twitter

Open up your IDE(IDLE or other)

Import

Import tweepy, time, datetime, and sys. Everything but tweepy should be included in python at the start. If datetime isn't, install it via pip. This will let us use all of the framework that we need as well as make the program time based. Time is actually super important for a program like this as we will be scheduling posts.

import tweepy, datetime, time, sys

Connecting to your new twitter account

Here's where the numbers that we got in the last step are going to come in handy.

CONSUMER_KEY = ''
CONSUMER_SECRET = '' ACCESS_KEY = '' ACCESS_SECRET = '' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth)

If you are wondering which numbers correspond to what variable, I listed that in the last step. Please make sure to include the single quotation marks when making your code. Just copy each value between the quotes.

Congrats, you're connected! Now what?

Run your code and make sure there are no errors. To run the code, open your command prompt and navigate to the folder where your code is stored. You can change directory one at a time by entering "cd directoryname" until you get there if you are unsure how. From there, simply type "python filename.py" and your code should run.

To actually achieve your tasks, go on to the next step!

Step 4: Step 4: Tweet Function

You can configure your program to tweet in many different ways. I prefer to do this in a pretty standard way - by making a function!

Tweet Function

Here is my function for making a tweet.

firsttweet = "first automated tweet" #string for later use

secondtweet = "second automated tweet" #string for later use

def tweetFun(phrase):
api.update_status(phrase) print("Tweet posted!") time.sleep(65)

tweetFun(firstphrase)

Let's break it down.

def tweetFun(phrase):

This is the function header. You'll call this with the piece of code right under the function. Phrase is a string that I made in my code that I'll specify when calling the function.

api.update_status(phrase)

This is the code that does the actual tweeting. It uses the phrase we specify in the call "tweetFun."

print("Tweet posted!")

This is the code that prints to the console. Nothing will happen on twitter, but you will be able to debug and view when things have been posted from your terminal if you print to it with statements like this.

time.sleep(65)

This uses the time function to make your program sleep for 65 seconds once you have tweeted. This value is up to your discretion, but I use it for time based scripts where I specify the the minute when something will be posted.the

tweetFun(firstphrase)

This is how we call the function. You can place this anywhere in your program and with any conditions you want. Note: if you tweet a duplicate tweet, your program will crash. There may also be limits on the amount of time between your tweets, so if that is the case, do not break it or your program will probably crash.

Step 5: Step 5: Retweet/Favorite Function

Now we're going to create a retweet and favorite function. I will only break down the parts of this function I did not break down in the last one.

Retweet Function

mvgleague = api.user_timeline(id = 'mvgleague', count = 1)

recentmvg = mvgleague[0].id

def retweetFun(tweetid):

api.retweet(tweetid) api.create_favorite(tweetid) print("Retweet posted") time.sleep(65)

retweetFun(recentmvg)

Here we go.

mvgleague = api.user_timeline(id = 'mvgleague', count = 1)

This first line assigns the account timeline of a twitter account to a variable. Basically, change "mvgleague" to the account name of any account you want. The account name is what follows the @ on twitter. This can be used to get more than one tweet as it stores them as an array. For this example we will only be getting and using the most recent tweet.

recentmvg = mvgleague[0].id

This line sets the variable to the specific tweet. The array starts at 0. This means that the tweet stored in this variable will be the most recent tweet.

api.retweet(tweetid)

This line does the retweeting.

api.create_favorite(tweetid)

This line does that favoriting.

retweetFun(recentmvg)

This line is the function call. Simply call the function with the value of the most recent tweet that we found at the start of above.

Step 6: Step 5: Using Time, Logic, and Loops

Here's where the time files come in. This is how you set up your bot to tweet, retweet, or favorite at certain times of day.

Time and date

now = datetime.datetime.now()

This is the function utilizing datetime to get a lot of information about - you guessed it - the current time and date. Let's see how this works.

print("Year: ")

print(now.year)

print("Month: ") print(now.month) print("Day: ") print(now.day) print("Week day: ") print(now.weekday) print("Hour: ") print(now.hour) print("Minute: ") print(now.minute)

Try running this code on top of what you already have or in a new script with datetime and time still imported. This will show you what each of these values is.

For reference, weekday -> mon-sun = 0-6, year = 2018(current), minute = 0-59(current), hour = 0-23(current, military time)

You will use these for your logical functions(if and else if) when making a tweet. Let's see this logic.

Logic

It's best to show an example of this.

recent2gg = 0

recentmvg = 0

while True:

today=datetime.date.today() dayofweek=today.weekday() now = datetime.datetime.now()

#monday

if now.weekday == 0: if now.month == 4 and now.date == 1 now.hour == 13 and now.minute == 1: twogg = api.user_timeline(id = '2GGaming',count = 1) if twogg[0].id != recent2gg: recent2gg = twogg[0].id retweetFun(recent2gg) elif now.hour == 16 and now.minute == 1: mvgleague = api.user_timeline(id = 'mvgleague', count = 1) if mvgleague[0].id != recentmvg: recentmvg = mvgleague[0].id retweetFun(recentmvg)

time.sleep(60)

From above we can see that this incorporates the previous function calls that we wrote, as well as some new logic and loops that I'll explain now.

if now.weekday == 0:

This is our logic for determining the day of the week. If now.weekday == 0, it's monday. This particular code will only execute if it is monday.

if now.month == 4 and now.date == 1 now.hour == 13 and now.minute == 1:

This is our logic for determining the particular time and date at which the retweet will happen. As you can see, this particular piece of logic specifies the month as 4(April), the date as 1(1st), the hour as 13(1 pm) and the minute as 1(retweet will happen at 1:01pm). I chose to use elif after this first statement for all of the future instances. I applied this to the weekday portion as well.

if twogg[0].id != recent2gg:

.

.

.

if mvgleague[0].id != recentmvg:

This is how I check that the old tweets are not duplicates. I set the value before doing the loop to run the program. In theory, if you run this program continuously, this will check for duplicates. However, if you continually edit the program and start it over, it may post duplicates. The tweepy framework may have information on how to deal with this in other ways, though.

Loops

I only used one loop for this program, but it may call for more depending on your purposes.

while True:

The while True: loop is a special one in that it will continuously run all of the code inside it until the end of time(or until you stop the program, or errors, or whatever). Place all the code that you want to run in this loop and you'll be good.

Step 7: Step 7: Final Thoughts and Final Code

This code is certainly a bit makeshift and a bit incomplete, but it does its job. I wrote this tutorial to explain some of the basic functions that you may want in a twitter bot without having to know anything about the tweepy documentation. That being said, you'll probably want to learn more once you're done with this and caught up with me, so here is the documentation.

Thoughts on more things to do

The tweepy framework allows you to do so much more, and here are some ideas.

  • Parse the tweets. Search through each tweet for hastags or for keywords and only retweet those tweets with the parameters that you want.
  • Follow. Follow people who post content your bot is related to.
  • Post videos and pictures.
  • Use beautifulsoup to parse other websites and make posts based on those websites.

Places to host your script

The most reliable is definitely your home PC but there are a couple of options that you may want to consider.

  • Paid hosting - a VPS can be used such as AWS. This will free up your home computer entirely, but costs a certain amount each month and is not easy to set up if you don't know what you're doing.
  • Pythonanywhere - this site can host your script. You will have to upload tweepy to the files as well as well as look up how to change the time zone of your console or use their time zone and it is prone to random shut downs. It is free on a limited basis however.
  • Heliohost - It seems like a good option but I found it difficult to set up, even using cgi. The instructions I found weren't clear and in the end I couldn't get it working. Let everyone know if you can.
  • Raspberry pi - you can definitely run scripts on a raspberry pi which is less power consumption and you're less likely to need to turn it off compared to a laptop or home PC.

Final code

I gave you pieces, but this code should work if you substitute in your own values. It's a slightly modified version of my original code with some things tweaked(only monday and tuesday included, uses a non-optimal day of the week system). I specified how to use a more optimal weekday system in the code

import tweepy, datetime, time, sys

CONSUMER_KEY = '1'#keep the quotes, replace this with your consumer key CONSUMER_SECRET = ''#keep the quotes, replace this with your consumer secret key ACCESS_KEY = ''#keep the quotes, replace this with your access token ACCESS_SECRET = ''#keep the quotes, replace this with your access token secret auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth)

#april month = 4 #minute = real minute #2:24 = 2 for hour

twogg = 0 recent = 0 recent2gg = 0 recentmvg = 0 recentesa = 0 recentvgbc = 0

msmphrase = "Tune in to MSM: https://www.twitch.tv/2ggaming" wnfphrase = "Tune in to WNF: https://www.twitch.tv/2ggaming" gomlphrase = "Tune into GOML Friday-Sunday: https://www.twitch.tv/evenmatchupgaming" momophrase = "Tune into MoMoCon Friday-Saturday: (no info yet)" combophrase = "Tune into Combo Breaker: (no stream announced yet)" snsphrase = "Tune into Smash and Splash 4: https://www.twitch.tv/gamershqtv" respawnphrase = "Tune in to Respawn 6: https://www.twitch.tv/geekygoonsquad" masonvsphrase = "Tune into Mason Vs - MR. E: https://www.twitch.tv/gmusmashbros" flatironphrase = "Tune into Flatiron 3 this weekend: https://www.twitch.tv/endgametv1" xanaduphrase = "Tune in to Xanadu for Smash Wii U: https://www.twitch.tv/vgbootcamp" fpfphrase = "Tune in to Falcon Punch Friday: https://www.twitch.tv/esasmash" collisionphrase = "Hyped for Collision today? Tune in starting at 12:00pm PST for Wii U doubles! https://www.twitch.tv/masterhandgaming #smash #collision" noodsphrase = "NOODS NOODS NOODS! Let's go! https://www.twitch.tv/esasmash #noodsnoodsnodds #smash " immortalphrase = "Immortal Tech ft. Marss, Light, and more! twitch.tv/claimtofameentertainment #smash #wiiu "

def tweetFun(phrase): api.update_status(phrase) print("Tweet posted!") time.sleep(65)

def retweetFun(accid): api.retweet(accid) api.create_favorite(accid) print("Retweet posted") time.sleep(65)

while True:

today=datetime.date.today() dayofweek=today.weekday() now = datetime.datetime.now()

#monday

if dayofweek == 0: if now.hour == 11 and now.minute == 1: twogg = api.user_timeline(id = '2GGaming',count = 1) if twogg[0].id != recent2gg: recent2gg = twogg[0].id retweetFun(recent2gg) elif now.hour == 12 and now.minute == 1: mvgleague = api.user_timeline(id = 'mvgleague', count = 1) if mvgleague[0].id != recentmvg: recentmvg = mvgleague[0].id retweetFun(recentmvg) elif now.hour == 13 and now.minute == 1: esasmash = api.user_timeline(id = 'ESA_Smash', count = 1) if esasmash[0].id != recentesa: recentesa = esasmash[0].id retweetFun(recentesa) elif now.hour == 14 and now.minute == 1: vgbc = api.user_timeline(id = 'VGBootCamp', count = 1) if vgbc[0].id != recentvgbc: recentvgbc = vgbc[0].id retweetFun(recentvgbc) else: time.sleep(55)

#tuesday if dayofweek == 1: if now.hour == 11 and now.minute == 1: twogg = api.user_timeline(id = '2GGaming',count = 1) if twogg[0].id != recent2gg: recent2gg = twogg[0].id retweetFun(recent2gg) elif now.hour == 12 and now.minute == 1: mvgleague = api.user_timeline(id = 'mvgleague', count = 1) if mvgleague[0].id != recentmvg: recentmvg = mvgleague[0].id retweetFun(recentmvg) elif now.hour == 13 and now.minute == 1: esasmash = api.user_timeline(id = 'ESA_Smash', count = 1) if esasmash[0].id != recentesa: recentesa = esasmash[0].id retweetFun(recentesa) elif now.hour == 14 and now.minute == 1: vgbc = api.user_timeline(id = 'VGBootCamp', count = 1) if vgbc[0].id != recentvgbc: recentvgbc = vgbc[0].id retweetFun(recentvgbc) else: time.sleep(55)

This is my script for a smash bros tournament tweeter. The rest is available on my github if you are interested.