0
import tweepy
from tweepy.streaming import StreamingClient
from dotenv import load_dotenv
import os
import queue
import nlp_model
import time

load_dotenv()

api_key = os.getenv('API_KEY')
api_secret = os.getenv('API_KEY_SECRET')
bearer_token = os.getenv('BEARER_TOKEN')
access_token = os.getenv('ACCESS_TOKEN')
access_token_secret = os.getenv('ACCESS_TOKEN_SECRET')

client = tweepy.Client(bearer_token, api_key, api_secret, access_token, access_token_secret)

auth = tweepy.OAuth1UserHandler(api_key, api_secret, access_token, access_token_secret)
api = tweepy.API(auth)

class IDPrinter(tweepy.StreamingClient):

    def on_tweet(self, tweet):
        print(tweet.text)


printer = IDPrinter(bearer_token)
printer.add_rules(tweepy.StreamRule("python"))
printer.add_rules(tweepy.StreamRule("programming"))
printer.add_rules(tweepy.StreamRule("software"))
printer.filter()

Hello, I am using tweepy and this is my code. I want to filter the tweets, but the results are returned unfiltered. There are many things other than the subjects I want. Do you know, can you help?

I tried get filtered tweets but I just got unfiltered irrelevant tweet data

1 Answers1

0

Firstly, it seems that you're using the wrong class for creating your streaming client. Instead of tweepy.StreamingClient, you should use tweepy.Stream. The correct class to inherit from is tweepy.StreamListener, which provides the necessary methods for handling incoming tweets.

import tweepy
from tweepy.streaming import StreamListener
from dotenv import load_dotenv
import os

load_dotenv()

api_key = os.getenv('API_KEY')
api_secret = os.getenv('API_KEY_SECRET')
bearer_token = os.getenv('BEARER_TOKEN')
access_token = os.getenv('ACCESS_TOKEN')
access_token_secret = os.getenv('ACCESS_TOKEN_SECRET')

auth = tweepy.OAuthHandler(api_key, api_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

class TweetListener(StreamListener):
    def on_status(self, status):
        print(status.text)

stream_listener = TweetListener()
stream = tweepy.Stream(auth=api.auth, listener=stream_listener)
stream.filter(track=["python", "programming", "software"])

The TweetListener class inherits from tweepy.StreamListener and overrides the on_status method to handle incoming tweets. In this example, it simply prints the tweet text, but you can modify it to suit your needs.

The tweepy.Stream class is used to create a stream and initialize it with the authentication and listener.

The filter method is called on the stream object, with the track parameter set to a list of subjects you want to filter for. In this case, it includes "python", "programming", and "software". The stream will then receive and handle tweets that match these subjects.

thumbsup
  • 16
  • 2