-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTwitter.js
96 lines (82 loc) · 2.86 KB
/
Twitter.js
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
import { TwitterApi } from 'twitter-api-v2'
import axios from 'axios'
const MAX_MEDIA_UPLOAD_RETRYS = 3
class Twitter {
sleep = (time) => new Promise((resolve) => setTimeout(resolve, time))
constructor(apiKey, apiKeySecret, token, tokenSecret, webhookURL, webhookURLImage) {
this.twitterClient = new TwitterApi({
appKey: apiKey,
appSecret: apiKeySecret,
accessToken: token,
accessSecret: tokenSecret,
})
this.webhookURL = webhookURL
this.tweetAtWebHookImage = webhookURLImage
}
async tweet(text, filesBuffer) {
const payload = {
text: text
}
try {
if (filesBuffer.length == 1 && filesBuffer[0].type == "image/jpeg" && this.tweetAtWebHookImage) {
await this.tweetAtWebHook(this.tweetAtWebHookImage, text, filesBuffer[0].url)
return
} else if (filesBuffer.length > 0) {
const mediaIds = await this.uploadMedia(filesBuffer)
if (mediaIds.length > 0) payload.media = { media_ids: mediaIds }
} else if (this.webhookURL != undefined) {
await this.tweetAtWebHook(this.webhookURL, text)
return
}
await this.twitterClient.v2.tweet(payload)
} catch (error) {
console.error(error)
}
}
async uploadMedia(filesBuffer) {
const ids = await Promise.all(filesBuffer.map(async (file) => {
let retryCount = 0
const buffer = file.buffer
const type = file.type
const option = { mimeType: type }
if (type == "video/mp4") {
option.longVideo = true
}
while (retryCount < MAX_MEDIA_UPLOAD_RETRYS) {
try {
const id = await this.twitterClient.v1.uploadMedia(buffer, option)
return id
} catch (error) {
retryCount++
console.error(`Retry uploadMedia. retryCount:${retryCount}`)
console.error(error)
await this.sleep(1000)
}
}
return undefined
}))
return ids.filter(v => v)
}
async tweetAtWebHook(url, text, imageURL = undefined) {
let data = {
"value1": text,
"value2": imageURL
}
let config = {
method: 'post',
url: url,
headers: {
'Content-Type': 'application/json'
},
data: data
}
try {
await axios(config)
} catch (error) {
const responseStatus = error.response.status
console.error(`Failed to tweet on WebHook. code:${responseStatus}`)
throw error
}
}
}
export default Twitter