forked from FelixWaweru/TiktokChatGPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
269 lines (235 loc) · 9.6 KB
/
app.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
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
266
267
268
269
const chat = require('./gpt.js');
const vocaliser = require('./voice.js');
const sound = require("sound-play");
const path = require("path");
const {
WebcastPushConnection
} = require('tiktok-live-connector');
const Sentiment = require('sentiment');
require('dotenv').config();
const log = require('./logger.js');
var sentiment = new Sentiment();
var respondingTo = '';
var responseStreamDelay = 5000; // The delay between each stream event i.e 'gift'
var backlogStreamDelay = 10000; // The delay between each backlogged stream event
var liveIdleTime = 60000; // The amount of time within which the stream has been idle for too long
async function liveStream() {
// Username of someone who is currently live
let tiktokUsername = process.env.TIKTOK_USERNAME;
let speaking = false;
let lastChatActivity = Date.now();
let liveEvents = [];
// Create a new wrapper object and pass the username
let tiktokLiveConnection = new WebcastPushConnection(tiktokUsername);
// Connect to the chat (await can be used as well)
tiktokLiveConnection.connect().then(state => {
log(`Connected to roomId ${state.roomId}`);
}).catch(err => {
console.error('Failed to connect', err);
});
// In this case we listen to chat messages (comments)
tiktokLiveConnection.on('chat', data => {
// Wait for response
if (!speaking) {
speaking = true;
log(`${data.uniqueId} (userId:${data.userId}) writes: ${data.comment}`);
// Generate response
respondingTo = data.uniqueId;
responseGenerator(data.comment, 'chat', respondingTo).then(async response => {
// Manual delay to give bot response time
await new Promise(resolve => setTimeout(resolve, responseStreamDelay));
// Complete response
speaking = false;
});
lastChatActivity = Date.now();
}
});
tiktokLiveConnection.on('gift', data => {
// Generate response
respondingTo = data.uniqueId;
const statement = `${data.uniqueId} for gifting ${data.repeatCount} ${data.giftName}`
// Wait for response
if (!speaking) {
speaking = true;
if (data.giftType === 1 && data.repeatEnd) {
log(`${data.uniqueId} (userId:${data.nickname}) gifted: ${data.repeatCount} x ${data.giftName}`);
// Streak ended or non-streakable gift => process the gift with final repeat_count
responseGenerator(statement, 'gift', respondingTo).then(async response => {
// Manual delay to give bot response time
await new Promise(resolve => setTimeout(resolve, responseStreamDelay));
// Complete response
speaking = false;
});
}
lastChatActivity = Date.now();
}
else {
if (data.giftType === 1 && data.repeatEnd) {
// Streak ended or non-streakable gift => process the gift with final repeat_count
liveEvents.push({
respondingTo, respondingTo,
statement: statement,
event: 'gift'
});
}
}
})
tiktokLiveConnection.on('follow', (data) => {
// Generate response
respondingTo = data.uniqueId;
const statement = `${data.uniqueId}`
// Wait for response
if (!speaking) {
speaking = true;
log(`${data.uniqueId} (userId:${data.uniqueId}) followed`);
responseGenerator(statement, 'follow', respondingTo).then(async response => {
// Manual delay to give bot response time
await new Promise(resolve => setTimeout(resolve, responseStreamDelay));
// Complete response
speaking = false;
});
lastChatActivity = Date.now();
}
else {
liveEvents.push({
respondingTo: respondingTo,
statement: statement,
event: 'follow'
});
}
});
tiktokLiveConnection.on('emote', data => {
// Generate response
respondingTo = data.uniqueId;
const statement = `${data.uniqueId}`
// Wait for response
if (!speaking) {
speaking = true;
log(`${data.uniqueId} (userId:${data.nickname}) emoted`);
responseGenerator(statement, 'emote', respondingTo).then(async response => {
// Manual delay to give bot response time
await new Promise(resolve => setTimeout(resolve, responseStreamDelay));
// Complete response
speaking = false;
});
lastChatActivity = Date.now();
}
else {
liveEvents.push({
respondingTo: respondingTo,
statement: statement,
event: 'emote'
});
}
});
tiktokLiveConnection.on('member', (data) => {
// Generate response
respondingTo = data.uniqueId;
const statement = `${data.uniqueId}`
// Wait for response
if (!speaking) {
speaking = true;
log(`${data.uniqueId} (userId:${data.uniqueId}) joined livestream`);
responseGenerator(statement, 'join', respondingTo).then(async response => {
// Manual delay to give bot response time
await new Promise(resolve => setTimeout(resolve, responseStreamDelay));
// Complete response
speaking = false;
});
lastChatActivity = Date.now();
}
else {
liveEvents.push({
respondingTo: respondingTo,
statement: statement,
event: 'join'
});
}
});
// When there is no livestream activity for more than 120 seconds
while(Date.now() - lastChatActivity > liveIdleTime && speaking === false){
log("Stream Idle. Passing some time...");
speaking = true;
responseGenerator('Come up with a story or tell us something about yourself to pass the time', 'chat', 'Everyone').then(async response => {
// Manual delay to give bot response time
await new Promise(resolve => setTimeout(resolve, responseStreamDelay));
// Complete response
speaking = false;
});
lastChatActivity = Date.now();
}
// Stores special livestream events (gifting, follow, emote) and responds to them after the bot has finished responding to the chat
while(liveEvents.length > 0 && speaking === false){
log(`RESPONDING TO BACKLOG: ${liveEvents}`);
for (let i = 0; i < liveEvents.length; i++) {
log(`SPK: ${speaking}`)
if (!speaking) {
speaking = true;
await responseGenerator(liveEvents[i].statement, liveEvents[i].event, liveEvents[i].respondingTo).then(async response => {
// Shorter manual delay to give bot response time
await new Promise(resolve => setTimeout(resolve, backlogStreamDelay));
speaking = false;
});
}
}
liveEvents = [];
}
}
async function textResponseGenerator(statement, liveEvent, callback) {
// Sentiment analysis
var result = sentiment.analyze(statement); // Score: -2, Comparative: -0.666
// Response types
const positive = ["funny", "witty", "empathetic", "flirty", "hillarious"];
const neutral = ["mildly sarcastic", "neutral", "normal", "serious"];
const negative = ["sarcastic", "very sarcastic", "angry"];
// vary response type based on sentiment analysis
let conversationType = {};
let conversationTone = "";
if (result.score >= 4) {
conversationTone = positive[Math.floor(Math.random() * positive.length)];
} else if (result.score >= 1 || result.score < 4) {
conversationTone = neutral[Math.floor(Math.random() * neutral.length)];
} else if (result.score <= 0) {
conversationTone = negative[Math.floor(Math.random() * negative.length)];
}
conversationType = {
conversationTone: conversationTone,
liveEvent: liveEvent
};
await chat(statement, conversationType, function(result) {
callback(result);
});
}
async function responseGenerator(statement, liveEvent, respondingTo) {
// Generate Text response from chatGPT
let textResponse = "";
await textResponseGenerator(statement, liveEvent, function(result) {
switch (liveEvent) {
case 'chat':
textResponse = `${result}`;
break;
case 'gift':
textResponse = `Yo! ${respondingTo}! ${result}`;
break;
case 'emote':
textResponse = `Hey ${respondingTo}. ${result}`;
break;
case 'follow':
textResponse = `Welcome to the club ${respondingTo}. ${result}`;
break;
case 'join':
textResponse = `Welcome to the stream ${respondingTo}`;
break;
default:
break;
}
// Pass the response to the vocal module
vocaliser(textResponse, respondingTo).then(async response => {
log(`RES: ${response}`); // TODO: Await playing audio to complete before ending function
const filePath = path.join(__dirname, response);
await sound.play(filePath);
log("done");
});
});
}
liveStream();