在 Python 中编程的 Twitter 回复提及机器人运行一次然后崩溃并出现错误 400:问题是什么?
Twitter reply-to-mentions bot programmed in Python works once and then crashes with error 400: what is the problem?
我一直在构建一个机器人,它完全按预期工作,但只针对一条推文。然后,它等待 60 秒,如果它没有找到要回复的新推文(因为它被配置为回复最新的推文),它会抛出一个错误(它是 400,如“400: Bad Authentication Data”,但我认为问题不在于此,因为 bot 在 Twitter 上发布过一次没有任何问题。但是,我确实认为这可能是某种 Bad Request 错误)。
每当它崩溃时,我都可以在我的命令“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
非常感谢!
400 HTTP 错误状态代码通常表示错误请求,这里很可能就是这种情况。当没有要回复的新推文时,不会进入 for
循环,并返回 check_mentions
函数本身。然后在返回时将其设置为 since_id
,并在下次调用 check_mentions
时将其用作 ID。这可能最终将类似 "<function check_mentions at 0x0000028E6C729040>"
的内容传递给 API 作为 since_id
.
我一直在构建一个机器人,它完全按预期工作,但只针对一条推文。然后,它等待 60 秒,如果它没有找到要回复的新推文(因为它被配置为回复最新的推文),它会抛出一个错误(它是 400,如“400: Bad Authentication Data”,但我认为问题不在于此,因为 bot 在 Twitter 上发布过一次没有任何问题。但是,我确实认为这可能是某种 Bad Request 错误)。 每当它崩溃时,我都可以在我的命令“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
非常感谢!
400 HTTP 错误状态代码通常表示错误请求,这里很可能就是这种情况。当没有要回复的新推文时,不会进入 for
循环,并返回 check_mentions
函数本身。然后在返回时将其设置为 since_id
,并在下次调用 check_mentions
时将其用作 ID。这可能最终将类似 "<function check_mentions at 0x0000028E6C729040>"
的内容传递给 API 作为 since_id
.