From 0613299835c9ddedb28b1c75262f6e60eea7297c Mon Sep 17 00:00:00 2001 From: Louis Date: Mon, 20 Sep 2021 17:43:42 +0200 Subject: [PATCH] feat: Tweet thread helper --- doc/v1.md | 26 ++++++++++++++++++++++++++ src/v1/client.v1.write.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/doc/v1.md b/doc/v1.md index ef2365c..1adb41f 100644 --- a/doc/v1.md +++ b/doc/v1.md @@ -24,6 +24,7 @@ For streaming API, see [Streaming part](./streaming.md). * [Post and retrieve tweets](#Postandretrievetweets) * [Create a tweet](#Createatweet) * [Reply to a tweet](#Replytoatweet) + * [Tweet a thread of tweet](#Tweetathreadoftweet) * [Delete a tweet](#Deleteatweet) * [Embed a tweet](#Embedatweet) * [Get a single tweet](#Getasingletweet) @@ -271,6 +272,31 @@ await client.v1.reply( ); ``` +### Tweet a thread of tweet + +Post multiple tweets at one time. +Tweet mode is `extended` by default. + +**Method**: `.tweetThread()` + +**Endpoint**: `statuses/update.json` + +**Right level**: `Read-write` + +**Arguments**: + - `tweets: (SendTweetV1Params | string)[]` + +**Returns**: `TweetV1[]`: Created tweets (in the right order), first sent first position + +**Example** +```ts +await client.v1.tweetThread([ + 'Hello, lets talk about Twitter!', + { status: 'Twitter is a fantastic social network. Look at this:', media_ids: '20' }, + 'This thread is automatically made with twitter-api-v2 :D', +]); +``` + ### Delete a tweet Delete a tweet that belongs to you. diff --git a/src/v1/client.v1.write.ts b/src/v1/client.v1.write.ts index cb1828c..76bb41f 100644 --- a/src/v1/client.v1.write.ts +++ b/src/v1/client.v1.write.ts @@ -59,6 +59,32 @@ export default class TwitterApiv1ReadWrite extends TwitterApiv1ReadOnly { return this.post('statuses/update.json', queryParams); } + /** + * Post a series of tweets. + * https://developer.twitter.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-update + */ + public async tweetThread(tweets: (SendTweetV1Params | string)[]) { + const postedTweets: TweetV1[] = []; + + for (const tweet of tweets) { + // Retrieve the last sent tweet + const lastTweet = postedTweets.length ? postedTweets[postedTweets.length - 1] : null; + // Build the tweet query params + const queryParams: SendTweetV1Params = { ...(typeof tweet === 'string' ? ({ status: tweet }) : tweet) }; + // Reply to an existing tweet if needed + const inReplyToId = lastTweet ? lastTweet.id_str : queryParams.in_reply_to_status_id; + const status = queryParams.status; + + if (inReplyToId) { + postedTweets.push(await this.reply(status, inReplyToId, queryParams)); + } else { + postedTweets.push(await this.tweet(status, queryParams)); + } + } + + return postedTweets; + } + /** * Reply to an existing tweet. Shortcut to `.tweet` with tweaked parameters. * https://developer.twitter.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-update