-
Notifications
You must be signed in to change notification settings - Fork 2
/
chat.js
307 lines (237 loc) · 11 KB
/
chat.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
const { Reply, Message, MessageHistory, OutgoingMessage } = require("./message");
const Parser = require('./parser');
const jimp = require('jimp');
class Chat {
constructor(client, characterId, continueBody) {
this.characterId = characterId;
this.externalId = continueBody.external_id;
this.client = client;
const ai = continueBody.participants.find(
(participant) => participant.is_human === false
);
this.aiId = ai.user.username;
this.requester = client.requester;
}
async fetchHistory(pageNumber) {
if (!this.client.isAuthenticated()) throw Error('You need to be authenticated');
if (pageNumber) {
if (typeof(pageNumber) != "number") throw Error("Invalid arguments");
}
const client = this.client;
const pageString = pageNumber ? `&page_num=${pageNumber}` : ''
const request = await this.requester.request(`https://beta.character.ai/chat/history/msgs/user/?history_external_id=${this.externalId}${pageString}`, {
headers:client.getHeaders()
})
if (request.status() === 200) {
const response = await Parser.parseJSON(request)
const historyMessages = response.messages;
const messages = [];
for (let i = 0; i < historyMessages.length; i++) {
const message = historyMessages[i];
messages.push(new Message(this, message));
}
const hasMore = response.has_more;
const nextPage = response.next_page;
return new MessageHistory(this, messages, hasMore, nextPage);
} else Error('Could not fetch the chat history.')
}
async send(optionsOrMessage, singleReply) {
if (!this.client.isAuthenticated()) throw Error('You need an authentication');
const payload = new OutgoingMessage(this, optionsOrMessage)
const client = this.client;
if (!client.isAuthenticated()) throw Error('You need an authentication');
const request = await this.requester.request('https://beta.character.ai/chat/streaming/', {
body:Parser.stringify(payload),
method:'POST',
headers:client.getHeaders(),
client:this.client
}, true)
if (request.status() === 200) {
const response = await Parser.parseJSON(request);
const replies = response.replies;
const messages = []
for (let i = 0; i < replies.length; i++) {
messages.push(new Reply(this, response));
}
if (!singleReply) return messages;
else return messages.pop();
} else throw Error('Message sending failure')
}
async uploadImage(content) {
if (!this.client.isAuthenticated()) throw Error('You need an authentication');
let buffer;
try {
const image = await jimp.read(content);
buffer = image.getBase64('image/png');
} catch (error) {
throw Error("Content is either invalid or is not an image");
}
if (!buffer) throw Error("Invalid content");
const client = this.client;
const error = () => {throw Error('Image uploading failure');}
try {
const request = this.requester.uploadBuffer(buffer, client);
if (request.status() === 200) {
return `https://characterai.io/i/400/static/user/${request.response}`;
} else error();
} catch (error) { error(); }
}
async generateImage(prompt) {
if (!this.client.isAuthenticated()) throw Error('You need an authentication');
const client = this.client;
if (typeof(prompt) != "string") throw Error("Invalid arguments");
const request = await this.requester.request('https://beta.character.ai/chat/generate-image/', {
headers:client.getHeaders(),
method:'POST',
client:this.client,
body: Parser.stringify({image_description:prompt})
}, true)
if (request.status() === 200) {
const response = await Parser.parseJSON(request);
return response.image_rel_path;
} else throw Error('Failed generating image.')
}
async changeConversationById(conversationExternalId, force = false) {
if (typeof(conversationExternalId) != 'string' || typeof(force) != 'boolean') throw Error("Invalid arguments");
if (!this.client.isAuthenticated()) throw Error('You need an authentication');
let passing = false;
if (!force) {
let conversations = await this.getSavedConversations();
conversations = conversations.histories;
for (let i = 0; i < conversations.length; i++) {
const conversation = conversations[i];
if (conversation.external_id == conversationExternalId) passing = true;
}
} else passing = true;
if (passing) this.externalId = conversationExternalId;
else Error("Could not switch to conversation, it either doesn't exist or is invalid.")
}
async getSavedConversations(amount = 50) {
if (typeof(amount) != 'number') throw Error("Invalid arguments");
if (!this.client.isAuthenticated()) throw Error('You need an authentication');
const client = this.client;
const request = await this.requester.request(`https://beta.character.ai/chat/character/histories/`, {
headers:client.getHeaders(),
method:'POST',
body: Parser.stringify({
"external_id" : this.characterId,
"number" : amount
})
})
if (request.status() === 200) {
const response = await Parser.parseJSON(request)
this.externalId = response.external_id;
return response;
} else throw Error('Failed while saving & creating new chat')
}
async getMessageById(messageId) {
messageId = messageId.toString();
if (!this.client.isAuthenticated()) throw Error('You need an authentication');
const history = await this.fetchHistory()
const historyMessages = history.messages;
for (let i = 0; i < historyMessages.length; i++) {
const message = historyMessages[i];
if (message.id == messageId) return message;
}
return null;
}
async deleteMessage(messageId) {
if (typeof(messageId) != 'string') throw Error('Invalid arguments');
if (!this.client.isAuthenticated()) throw Error('You need an authentication');
if (this.client.isGuest()) throw Error('Guest accounts cannot delete messsages');
const client = this.client;
const request = await this.requester.request(`https://beta.character.ai/chat/history/msgs/delete/`, {
headers:client.getHeaders(),
method:'POST',
body: Parser.stringify({
"history_id" : this.externalId,
"ids_to_delete" : [messageId],
"regenerating" : false
})
})
let passing = false;
if (request.status() === 200) {
const response = await Parser.parseJSON(request);
if (response.status === 'OK') passing = true;
}
if (!passing) throw Error('Failed to delete the message');
}
async deleteMessages(messageIds) {
if (!this.client.isAuthenticated()) throw Error('You need an authentication');
if (this.client.isGuest()) throw Error('Guest accounts cannot delete messsages');
const messagesToDelete = [];
try {
for (let i = 0; i < messageIds.length; i++) {
const messageId = messageIds[i];
if (typeof(messageId) == "string") {
messagesToDelete.push(messageId);
}
}
} catch (error) {
throw Error("Failed to delete messages.")
};
const client = this.client;
const request = await this.requester.request(`https://beta.character.ai/chat/history/msgs/delete/`, {
headers:client.getHeaders(),
method:'POST',
body: Parser.stringify({
"history_id" : this.externalId,
"ids_to_delete" : messagesToDelete,
"regenerating" : false
})
})
let passing = false;
if (request.status() === 200) {
const response = await Parser.parseJSON(request);
if (response.status === 'OK') passing = true;
}
if (!passing) throw Error('Failed to delete messages.');
}
async deleteMessagesBulk(amount = 50, descending = false) {
if (typeof(amount) != 'number') throw Error('Invalid arguments');
if (!this.client.isAuthenticated()) throw Error('You need an authentication');
if (this.client.isGuest()) throw Error('Guest accounts cannot bulk delete messsages');
let idsToDelete = [];
const history = await this.fetchHistory()
const historyMessages = history.messages;
for (let i = 0; i < amount; i++) {
if (!descending) i = (amount - i);
const message = historyMessages[i];
if (message) idsToDelete.push(message.id);
}
if (idsToDelete.length == 0) return;
const client = this.client;
const request = await this.requester.request(`https://beta.character.ai/chat/history/msgs/delete/`, {
headers:client.getHeaders(),
method:'POST',
body: Parser.stringify({
"history_id" : this.externalId,
"ids_to_delete" : idsToDelete,
"regenerating" : false
})
})
let passing = false;
if (request.status() === 200) {
const response = await Parser.parseJSON(request);
if (response.status === 'OK') passing = true;
}
if (!passing) throw Error('Failed while bulk deleting messages');
}
async newChat() {
if (!this.client.isAuthenticated()) throw Error('You need an authentication');
const client = this.client;
const request = await this.requester.request(`https://beta.character.ai/chat/history/create/`, {
headers:client.getHeaders(),
method:'POST',
body: Parser.stringify({
"character_external_id" : this.characterId
})
})
if (request.status() === 200) {
const response = await Parser.parseJSON(request)
this.externalId = response.external_id;
return response;
} else throw Error('Failed while saving & creating new chat')
}
}
module.exports = Chat