使用Tweepy创建Twitter线程:解决名言类Bot超长内容续发问题
Hey there! I’ve built similar Twitter bots for quote threads before, so let’s walk through how to implement this with Tweepy step by step. The core idea is splitting your long quote into manageable chunks, then sending them as a reply chain (thread) starting with the first tweet.
1. First: Split Your Long Quote into Tweet-Sized Chunks
The first challenge is breaking up the quote without cutting words mid-sentence, while adding clear numbering (like "1/3") so followers know where they are in the thread. Here’s a robust function to handle that:
def split_quote_into_thread(quote, max_content_length=270): # Leave ~10 chars for numbering (e.g., "2/3 | ") chunks = [] current_chunk = "" words = quote.split() total_chunks = 1 # First pass: calculate total number of chunks needed temp_length = 0 for word in words: temp_length += len(word) + 1 # +1 for space required_length = len(f"{total_chunks}/{total_chunks} | ") + temp_length if required_length > max_content_length + len(word) + 1: total_chunks += 1 temp_length = len(word) + 1 # Second pass: split into actual chunks with numbering chunk_num = 1 for word in words: potential_chunk = f"{current_chunk} {word}".strip() full_chunk_text = f"{chunk_num}/{total_chunks} | {potential_chunk}" if len(full_chunk_text) <= max_content_length + len(f"{chunk_num}/{total_chunks} | "): current_chunk = potential_chunk else: chunks.append(f"{chunk_num}/{total_chunks} | {current_chunk}") chunk_num += 1 current_chunk = word # Add the final chunk chunks.append(f"{chunk_num}/{total_chunks} | {current_chunk}") return chunks
2. Send the Thread with Tweepy
Once you have your chunks, you’ll send the first tweet, then each subsequent chunk as a reply to the previous one. This creates the threaded conversation.
First, initialize your Tweepy Client (make sure you have your API credentials set up from the Twitter Developer Portal):
import tweepy import time # Initialize Tweepy Client client = tweepy.Client( bearer_token="YOUR_BEARER_TOKEN", consumer_key="YOUR_API_KEY", consumer_secret="YOUR_API_SECRET", access_token="YOUR_ACCESS_TOKEN", access_token_secret="YOUR_ACCESS_TOKEN_SECRET" )
Then, the function to send the thread:
def send_quote_thread(quote): thread_chunks = split_quote_into_thread(quote) if not thread_chunks: print("No content to tweet!") return # Send the first tweet in the thread try: first_tweet_response = client.create_tweet(text=thread_chunks[0]) if not first_tweet_response.data: print("Failed to send the first tweet.") return previous_tweet_id = first_tweet_response.data["id"] print(f"Sent first tweet: {previous_tweet_id}") except tweepy.TweepyException as e: print(f"Error sending first tweet: {e}") return # Send remaining chunks as replies for chunk in thread_chunks[1:]: try: tweet_response = client.create_tweet( text=chunk, in_reply_to_tweet_id=previous_tweet_id ) previous_tweet_id = tweet_response.data["id"] print(f"Sent thread chunk: {previous_tweet_id}") # Add a small delay to avoid hitting rate limits time.sleep(2) except tweepy.TweepyException as e: print(f"Error sending chunk: {e}") break
3. Pro Tips for Smooth Operation
- Adjust Character Limits: Twitter allows 280 characters per tweet. The
max_content_lengthin the split function leaves room for numbering—tweak it if you want to add emojis (like 📖) to your chunk headers. - Rate Limits: Twitter’s API has rate limits for tweet creation. Adding a 1-2 second delay between chunks helps avoid getting blocked.
- Error Handling: The example includes basic error handling, but you can expand it to log failures or retry failed tweets (with backoff) if needed.
- Testing: Test with extra-long quotes first to make sure the splitting logic works—you don’t want to cut off a mid-sentence!
内容的提问来源于stack exchange,提问作者Jon Evan Moore

