kana natasha
kana natasha

Reputation: 29

My tweetbot code runs just fine but after iterating throughg some tweets it breaks with a UnicodeEncodeError

This tweetbot is supposed to go through my timeline, like and retweet tweets I haven't yet reacted to, and also follow people I do not follow yet. It returns a few results but then crashes with a unicodeEncodeError. What can I do to fix this?

Here is the code:

def favs():
    
    time_line = api.home_timeline(count=50)
    for tweet in time_line:
        if tweet.user.name != "flaxemsystem":
             if not tweet.favorited:
                try:
                    print(f"liking {tweet.author.name}")
                    api.create_favorite(tweet.id)
                    time.sleep(2)
                except tweepy.errors.TweepyException as e:
                    print(e)

                
             if not tweet.retweeted:
                try:
                    api.retweet(tweet.id)
                    print(f"retweeted {tweet.author.name} -{tweet.id}")
                    time.sleep(2)
                except tweepy.errors.TweepyException as e:
                    print(e)
             if not tweet.user.following:
                if not tweet.user.follow_request_sent:
                    try:
                        api.create_friendship(tweet.user.id)
                        print(f"followed {tweet.author.name}")
                    except tweepy.errors.TweepyException as e:
                        print(e)

It produces just these 2 results, and then crashes with this error:

liking Urban Television
retweeted Urban Television -1557805180179173376
liking Bloomberg
retweeted Bloomberg -1557805069655056384
Traceback (most recent call last):
  File "c:\Users\Kweronda\Desktop\twtflax2\app.py", line 89, in <module>
    favs()
  File "c:\Users\Kweronda\Desktop\twtflax2\app.py", line 51, in favs
    print(f"liking {tweet.author.name}")
  File "C:\Python38\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 18-19: character maps to <undefined>

Upvotes: 0

Views: 52

Answers (1)

Micka&#235;l Martinez
Micka&#235;l Martinez

Reputation: 1843

Did you try to use .encode('utf-8')?

print(f"liking {tweet.author.name.encode('utf-8')}")

I am not sure about why you're facing this encoding error, but it should fix it.

Upvotes: 2

Related Questions