Skip to content

Instantly share code, notes, and snippets.

@GitMoIO
Created June 22, 2014 17:26
Show Gist options
  • Save GitMoIO/1df139390d465d9213d8 to your computer and use it in GitHub Desktop.
Save GitMoIO/1df139390d465d9213d8 to your computer and use it in GitHub Desktop.
Streaming data from Twitter using Tweepy
import tweepy
import json
# Authentication details. To obtain these visit dev.twitter.com
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
# This is the listener, resposible for receiving data
class StdOutListener(tweepy.StreamListener):
def on_data(self, data):
# Twitter returns data in JSON format - we need to decode it first
decoded = json.loads(data)
# Also, we convert UTF-8 to ASCII ignoring all bad characters sent by users
print '@%s: %s' % (decoded['user']['screen_name'], decoded['text'].encode('ascii', 'ignore'))
print ''
return True
def on_error(self, status):
print status
if __name__ == '__main__':
l = StdOutListener()
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
print "Showing all new tweets for #programming:"
# There are different kinds of streams: public stream, user stream, multi-user streams
# In this example follow #programming tag
# For more details refer to https://dev.twitter.com/docs/streaming-apis
stream = tweepy.Stream(auth, l)
stream.filter(track=['programming'])
@salahawk
Copy link

salahawk commented Jun 6, 2023


class TweetStream(tweepy.StreamingClient):
    def __init__(self, bearer_token):
        super().__init__(bearer_token)

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


class TwitterClient:
    client: TweetStream

    def __init__(self, bearer_token, user_ids):
        self.client = TweetStream(bearer_token)
        # Sets new rules
        # rules = [{"value": f"from:{user_id}", "tag": user_id} for user_id in user_ids]
        # self.client.add_rules(rules)
        print(self.client.bearer_token)

    def stream_tweets(self):
        self.client.sample()

Here's the code I tried using Bearer Token, but it shows the following error

image

Can you please help me with this? (I've confirmed bearer token several times and it works fine with other bots)

@salahawk
Copy link

salahawk commented Jun 6, 2023

i'm using

  • python 3.10.11
  • tweepy 4.14.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment