Search code examples
pythontweepy

Tweepy, a bytes-like object is required, not str. How do i fix this error?


error: Traceback (most recent call last): File "C:\Users\zakar\PycharmProjects\Tweepy-bots\main.py", line 29, in c=c.replace("im ","") TypeError: a bytes-like object is required, not 'str'

error Error picture

this is how the code looks like:

`import tweepy
import tweepy as tt
import time
import sys
import importlib
importlib.reload(sys)




#login credentials twitter account
consumer_key = '-NOT GOING TO PUT THE ACTUAL KEY IN-'
consumer_secret = '-NOT GOING TO PUT THE ACTUAL KEY IN-'
access_token = '-NOT GOING TO PUT THE ACTUAL KEY IN-'
access_secret = '-NOT GOING TO PUT THE ACTUAL KEY IN-'

#login
auth = tt.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tt.API(auth)
search_query = "barca"
user = api.me()
print(user.name)

max_tweets = 100

for tweet in tweepy.Cursor(api.search, q=search_query).items(max_tweets):
    c=tweet.text.encode('utf8')
    c=c.replace("im ","")
    answer="@"+tweet.user.screen_name+" Hi " + c + ", I'm a bot!"
    print ("Reply:",answer)
    api.update_status(status=answer,in_reply_to_status_id=tweet.id)
    time.sleep(300) #every 5 minutes`

Solution

  • The problem is because you are encoding the text , and then replacing.

    here

    c=tweet.text.encode('utf8')
    c=c.replace("im ","")
    

    encode() will return bytes not a string. So in replace also you need to use the bytes. Like

    c=tweet.text.encode('utf8')
    c=c.replace(b"im ",b"")
    

    Or you replace the content first and then encode.