-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.js
257 lines (215 loc) · 8.74 KB
/
client.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
const Chat = require('./chat')
const { v4: uuidv4 } = require('uuid');
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
class Client {
#token = undefined;
#isGuest = false;
#authenticated = false;
#guestHeaders = {
'Content-Type': 'application/json'
}
constructor() {
this.#token = undefined;
}
// api fetching
async fetchCategories() {
const request = await fetch('https://beta.character.ai/chat/character/categories/')
if (request.status === 200) return await request.json();
else throw Error('Failed to fetch categories');
}
async fetchUserConfig() {
const request = await fetch('https://beta.character.ai/chat/config/', {
headers:this.#guestHeaders
})
if (request.status === 200) {
const response = await request.json()
return response;
} else Error('Failed fetching user configuration.')
}
async fetchUser() {
if (!this.isAuthenticated()) throw Error('You must be authenticated to do this.');
const request = await fetch('https://beta.character.ai/chat/user/', {
headers:this.getHeaders()
})
if (request.status === 200) {
const response = await request.json()
return response;
} else Error('Failed fetching user.')
}
async fetchFeaturedCharacters() {
if (!this.isAuthenticated()) throw Error('You must be authenticated to do this.');
const request = await fetch('https://beta.character.ai/chat/characters/featured_v2/', {
headers:this.getHeaders()
})
if (request.status === 200) {
const response = await request.json()
return response;
} else Error('Failed fetching featured characters.')
}
async fetchCharactersByCategory(curated = false) {
if (curated == undefined || typeof(curated) != 'boolean') throw Error('Invalid arguments.')
const url = `https://beta.character.ai/chat/${
curated ? 'curated_categories' : 'categories'
}/characters/`;
const request = await fetch(url, {
headers:this.#guestHeaders
})
const property = curated
? 'characters_by_curated_category'
: 'characters_by_category';
if (request.status === 200) {
const response = await request.json()
return response[property]
} else Error('Failed fetching characters by category.')
}
async fetchCharacterInfo(characterId) {
if (!this.isAuthenticated()) throw Error('You must be authenticated to do this.');
if (characterId == undefined || typeof(characterId) != 'string') throw Error('Invalid arguments.')
const request = await fetch(`https://beta.character.ai/chat/character/info-cached/${characterId}/`, {
headers:this.getHeaders()
})
if (request.status === 200) {
const response = await request.json()
return response.character;
} else Error('Could not fetch character information.')
}
async searchCharacters(characterName) {
if (!this.isAuthenticated()) throw Error('You must be authenticated to do this.');
if (this.#isGuest) throw Error('Guest accounts cannot use the search feature.');
if (characterName == undefined || typeof(characterName) != 'string') throw Error('Invalid arguments.')
const request = await fetch(`https://beta.character.ai/chat/characters/search/?query=${characterName}`, {
headers:this.getHeaders()
})
if (request.status === 200) {
const response = await request.json()
return response;
} else Error('Could not search for characters.')
}
async getRecentConversations() {
if (!this.isAuthenticated()) throw Error('You must be authenticated to do this.');
const request = await fetch(`https://beta.character.ai/chat/characters/recent/`, {
headers:this.getHeaders()
})
if (request.status === 200) {
const response = await request.json()
return response;
} else Error('Could not get recent conversations.')
}
// chat
async createOrContinueChat(characterId, externalId = null) {
if (!this.isAuthenticated()) throw Error('You must be authenticated to do this.');
if (characterId == undefined || typeof(characterId) != 'string' || typeof(externalId != null ? externalId : '') != 'string') throw Error('Invalid arguments.')
let request = await fetch('https://beta.character.ai/chat/history/continue/', {
body:JSON.stringify({
character_external_id: characterId,
history_external_id: externalId,
}),
method:'POST',
headers:this.getHeaders()
})
if (request.status === 200 || request.status === 404) {
let response = await request.text()
if (response === "No Such History" || response === "there is no history between user and character") { // Create a new chat
request = await fetch('https://beta.character.ai/chat/history/create/', {
body:JSON.stringify({
character_external_id: characterId,
history_external_id: null,
}),
method:'POST',
headers:this.getHeaders()
})
if (request.status === 200) response = await request.json()
else Error('Could not create a new chat.')
}
// If a text gets returned, we try to parse it to JSON!
try {
response = JSON.parse(response);
} catch (error) {}
// Continue it
const continueBody = response;
return new Chat(this, characterId, continueBody)
} else Error('Could not create or resume a chat.')
}
// authentification
async authenticateWithToken(token) {
if (this.isAuthenticated()) throw Error('Already authenticated');
if (!token || typeof(token) != 'string') throw Error('Specify a valid token');
const request = await fetch('https://beta.character.ai/dj-rest-auth/auth0/', {
method:'POST',
body:JSON.stringify({
access_token: token
}),
headers:{
'Content-Type': 'application/json',
}
})
if (request.status === 200) {
const response = await request.json()
this.#isGuest = false;
this.#authenticated = true;
this.#token = response.key;
return response.token
} else throw Error('Token is invalid')
}
async authenticateAsGuest() {
if (this.isAuthenticated()) throw Error('Already authenticated');
const uuid = uuidv4();
const request = await fetch('https://beta.character.ai/chat/auth/lazy/', {
method:'POST',
body:JSON.stringify({
lazy_uuid: uuid
}),
headers: this.#guestHeaders
})
if (request.status === 200) {
const response = await request.json()
if (response.success === true) {
this.#isGuest = true;
this.#authenticated = true;
this.#token = response.token;
return response.token;
} else throw Error('Registering failed');
} else throw Error('Failed to fetch a lazy token')
}
unauthenticate() {
if (this.isAuthenticated()) {
this.#authenticated = false;
this.#isGuest = false;
this.#token = undefined;
}
}
// getters
getToken() {
return this.#token;
}
setToken(token) {
this.#token = token;
}
isGuest() {
return this.#isGuest;
}
setGuest(a) {
this.#isGuest = a;
}
isAuthenticated() {
return (this.#authenticated)
}
setAuthenticated(a) {
this.#authenticated = a;
}
// headers
getHeaders() {
return {
authorization: `Token ${this.#token}`,
'Content-Type': 'application/json',
//'sec-ch-ua': `"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"`,
//'sec-ch-ua-mobile': '?0'
/*'sec-ch-ua-platform': "Windows",
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',*/
//'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
};
}
}
module.exports = Client