【问题标题】:Tweepy Error response 400: can anyone tell what is wrong with my code?Tweepy 错误响应 400:谁能告诉我的代码有什么问题?
【发布时间】:2021-08-15 04:22:51
【问题描述】:

我正在尝试在 Python 中构建一个机器人,并且在修复了我的 Config 模块(其中定义了 create_api)之后,我在创建 API 之后执行代码时遇到了一些问题。由于错误的呈现方式,我猜它与check_mentions 的定义方式有关,但我想知道究竟是什么触发了这里的问题。我想知道是否有人可以检查代码的一般结构,并给我一个关于它缺少什么/如果在那里定义错误的线索。先感谢您!!! 这是目前的完整代码:

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()


api = tweepy.API

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')
        

        # 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))

        if keywords_search is not None:

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


        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:
                                output_info.append(word)
                                infostring = ' '.join(output_info)
                else:
                                infostring=None


        if infostring is not None:
                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=False)

        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=False)

        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)

if __name__ == "__main__":
    main()

配置如下(注意API在代码执行时有效地显示“创建”):

# 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

我已尝试按照我的定义打印内容,并且代码似乎总体上可以正常工作,但由于某种原因它最终无法在 Twitter 中执行。 完整的追溯在这里:

Traceback (most recent call last):
  File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring23.py", line 85, in <module>
    main()
  File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring23.py", line 80, in main
    since_id = check_mentions(api, since_id)
  File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring23.py", line 28, 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

我想我还应该提到我已经尝试将api.update_status() 更改为api.update_status(status=""),这是我在类似帖子中看到的,但不幸的是,这并没有解决我的问题。 再次感谢大家!!!!

【问题讨论】:

    标签: python twitter bots tweepy


    【解决方案1】:

    400 状态代码是来自 Twitter API 的错误请求错误:

    请求无效或无法以其他方式提供服务。随附的错误消息将进一步解释。未经身份验证或查询参数无效的请求被视为无效,并会产生此响应。

    https://developer.twitter.com/en/support/twitter-api/error-troubleshooting

    这可能是您的身份验证存在问题。如果没有看到create_api,就不可能确定确切的原因,但您应该检查您的凭据。

    【讨论】:

    • 嗨!谢谢,刚刚在原帖上加了create_api的代码!!
    猜你喜欢
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 2021-09-06
    • 2018-10-25
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2011-09-03
    相关资源
    最近更新 更多