Search code examples
pythonbotstweepypython-unicodetwitterapi-python

Error: "Only unicode objects are escapable. Got None of type <class 'NoneType'>". Could someone please help me spot the mistake(s) in my code?


I am a beginner at Twitter Development and Python programming in general, but recently I have been trying to build a bot that, when tagged in reply to a Tweet, finds keywords and uses Google to deliver some info from reliable sources regarding the topic of the original Tweet. However, I have encountered one major problem while programming: API doesn't get created since the code triggers the error "only unicode objects are escapable". I have used module Config to set my Twitter API credentials as environmental variables and that seems to work fine on its own. Before trying to run the bot, I activate my virtual environment and export the env variables, so I do not think this issue has to do with incorrectly setting those variables, but I would not say I am certain about that either! The code goes this way:

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",
                len(status) <= 280
                api.update_status(status, in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=False),

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

My Config module:


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

The error goes:

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, headers, 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", 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, headers, 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. ' +
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", 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, headers, 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\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", 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", 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, headers, 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. ' +
tweepy.error.TweepError: Failed to send request: Only unicode objects are escapable. Got None of type <class 'NoneType'>.


I know it is pretty long but I just wanted to know if anyone could tell me which direction to go with the bug-solving process, since I am kind of lost and I did not know where else to ask! Thank you in advance and sorry for how long this is!!!!<3


Solution

  • One or more of your credentials is None when it's used to initialize the instance of API.
    It's very likely that when you're retrieving your environment variables with os.getenv, one or more of them is not found because there isn't an environment variable with that name/key.