Как настроить tweepy поток, чтобы получать только новые твиты? - PullRequest
0 голосов
/ 07 марта 2020

У меня есть программа, включающая отфильтрованный твип-поток, однако результаты, которые она возвращает, часто бывают твитами за несколько часов go, как я могу убедиться, что она получает живые твиты только в течение нескольких минут?

Есть достаточно новых твитов.

Вот мой код

import tweepy
from datetime import datetime
import pytz
import time

tz_AU = pytz.timezone('Australia/Sydney') 
datetime_AU = datetime.now(tz_AU)

class MyStreamListener(tweepy.StreamListener):
    def __init__(self, api):
        self.api = api
        self.me = api.me()


    def on_status(self, tweet):
        datetime_AU = datetime.now(tz_AU)
        if tweet.in_reply_to_status_id is not None or tweet.user.id == self.me.id:
            return
        try:
            status = api.show_friendship(source_id = api.me().id,target_id = tweet.user.id)
        except Exception as e:
            print(e)
        if status[0].following == False and status[1].following == False:
            doNotFollow = 0
            nofollow = [line.rstrip() for line in open("nofollow.txt")]
            for i in nofollow: 
                if(i == tweet.user.id):
                    doNotFollow = 1
                    print("{} | On no follow list\n".format(datetime_AU.strftime("%d/%m/%y %I:%M %p")))
            if doNotFollow == 0:
                try:
                    tweet.user.follow()
                    print("{0} | Followed user: {1}\n".format(datetime_AU.strftime("%d/%m/%y %I:%M %p"), tweet.user.name.encode('unicode-escape').decode('utf-8')))
                except Exception as e:
                    print("{0} | Follow error: {1}\n".format(datetime_AU.strftime("%d/%m/%y %I:%M %p"), e))
                time.sleep(60)
                try:
                    tweet.favorite()
                    print("{} | Liked Tweet\n".format(datetime_AU.strftime("%d/%m/%y %I:%M %p")))
                except Exception as e:
                    print("{0} | Like error: {1}\n".format(datetime_AU.strftime("%d/%m/%y %I:%M %p"), e))
                time.sleep(150)
        else:
            print("{} | Already following or follows us\n".format(datetime_AU.strftime("%d/%m/%y %I:%M %p")))


    def on_error(self, status):
        print("Error detected\n")

while 1 == 1:
    try:
        # Authenticate to Twitter
        auth = tweepy.OAuthHandler("SECRET", "SECRET")
        auth.set_access_token("SECRET", "SECRET")

        print("{} | Authenticated with twitter\n".format(datetime_AU.strftime("%d/%m/%y %I:%M %p")))

        # Create API object
        api = tweepy.API(auth, wait_on_rate_limit=True,
            wait_on_rate_limit_notify=True)

        tweets_listener = MyStreamListener(api)
        stream = tweepy.Stream(api.auth, tweets_listener)
        stream.filter(track=["#WritersLift", "#writerlift", "#writerlifts", "#writingcommunity"], languages=["en"])


    except Exception as e:
        print(e)

Любое руководство будет оценено.

Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...