如何防止Tweepy Twitter机器人超过Twitter的速率限制?

时间:2019-04-02 19:36:23

标签: python tweepy

我很难阻止我的Twitter机器人超过Twitter的速率限制,并且想知道我是否可以帮助实现解决此问题的方法。

Tweepy的API和许多Google搜索建议使用函数“ def limit_handled(cursor)”来限制它。

# Prevents sending too many requests to Twitter's servers
def limit_handled(cursor):
    while True:
        try:
            yield cursor.next()
        except tweepy.RateLimitError:
            time.sleep(15 * 60)

所以我决定通过更改来实现这一目标

search_results = api.search(q="#henny",count=10000,
                           lang="en",
                           since_id=last_seen_id,tweet_mode='extended')

search_results = limit_handled(tweepy.Cursor(api.search,q="#henny",count=10000, 
                           lang="en", since_id=last_seen_id,tweet_mode='extended').items())

使用tweepy.Cursor似乎是使用'limit_handled'函数的唯一方法,因为该函数需要一个游标作为输入。此实现有两个问题:

1。)

我遇到此错误:

Traceback (most recent call last):
  File "henny_twitter_bot.py", line 39, in limit_handled
    yield cursor.next()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tweepy/cursor.py", line 197, in next
    self.current_page = self.page_iterator.next()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tweepy/cursor.py", line 134, in next
    raise StopIteration
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "henny_twitter_bot.py", line 84, in <module>
    respond_to_search(search_results, tweet_list)
  File "henny_twitter_bot.py", line 60, in respond_to_search
    for result in search_results:
RuntimeError: generator raised StopIteration

也许这个错误正是我想要的?当我以这种方式运行代码并登录到Twitter时,没有像我第一次运行该程序时没有考虑到速率限制的情况那样,收到关于我已向其服务器发送垃圾邮件的通知。

2。)

该程序似乎不再关注我的'last_seen_id'变量,这阻止了我的程序发送重复的响应。

这是我的代码:

CONSUMER_KEY = config.CONSUMER_KEY
CONSUMER_SECRET = config.CONSUMER_SECRET
ACCESS_KEY = config.ACCESS_KEY
ACCESS_SECRET = config.ACCESS_SECRET

# Twitter authorization
auth = tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth,wait_on_rate_limit = True)



FILE_NAME = 'last_seen_id.txt'

# Methods for updating the last seen tweet to prevent duplicate posts
def retrieve_last_seen_id(file_name):
    f_read = open(file_name, 'r')
    last_seen_id = int(f_read.read().strip())
    f_read.close()
    return last_seen_id

def store_last_seen_id(last_seen_id, file_name):
    f_write = open(file_name, 'w')
    f_write.write(str(last_seen_id))
    f_write.close()
    return

# Prevents sending too many requests to Twitter's servers
def limit_handled(cursor):
    while True:
        try:
            yield cursor.next()
        except tweepy.RateLimitError:
            time.sleep(15 * 60)

last_seen_id = retrieve_last_seen_id(FILE_NAME)


# Create list of tweets
tweet_list = []
tweet_list.append("Follow me for a free bottle of henny! Hit my DMs!")
tweet_list.append("Want a free bottle of henny?? Follow my account and shoot me a DM!")
tweet_list.append("Free bottle of henny to the next 50 people that follow me!")

# Search Twitter for tweets including keyword
search_results = api.search(q="#henny",count=10000,
                           lang="en",
                           since_id=last_seen_id,tweet_mode='extended')

def respond_to_search(search_results, tweet_list):

    # Loops through resulting tweets
    for result in reversed(search_results):

        # Chooses random tweet from list
        tweet = random.choice(tweet_list)

        # Prints 
        print(result.id)
        print("HENNY BOT INITIATED")

        # Posts resulting tweets and shows what the bot will tweet
        print("@" + result.user.screen_name + ": '" + result.full_text + "'")
        print("@TheDJHenny: '@" + result.user.screen_name + " " + tweet + "'\n")

        # Updated last_seen_id to prevent responding to the same tweet
        last_seen_id = result.id
        store_last_seen_id(last_seen_id, FILE_NAME)

        # Posts Tweet
        api.update_status('@' + result.user.screen_name + 
                            " " + random.choice(tweet_list), result.id)

    return None

# Runs function
respond_to_search(search_results, tweet_list)



如果有人可以帮助我解决这个问题,将不胜感激!我创建这个机器人的目的仅仅是出于教育目的。

0 个答案:

没有答案