如何解决错误:“只有 unicode 对象是可转义的没有类型 <class 'NoneType'>”有人可以帮我找出代码中的错误吗?
总的来说,我是 Twitter 开发和 Python 编程的初学者,但最近我一直在尝试构建一个机器人,当标记为回复推文时,它会查找关键字并使用 Google 从可靠来源提供一些关于原始推文的主题。但是,我在编程时遇到了一个主要问题:API
没有被创建,因为代码触发了“只有 unicode 对象是可转义的”错误。我已经使用模块 Config 将我的 Twitter API 凭据设置为环境变量,这似乎可以正常工作。在尝试运行机器人之前,我激活了我的虚拟环境并导出了 env 变量,所以我不认为这个问题与错误设置这些变量有关,但我也不会说我对此有把握!
代码是这样的:
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,keywords,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 = prevIoUs_tweet.id
status_id = tweet.in_reply_to_status_id
tweet_u = api.get_status(status_id,tweet_mode='extended')
#to store the output -links- as a variable to use it later
old_stdout = sys.stdout
new_stdout = io.StringIO()
sys.stdout = new_stdout
output = new_stdout.getvalue()
sys.stdout = old_stdout
print(output)
text = output
# remove words that are between 1 and 3 characters long
shortword = re.compile(r'\W*\b\w{1,3}\b')
print(shortword.sub('',text))
keywords_search = print(shortword.sub('',text))
if keywords_search is not None:
mystring = search(keywords_search,num_results=500)
else:
mystring = search("error",num_results=1)
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:
print(word)
#to store the output -links- as a variable to use it later
old_stdout = sys.stdout
new_stdout = io.StringIO()
sys.stdout = new_stdout
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:
print(word)
#to print normally again
output = new_stdout.getvalue()
sys.stdout = old_stdout
print(output)
if output is not None:
status = "Hi there! This may be what you're looking for" and print(output),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",return new_since_id
def main():
api = create_api()
since_id = 1 #the last mention you have.
while True:
print(since_id)
since_id = check_mentions(api,["help","support"],since_id)
logger.info("Waiting...")
time.sleep(15)
if __name__ == "__main__":
main()
我的配置模块:
import tweepy
import logging
import os
logger = logging.getLogger()
def create_api():
consumer_key = os.getenv("XXXXXXXXXX")
consumer_secret = os.getenv("XXXXXXXXXX")
access_token = os.getenv("XXXXXXXXXX")
access_token_secret = os.getenv("XXXXXXXXXX")
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
错误:
ERROR:root:Error creating API
Traceback (most recent call last):
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\tweepy\binder.py",line 184,in execute
resp = self.session.request(self.method,File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\requests\sessions.py",line 516,in request
prep = self.prepare_request(req)
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\requests\sessions.py",line 449,in prepare_request
p.prepare(
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\requests\models.py",line 318,in prepare
self.prepare_auth(auth,url)
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\requests\models.py",line 549,in prepare_auth
r = auth(self)
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\requests_oauthlib\oauth1_auth.py",line 108,in __call__
r.url,headers,_ = self.client.sign(
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py",line 313,in sign
('oauth_signature',self.get_oauth_signature(request)))
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py",line 127,in get_oauth_signature
uri,body = self._render(request)
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py",line 209,in _render
headers = parameters.prepare_headers(
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\oauthlib\oauth1\rfc5849\utils.py",line 32,in wrapper
return target(params,*args,**kwargs)
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\oauthlib\oauth1\rfc5849\parameters.py",line 59,in prepare_headers
escaped_value = utils.escape(value)
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\oauthlib\oauth1\rfc5849\utils.py",line 56,in escape
raise ValueError('Only unicode objects are escapable. ' +
ValueError: Only unicode objects are escapable. Got None of type <class 'nonetype'>.
During handling of the above exception,another exception occurred:
Traceback (most recent call last):
File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\config.py",line 23,in create_api
api.verify_credentials()
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\tweepy\api.py",line 672,in verify_credentials
return bind_api(
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 192,in execute
six.reraise(TweepError,TweepError('Failed to send request: %s' % e),sys.exc_info()[2])
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\six.py",line 702,in reraise
raise value.with_traceback(tb)
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\tweepy\binder.py",in escape
raise ValueError('Only unicode objects are escapable. ' +
tweepy.error.TweepError: Failed to send request: Only unicode objects are escapable. Got None of type <class 'nonetype'>.
Traceback (most recent call last):
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\python39\site-packages\tweepy\binder.py",another exception occurred:
Traceback (most recent call last):
File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring20.py",line 114,in <module>
main()
File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring20.py",line 105,in main
api = create_api()
File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\config.py",line 26,in create_api
raise e
File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\config.py",in escape
raise ValueError('Only unicode objects are escapable. ' +
tweepy.error.TweepError: Failed to send request: Only unicode objects are escapable. Got None of type <class 'nonetype'>.
我知道它很长,但我只是想知道是否有人可以告诉我解决错误的过程应该朝哪个方向发展,因为我有点迷茫,我不知道还能去哪里问!在此先感谢您,很抱歉这么长时间!!!!
解决方法
当您的一个或多个凭据用于初始化 None
的实例时,它是 API
。
当您使用 os.getenv
检索环境变量时,很可能找不到其中一个或多个,因为没有具有该名称/键的环境变量。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。