首页 > 解决方案 > 用 Python 编程的 Twitter 回复提及机器人工作一次,然后崩溃并出现错误 400:问题是什么?

问题描述

我一直在构建一个机器人,它完全按照预期工作,但仅限于一条推文。然后,它等待 60 秒,如果它没有找到要回复的新推文(因为它被配置为回复最近的推文),它会抛出一个错误(它是 400,如“400:错误的身份验证数据”,但我认为问题不在于,因为该机器人在 Twitter 上发布过一次没有任何问题。但是,我确实认为这可能是某种错误请求错误)。每当它崩溃时,我都可以在我的命令“python(botname).py”中运行,如果现在有新的推文,它会工作一次,但随后又会崩溃。我希望机器人能够自行正常运行,所以我非常感谢一些帮助!这是我文件中的代码:


#!/usr/bin/env python
# tweepy-bots/bots/autoreply.py


import tweepy
import logging
from config import create_api
import time
import re
from googlesearch import search
import sys
import io


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()


def check_mentions(api, since_id):

    logger.info("Collecting info")

    new_since_id = since_id

    for tweet in tweepy.Cursor(api.mentions_timeline,
        since_id=since_id).items():

        new_since_id = max(tweet.id, new_since_id)


        if tweet.in_reply_to_status_id is not None:
            in_reply_to_status_id = tweet.id
            status_id = tweet.in_reply_to_status_id
            tweet_u = api.get_status(status_id,tweet_mode='extended')

        logger.info(f"Answering to {tweet.user.name}")
        

        # remove words between 1 and 3
        shortword = re.compile(r'\W*\b\w{1,3}\b')

        keywords_search = str(shortword.sub('', tweet_u.full_text))

        print(keywords_search)

        if keywords_search is not None:

                mystring = search(keywords_search, num_results=500)
        else:
                mystring = search("error", num_results=1)

        print(mystring)

        output_info=[]
        for word in mystring:
                if "harvard" in word or "cornell" in word or "researchgate" in word or "yale" in word or "rutgers" in word or "caltech" in word or "upenn" in word or "princeton" in word or "columbia" in word or "journal" in word or "mit" in word or "stanford" in word or "gov" in word or "pubmed" in word or "theguardian" in word or "aaas" in word or "bbc" in word or "rice" in word or "ams" in word or "sciencemag" in word or "research" in word or "article" in word or "publication" in word or "nationalgeographic" in word or "ngenes" in word:
                                output_info.append(word)
                                infostringa = ' '.join(output_info)


        if output_info:
                output_info4 = output_info[:5]
                infostring = ' '.join(output_info4)
                print(infostring)
                status = "Hi there! This may be what you're looking for " + infostring
                len(status) <= 280
                api.update_status(status, in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=True)

        else:
                status = "Sorry, I cannot help you with that :(. You might want to try again with a distinctly sourced Tweet"
                api.update_status(status, in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=True)

        print(status)

        return new_since_id
    return check_mentions





def main():
    api = create_api()
    since_id = 1 #the last mention you have.
    while True:
        since_id = check_mentions(api, since_id)
        logger.info("Waiting...")
        time.sleep(60)

main()

我的配置模块:

# tweepy-bots/bots/config.py
import tweepy
import logging
import os

logger = logging.getLogger()

def create_api():
    consumer_key = os.getenv("CONSUMER_KEY")
    consumer_secret = os.getenv("CONSUMER_SECRET")
    access_token = os.getenv("ACCESS_TOKEN")
    access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True, 
        wait_on_rate_limit_notify=True)
    try:
        api.verify_credentials()
    except Exception as e:
        logger.error("Error creating API", exc_info=True)
        raise e
    logger.info("API created")
    return api

引发的错误:

Traceback (most recent call last):
  File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring32.py", line 92, in <module>
    main()
  File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring32.py", line 87, in main
    since_id = check_mentions(api, since_id)
  File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring32.py", line 26, in check_mentions
    for tweet in tweepy.Cursor(api.mentions_timeline, since_id=since_id).items():
  File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\cursor.py", line 51, in __next__
    return self.next()
  File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\cursor.py", line 243, in next
    self.current_page = self.page_iterator.next()
  File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\cursor.py", line 132, in next
    data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kwargs)
  File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py", line 253, in _call
    return method.execute()
  File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py", line 234, in execute
    raise TweepError(error_msg, resp, api_code=api_error_code)
tweepy.error.TweepError: Twitter error response: status code = 400

非常感谢!

标签: pythontwitterbotstweepy

解决方案


400 HTTP 错误状态代码通常意味着错误请求,这很可能是这里的情况。如果没有要回复的新推文,for则不进入循环,并check_mentions返回函数本身。然后,您将其设置为since_id返回时,并在下次check_mentions调用时将其用作 ID。这可能最终会将类似的东西传递"<function check_mentions at 0x0000028E6C729040>"给 API 作为since_id.


推荐阅读