'Is there a Tweety python function to split long tweets into threads?

I'm working on a bot that pulls information from a public source and tweets out a list of information to my followers. If the list is longer than 280 characters I'd like the bot to separate the tweet into threads.

Before I write logic to determine when to break, save the slice, create a new one, and then tweet all slices... is there a way already completed?

Here's my code:

for state in payload['data']:
    for city2 in payload['data'][state]:
        if city2['status'] != "Available" and (city2['state'] in stateList or len(stateList) == 0):
            availList.append(string.capwords(city2['city']) + " (" + convert_percentage(city2['pctAvailable']) + " avail)")

if len(availList) > 0:
    strMessage += "\n".join(sorted(availList))
    twitterMessage = str(len(availList)) + " CVS locations have appointments in " + stateList[0] + ":\n" + strMessage
    api.update_status(twitterMessage)

If the list is longer than 280 chars, I want to break it up into threads



Solution 1:[1]

Not ideal, but this will work and split your tweets into chunks if they exceed 280 characters - but only after periods (you can also use \n etc.):

import tweepy
import re
from time import sleep

tweets = 'Lorem ipsum dolor sit amet, postea corpora id mel,
ne vel accusam mandamus, te quot repudiare pri. Ne pri congue 
oportere intellegam, doctus animal mnesarchum ei sit. Eu per 
quis dico choro. Perfecto scriptorem ei mea. Soluta verterem 
te qui, volumus antiopam oportere et nec. Cu quo dictas 
suavitate concludaturque, pri te graece repudiandae. Quis 
movet molestiae ad pri.'

# Twitter token
client = tweepy.Client(
    bearer_token='xyz',
    consumer_key='xyz',
    consumer_secret='xyz',
    access_token='xyz',
    access_token_secret='xyz'
)

# split only after periods followed by whitespace
chunks = re.split('\.\s', tweets)

# check if tweet is longer than 280 characters, then split into chunks
def joiner(chunks):
    i = 0
    newchunks = []
    while (i < len(chunks)):
        try:
            if len(chunks[i]) + len(chunks[i+1]) < 280:
                # put periods back
                newchunks.append(chunks[i]+'. '+chunks[i+1])
                i += 1
            else:
                newchunks.append(chunks[i])
            i += 1
        except IndexError:
            newchunks.append(chunks[i])
            i += 1
    if chunks == newchunks:  # if at maximum chunking
        return chunks
    else:
        return joiner(newchunks)


# tweet chunks as thread
tweets = joiner(chunks)
id = None
for i in range(len(tweets)):
    # tweet first tweet as normal tweet with id=None
    client.create_tweet(text=tweets[i], in_reply_to_tweet_id=id)
    sleep(10) # delay for API call
    # get newest id for thread in user @xyz (0000000000000000000)
    newest_id = client.get_users_tweets(id=0000000000000000000, max_results=5)
    id = newest_id.meta['newest_id']
print(tweets)

If you want to split your tweets at random, you can use this snippet with textwrap.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1