【问题标题】:Is my Tweepy stream to follow specific user's Tweets set up correctly?我的 Tweepy 流是否正确设置了关注特定用户的推文?
【发布时间】:2022-07-05 00:59:39
【问题描述】:

您好,我是 Python 的新手,我正在尝试编写代码来检测 Twitter 帐户何时使用 Tweepy 发帖,将 Tweet 的文本保存为变量,然后使用 PRAW 将 Tweet 发布到 subreddit。我在网上找到了一个代码,它将发布到指定的 subreddit 并且它确实有效,所以我只需要从 Tweepy 获取传入数据流。我尝试设置一个 stream.filter.follow(user_id) 并且没有收到错误消息,但它似乎没有连接到我为测试它而创建的 Twitter 帐户。当我发推文时,我没有看到它们出现在我的代码中,尽管我认为我已经将它设置为打印推文的 raw_data.full_text。这是我的代码,任何人都可以查看它是否有问题。我有所有的访问代码和我的开发者帐户,我从一个网站获得了我的 screen_id,我在其中输入了我的 @ 以获取一个数字 id。我已从代码中删除此敏感信息。

import time
import tweepy
import praw

#Variables that contains the credentials to access Twitter API and REDDIT
USERNAME = 
PASSWORD = 
CLIENT_ID = 
CLIENT_SECRET = 
consumer_key = 
consumer_secret = 
access_token = 
access_secret =

#Creating stream listener
class Listener(tweepy.Stream):
    
    def on_data(self, raw_data):
        self.proccess_data(raw_data)

        return True
    
    def process_data(self, raw_data):
        print("ID: {}".format(raw_data.id))
        print(raw_data.full_text)


    def on_error(self, status_code):
        if status_code ==420:
#return False if on_data disconnects the stream
            return False

#Twitter authentication
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)

api = tweepy.API(auth)
        
#Creating Stream
stream_tweet_listener = Listener(consumer_key, consumer_secret, access_token, access_secret)
stream_tweet = tweepy.Stream(consumer_key, consumer_secret, access_token, access_secret)

#auth = api.auth, listener = stream_tweet_listener

#stream tweets
screen_id = 
stream_tweet.filter(follow = screen_id)

【问题讨论】:

    标签: python twitter tweepy reddit praw


    【解决方案1】:

    您正在使用tweepy.Stream 的实例,默认情况下它只记录接收到的数据,而不是它的子类。

    【讨论】:

    • 感谢您在我的其他帖子中指导我!所以我不确定问题仍然在哪里?就像在尝试创建流时,它应该只是 Listener 而不是使用 tweepy.Stream ,因为那是我的子类(python noob 所以这可能没有意义)?
    • 是的,Listener 是您的子类,stream_tweet_listener 是您已初始化的子类的实例。
    【解决方案2】:
        PersonId = client.get_user(username="username").data.id
        class MyStream(tweepy.StreamingClient):
    
    def on_connect(self):
        print("Connected")
    
    def on_tweet(self, tweet):
    
        #if tweet.referenced_tweets == None: 
            print(tweet.text)
        if tweet.author_id == PersonId : 
            print(tweet.text)
    
        stream = MyStream(bearer_token=bearer_token)
        #Pay attention to bearer_token recently you must tou use it
    

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 2023-04-11
      • 1970-01-01
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      相关资源
      最近更新 更多