-
-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathtwitter.ts
More file actions
265 lines (227 loc) · 5.56 KB
/
twitter.ts
File metadata and controls
265 lines (227 loc) · 5.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import pMap from 'p-map'
import pMemoize from 'p-memoize'
import pThrottle from 'p-throttle'
import * as types from './types'
// enforce twitter rate limit of 200 tweets per 15 minutes
const throttle1 = pThrottle({
limit: 200,
interval: 15 * 60 * 1000
})
const throttle2 = pThrottle({
limit: 1,
interval: 1000,
strict: true
})
export const createTweet = throttle1(throttle2(createTweetImpl))
async function createTweetImpl(
body: Parameters<types.TwitterClient['tweets']['createTweet']>[0],
{
twitter,
dryRun
}: {
twitter: types.TwitterClient
dryRun?: boolean
}
) {
if (dryRun) return null
try {
const res = await twitter.tweets.createTweet(body)
const tweet = res?.data
if (tweet?.id) {
return tweet
} else {
console.error('unknown error creating tweet', res)
throw new Error('unknown error creating tweet: empty tweet id')
}
} catch (err) {
console.error('error creating tweet', JSON.stringify(err, null, 2))
if (err.status === 403) {
// user may have deleted the tweet we're trying to respond to
const error = new types.ChatError(
err.error?.detail || `error creating tweet: 403 forbidden`
)
error.isFinal = true
error.type = 'twitter:forbidden'
throw error
} else if (err.status === 400) {
if (
/value passed for the token was invalid/i.test(
err.error?.error_description
)
) {
const error = new types.ChatError(
`error creating tweet: invalid auth token`
)
error.isFinal = false
error.type = 'twitter:auth'
throw error
}
} else if (err.status === 429) {
const error = new types.ChatError(
`error creating tweet: too many requests`
)
error.isFinal = false
error.type = 'twitter:rate-limit'
throw error
}
if (err.status >= 400 && err.status < 500) {
const error = new types.ChatError(
`error creating tweet: ${err.status} ${err.error?.description || ''}`
)
error.type = 'unknown'
throw error
}
throw err
}
}
/**
* Returns the larger of two Twitter IDs, which is used in several places to
* keep track of the most recent tweet we've seen or processed.
*/
export function maxTwitterId(tweetIdA?: string, tweetIdB?: string): string {
if (!tweetIdA && !tweetIdB) {
return null
}
if (!tweetIdA) {
return tweetIdB
}
if (!tweetIdB) {
return tweetIdA
}
if (tweetIdA.length < tweetIdB.length) {
return tweetIdB
} else if (tweetIdA.length > tweetIdB.length) {
return tweetIdA
}
if (tweetIdA < tweetIdB) {
return tweetIdB
}
return tweetIdA
}
/**
* Returns the smaller of two Twitter IDs, which is used in several places to
* keep track of the least recent tweet we've seen or processed.
*/
export function minTwitterId(tweetIdA?: string, tweetIdB?: string): string {
if (!tweetIdA && !tweetIdB) {
return null
}
if (!tweetIdA) {
return tweetIdB
}
if (!tweetIdB) {
return tweetIdA
}
if (tweetIdA.length < tweetIdB.length) {
return tweetIdA
} else if (tweetIdA.length > tweetIdB.length) {
return tweetIdB
}
if (tweetIdA < tweetIdB) {
return tweetIdA
}
return tweetIdB
}
/**
* JS comparator function for comparing two Tweet IDs.
*/
export function tweetIdComparator(a: string, b: string): number {
if (a === b) {
return 0
}
const max = maxTwitterId(a, b)
if (max === a) {
return 1
} else {
return -1
}
}
/**
* JS comparator function for comparing two tweet-like objects.
*/
export function tweetComparator(
tweetA: { id: string },
tweetB: { id: string }
): number {
const a = tweetA.id
const b = tweetB.id
return tweetIdComparator(a, b)
}
/**
* Tweets each tweet in the response thread serially one after the other.
*/
export async function createTwitterThreadForChatGPTResponse({
mention,
tweetTexts,
twitter,
dryRun
}: {
mention?: any
tweetTexts: string[]
twitter?: types.TwitterClient
dryRun?: boolean
}): Promise<types.CreatedTweet[]> {
let prevTweet = mention
const tweets = (
await pMap(
tweetTexts,
async (text): Promise<types.CreatedTweet> => {
const reply = prevTweet?.id
? {
in_reply_to_tweet_id: prevTweet.id
}
: undefined
// Note: this call is rate-limited on our side
const tweet = await createTweet({ text, reply }, { twitter, dryRun })
if (tweet) {
prevTweet = tweet
}
console.log('tweet response', JSON.stringify(tweet, null, 2))
return tweet
},
{
// This has to be set to 1 because each tweet in the thread replies
// the to tweet before it
concurrency: 1
}
)
).filter(Boolean)
return tweets
}
const getUserByIdThrottle = pThrottle({
limit: 1,
interval: 1000,
strict: true
})
export const getUserById = pMemoize(getUserByIdThrottle(getUserByIdImpl))
async function getUserByIdImpl(
userId: string,
{
twitterV1
}: {
twitterV1: types.TwitterClientV1
}
) {
// const { data: user } = await twitter.users.findUserById(userId)
// return user
const res = await twitterV1.users({ user_id: userId })
return res[0]
}
const getTweetsByIdsThrottle = pThrottle({
limit: 1,
interval: 1005,
strict: true
})
export const getTweetsByIds = pMemoize(
getTweetsByIdsThrottle(getTweetsByIdsImpl)
)
async function getTweetsByIdsImpl(
tweetIds: string | string[],
{
twitterV1
}: {
twitterV1: types.TwitterClientV1
}
) {
return twitterV1.tweets(tweetIds)
}