DEV Community

Suhem Parack
Suhem Parack

Posted on

Getting COVID-19 Tweets using the Twitter API v2

In April 2020, Twitter launched the COVID-19 stream endpoint that enabled qualified developers & researchers to study the public conversation around COVID in real-time. This data can be obtained using the filtered stream endpoint in the Twitter API v2. In this tutorial, I will show you how to get COVID-19 related Tweets using the filtered stream endpoint in Python.

Note: In order to use the Twitter API v2, you need to apply for a developer account. To do so, simply visit t.co/signup and sign up for access. Once you have access to the Twitter API v2, you can connect an app to your project and get your bearer token that you will need to connect to the Twitter API v2 in order to get Tweets.

The filtered stream endpoint lets you filter for Tweets in real time based on the filters you set. In our case, we want all Tweets about the COVID-19 topic. For this, we will use the COVID-19 Tweet Annotation. Tweet Annotations provide contextual information about Tweets. So, if we want to filter for all Tweets about COVID-19 instead of using a filter like COVID OR COVID-19 OR COVID19 etc. we can use the context operator in our filter and use the value of the COVID-19 Tweet Annotation, which is 123.1220701888179359745. Thus, our search query or filter will be context:123.1220701888179359745. This will gives us all Tweets about COVID-19. An example of search terms that power this annotation can be found here.

In order work with the Twitter API v2 in Python, we will use the Tweepy package. To install it, you can running the following in your terminal:

pip3 install tweepy
Enter fullscreen mode Exit fullscreen mode

Once this package is installed, you can run the following script. Replace the BEARER_TOKEN with your own token.

import tweepy

class IDPrinter(tweepy.StreamingClient):

    # This will print the Tweet ID and Tweet text for each Tweet
    def on_tweet(self, tweet):
        print(tweet.id)
        print(tweet.text)

# Replace with your own bearer token below
printer = IDPrinter('BEARER_TOKEN')
# This is where we set our filter rule
printer.add_rules(tweepy.StreamRule("context:123.1220701888179359745"))
printer.filter()
Enter fullscreen mode Exit fullscreen mode

To learn about the common questions about Tweet Annotations, check out our FAQ section.

If you have any additional questions, feel free to DM me on Twitter

Top comments (0)