【发布时间】:2020-06-09 23:30:12
【问题描述】:
我正在尝试构建一个 Twitter 机器人,它根据给定的关键字列表来传输推文。
在使用 Twitter 设置身份验证时,我已将 wait_on_rate_limit 和 wait_on_rate_limit_notify 指定为 True,如下面的代码中所述。
tweepy.API(self.auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True)
但是,当使用此身份验证凭据从 Tweepy 启动流时,它会将 wait_on_rate_limit 和 wait_on_rate_limit_notify 的值重置为 False。
print(f'Twitter API Client Retry and Wait :',api.api.wait_on_rate_limit)
print(f'Streaming Class Retry and Wait :',myStreamListener.api.wait_on_rate_limit)
print(f'Stream Object Retry and Wait :',myStream.api.wait_on_rate_limit)
Twitter API Client Retry and Wait : True
Streaming Class Retry and Wait : False
Stream Object Retry and Wait : False
如何将这些选项从 Tweepy.stream 设置为 True?
完整代码:
#import re
import tweepy
from tweepy import OAuthHandler
#from textblob import TextBlob
# creating object of TwitterClient Class
class TwitterClient(object):
'''
Generic Twitter Class
'''
def __init__(self):
'''
Class constructor or initialization method.
'''
# keys and tokens from the Twitter Dev Console
consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
# attempt authentication
try:
# create OAuthHandler object
self.auth = OAuthHandler(consumer_key, consumer_secret)
# set access token and secret
self.auth.set_access_token(access_token, access_token_secret)
# create tweepy API object to fetch tweets
self.api = tweepy.API(self.auth,wait_on_rate_limit=True,
wait_on_rate_limit_notify=True)
except:
print("Error: Authentication Failed")
# Streaming Class
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
print(status.user.screen_name)
print('--------------------------------------------------------------')
print(status.text)
print('--------------------------------------------------------------')
def on_error(self, status):
print (status)
# Twitter Client API Auth
api = TwitterClient()
# Initialize Streaming Object
myStreamListener = MyStreamListener()
# Establish a Stream With API and Streaming Object
myStream = tweepy.Stream(auth = api.auth,tweet_mode="extended",
include_rts=False ,listener=myStreamListener)
# Stream Tweets Based on Key Words
myStream.filter(track=['CAA NRC India'], is_async=True)
print(f'Twitter API Client Retry and Wait :',api.api.wait_on_rate_limit)
print(f'Streaming Class Retry and Wait :',myStreamListener.api.wait_on_rate_limit)
print(f'Stream Object Retry and Wait :',myStream.api.wait_on_rate_limit)
myStream.running = False
Twitter API Client Retry and Wait : True
Streaming Class Retry and Wait : False
Stream Object Retry and Wait : False
【问题讨论】:
标签: python twitter twitter-oauth tweepy