Guilherme Goulart
Guilherme Goulart

Reputation: 51

Creating a twitter thread on tweepy not working

This is my first question here, so let me know if you need me to add anything.

I have a bot on twitter using tweepy that tweets phrases from a book. When I have a phrase with < 280 characters, I tweet it. If my phrase has > 280 characters, I have a method that breaks down that phrase with more than 280 characters into a list of "tweetable" "subphrases".

So, I want to create a twitter thread with that list, in a way that the phrase would continue to form through each tweet that replied to the previous.

#tweet_list is the broke down phrase

home = api.user_timeline(user_id = "myuser", count = 50, tweet_mode="extended")
first_tweet = True

for i in range(len(tweet_list)):
            if first_tweet == True:
                tweet = tweet_list[0]
                api.update_status(status=tweet)
                first_tweet = False
                time.sleep(30)

            else:
                tweet = tweet_list[i]
                last_tweeted = home[0] #gets the latest tweet from my account
                api.update_status(status=tweet, in_reply_to_status_id=last_tweeted.id, auto_populate_reply_metadata=True)
                time.sleep(30)

The idea was that I would iterate the tweet_list, tweeting first the first part of the phrase, and then proceed to the next part of the code where I would get the latest tweet and reply to it. I don't know if that is the best solution and probably it isn't, because Tweepy is returning me this error:

tweepy.error.TweepError: [{'code': 187, 'message': 'Status is a duplicate.'}]

The bot is working fine if I try to tweet < 280 characters phrases.

Thanks in advance!

Upvotes: 2

Views: 375

Answers (1)

Bendik Knapstad
Bendik Knapstad

Reputation: 1458

this is how I've done it. I made a function to devide the text in to chunks.

def devide_post(message):
    if len(message) > 240:
        parts = math.ceil(len(message) / 240)
        message = message.split()

        messagelength = math.ceil(len(message) / parts)
        chunks = [
            message[i : i + messagelength]
            for i in range(0, len(message), messagelength)
        ]
        message_chunks = []
        for i, j in enumerate(chunks):
            message_chunks.append(" ".join(j).strip() + f" {i+1}/{len(chunks)}")
        return message_chunks
    else:
        return [message]

This will divide your message in to a list of messages. it also adds a counter to the end "1/4" if there is 4 tweets in that chunck. You can remove this part if you want.

then i post my tweets like this:

message = "my messages"
previous_message = None
for i in devide_post(message):
    previous_message = post_tweet(i, previous_message).id

Edit: this is my post_tweet function:

def post_tweet(message, reply=None):
    return api.update_status(message, reply)

Upvotes: 2

Related Questions