How to, Programming

How To Create A Twitter Bot Using Python Which Replies Back With Pictures

twitter bot

Twitter bot replying with photo comment

In this article, I will guide you to build your own Twitter bot which you can use for different purposes as you wish. There are lots of articles about the Twitter bot that can perform the simple task of retweeting or favoriting a post. Very few have covered how to auto-reply with text/image. When Tweepy detects a user’s post with a certain keyword. For eg., our bot will reply with pictures/text when it senses a tweet with a tag #inspirationalquotes on it. So let’s start building!

First of all, you need to download tweepy. You can do this by using pip package manager

$ pip install tweepy

Now you have to import following packages

import tweepy as tp
import time
import os
import random

Next, we have to create Twitter credentials because we have to link our Twitter account with the python script. Creating credentials is quite an easy process. You can create yours from here: https://developer.twitter.com/en . If you need an entire article on how to create Twitter credentials let me know in the comment section.

You will get your own credentials like this:

twitter developer credentials
Fig: Credentials
print('this is my twitter bot', flush=True) #prints on your terminal

Now you have to input all the credentials you just generated below.

Credentials of Twitter

# credentials to login to twitter api
consumer_key = ''
consumer_secret = ''
access_token = ''
access_secret = ''

Now authenticate your account with tweepy.

# login to twitter account api
auth = tp.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tp.API(auth)

This is all standard and you have to do exactly like this for all the Twitter bot project.

Now you have to create a .txt file with file name last_seen_id.txt

FILE_NAME = 'last_seen_id.txt'
print(os.getcwd()) 
#Python method getcwd() returns current working directory of a process

Then lets store and retrieve the last seen id to our file by the following code. The idea for doing this is to check all the mentions with #inspirationalquote and avoid replying back to the same user again and again.

Here we are retrieving the last seen id.

def retrieve_last_seen_id(file_name):
    f_read = open(file_name, 'r')
    last_seen_id = int(f_read.read().strip())
    f_read.close()
    return last_seen_id

Here we are storing the last seen id.

def store_last_seen_id(last_seen_id, file_name):
    f_write = open(file_name, 'w')
    f_write.write(str(last_seen_id))
    f_write.close()
    return

Now let’s write a function to reply to the tweet:

def reply_to_tweets():
   print('retrieving and replying to tweets...', flush=True)   #this will be printed out on your terminal

    # DEV NOTE: use 1060651988453654528 for testing.
    last_seen_id = retrieve_last_seen_id(FILE_NAME)
    # NOTE: We need to use tweet_mode='extended' below to show
    # all full tweets (with full_text). Without it, long tweets
    # would be cut off.
    mentions = api.mentions_timeline(
                        last_seen_id,
                        tweet_mode='extended')   #this will retrieve all the mentions
for mention in reversed(mentions):  #the reason for doing this is to check the old tweet first
print(str(mention.id) + ' - ' + mention.full_text, flush=True)
        last_seen_id = mention.id
        store_last_seen_id(last_seen_id, FILE_NAME) #storing the last mention.id to our last_seen_id.txt file

Now let’s check all the tweets with #inspirationalquote if found one we will create a function to reply back with an inspirational quote picture.

if '#inspirationalquote' in mention.full_text.lower():
            print('found #inspirationalquote!', flush=True)
            print('responding back...', flush=True)
            sn = mention.user.screen_name
            stat = "@" + sn + " Have a nice day "
            os.chdir('C:\\Users\\santosh\\PycharmProjects\\first_project\\quotes')	  #here you have to give proper directory to your folder which contains inspiration quote pictures
            model_image = random.choice(os.listdir('.'))      #C:\Users\santosh\PycharmProjects\first_project\quotes   #replying back with random pic
            api.update_with_media(model_image, stat, mention.id)

while True:
	    reply_to_tweets()
            time.sleep(15) #this bot checks for new mentions in every 15 seconds.

That’s it now you have your own Twitter bot. You can also deploy your bot on pythonanywhere and your bot will function 24 hrs a day. If this article was helpful you can follow the writer as well here: https://github.com/SantoshAcharya1200

Full Code:

import tweepy as tp
import time
import os
import random

print('this is my twitter bot', flush=True)

# credentials to login to twitter api
consumer_key = ''
consumer_secret = ''
access_token = ''
access_secret = ''

# login to twitter account api
auth = tp.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tp.API(auth)

FILE_NAME = 'last_seen_id.txt'
print(os.getcwd())



def retrieve_last_seen_id(file_name):
    f_read = open(file_name, 'r')
    last_seen_id = int(f_read.read().strip())
    f_read.close()
    return last_seen_id


def store_last_seen_id(last_seen_id, file_name):
    f_write = open(file_name, 'w')
    f_write.write(str(last_seen_id))
    f_write.close()
    return


def reply_to_tweets():
    print('retrieving and replying to tweets...', flush=True)

    # DEV NOTE: use 1060651988453654528 for testing.
    last_seen_id = retrieve_last_seen_id(FILE_NAME)
    # NOTE: We need to use tweet_mode='extended' below to show
    # all full tweets (with full_text). Without it, long tweets
    # would be cut off.
    mentions = api.mentions_timeline(
                        last_seen_id,
                        tweet_mode='extended')
    for mention in reversed(mentions):
        print(str(mention.id) + ' - ' + mention.full_text, flush=True)
        last_seen_id = mention.id
        store_last_seen_id(last_seen_id, FILE_NAME)

        if '#inspirationalquote' in mention.full_text.lower():
            print('found #inspirationalquote!', flush=True)
            print('responding back...', flush=True)
            sn = mention.user.screen_name
            stat = "@" + sn + " Have a nice day "
            os.chdir('C:\\Users\\santosh\\PycharmProjects\\first_project\\quotes')
            model_image = random.choice(os.listdir('.'))      #C:\Users\santosh\PycharmProjects\first_project\quotes
            api.update_with_media(model_image, stat, mention.id)


while True:
    reply_to_tweets()
    time.sleep(15)

Demo:

Twitter bot
Twitter bot up and running.

Also check out: How to download images from website using python !

Spread the love

Leave a Reply