How do I pull tweets from a user timeline for specific covid related keyword on python?

Viewed 117

I want to retrieve At least 1000 tweets from a {user} timeline replies included ● At least 100 tweets of the 1000 tweets are related to Covid-19 keyword like ["covid19", "wuhan", "mask", "lockdown", "quarantine", "sars-cov-2"] etc.

I wrote the function to retrieve the tweets:

def get_tweets_by_user(self, screen_name):
        '''
        Use user_timeline api to fetch POI related tweets, some postprocessing may be required.
        :return: List
        '''

        result = []

        tweets = api.user_timeline(screen_name=screen_name, 
                           # 200 is the maximum allowed count
                           count=200,
                           include_rts = True,
                           # Necessary to keep full_text 
                           # otherwise only the first 140 words are extracted
                           tweet_mode = 'extended'
                           )
        
        for tw in tweets:
            result.append(tw)

        return result

Now how do I retrieve 100 tweets related to covid-19 keywords from user timeline?

1 Answers

Register for Twitter developer API. You'll need a couple consumer keys. Tell them you're a student.

import requests as re
import json
import twitter # install this library to work with twitter dev.

consumer_key = "your key"
consumer_secret = "your key"
access_token = "your key"
access_token_secret = "your key"

api = twitter.Api(consumer_key=yourkey,
                  consumer_secret=yoursecret,
                  access_token_key=youraccesstoken,
                  access_token_secret=yourtokensecret)
FILTER = ["covid-19 string here"] # PUT YOUR COVID 19 STRING HERE
LANGUAGES = ['en']
store_file = "outputfileforcovidtweets.txt"
_location = ["put coordinates here"]
def main():
    with open(store_file, 'a') as z:
        for line in api.GetStreamFilter(track=FILTER, languages=LANGUAGES, locations=_location):
            z.write(json.dumps(line))
            z.write('\n')
            
main()

This will collect real-time tweets to your output file. :)

Related