UNPKG

2.19 kBJavaScriptView Raw
1// Run this and then telnet to localhost:2000 and chat with the bot
2
3import net from 'net';
4import superscript from 'superscript';
5
6const sockets = [];
7
8const botHandle = function botHandle(err, bot) {
9 const receiveData = function receiveData(socket, bot, data) {
10 // Handle incoming messages.
11 let message = `${data}`;
12
13 message = message.replace(/[\x0D\x0A]/g, '');
14
15 if (message.indexOf('/quit') === 0 || data.toString('hex', 0, data.length) === 'fff4fffd06') {
16 socket.end('Good-bye!\n');
17 return;
18 }
19
20 // Use the remoteIP as the name since the PORT changes on ever new connection.
21 bot.reply(socket.remoteAddress, message.trim(), (err, reply) => {
22 // Find the right socket
23 const i = sockets.indexOf(socket);
24 const soc = sockets[i];
25
26 soc.write(`\nBot> ${reply.string}\n`);
27 soc.write('You> ');
28 });
29 };
30
31 const closeSocket = function closeSocket(socket, bot) {
32 const i = sockets.indexOf(socket);
33 const soc = sockets[i];
34
35 console.log(`User '${soc.name}' has disconnected.\n`);
36
37 if (i !== -1) {
38 sockets.splice(i, 1);
39 }
40 };
41
42 const newSocket = function newSocket(socket) {
43 socket.name = `${socket.remoteAddress}:${socket.remotePort}`;
44 console.log(`User '${socket.name}' has connected.\n`);
45
46 sockets.push(socket);
47
48 // Send a welcome message.
49 socket.write('Welcome to the Telnet server!\n');
50 socket.write(`Hello ${socket.name}! ` + 'Type /quit to disconnect.\n\n');
51
52 // Send their prompt.
53 socket.write('You> ');
54
55 socket.on('data', (data) => {
56 receiveData(socket, bot, data);
57 });
58
59 // Handle disconnects.
60 socket.on('end', () => {
61 closeSocket(socket, bot);
62 });
63 };
64
65 // Start the TCP server.
66 const server = net.createServer(newSocket);
67
68 server.listen(2000);
69 console.log('TCP server running on port 2000.\n');
70};
71
72// This assumes the topics have been compiled to data.json first
73// See superscript/src/bin/parse for information on how to do that.
74
75// Main entry point
76const options = {
77 factSystem: {
78 clean: true,
79 },
80 importFile: './data.json',
81};
82
83superscript.setup(options, (err, bot) => {
84 botHandle(null, bot);
85});