<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Naveen Singh</title>
    <description>The latest articles on DEV Community by Naveen Singh (@naveenslog).</description>
    <link>https://dev.to/naveenslog</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F190224%2Fee23e987-58a9-43a2-94cc-ca2c83d14210.jpeg</url>
      <title>DEV Community: Naveen Singh</title>
      <link>https://dev.to/naveenslog</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/naveenslog"/>
    <language>en</language>
    <item>
      <title>Twitter Bot in python</title>
      <dc:creator>Naveen Singh</dc:creator>
      <pubDate>Thu, 04 Jul 2019 04:24:33 +0000</pubDate>
      <link>https://dev.to/naveenslog/twitter-bot-in-python-1oph</link>
      <guid>https://dev.to/naveenslog/twitter-bot-in-python-1oph</guid>
      <description>&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fs3.amazonaws.com%2Fcom.twilio.prod.twilio-docs%2Fimages%2Ftwitter-python-logos.width-808.jpg" alt="TwitterBot"&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;em&gt;Pic credit &lt;a href="https://www.twilio.com" rel="noopener noreferrer"&gt;https://www.twilio.com&lt;/a&gt;&lt;/em&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Social media is full of bots today and twitter is one of the most bot friendly enviorment these days. In this article, we are building a bot to automate twitter tasks. This program can integrate with the Twitter platform, automatically posting, retweeting, liking, or following other users.&lt;/p&gt;

&lt;h3&gt;
  
  
  How to make a Twitter bot
&lt;/h3&gt;

&lt;p&gt;To create a Twitter bot we'll be using tweetpy. It manages the Twitter API calls and provides a simple interface to work with. We can post tweet, like tweets and do much more with just a few lines of code. We can follow the bellow checklist to create our own bot&lt;/p&gt;

&lt;h4&gt;
  
  
  Bot Checklist
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;Make a task list for the bot&lt;/li&gt;
&lt;li&gt;Apply for a developer account &amp;amp; Create a Twitter app&lt;/li&gt;
&lt;li&gt;Authenticate&lt;/li&gt;
&lt;li&gt;Program the bot&lt;/li&gt;
&lt;li&gt;Deploy&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  1 Tasks for the bot
&lt;/h3&gt;

&lt;p&gt;This is going to be a very simple bot, we are adding the bellow functionality for now. later we can add more depending on the need&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Tweet chuck norris joke once a week&lt;/li&gt;
&lt;li&gt;Retweet posts if it contains a specific # tag&lt;/li&gt;
&lt;li&gt;Like tweets if it contains a specific # tag&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  2. Apply for a developer account
&lt;/h3&gt;

&lt;p&gt;First step is to get the credential from twitter.com, we can use this link &lt;a href="https://developer.twitter.com/apps" rel="noopener noreferrer"&gt;https://developer.twitter.com/apps&lt;/a&gt; to fill-in some basic details and create an app. Once done we can access Consumer Key (API Key) and the Consumer Secret (API Secret), both available from the Keys and Access Tokens which will be used to authenticate tweetpy session.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Authenticate
&lt;/h3&gt;

&lt;p&gt;This step involves little bit of coding. Once we have applied for a developer account and create a twitter app. we can obtain the Consumer key, Consumer secret, Access token and Access token secret from the &lt;strong&gt;Keys and tokens&lt;/strong&gt; tab.&lt;/p&gt;

&lt;p&gt;The code bellow will authenticate the API so that we can use the functionality. I am reading creadictials from a json file and using the credintials to authenticate the session but we can also save the credential in a form or string directly as mentioned on code comment&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import json 
import tweepy # !pip install tweepy
import requests # !pip install requests
from datetime import datetime as dt

## Reading creadictials from a json file
with open("localconfig.json", 'r') as config_file:
    config = json.load(config_file)
creds = config[0]['twitter']

## Saving credentials to a variable
consumer_key = creds['consumer_key']                    # or "your key xxxxxxxxxxxxx"
consumer_secret = creds['consumer_secret']              # or "your key xxxxxxxxxxxxx"
access_token = creds['access_token']                    # or "your key xxxxxxxxxxxxx"
access_token_secret = creds['access_token_secret']      # or " your key xxxxxxxxxxxxx"

## Authenticating
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

user = api.me()
print("Connected user {}".format(user.name)) ## Printing authentication status
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Connected user Naveen singh
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  4. Program the bot
&lt;/h3&gt;

&lt;p&gt;Now that we have all the credentials needed and our api is authenticated, we can write small functions to do a pirticular task. We can consolidate these functions to make our final bot&lt;/p&gt;
&lt;h5&gt;
  
  
  A function that takes text as input and tweets it
&lt;/h5&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Updating status update 
def update_status(text):
    try:
        api.update_status(text)
        print("Status updated sucessfully")
    except Exception as e:
        print("Error in update_status", str(e))

update_status("Hi, this is just a msg to test twitter bot")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  A Function that takes search query string as input searches for tweets with given query string and retweets it
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Like a post and retweet
def retweet_post(self, query):
    try:
        for tweet in tweepy.Cursor(self.api.search, q=query, rpp=100).items(10):
            tweet.retweet()
        print("Liked and favorated {}".tweet.text)
    except Exception as e:
        print("Error in like_and_retweet")

retweet_post("#100daysofcode")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  A Function that takes search query string as input searches for tweets with given query string and likes it
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Like a post and retweet
def like_tweet(self, query):
    try:
        for tweet in tweepy.Cursor(self.api.search, q=query, rpp=100).items(10):
            tweet.favorite()
        print("Liked and favorated {}".tweet.text)
    except Exception as e:
        print("Error in like_and_retweet")

like_tweet("#100daysofcode")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three basic functions are enough for now we can add more if required. I personally use only these 3 features most frequently but there is a lot we can do. A detailed documentation is available &lt;a href="http://docs.tweepy.org/en/v3.5.0/" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Full code Deployement
&lt;/h3&gt;

&lt;p&gt;Now we have understanding of the basing freatures, we can use this to create a program that can perform some scheduled tasks at a given time. This bot is going to perform the bellow tasks&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Post one chuck norris joke every saturday&lt;/li&gt;
&lt;li&gt;Retweet and like 10 posts every sunday&lt;/li&gt;
&lt;li&gt;Save the log of all activity in a json file&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We are going to use python schedule library for scheduling its a fairly simple library and makes it really easier to schedule tasks, for deployement I'll be using &lt;a href="https://pythonanywhere.com" rel="noopener noreferrer"&gt;https://pythonanywhere.com&lt;/a&gt; because it has a free plan and can be accessed from anywhere.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import tweepy
import requests

class TwitterAPI:

    def __init__(self):

        with open("localconfig.json", 'r') as config_file:
            config = json.load(config_file)
        creds = config[0]['twitter']

        consumer_key = creds['consumer_key']
        consumer_secret = creds['consumer_secret']
        access_token = creds['access_token']
        access_token_secret = creds['access_token_secret']

        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        self.api = tweepy.API(auth)

        user = self.api.me()
        print("Connected user {}".format(user.name))

    def get_chuck_joke(self):
        """ This function fetches a chuck norris joke from the internet """
        url = "http://api.icndb.com/jokes/random"
        jres = requests.get(url).json()
        return jres['value']['joke']

    def write_log(self, payload):
        """Creates a log of all the actions performed by the bot """
        try:
            with open("log.json", 'r') as log_file:
                data = json.load(log_file)
                data.append(payload[0])

            print("Saving logs")
            with open("log.json", 'w') as log_file:
                json.dump(data, log_file)

        except FileNotFoundError:
            print("Log file not found, writing new log")
            with open("log.json", 'w') as log_file:
                json.dump(payload, log_file)

    def like_and_retweet(self, query):
        try:
            with open("log.json", 'r') as log_file:
                data = json.load(log_file)
            last_id = max([i['id'] for i in data])
            for tweet in tweepy.Cursor(self.api.search, q=query, since_id=last_id).items():
                try:
                    tweet.retweet()
                    tweet.favorite()
                    print("Retweeted {} ".format(tweet.text))

                    ## Saving logs
                    tweet_id = tweet.id
                    text = tweet.text
                    payload = {
                        "id": tweet_id,
                        "type":"retweet",
                        "text":text,
                        "addedon": int(dt.strftime(dt.now(),"%s"))
                    }
                    write_log([payload])
                except Exception as e:
                    print(e)
                    continue
        except FileNotFoundError:
            for tweet in tweepy.Cursor(self.api.search, q=query, rpp=100).items(10):
                try:
                    tweet.retweet()
                    tweet.favorite()
                    print("Retweeted {} ".format(tweet.text))

                    ## Saving logs
                    tweet_id = tweet.id
                    text = tweet.text
                    payload = {
                        "id": tweet_id,
                        "type":"retweet",
                        "text":text,
                        "addedon": int(dt.strftime(dt.now(),"%s"))
                    }
                    write_log([payload])
                except TweepError as e:
                    print(e)
                    continue

    def update_status(self):
        """ This function tweets using the tweetpy API """
        try:
            joke = self.get_chuck_joke()
            joke = joke + " #TweetByBot"
            self.api.update_status(joke)
            with open("log.json", 'r') as log_file:
                data = json.load(log_file)
            tweet_id = [i for i in data if i['type'] == 'status_update']
            print(tweet_id)
            payload = {
                "id": len(tweet_id)+1,
                "type":"status_update",
                "text":text,
                "addedon": int(dt.strftime(dt.now(),"%s"))
            }
            write_log([payload])
        except Exception as e:
            print("Error in update_status", str(e))


import schedule # !pip install schedule
import time

twitter_api = TwitterAPI()    
schedule.every().saturday.do(twitter_api.update_status)
schedule.every().sunday.do(twitter_api.like_and_retweet, "#100DaysOfMLCode")

while True:
    schedule.run_pending()
    time.sleep(1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Connected user Naveen singh
Updating status
Tornados occur when Chuck Norris sneezes.#TweetByBot
Retwitting called
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Final Notes:
&lt;/h3&gt;

&lt;p&gt;We now have a working Twitter bot. We only have some basic features for now but we can add more features based on the requirements. We can also built some use cases to solve a specific need or do some basic ML tasks like sentiment analysis and other kind of text analysis. Full code repo is available on &lt;a href="https://github.com/naveenslog/twitter-bot" rel="noopener noreferrer"&gt;github&lt;/a&gt;. Feel free to check other sections and blog posts and leave a comment for any question or suggestion&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>twitterbot</category>
      <category>bot</category>
      <category>automation</category>
      <category>twitter</category>
    </item>
  </channel>
</rss>
