/
streamelements.ts
206 lines (183 loc) · 5.94 KB
/
streamelements.ts
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
import Axios from 'axios';
import chalk from 'chalk';
import io from 'socket.io-client-legacy';
import { getRepository } from 'typeorm';
import api from '../api.js';
import currency from '../currency';
import { User, UserTipInterface } from '../database/entity/user';
import { settings, ui } from '../decorators';
import { onChange, onStartup } from '../decorators/on';
import events from '../events';
import { triggerInterfaceOnTip } from '../helpers/interface/triggers';
import { error, info, tip } from '../helpers/log';
import eventlist from '../overlays/eventlist';
import alerts from '../registries/alerts';
import users from '../users';
import Integration from './_interface';
type StreamElementsEvent = {
_id: string;
channel: string;
type: 'cheer' | 'follow' | 'host' | 'raid' | 'subscriber' | 'tip';
provider: 'twitch' | 'facebook' | 'youtube';
flagged: boolean;
createdAt: string;
updatedAt: string;
data: {
tipId: string;
username: string;
amount: number;
currency: currency;
message: string;
items: any[];
avatar: string;
providerId: string;
displayName: string;
streak: number;
tier: '1000' | '2000' | '3000' | 'prime';
quantity: number
}
};
/* example payload (eventData)
{
_id: '5d967959cd89a10ce12818ad',
channel: '5afbafb0c3a79ebedde18249',
event: 'tip',
provider: 'twitch',
createdAt: '2019-10-03T22:42:33.023Z',
data: {
tipId: '5d967959531876d2589dd772',
username: 'qwe',
amount: 12,
currency: 'RUB',
message: 'saaaaaaa',
items: [],
avatar: 'https://static-cdn.jtvnw.net/user-default-pictures-uv/ebe4cd89-b4f4-4cd9-adac-2f30151b4209-profile_image-300x300.png'
},
updatedAt: '2019-10-03T22:42:33.023Z'
} */
class StreamElements extends Integration {
socketToStreamElements: any | null = null;
@settings()
@ui({ type: 'streamelements-jwt' })
jwtToken = '';
@onStartup()
@onChange('enabled')
onStateChange (key: string, val: boolean) {
if (val) {
this.connect();
} else {
this.disconnect();
}
}
async disconnect () {
if (this.socketToStreamElements !== null) {
this.socketToStreamElements.removeAllListeners();
this.socketToStreamElements.disconnect();
}
}
@onChange('jwtToken')
async connect () {
this.disconnect();
if (this.jwtToken.trim() === '' || !this.enabled) {
return;
}
// validate token
try {
await Axios('https://api.streamelements.com/kappa/v2/channels/me', {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'Bearer ' + this.jwtToken,
},
});
info(chalk.yellow('STREAMELEMENTS:') + ' JWT token check OK.');
} catch (e) {
error(chalk.yellow('STREAMELEMENTS:') + ' JWT token is not valid.');
return;
}
this.socketToStreamElements = io('https://realtime.streamelements.com', {
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: Infinity,
transports: ['websocket'],
});
this.socketToStreamElements.on('reconnect_attempt', () => {
info(chalk.yellow('STREAMELEMENTS:') + ' Trying to reconnect to service');
});
this.socketToStreamElements.on('connect', () => {
info(chalk.yellow('STREAMELEMENTS:') + ' Successfully connected socket to service');
if (this.socketToStreamElements !== null) {
this.socketToStreamElements.emit('authenticate', { method: 'jwt', token: this.jwtToken });
}
});
this.socketToStreamElements.on('authenticated', ({ channelId }: { channelId: string }) => {
info(chalk.yellow('STREAMELEMENTS:') + ` Successfully authenticated on service (channel ${channelId})`);
});
this.socketToStreamElements.on('disconnect', () => {
info(chalk.yellow('STREAMELEMENTS:') + ' Socket disconnected from service');
if (this.socketToStreamElements) {
this.socketToStreamElements.open();
}
});
this.socketToStreamElements.on('event', async (eventData: StreamElementsEvent) => {
this.parse(eventData);
});
}
async parse(eventData: StreamElementsEvent) {
if (eventData.type !== 'tip') {
return;
}
const { username, amount, message } = eventData.data;
const DONATION_CURRENCY = eventData.data.currency;
const user = await users.getUserByUsername(username);
const newTip: UserTipInterface = {
amount: Number(amount),
currency: DONATION_CURRENCY,
sortAmount: currency.exchange(Number(amount), DONATION_CURRENCY, currency.mainCurrency),
message,
tippedAt: Date.now(),
exchangeRates: currency.rates,
};
user.tips.push(newTip);
getRepository(User).save(user);
if (api.isStreamOnline) {
api.stats.currentTips += currency.exchange(amount, DONATION_CURRENCY, currency.mainCurrency);
}
tip(`${username.toLowerCase()}${user.userId ? '#' + user.userId : ''}, amount: ${Number(amount).toFixed(2)}${DONATION_CURRENCY}, message: ${message}`);
eventlist.add({
event: 'tip',
amount,
currency: DONATION_CURRENCY,
userId: String(await users.getIdByName(username.toLowerCase())),
message,
timestamp: Date.now(),
});
events.fire('tip', {
username: username.toLowerCase(),
amount: Number(amount).toFixed(2),
currency: DONATION_CURRENCY,
amountInBotCurrency: Number(currency.exchange(amount, DONATION_CURRENCY, currency.mainCurrency)).toFixed(2),
currencyInBot: currency.mainCurrency,
message,
});
alerts.trigger({
event: 'tips',
name: username.toLowerCase(),
amount: Number(Number(eventData.data.amount).toFixed(2)),
tier: 0,
currency: DONATION_CURRENCY,
monthsName: '',
message,
autohost: false,
});
triggerInterfaceOnTip({
username: username.toLowerCase(),
amount,
message,
currency: DONATION_CURRENCY,
timestamp: Date.now(),
});
}
}
export default new StreamElements();