All Smash Bot

Back in 1999 a band called Smash Mouth released a song called All Star. The song was used, and rose to fame in, the 2001 film Shrek. As of 2016, the song got stuck in my head and wouldn’t go away – so naturally I made a twitter bot….

 The Idea

If I hadn’t met my friend I wouldn’t know where to start, luckily I DID MEET MY FRIEND and she knows how this works apparently. Handily in fact she wrote an article on her website that you can find here.

If you want to cheat and see the final product then you can see that at this link.

In essence I wanted a twitter account that would tweet a random lyric from the song every half hour. This is the adventure that follows

 The Code

Because a tutorial as such already exists for this, I’m not going to go into too much detail. I may touch on some things she omitted originally, however do not expect this to be a complete guide.

The first step in doing this is being able to pick a line from the song. In order to do this there where a number of options. I chose the one that would make the coding part the easiest; that is to get the lyrics and use some regex automation to format it into a python style list – one item is one line of the song, there are 50 in total. Then we pick a random number and return the nth item.

import random, tweepy, time

def getTweet():
 lyrics = ['Somebody once told me the world is gonna roll me' , 'I ain't...]
 return(lyrics[random.randrange(1, 50)])
Things to note:
  • You can note the imported packages are random, Tweepy and time. This code segment only uses the random package, the other two come in later.
  • Please note I also cut off the list there so it’s actually readable. If you want the full code it’s available on my git hub – see the link at the bottom of the article.
  • Another thing to note is that the range is 1 to 50 not 0 to 49; this is because python ignores the 0th index

Honestly this is where the new code ends. The rest of this code is about sending it to Twitter. If you are to need help with this I once again recommend NotAGoat’s blog (link at the top of the page). I will run through the code however quickly.

def get_api(cfg):
    auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
    auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
    return tweepy.API(auth)

This is the first chunk of standardised code and also the first that uses the Tweepy import. You don’t need to worry too much about what it does but for the sake of education I’ll explain anyway. It’s the bit that actually contacts twitter and gets a connection set-up. It uses a pretty standard system to check some keys. If you want to read more on this system I recommend looking into Twitters API and authentication systems.

Into out main function now we come across this:

def main():
    cfg = {
    "consumer_key"          : "",     #these have been removed for security reasons
    "consumer_secret"       : "",     #ensure you enter your correct tokens and keys
    "access_token"          : "",     #for the bot to work
    "access_token_secret"   : ""
    }
    api = get_api(cfg)

This is probably the most important bit of the program to actually get right as it’s the bit that contains the keys to make a secure connection to the Twitter API.

We simple define cfg (which stands for config or configuration) as a dictionary with the attributes consumer_key, consumer_secret, access_token, and access_token_secret. As these are the things that actually let you into the Twitter account I have removed these for obvious reasons; you should put your own in.

But COLON How do get thowes???£?”!

Shut up will you….

Firstly be logged into the account you want the bot to tweet to and go to THIS LINK.

There you can create an ‘app’ and generate the required keys and tokens. It’s pretty self-explanatory but if you need any help drop a comment, why don’t you. Now you have them throw them buggers into the quotes.

Now we have a connection being set up we need to add the code to actually send the tweet; not to mention actually call the GetTweet() function.

So carrying on in the function main()

     while True:
        try:
            finTweet = getTweet()
            status = api.update_status(status=finTweet)
        except:
             continue
        else:
            break
    time.sleep(3600)
    main()

This code may look a little messy and unorthodox at first. But let me reassure you, it is very much messy and unorthodox – but its a bodge that works and god damn it, Imma see it through.

Firstly we have a while loop that goes on forever. Inside of that we have a try with the break command in the success section. This means it will only break out of the while loop if the tweet is sent. If it fails and an exception is thrown, it runs the continue command. This carries on the code without leaving the while loop and so goes to compile a new tweet again.

Once the code is successful and the while loop is exited, the program waits half an hour (3600 seconds) and calls the main body again to start the process once more.

The final piece of code here is a standard ‘phrase’ to include in most python programs but I’ll include it regardless for sake of completeness.

It just runs the main body of the code.

if __name__ == "__main__":
    main()

Well, that’s all folks please feel free to fork my Git repo and so in links below!!!

GitHub Repo – https://github.com/cooltennis01/AllSmash_Bot
Final Project – https://twitter.com/AllSmash_Bot


Update I am at this point aware of the stack overflow issue in the code. See it as a challenge to make it work you’re welcome. Really you should be paying me for this….

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.