-
Notifications
You must be signed in to change notification settings - Fork 4
/
cleverbot.js
executable file
·464 lines (415 loc) · 21.6 KB
/
cleverbot.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
/**
* Forum:
* GitHub: https://github.com/irgendwr/sinusbot-scripts
*/
registerPlugin({
name: 'Cleverbot',
version: '1.0',
description: 'Talk to cleverbot by using the ask command or in a specified channel.',
author: 'Jonas Bögle (irgendwr)',
backends: ['ts3', 'discord'],
engine: '>=1.0.0',
requiredModules: ['http', 'discord-dangerous'],
vars: [
{
name: 'channel',
title: 'Channel ID',
type: 'string'
},
{
name: 'minDelay',
title: 'Minimum Delay (in milliseconds)',
default: 1000,
type: 'number'
},
{
name: 'tts',
title: 'TTS (text to speech)',
default: false,
type: 'checkbox'
}
]
}, (_, {channel, minDelay, tts}, meta) => {
const http = require('http')
const event = require('event')
const engine = require('engine')
const backend = require('backend')
const helpers = require('helpers')
const audio = require('audio')
class Cleverbot {
constructor() {
// keeps track of the chat log
this.chat = []
// session token thing
this.XVIS = null
}
/**
* Creates a new session.
* @param {(error?: string) => void} [callback]
*/
init(callback) {
let date = new Date()
let month = date.getMonth()+1
let day = date.getDate()
let datestr = ''+date.getFullYear()
if (month < 10) datestr += '0'
datestr += month
if (day < 10) datestr += '0'
datestr += day
this._send('GET', Cleverbot.initURL+datestr, null, (error, response) => {
if (error) {
engine.log(`HTTP Error: ${error}`)
if (typeof callback === 'function') callback(`HTTP Error: ${error}`)
return
}
this.XVIS = Cleverbot._getCookie('XVIS', response.headers)
if (this.XVIS) {
//engine.log(`XVIS: ${this.XVIS}`)
if (typeof callback === 'function') callback()
} else {
engine.log('Error: cookie not found')
if (typeof callback === 'function') callback('Error: cookie not found')
}
})
}
/**
* Resets the current state and creates a new session.
* @param {(error?: string) => void} [callback]
*/
reset(callback) {
engine.log('reset')
this.chat = []
//this.XVIS = null
this.init(callback)
}
/**
* Ask Cleverbot something.
* @param {string} input
* @param {function} callback
* @param {number} retries How often to retry before giving up.
*/
ask(input, callback, retries=3) {
let len = this.chat.length
// Check if we have to wait for the bot to write something.
if (len % 2 !== 0) {
engine.log('Ignoring message since it\'s not our turn to speak. Hint: You can reset via the reset-cleverbot command.')
return;
}
let url = Cleverbot.api
let body = `stimulus=${Cleverbot._encode(input)}`
for (let i = 0; i < len && i < 7; i++) {
body += `&vText${i + 2}=${Cleverbot._encode(this.chat[len - i - 1])}`
}
this.chat.push(input)
/*
let lang = Cleverbot._guessLanguage(input);
if (lang) {
body += ('&cb_settings_language=' + lang);
}
*/
body += '&cb_settings_scripting=no';
if (this.sessionid) {
body += `&sessionid=${this.sessionid}`
}
body += '&islearning=1&icognoid=wsf&icognocheck=';
body += helpers.MD5Sum(body.substring(7, 33))
this._send('POST', url, body, (error, response) => {
if (error) {
this.chat.pop()
engine.log(`HTTP Error: ${error}`)
if (retries <= 0) {
if (typeof callback === 'function') callback(error, null)
return;
} else {
engine.log('retry...')
return this.ask(input, callback, --retries)
}
}
let res = response.data.toString().split('\r')
let answer = res[0].trim()
// Catch invalid answers such as:
// '<HTML><BODY>DENIED</BODY></HTML>'
// '<html>'
if (answer.toLowerCase().startsWith('<html>')) {
this.chat.pop()
engine.log('Error: Request denied by API')
if (typeof callback === 'function') callback('Request denied by API', null)
this.reset()
return;
// The default answer is also a bad sign:
} else if (answer == 'Hello from Cleverbot') {
this.reset(error => {
if (error) {
if (typeof callback === 'function') callback('Invalid response by API', null)
return;
}
engine.log('retry...')
this.ask(input, callback, --retries);
})
return;
}
this.chat.push(answer)
if (this.chat.length > Cleverbot.chatLen) {
// remove first two
this.chat.splice(0, 2)
}
if (!this.sessionid) {
this.sessionid = res[1]
engine.log(`sessionid: ${this.sessionid}`)
}
//engine.log(`answer: ${answer}`)
if (typeof callback === 'function') callback(null, answer)
})
}
/**
* @private
* @param {string} method
* @param {string} url
* @param {string} body
* @param {function} callback
*/
_send(method, url, body, callback) {
//engine.log(url)
//engine.log(body)
let cookies = this.XVIS ? `XVIS=${this.XVIS}` : null
return http.simpleRequest({
method: method,
url: url,
timeout: Cleverbot.defaultTimeout,
body: body,
headers: {
'Referer': Cleverbot.base,
'Cookie': cookies
}
}, callback.bind(this))
}
/**
* Encodes a parameter.
* @private
* @static
* @param {string} input
* @returns {string}
*/
static _encode(input) {
let out = ''
input = input.replace(/[|]/g, '{*}')
for (let i = 0; i <= input.length; i++) {
if (input.charCodeAt(i) > 255) {
let escapedChar = escape(input.charAt(i))
if (escapedChar.substring(0, 2) == '%u') {
out += ('|' + escapedChar.substring(2, escapedChar.length))
} else {
out += escapedChar
}
} else {
out += input.charAt(i)
}
}
out = out.replace(/\|201[CD89]|`|%B4/g, '\'').replace(/\|FF20|\|FE6B/g, '')
return escape(out)
}
/**
* Returns the value of a cookie.
* @private
* @static
* @param {string} name Name
* @param {object} headers HTTP Headers
* @return {?string}
*/
static _getCookie(name, headers) {
let cookies = headers['Set-Cookie']
if (!cookies || cookies.length === 0) return null;
for (let cookie of cookies) {
cookie = cookie.split('=')
if (cookie[0] == name) {
return cookie[1].split(';')[0]
}
}
return null
}
// TODO: either improve or remove
// /**
// * Guess language of given input.
// * @private
// * @static
// * @param {string} input Input
// * @return {?string} lang
// */
// static _guessLanguage(input) {
// const common = {
// de: ["aber", "ach egal", "achso", "aha ich", "alles", "also bist", "also doch", "also wie", "antwort", "auch", "auf", "aus deut", "ausgez", "beantwort", "bei dir", "bei mir", "beides", "bekomm", "beleid", "beschr", "besser", "bestimm", "beweis", "bin ich", "bissch", "bitte", "chatten", "danke", "dann", "darum", "das be", "das bin", "das du", "das freut", "das glaub", "das habe", "das ich", "das ist", "das stimm", "das war", "das weiss", "dein", "deine", "denke", "deswege", "diese", "deutsch",
// "dich", "doch", "ein mann", "ein mensch", "eine frau", "einfach", "entschuld", "erzahl", "es ist", "falsch", "find ich", "findest", "frau", "fresse", "freund", "freut", "ganz", "gar nicht", "geht", "gehst", "gibt", "gibst", "gib mir", "glaub", "gute", "gut und", "genau", "habe", "haben", "hast", "heiss", "heute", "ich auch", "ich bin", "ich hab", "ich hei", "ich wol", "immer", "junge", "kann", "kannst", "kein", "keine", "klar", "liebst", "madchen", "magst", "meine", "mir ist", "nein",
// "nicht", "sagst", "sagte", "schon", "sprech", "sprichst", "tust", "und", "viel", "warum", "was ist", "was mach", "weil", "wenn", "wer ist", "wieder", "wieso", "willst", "wirklich", "woher", "zum"],
// en: ["hello", "i am", "am I", "you", "you're", "your", "yourself", "i'm", "i'll", "i'd", "can't", "cannot", "don't", "won't", "would", "wouldn't", "could", "couldn't", "you", "is it", "it's", "it is", "isn't", "there", "their", "goodbye", "good", "bye", "what", "what's", "when", "where", "which", "who", "who's", "why", "how", "think", "the", "they", "them", "that", "this", "that's", "very", "favorite", "favourite", "of", "does", "doesn't", "did", "didn't", "yes", "not", "aren't", "never", "every",
// "everything", "anything", "something", "nothing", "thing", "about", "blush", "blushes", "kiss", "kisses", "down", "look", "looks", "more", "even", "around", "into", "get", "got", "love", "i like", "were", "want", "play", "out", "know", "now", "to be", "live", "living", "friend", "friends", "wish", "with", "marry", "wear", "wearing", "doing", "being", "seeing", "smile", "smiles", "gonna", "wanna", "any", "anyway", "sing", "everyone", "everybody", "always", "nope", "maybe", "i do", "really", "indeed",
// "mean", "course", "fine", "well", "sorry", "exactly", "welcome", "because", "sometimes", "tell", "liar", "true", "wrong", "right", "either", "neither", "giggles", "boy", "girl", "agree", "nevermind", "mind", "intelligence", "software", "guess", "interesting", "said", "meaning", "life", "from", "between", "please", "laughs", "talk", "talking", "old", "my name", "understand", "confuse", "confusing", "speak", "speaking", "joke", "awesome", "today", "alright", "sense", "explain", "need", "have",
// "haven't", "make", "makes", "ask", "asking", "question", "english", "is he", "she", "meet", "lies", "probably", "much", "dunno", "ahead", "boyfriend", "girlfriend", "story", "obviously", "first", "correct"],
// es: ["conoces", "crees", "cuando", "donde", "eres", "hablo", "hablas", "pues", "quien", "quiero", "quieres", "sabes", "seguro", "sobre", "aburrido", "acabas", "ademas", "ah vale", "ahora", "alegro", "alguien", "ayer", "bien", "bonito", "comiendo", "como", "conoces", "contigo", "cuando", "cuanto", "dame un", "de nada", "dije", "dijiste", "dimelo", "donde", "encanta", "entonces", "eres", "estamos", "estas", "estoy", "gracias", "gusta", "hablamos", "hacemos", "hola", "hombre", "igual", "interesante",
// "llamas", "llamo", "maquina", "me alegro", "me caes", "mentira", "mi casa", "puedes", "puedo", "pues", "que bueno", "que haces", "que hora", "que pasa", "que tal", "quien", "quieres", "sabes", "seguro", "tambien", "tampoco", "tengo", "tienes", "tu casa", "vamos", "verdad", "vives", "yo soy", "beso", "no se", "espanol", "espa\u00c3\u00b1ol"],
// fr: ["oui", "bien", "bien sur", "d'accord", "j'ai", "au revoir", "toi", "moi", "suis", "je ne", "un peu", "connais", "aimes", "savais", "veux", "voudrais", "ca va", "aussi", "pourquoi", "qu'est", "mais", "bonne", "interessant", "francais", "fran\u00c3\u00a7ais", "comprends", "parce que", "bonjour", "combien", "garcon", "fille", "deja", "voila", "desole", "n'est", "m'aime", "m'appelle", "t'aime", "depuis", "toujours", "quelle", "as-tu", "contraire", "revoir", "aucun", "avec", "vous", "alors",
// "bah alors", "bah c'est", "bah je", "maintenant", "moi non", "bah oui", "bah non", "beaucoup", "laisse", "dites", "c'est bien", "amusant", "dommage", "c'est faux", "c'est gentil", "c'est pas", "c'est un", "car tu", "chacun", "comme", "puis", "t'appelles", "comment tu", "donne", "donnes", "toi tu", "il n'y a", "crois", "vais", "tres drol", "aimez", "quand", "tu as", "mieux", "habites", "j'habite", "voulez", "pouvez", "non plus", "manges", "pensez", "je te", "evidemment", "connait", "que fait",
// "j'avais", "embrasse"],
// it: ["grazie", "questo", "prego", "sicuro", "quando", "come stai", "arrivederchi", "quanti", "tutti", "per favore", "molte", "di niente", "buongiorno", "buona sera", "scusa", "scusi", "bacio", "perche", "chiami", "chiama", "come ti", "anni hai", "femmina", "maschio", "come va", "ti amo", "va bene", "vabbe", "chi sei", "dove sei", "abiti", "sono", "piacere", "anch'io", "anchio", "anche", "quando", "invece", "dimmi", "te lo", "dico", "che", "e come", "cosa fai", "vivi", "nessuno", "nulla", "infatti",
// "quale", "chi e", "certo", "dimmelo", "quindi", "parlo", "italiano", "con te", "allora", "bello", "benissimo", "piu", "capisco", "conosci", "tutto", "quello", "vuoi", "ragione", "credo", "fidanzata", "a mi", "capito", "sei un", "sei una", "andare", "piaccio"],
// nl: ["hoezo", "een", "geen", "uit", "op wie", "hoe is", "niet", "doei", "jawel", "meisje", "waarom", "waar", "nederlands", "mooi", "oud", "ben je", "ik wel", "goed", "jongen", "gaat", "weet", "dankje", "lekker", "woon", "heet", "jij", "leuk", "hou", "hoor", "jou", "tuurlijk", "haat", "daarom", "leuke", "graag", "bedankt", "gewoon", "vind", "schatje", "noem", "klopt", "praten", "praat", "eerst", "mij", "juist", "ik ben", "ben ik"],
// da: ["hvordan", "hej"],
// pl: ["kochasz", "znasz", "polski", "polska", "zemu", "wiem", "masz", "fajnie", "kocham", "dobre", "dobry", "dobrze", "robisz", "dlaczego", "co tam", "imie", "lubisz", "ja tez", "ja nie", "gdzie", "jestem", "jestes", "czego", "bardzo", "ale co", "powiem", "prawda", "mnie", "ciebie", "znaszy", "co to", "jasne", "w domu", "polsce", "lubie", "co nie", "pisze", "pisz", "polsku", "ty tez", "nieprawda", "normalnie", "nie nie", "masz", "gadaj", "nudze", "bo ty", "wiesz", "muw", "cze\u00c5\u203a\u00c4\u2021"],
// pt: ["qual o", "qual e", "quem e", "quem o", "voce e", "voce est", "voce ta", "quer", "quem", "nao", "fala", "falar", "portugues", "portuguesa", "falo port", "tenho", "conhece", "para que", "o que", "meu", "seu", "estou", "isso", "entao", "seu nome", "sim est", "sou", "vou", "tambem", "homem", "mulher", "muito", "bem", "obrigada", "voc\u00c3\u00aa"],
// tr: ["merhaba", "nas\u00c4\u00b1ls\u00c4\u00b1n"]
// }
// for (let lang in common) {
// for (let str of common[lang]) {
// if (input.includes(str)) {
// //engine.log(`detected lang ${lang} due to string ${str}`)
// return lang
// }
// }
// }
// return null
// }
}
Cleverbot.base = 'https://www.cleverbot.com/'
Cleverbot.initURL = 'https://www.cleverbot.com/extras/conversation-social-min.js?'
Cleverbot.api = Cleverbot.base+'webservicemin?uc=UseOfficialCleverbotAPI&'
Cleverbot.defaultTimeout = 10 * 1000
Cleverbot.chatLen = 10
const bot = new Cleverbot()
const errResponse = 'Sorry, I was unable to process that due to an API error :confused:'
engine.log(`Loaded ${meta.name} v${meta.version} by ${meta.author}.`)
event.on('load', () => {
bot.init()
const command = require('command')
if (!command) {
engine.log('command.js library not found! Please download command.js to your scripts folder and restart the SinusBot, otherwise this script will not work.');
engine.log('command.js can be found here: https://github.com/Multivit4min/Sinusbot-Command/blob/master/command.js');
return;
}
command.createCommand('ask')
.alias('cleverbot')
.help('Ask something')
.manual('Ask something.')
.addArgument(args => args.rest.setName('message').min(1))
.exec((client, args, reply, ev) => {
let start = Date.now()
typing(ev.channel.id())
bot.ask(args.message, (err, response) => delay(start, () => {
if (err) {
reply(errResponse)
if (engine.getBackend() === 'discord') {
ev.message.createReaction('❌')
}
return;
}
reply(response)
if (tts) audio.say(response)
}))
})
command.createCommand('reset-cleverbot')
.alias('cleverbot')
.help('Reset cleverbot.')
.manual('Reset cleverbot.')
.exec((client, args, reply, ev) => {
engine.log(`Cleverbot reset by: ${client.name()} (${client.uid()})`)
bot.reset()
if (engine.getBackend() === 'discord') {
ev.message.createReaction('✅')
}
})
})
event.on('chat', (/** @type {Message} */ev) => {
if (ev.channel && ev.channel.id().endsWith(channel)) {
// ignore own messages
if (ev.client.isSelf()) return;
let text = ev.text
// ignore messages starting with "//"
if (text.startsWith('//')) return;
// ignore messages starting with "http(s)://"
if (text.startsWith('https://') || text.startsWith('http://')) return;
let start = Date.now()
typing(ev.channel.id())
bot.ask(text, (err, response) => delay(start, () => {
if (err) {
ev.channel.chat(errResponse)
return;
}
ev.channel.chat(response)
if (tts) audio.say(response)
}))
}
})
/**
* Adds a reaction to a message.
* @param {string} channelID Channel ID
* @param {string} messageID Message ID
* @param {string} emoji Emoji
* @return {Promise<object>}
* @author Jonas Bögle
* @license MIT
*/
function createReaction(channelID, messageID, emoji) {
return discord('PUT', `/channels/${channelID}/messages/${messageID}/reactions/${emoji}/@me`, null, false);
}
/**
* Post a typing indicator for the specified channel.
* @param {string} channelID
* @author Jonas Bögle
* @license MIT
*/
function typing(channelID) {
if (engine.getBackend() !== 'discord') return;
if (channelID.includes('/')) channelID = channelID.split('/')[1];
backend.extended().rawCommand('POST', `/channels/${channelID}/typing`, {}, err => {
if (err) {
engine.log(err)
}
})
}
/**
* Executes a discord API call
* @param {string} method http method
* @param {string} path path
* @param {object} [data] json data
* @param {boolean} [repsonse] `true` if you're expecting a json response, `false` otherwise
* @return {Promise<object>}
* @author Jonas Bögle
* @license MIT
*/
function discord(method, path, data=null, repsonse=true) {
if (engine.getBackend() !== 'discord') return;
return new Promise((resolve, reject) => {
backend.extended().rawCommand(method, path, data, (err, data) => {
if (err) return reject(err);
if (repsonse) {
let res;
try {
res = JSON.parse(data);
} catch (err) {
engine.log(`${method} ${path} failed`)
engine.log(`${data}`)
return reject(err);
}
if (res === undefined) {
engine.log(`${method} ${path} failed`)
engine.log(`${data}`)
return reject('Invalid Response');
}
return resolve(res);
}
resolve();
});
});
}
/**
* Calls a function with a minimum delay.
* @param {number} start timestamp in ms
* @param {function} callback
*/
function delay(start, callback) {
let diff = Date.now() - start
if (diff >= minDelay) {
callback()
} else {
setTimeout(callback, minDelay-diff)
}
}
})