Twitter回复提到用Python编程的机器人工作过一次,然后崩溃并出现错误400:问题出在哪里



我一直在构建一个机器人,它完全按照预期工作,但只针对一条推文。然后,它等待60秒,如果它没有找到新的推文来回复(因为它被配置为回复最近的推文(,它就会抛出一个错误(它是400,就像"400:错误的身份验证数据"中一样,但我认为问题并不是这样,因为机器人在推特上发布了一次,没有任何问题。然而,我确实认为这可能是某种错误请求错误(。每当它崩溃的时候,我就可以按照我的命令运行"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*bw{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:UsersmariaOneDriveDocumentosLaraPythonFactualbotbotstring32.py", line 92, in <module>
main()
File "C:UsersmariaOneDriveDocumentosLaraPythonFactualbotbotstring32.py", line 87, in main
since_id = check_mentions(api, since_id)
File "C:UsersmariaOneDriveDocumentosLaraPythonFactualbotbotstring32.py", line 26, in check_mentions
for tweet in tweepy.Cursor(api.mentions_timeline, since_id=since_id).items():
File "C:UsersmariaAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagestweepycursor.py", line 51, in __next__
return self.next()
File "C:UsersmariaAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagestweepycursor.py", line 243, in next
self.current_page = self.page_iterator.next()
File "C:UsersmariaAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagestweepycursor.py", line 132, in next
data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kwargs)
File "C:UsersmariaAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagestweepybinder.py", line 253, in _call
return method.execute()
File "C:UsersmariaAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagestweepybinder.py", line 234, in execute
raise TweepError(error_msg, resp, api_code=api_error_code)
tweepy.error.TweepError: Twitter error response: status code = 400

非常感谢!

400 HTTP错误状态代码通常意味着错误请求,这里可能就是这种情况。当没有新的Tweet可回复时,不会输入for循环,并返回函数本身check_mentions。然后在返回时将其设置为since_id,并在下次调用check_mentions时将其用作ID。这可能最终会将类似"<function check_mentions at 0x0000028E6C729040>"的内容作为since_id传递给API。

最新更新