How to collect Tweets in real time with tweepy in Python

Asked

Viewed 242 times

1

I am working on a project that consists of collecting the tweets posted here in Brazil, I am using the Twitter API and the tweepy library of Python, I can take the terms that are in trending Topics and do a search for them and collect their tweets, but I wanted to do it randomly and in real time. I can make collections in real time with the StreamListener but I don’t know how I do it to collect the tweets randomly. my code:

class MyStreamListener(tweepy.StreamListener):

    def on_status(self, status):
        print(status.text)


myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = autenticacao, listener=myStreamListener)
myStream.filter(track=['python'])

in the myStream.filter I specify what I want to search for, but I don’t want to do a specific search I want to collect the tweets that are being posted here in Brazil in real time. If anyone knows any way to do that it would help me a lot.

1 answer

1


Importing the tweepy:

import tweepy

Over screve tweepy.Streamlistener:

class MyStreamListener(tweepy.StreamListener):

    def on_status(self, status):
        print(status.text)

Credentials:

consumer_key = 'SUA_API_KEY'
consumer_secret = 'SUA_API_SECRET'

access_token = 'SEU_ACCESS_TOKEN'
access_token_secret = 'SEU_ACCESS_SECRET_TOKEN'

Creating the authentication:

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

Instantiating Mystreamlistener:

myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = auth, listener = myStreamListener)

Here you filter tweets by location:

location = [-73.5,-33.0,-34.7,4.9]
myStream.filter( locations= location)

Note: You must improve longitude and latitude to catch exactly from Brazil. I put only one example.

You can use this site to retrieve location data.

  • 1

    Vlw friend, you saved me here!

  • You have to draw around the map of Brazil that below it generates some coordinates.

  • 1

    I’m getting through

  • Do you know if it is possible to pass two locations?

  • 1

    Possibly yes, in the form of two different lists, for example: location = [[-73.5,-33.0,-34.7,4.9], [-76.5,-32.0,-32.7,2.9]]

  • 1

    I get it, thank you!

  • 1

    You’re welcome Renato! Hug!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.