How to Make a Simple Twitter Bot

This is just a simple tutorial to get you started on making a basic twitter bot. Python is the easiest and fastest way to produce prototypes, I will be using some easy python libraries to interface with the twitter API. This tutorial will go over how to use the twitter stream class to create a responsive tweet bot.

 

Step 1. Get your app creds.

Once you are logged into the twitter account you plan on making into a bot, go to https://apps.twitter.com/. Here you will set up an app that gives you the credentials you need to securely access your account remotely. Go ahead and follow the instructions to set up the app (Name, Description, etc.). You will need to make sure you have an Access level for “read” and “write” privileges. Under the “keys and access token” tab you will generate the access tokens needed to communicate through the API.

What you need:
* Consumer Key (API Key)
* Consumer Secret (API Secret)
* Owner Name
* Owner ID #
* Access Token
* Access Token Secret

Step 2. Install Tweepy and Json

Using pip:
pip install tweepy
pip install json

Installing from source:
git clone https://github.com/tweepy/tweepy.git
cd tweepy
python setup.py install

Step 3. Save your creds in a config file.

Example: myconfig.cfg

[mytwitterbot]
consumerKey=1234abcd...
consumerSecret=1234abcd...
accessKey=1234abcd...
accessSecret=1234abcd…
ownerName=123...
ownerId=123…

Step 4. Use ConfigParser to load your creds.

import ConfigParser
import os

config = ConfigParser.ConfigParser()

#Get config file from the executing directory.
config.read(os.path.join(os.path.dir(__file__),“myconfig.cfg”))

CONSUMERKEY=config.get(‘mytwitterbot’,‘consumerKey’)
CONSUMERSECRET=config.get(‘mytwitterbot’, ‘consumerSecret’)
ACCRESSKEY=config.get(‘mytwitterbot’, ‘accessKey’)
ACCRESSSECRET=config.get(‘mytwitterbot’, ‘accessSecret’)
OWERNAME=config.get(‘mytwitterbot’, ‘ownerName’).
OWNERID=config.get(‘mytwitterbot’, ‘ownerId’)

Step 5. Setup the Streaming API

The StreamListener class returns a json data object. Below is an example:

{
  “contributors”: null,
  “coordinates”: null,
  “created_at”: “Mon Dec 19 20:33:40 +0000 2016”,
  “entities”: {
    “hashtags”: [],
    “symbols”: [],
    “urls”: [],
    “user_mentions”: [
      {
        “id”: 809176297511366656,
        “id_str”: “809176297511366656”,
        “indices”: [
          0,
          13
        ],
        “name”: “MalwareScore”,
        “screen_name”: “malwarescore”
      }
    ]
  },
  “favorite_count”: 0,
  “favorited”: false,
  “filter_level”: “low”,
  “geo”: null,
  “id”: 810946220252237824,
  “id_str”: “810946220252237824”,
  “in_reply_to_screen_name”: “malwarescore”,
  “in_reply_to_status_id”: null,
  “in_reply_to_status_id_str”: null,
  “in_reply_to_user_id”: 809176297511366656,
  “in_reply_to_user_id_str”: “809176297511366656”,
  “is_quote_status”: false,
  “lang”: “en”,
  “place”: null,
  “retweet_count”: 0,
  “retweeted”: false,
  “source”: “<a href=\”http://twitter.com/download/iphone\” rel=\”nofollow\”>Twitter for iPhone</a>”,
  “text”: “@malwarescore test”,
  “timestamp_ms”: “1482179620217”,
  “truncated”: false,
  “user”: {
    “contributors_enabled”: false,
    “created_at”: “Fri Feb 14 20:11:51 +0000 2014”,
    “default_profile”: false,
    “default_profile_image”: false,
    “description”: “Malware Research Unicorn @EndgameInc TRAPUNIT. My thoughts are my own.”,
    “favourites_count”: 3040,
    “follow_request_sent”: null,
    “followers_count”: 4778,
    “following”: null,
    “friends_count”: 416,
    “geo_enabled”: false,
    “id”: 2344060088,
    “id_str”: “2344060088”,
    “is_translator”: false,
    “lang”: “en”,
    “listed_count”: 129,
    “location”: “San Francisco, CA”,
    “name”: “Malware Unicorn”,
    “notifications”: null,
    “profile_background_color”: “000000”,
    “profile_background_image_url”: “http://abs.twimg.com/images/themes/theme1/bg.png”,
    “profile_background_image_url_https”: “https://abs.twimg.com/images/themes/theme1/bg.png”,
    “profile_background_tile”: false,
    “profile_banner_url”: “https://pbs.twimg.com/profile_banners/2344060088/1461183082”,
    “profile_image_url”: “http://pbs.twimg.com/profile_images/810125430606864384/XJuTjkav_normal.jpg”,
    “profile_image_url_https”: “https://pbs.twimg.com/profile_images/810125430606864384/XJuTjkav_normal.jpg”,
    “profile_link_color”: “9266CC”,
    “profile_sidebar_border_color”: “000000”,
    “profile_sidebar_fill_color”: “000000”,
    “profile_text_color”: “000000”,
    “profile_use_background_image”: false,
    “protected”: false,
    “screen_name”: “malwareunicorn”,
    “statuses_count”: 2353,
    “time_zone”: “Pacific Time (US & Canada)”,
    “url”: “http://amanda.secured.org”,
    “utc_offset”: -28800,
    “verified”: false
  }
}

 

Here is the code to add the Stream Listener:

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import API
from random import randint
auth = OAuthHandler(CONSUMERKEY, CONSUMERSECRET)
auth.set_access_token(ACCESSKEY, ACCESSSECRET)
api = API(auth)
class MyTwitterStream(StreamListener):
    def on_data(self, data):
       #short circuit if None
        if not data:
           return
        #make sure the string can be decoded
        try:
            tweet = json.loads(data.strip())
        except ValueError, e:
            return
        # Get the user id mention in the tweetand compare with account’s id
        from_self = tweet.get(‘user’,{}).get(‘id_str’,”) == OWNERID
        # We only care about other’s tweets
        if from_self:
            return
        tweetId = tweet.get(‘id_str’)
        screenName = tweet.get(‘user’,{}).get(‘screen_name’)
        tweetText = tweet.get(‘text’)
        #Choose any chatbot or function here to add your response.
        yourResponse = [“Hello There”,”Hi”,”Who cares?”]
        replyText = ‘@’ + screenName + ‘ ‘ + yourResponse[randint(0, len(yourResponse))]
        #check if repsonse is over 140 char
        if len(replyText) > 140:
            replyText = replyText[0:139] + ‘.’
        print(‘Tweet ID: ‘ + tweetId)
        print(‘From: ‘ + screenName)
        print(‘Tweet Text: ‘ + tweetText)
        print(‘Reply Text: ‘ + replyText)
        api.update_status(status=replyText, in_reply_to_status_id=tweetId)
    def on_error(self, status):
        print status
if __name__ == ‘__main__’:
    myTwitterSteam =  MyTwitterStream()
    twitterStream = Stream(auth=auth, listener=myTwitterSteam())
    twitterStream.userstream(_with=’user’)


Once you run the python program it will continue to listen for changes in your twitter stream. You can simply kill the program or create a graceful shut down for your python script.

$python mytwitterbot.py


If you want to get fancy such as following other twitter profiles or monitoring key words, the Tweepy API reference docs provide many options. Keep in mind that these search API’s are limited to your twitter usage rates. If you reach your rate limit it will return a RateLimitError.

Have fun!