How to fix "TypeError: StreamingClient.add_rules() missing 1 required positional argument: 'add'"

Viewed 20

I'm trying to use tweepy to stream tweets and print the tweet body. When I run my code I get the following error:

TypeError: StreamingClient.add_rules() missing 1 required positional argument: 'add'

I've been reading the documentation and as far as I can tell I'm using the right syntax. The tweepy documentation uses this as an example of adding rules:

streaming_client.add_rules(tweepy.StreamRule("Tweepy"))
streaming_client.filter()

My code is as follows:

from multiprocessing.connection import Listener
import tweepy
from dotenv import load_dotenv
import os

load_dotenv()

# twitter api consumer key, consumer secret, access token, access secret.
btoken=os.getenv('btoken')

streamingClient = tweepy.StreamingClient(f"{btoken}")

class client(tweepy.StreamingClient):
    
    def on_data(self, data):
        print(data.text)
        return(True)

    def on_error(self, status):
        print(status)
        # Stops stream if rate limit is reached (status code 420)
        if status == 420:
            return False
        if status == 401:
            print("Authentication Error")
            return False

# Placeholder tracking keyword
trackKey = "walmart"
    
rule = tweepy.StreamRule((f"{trackKey} lang:en -is:retweet place_country:US"))

client.add_rules(rule)

client.filter

I'm using tweepy v4.10.1 Any help would be greatly appreciated and thanks in advance.

1 Answers

The error is because, after declaring the class client, you hadn't created an object of this class, but attempted to call the method (inherited by this class from the class tweepy.StreamingClient) directly.
Normally class methods receive at least one argument: the object of the class, which is usually called self. This argument is usually passed automatically if the method is called like this objectName.method(). In this example, objectName is passed to the method method() as an argument self. But since you call this method not from an object of the class, but from the class itself, no first argument self is passed automatically. So the method believes that rule is that object of the class tweepy.StreamingClient (but hadn't had enough time yet to verify that and trigger a separate error) and complains about not receiving the second argument add.

Related