Twitter is social media site which allows user to share their thoughts in 140 characters with features like retweet, reply and follow other users etc. Lets make a twitter bot that gets a random Chuck Norris quote from the free API and post it to your twitter timeline after every 1 minutes.

We will use the tweepy module in Python for authorization and posting tweet on twitter.



Install Tweepy:-

Installing the tweepy is so simple ,Put this command in the console.

[code]pip install –U tweepy[/code]



Creating a Twitter App.

First we need to create a Twitter Application, Navigate to http://apps.twitter.com/ and create an App.

Make sure it has read and write permission as given in below mentioned screenshot.

Getting the App Keys:

Navigate to the Keys and Access Tokens tab and note the following Keys.

1.Consumer Key (API Key)

2.Consumer Secret (API Secret)

3.Access Token

4.Access Token Secret

Authorization using twitter bot:

Create a Python file with Main function and paste the code(Enter your Keys values in place of xxxxx)

[python]consumer_secret=’xxxxx’

access_key=’xxxxxxx’

access_secret=’xxxxxx’

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

auth.set_access_token(access_key, access_secret)

api = tweepy.API(auth)

[/python]

Posting Random Joke on Timeline:

Now we are logged into twitter using our bot, Lets get the Chuck Norris random joke and post it to twitter.

[python]responeData = requests.get("http://api.icndb.com/jokes/random/?escape=javascript")

myStatusText = str(responeData.json()[‘value’][‘joke’])

api.update_status(status=myStatusText)[/python]

Lets call this function in every 1 minute and our simple twitter bot is ready.

In the next tutorial, We will use our bot to follow users, retweet and reply etc.

Full Code



[python]

import tweepy, sys, time

import requests

def tweetToTwitter():

consumer_key = ‘xxxxxx’

consumer_secret = ‘xxxxxx’

access_key = ‘xxxxx’

access_secret = ‘xxxxxxx’

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

auth.set_access_token(access_key, access_secret)

api = tweepy.API(auth)

responeData = requests.get("http://api.icndb.com/jokes/random/?escape=javascript")

myStatusText = str(responeData.json()[‘value’][‘joke’])

api.update_status(status=myStatusText)

def main():

print("Welcome to the TweetBot by ScrollTest.com")

while True:

tweetToTwitter()

time.sleep(60) #1 minute

if __name__ == "__main__":

main()

[/python]

Let me know your thoughts in comments. In next tutorial we will explore more about tweepy.