This repository was archived by the owner on Oct 7, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
190 lines (161 loc) · 5.73 KB
/
Copy pathindex.js
File metadata and controls
190 lines (161 loc) · 5.73 KB
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
/* eslint-disable max-len */
const cors = require("cors");
const path = require("path");
const axios = require("axios");
const morgan = require("morgan");
const dotenv = require("dotenv");
const express = require("express");
const compression = require("compression");
const serveStatic = require("serve-static");
dotenv.config();
// LOCALSTORAGE
if (typeof localStorage === "undefined" || localStorage === null) {
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./scratch');
localStorage.clear();
}
// EXPRESS
const app = express();
const port = process.env.PORT || 3000;
//app.use(express.json()); // parse the JSON request body
const HttpError = require("http");
// TELEGRAM BOT
const { Bot, GrammyError } = require("grammy");
//const { Bot, webhookCallback } = require("grammy");
const { Agent } = require("https");
//const { GOOGLE_CLOUD_PROJECT_ID, TELEGRAM_BOT_TOKEN ,GOOGLE_CLOUD_REGION } = process.env;
// Create a bot object
const bot = new Bot(process.env.TELEGRAM_TOKEN);
/*const bot = new Bot(process.env.TELEGRAM_TOKEN, {
client: {
// We accept the drawback of webhook replies for typing status.
canUseWebhookReply: (method) => method === "sendChatAction",
// Set the local Bot API URL
apiRoot: process.env.WEBHOOK, //`https://${GOOGLE_CLOUD_REGION}-${GOOGLE_CLOUD_PROJECT_ID}.cloudfunctions.net/${process.env.FUNCTION_TARGET}`
baseFetchConfig: {
compress: true,
agent: new Agent({
keepAlive: true,
// Disable Bot API server certificate verification
rejectUnauthorized: false,
}),
},
},
});*/
// Greeting
bot.command("start", (ctx) => ctx.reply("Hei"));
// Register listeners to handle messages
//bot.on("message:text", (ctx) => ctx.reply("Echo: " + ctx.message.text));
bot.on("message:text", async (ctx) => {
// the message object
const message = ctx.message; //req.body.message || req.body.edited_message;
const messageText = ctx.message.text; //req.body.message || req.body.edited_message;
//console.log(message); //This shows it as json? cool
let isFallback = false;
let responseText = null;
let rating = 0;
//let action = null;
try {
let query = decodeURIComponent(messageText).replace(/\s+/g, " ").trim() || "Hello";
//const humanInput = lowerCase(query.replace(/(\?|\.|!)$/gim, "")); // Remove this?
//console.log("query: "+query);
// HISTORY
let historyEnabled = false;
if (historyEnabled == true) {
let queryHistory = "";
//localStorage.setItem("queryHistory",null);
if (localStorage.getItem("queryHistory") != null) {
queryHistory = localStorage.getItem("queryHistory");
}
// If long history, delete oldest line
if (queryHistory.split(/\r\n|\r|\n/).length > 20) {
queryHistory.split("\n").slice(2).join("\n"); //This doesn't seem to work...
}
//localStorage.setItem("queryHistory",queryHistory+"\nUser: "+query);
//console.log("query history: "+queryHistory);
}
//action = "main_chat";
// Get answer from CharacterAI.
const CharacterAI = require('node_characterai');
const characterAI = new CharacterAI();
await characterAI.authenticateWithToken(process.env.CHARACTERAI_ACCESSTOKEN);// or authenticateAsGuest();
const characterId = process.env.CHARACTERAI_ID;
console.log("Retrieving answer from CharacterAI...");
// Chat histroy
if (historyEnabled == true) {
// Add history to query here
if (queryHistory!=null) {
queryWithHistory = "Chat history: ["+queryHistory+"]\n"+query;
}
console.log("query: "+queryWithHistory);
}
// Send typing indicator
await ctx.replyWithChatAction('typing');
const chat = await characterAI.createOrContinueChat(characterId);
const response = await chat.sendAndAwaitResponse(query, true); //or queryWithHistory
// use response.text to use it in a string.
responseText = response.text;
// Save to message history
if (historyEnabled == true) {
localStorage.setItem("queryHistory",queryHistory+"\n{{user}}: "+query+"\n{{char}}: "+responseText);
}
// Send the answer to Telegram
//ctx.reply(responseText);
ctx.reply(responseText, {
// `reply_to_message_id` specifies the actual reply feature.
reply_to_message_id: ctx.msg.message_id,
});
console.log("Response message sent.");
/*res.json({
responseText,
query,
rating,
action,
isFallback,
similarQuestion,
});*/
} catch (error) {
console.log(error);
if (error.message.includes("URI")) {
res.status(500).send({ error: error.message, code: 500 });
} else {
res.status(500).send({ error: "Internal Server Error!", code: 500 });
}
}
});
// Start the bot (using long polling)
bot.start();
// Telegram bot error handling
bot.catch((err) => {
const ctx = err.ctx;
console.error(`Error while handling update ${ctx.update.update_id}:`);
const e = err.error;
if (e instanceof GrammyError) {
console.error("Error in request:", e.description);
} else if (e instanceof HttpError) {
console.error("Could not contact Telegram:", e);
} else {
console.error("Unknown error:", e);
}
});
// IF USING WEBHOOKS - (Couldn't get this working)
// Register a handler for the bot
//app.post("/webhook", webhookCallback(bot, 'express'));
//?
/*app.post(`/api/telegram${process.env.TELEGRAM_TOKEN}`, async (req, res) => {
const message = req.body.message || req.body.edited_message;
...
});*/
// Set webhook for handler in Bot API
//bot.api.setWebhook(process.env.WEBHOOK);
//app.listen(port, () => console.log(`app listening on port ${port}!`));
const server = app.listen(port, () => console.log(`app listening on port ${port}!`));
// Handle server errors
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.error(`Port ${port} is already in use. Please choose a different port.`);
process.exit(1);
} else {
console.error(err);
}
});