-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventSub.js
223 lines (172 loc) · 6.46 KB
/
eventSub.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
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
const request = require('request')
const express = require('express');
const queryString = require('querystring');
const bodyParser = require('body-parser');
var jsonParser = bodyParser.json()
//server setup
const app = express();
const clientID = '<YOUR TWITCH CLIENT ID>'
const clientSecret = '<YOUR TWITCH CLIENT SECRET>'
const callbackURL = '<YOUR NGROK URL>'
const getAppAccessToken = async () => {
//get app access token
var tokenOptions = {
url: `https://id.twitch.tv/oauth2/token?` +
queryString.stringify({
client_id: clientID,
client_secret: clientSecret,
grant_type: 'client_credentials',
scope: 'channel:read:redemptions' // modify this depending on your subscription types(if providing multiple, separate with a space: ' ')
}),
method: 'POST'
};
let appAccessToken = await new Promise((resolve, reject)=>{
request(tokenOptions, (error, response)=>{
console.log(response.body)
if(!error){
resolve(JSON.parse(response.body).access_token)
} else {
console.log(error)
}
})
})
return appAccessToken
}
const validateToken = async (appAccessToken) => {
//validate app access token
var headers = {
'Authorization': 'OAuth ' + appAccessToken
};
var validationOptions = {
url: 'https://id.twitch.tv/oauth2/validate',
headers: headers
};
let isTokenValid = await new Promise((resolve, reject)=> {
request(validationOptions, (error, response)=>{
let parsedResponse = JSON.parse(response.body)
if(!parsedResponse.status){
resolve(true)
} else {
resolve(false)
}
})
})
return isTokenValid
}
const createNewSubscription = async (appAccessToken, broadcaster_id, subscriptionType) => {
var subscriptionHeaders = {
'Client-ID': clientID,
'Authorization': 'Bearer ' + appAccessToken,
'Content-Type': 'application/json'
};
var dataString = JSON.stringify({
"type": subscriptionType,
"version": "1",
"condition": {
"broadcaster_user_id": broadcaster_id
},
"transport": {
"method": "webhook",
"callback": callbackURL + "/path", // -- endpoint must match express endpoint
"secret": "my7secret7haha" //your secret
}
})
var subscriptionOptions = {
url: 'https://api.twitch.tv/helix/eventsub/subscriptions',
method: 'POST',
headers: subscriptionHeaders,
body: dataString
};
let newSubscriptionCreated = await new Promise((resolve, reject)=>{
request(subscriptionOptions, (error, response)=>{
let parsedResponse = JSON.parse(response.body)
if(!parsedResponse.error){
resolve(parsedResponse)
} else {
console.log(parsedResponse)
}
})
})
return newSubscriptionCreated
}
const getAllSubscriptions = async (appAccessToken) => {
//get all existing subscriptions
var headers = {
'Client-ID': clientID,
'Authorization': 'Bearer ' + appAccessToken
};
var getListOptions = {
url: 'https://api.twitch.tv/helix/eventsub/subscriptions',
headers: headers
};
let allSubscriptions = await new Promise((resolve, reject)=>{
request(getListOptions, (error, response)=>{
let parsedResponse = JSON.parse(response.body)
if(!parsedResponse.error){
resolve(parsedResponse)
} else {
console.log(parsedResponse)
}
})
})
return allSubscriptions
}
const deleteSubscription = async (appAccessToken, subscriptionID) => {
var headers = {
'Client-ID': clientID,
'Authorization': 'Bearer ' + appAccessToken
};
var deleteOptions = {
url: 'https://api.twitch.tv/helix/eventsub/subscriptions?id=' + subscriptionID,
method: 'DELETE',
headers: headers
};
let deletionStatus = await new Promise((resolve, reject)=>{
request(deleteOptions, (error, response)=>{
if(response.body === ''){
resolve('successessfully deleted sub of id: ' + subscriptionID)
} else {
console.log(response.body)
}
})
})
return deletionStatus
}
//Handles all function calls
const eventSubHandler = async () => {
let appAccessToken = await getAppAccessToken()
let isTokenValid = await validateToken(appAccessToken)
if(!isTokenValid){
//if app access token is invalid then get a new one
appAccessToken = await getAppAccessToken()
}
//broadcaster_id and subscriptionType should be set for your specific requirements
let broadcaster_id = '<BROADCASTER/CHANNEL ID FOR SUBSCRIPTION>' // the channel you would like the subscription set up on
let subscriptionType = 'channel.channel_points_custom_reward.add' // the type of subscription you would like ref: https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types
//creates new subscription
let newSubscription = await createNewSubscription(appAccessToken, broadcaster_id, subscriptionType)
let subscriptionList = await getAllSubscriptions(appAccessToken)
console.log(subscriptionList)
//deletes first subscription in subscriptionList -- change 'subscriptionList.data[0].id with the id of the specific subscription you would like deleted
let runDelete = false //set to true if you want to run deletion sequence
if(runDelete === true && subscriptionList.data.length > 0){
let deletionStatus = await deleteSubscription(appAccessToken, subscriptionList.data[0].id)
console.log(deletionStatus)
}
}
eventSubHandler()
//request handler - receives requests from ngrok
app.post('/path', jsonParser, (req, res)=>{
//to validate that you own the callback you must return the challenge back to twitch
if(req.body.challenge){
res.send(req.body.challenge)
} else {
console.log(req.body)
//response to twitch with 2XX status code if successful (prevents multiple of the same notifications)
res.send('2XX')
}
})
//setup express server and ngrok connection
const server = app.listen(3000, ()=> {
console.log('listening on port 3000')
});