2023-04-12 10:17:18 -04:00
|
|
|
import "dotenv/config.js";
|
|
|
|
import fetch from 'node-fetch';
|
|
|
|
import { emptyResponses } from './assets/emptyMessages.js';
|
|
|
|
import { resetResponses, userResetMessages } from './assets/resetMessages.js';
|
|
|
|
import { errorMessages, busyResponses } from './assets/errorMessages.js';
|
2023-04-16 21:17:15 -04:00
|
|
|
import cpuStat from 'cpu-stat';
|
2023-04-16 21:57:02 -04:00
|
|
|
import os from 'os';
|
2023-05-05 20:32:10 -04:00
|
|
|
import isNotDefined from 'is-not-defined'
|
|
|
|
import urban from 'urban'
|
2023-04-16 21:17:15 -04:00
|
|
|
|
2023-04-16 20:30:38 -04:00
|
|
|
import {
|
|
|
|
Client,
|
|
|
|
GatewayIntentBits,
|
|
|
|
ActivityType,
|
|
|
|
Partials
|
|
|
|
} from 'discord.js';
|
2023-04-09 12:07:32 -04:00
|
|
|
|
|
|
|
const client = new Client({
|
2023-04-09 19:49:51 -04:00
|
|
|
intents: [
|
|
|
|
GatewayIntentBits.DirectMessages,
|
|
|
|
GatewayIntentBits.Guilds,
|
2023-04-12 10:17:18 -04:00
|
|
|
GatewayIntentBits.GuildModeration,
|
2023-04-09 19:49:51 -04:00
|
|
|
GatewayIntentBits.GuildMessages,
|
|
|
|
GatewayIntentBits.MessageContent,
|
|
|
|
],
|
|
|
|
partials: [Partials.Channel],
|
2023-04-09 12:07:32 -04:00
|
|
|
});
|
|
|
|
|
2023-04-11 08:50:19 -04:00
|
|
|
// Grab ChannelIDs from the .env file
|
|
|
|
const channelIDs = process.env.CHANNEL_IDS.split(',');
|
2023-04-09 12:07:32 -04:00
|
|
|
|
|
|
|
const conversations = new Map();
|
|
|
|
|
2023-04-09 21:28:41 -04:00
|
|
|
function setBusy(userId, isBusy) {
|
|
|
|
if (conversations.has(userId)) {
|
2023-04-09 21:50:45 -04:00
|
|
|
conversations.get(userId).busy = isBusy;
|
2023-04-09 21:28:41 -04:00
|
|
|
} else {
|
2023-04-09 22:38:38 -04:00
|
|
|
conversations.set(userId, {
|
|
|
|
busy: isBusy
|
|
|
|
});
|
2023-04-09 21:28:41 -04:00
|
|
|
}
|
2023-04-09 21:50:45 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
function isAnyConversationBusy() {
|
2023-04-09 21:28:41 -04:00
|
|
|
for (const conversation of conversations.values()) {
|
2023-04-09 21:50:45 -04:00
|
|
|
if (conversation.busy) {
|
2023-04-09 22:12:42 -04:00
|
|
|
setPresenceBusy()
|
2023-04-09 21:50:45 -04:00
|
|
|
return true;
|
|
|
|
}
|
2023-04-09 21:28:41 -04:00
|
|
|
}
|
|
|
|
return false;
|
2023-04-09 21:50:45 -04:00
|
|
|
}
|
|
|
|
|
2023-04-09 22:12:42 -04:00
|
|
|
function setPresenceBusy() {
|
2023-04-09 19:49:51 -04:00
|
|
|
client.user.setPresence({
|
|
|
|
activities: [{
|
2023-04-09 22:12:42 -04:00
|
|
|
name: `Processing a Request`,
|
2023-04-09 19:49:51 -04:00
|
|
|
type: ActivityType.Playing
|
|
|
|
}],
|
|
|
|
status: 'dnd',
|
|
|
|
});
|
2023-04-09 22:12:42 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
function setPresenceOnline() {
|
|
|
|
client.user.setPresence({
|
|
|
|
activities: [{
|
|
|
|
name: `Ready for Request`,
|
|
|
|
type: ActivityType.Playing
|
|
|
|
}],
|
|
|
|
status: 'online',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
client.once('ready', () => {
|
|
|
|
console.log('Bot is ready.');
|
2023-04-09 22:38:38 -04:00
|
|
|
setPresenceOnline()
|
2023-04-09 12:07:32 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
client.on('messageCreate', async (message) => {
|
2023-04-09 21:50:45 -04:00
|
|
|
|
|
|
|
async function sendRand(array) {
|
|
|
|
const arrayChoice = array[Math.floor(Math.random() * array.length)];
|
|
|
|
await message.channel.send(arrayChoice); // give a notification of reset using a human like response.
|
|
|
|
}
|
|
|
|
|
|
|
|
async function sendRandDM(array) {
|
|
|
|
const arrayChoice = array[Math.floor(Math.random() * array.length)];
|
|
|
|
await message.author.send(arrayChoice); // give a notification of reset using a human like response.
|
|
|
|
}
|
|
|
|
|
2023-04-09 19:49:51 -04:00
|
|
|
// Only respond in the specified channels
|
2023-04-11 08:50:19 -04:00
|
|
|
if (!channelIDs.includes(message.channel.id)) {
|
2023-04-16 20:07:41 -04:00
|
|
|
return;
|
2023-04-09 19:49:51 -04:00
|
|
|
}
|
2023-04-11 08:50:19 -04:00
|
|
|
|
2023-04-09 19:49:51 -04:00
|
|
|
if (message.author.bot) return; // Ignore messages from bots
|
2023-04-09 12:07:32 -04:00
|
|
|
|
2023-04-09 22:12:42 -04:00
|
|
|
// Check if any conversation is busy
|
2023-04-09 21:28:41 -04:00
|
|
|
if (isAnyConversationBusy()) {
|
2023-04-09 22:12:42 -04:00
|
|
|
// Update bot presence to "Busy"
|
|
|
|
setPresenceBusy()
|
|
|
|
message.delete();
|
|
|
|
sendRandDM(busyResponses);
|
2023-04-09 19:49:51 -04:00
|
|
|
return;
|
2023-04-09 21:50:45 -04:00
|
|
|
}
|
2023-04-09 19:49:51 -04:00
|
|
|
const userID = message.author.id;
|
|
|
|
let conversation = conversations.get(userID) || {
|
|
|
|
messages: [],
|
|
|
|
busy: false
|
|
|
|
};
|
|
|
|
|
|
|
|
if (conversation.messages.length === 0) {
|
|
|
|
conversation.messages.push({
|
|
|
|
role: 'user',
|
2023-04-16 18:50:04 -04:00
|
|
|
content: ` ${process.env.INIT_PROMPT}`
|
2023-04-09 19:49:51 -04:00
|
|
|
});
|
|
|
|
conversation.messages.push({
|
|
|
|
role: 'user',
|
2023-04-16 08:47:04 -04:00
|
|
|
content: ` User name: ${message.author.username}.`
|
2023-04-09 19:49:51 -04:00
|
|
|
});
|
|
|
|
conversation.messages.push({
|
|
|
|
role: 'assistant',
|
2023-04-16 08:47:04 -04:00
|
|
|
content: ` Hello, ${message.author.username}, how may I help you?`
|
2023-04-09 19:49:51 -04:00
|
|
|
});
|
|
|
|
}
|
2023-04-09 21:50:45 -04:00
|
|
|
|
2023-04-09 19:49:51 -04:00
|
|
|
if (message.content === '!reset' || message.content === '!r') {
|
|
|
|
conversations.delete(userID); // Delete user's conversation map if they request reset
|
2023-04-09 21:50:45 -04:00
|
|
|
sendRand(userResetMessages)
|
2023-04-09 19:49:51 -04:00
|
|
|
return;
|
|
|
|
}
|
2023-04-09 12:07:32 -04:00
|
|
|
|
2023-04-09 19:45:06 -04:00
|
|
|
// Append user message to conversation history
|
2023-04-09 19:49:51 -04:00
|
|
|
conversation.messages.push({
|
|
|
|
role: 'user',
|
2023-04-16 08:48:18 -04:00
|
|
|
content: ` ${message.cleanContent}`
|
2023-04-09 19:49:51 -04:00
|
|
|
});
|
2023-04-09 12:07:32 -04:00
|
|
|
|
2023-04-09 19:49:51 -04:00
|
|
|
try {
|
2023-04-09 22:12:42 -04:00
|
|
|
setPresenceBusy()
|
2023-04-09 21:28:41 -04:00
|
|
|
setBusy(message.author.id, true);
|
2023-04-09 19:49:51 -04:00
|
|
|
|
2023-05-05 20:32:10 -04:00
|
|
|
|
|
|
|
// begin commands area
|
|
|
|
if (message.content.includes("!urban")) {
|
|
|
|
const regex = /"([^"]+)"/g;
|
|
|
|
const searchTerm = message.content.match(regex);
|
|
|
|
const search = urban(searchTerm)
|
|
|
|
search.first(function (data) {
|
|
|
|
if (!isNotDefined(data)) {
|
|
|
|
const lastMessageIndex = conversation.messages.length - 1;
|
|
|
|
conversation.messages[lastMessageIndex].content = `The definition of ${searchTerm} is: ${data.definition} comment on this exact definition in detail.`;
|
|
|
|
console.log(`Fetching urban for AI for ${searchTerm}`)
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// end commands area
|
|
|
|
|
2023-04-16 20:07:41 -04:00
|
|
|
const response = await generateResponse(conversation, message);
|
2023-04-09 19:49:51 -04:00
|
|
|
|
|
|
|
// Append bot message to conversation history
|
|
|
|
conversation.messages.push({
|
|
|
|
role: 'assistant',
|
|
|
|
content: response
|
|
|
|
});
|
|
|
|
|
|
|
|
if (response && response.trim()) {
|
|
|
|
// Send response to user if it's not empty
|
2023-04-16 22:39:24 -04:00
|
|
|
const limit = 1980;
|
|
|
|
|
|
|
|
// if we are over the discord char limit we need chunks...
|
|
|
|
if (response.length > limit) {
|
2023-05-05 10:55:29 -04:00
|
|
|
const chunks = response.match(new RegExp(`.{1,${limit}}`, "g"));
|
|
|
|
for (let i = 0; i < chunks.length; i++) {
|
|
|
|
setTimeout(() => {
|
|
|
|
message.channel.send(chunks[i]);
|
2023-05-05 15:07:39 -04:00
|
|
|
}, i * (process.env.OVERFLOW_DELAY || 3) * 1000); // delay of 3 seconds between each chunk to save on API requests
|
2023-05-05 10:55:29 -04:00
|
|
|
}
|
2023-04-16 22:39:24 -04:00
|
|
|
} else {
|
2023-05-05 10:55:29 -04:00
|
|
|
// We are good to go, send the response
|
|
|
|
await message.channel.send(response);
|
2023-04-16 22:39:24 -04:00
|
|
|
}
|
2023-05-05 10:55:29 -04:00
|
|
|
|
2023-04-09 22:12:42 -04:00
|
|
|
setPresenceOnline()
|
2023-04-09 21:28:41 -04:00
|
|
|
setBusy(message.author.id, false);
|
2023-04-09 19:49:51 -04:00
|
|
|
} else {
|
|
|
|
// Handle empty response here
|
2023-04-09 21:50:45 -04:00
|
|
|
sendRand(emptyResponses)
|
2023-04-09 19:49:51 -04:00
|
|
|
conversations.delete(userID); // Delete user's conversation map if they request reset
|
2023-04-09 23:18:15 -04:00
|
|
|
sendRand(resetResponses)
|
2023-04-09 22:12:42 -04:00
|
|
|
setPresenceOnline()
|
2023-04-09 19:49:51 -04:00
|
|
|
conversation.busy = false;
|
|
|
|
}
|
|
|
|
conversations.set(userID, conversation); // Update user's conversation map in memory
|
2023-05-05 10:55:29 -04:00
|
|
|
console.log(conversation)
|
|
|
|
|
2023-04-09 19:49:51 -04:00
|
|
|
} catch (err) {
|
|
|
|
console.error(err);
|
2023-05-05 11:48:32 -04:00
|
|
|
return sendRand(errorMessages)
|
2023-04-09 21:50:45 -04:00
|
|
|
} finally {
|
2023-04-09 22:12:42 -04:00
|
|
|
setPresenceOnline()
|
2023-04-09 21:50:45 -04:00
|
|
|
setBusy(message.author.id, false);
|
|
|
|
}
|
2023-04-09 12:07:32 -04:00
|
|
|
});
|
|
|
|
|
2023-05-05 10:55:29 -04:00
|
|
|
import cheerio from 'cheerio';
|
2023-04-16 20:07:41 -04:00
|
|
|
|
|
|
|
async function generateResponse(conversation, message) {
|
2023-05-05 10:55:29 -04:00
|
|
|
|
2023-05-05 20:32:10 -04:00
|
|
|
|
2023-05-05 10:55:29 -04:00
|
|
|
// Check if message contains a URL
|
|
|
|
const urlRegex = /(https?:\/\/[^\s]+)/g;
|
|
|
|
const urls = message.content.match(urlRegex);
|
|
|
|
|
|
|
|
if (urls) {
|
|
|
|
// If there are multiple URLs, process them one by one
|
|
|
|
for (const url of urls) {
|
|
|
|
try {
|
|
|
|
const res = await fetch(url);
|
|
|
|
const html = await res.text();
|
|
|
|
const $ = cheerio.load(html);
|
|
|
|
|
|
|
|
// Extract page title, meta description and content
|
|
|
|
const pageTitle = $('head title').text().trim();
|
|
|
|
const pageDescription = $('head meta[name="description"]').attr('content');
|
|
|
|
const pageContent = $('body').text().trim();
|
|
|
|
|
|
|
|
// Construct response message with page details
|
|
|
|
let response = `Title: ${pageTitle}\n`;
|
|
|
|
if (pageDescription) {
|
|
|
|
response += `Description: ${pageDescription}\n`;
|
|
|
|
}
|
|
|
|
if (pageContent) {
|
2023-05-05 12:12:10 -04:00
|
|
|
const MAX_CONTENT_LENGTH = process.env.MAX_CONTENT_LENGTH;
|
2023-05-05 13:08:13 -04:00
|
|
|
let plainTextContent = $('<div>').html(pageContent).text().trim().replace(/[\r\n\t]+/g, ' ');
|
2023-05-05 12:31:24 -04:00
|
|
|
const codePattern = /\/\/|\/\*|\*\/|\{|\}|\[|\]|\bfunction\b|\bclass\b|\b0x[0-9A-Fa-f]+\b|\b0b[01]+\b/;
|
|
|
|
const isCode = codePattern.test(plainTextContent);
|
2023-05-05 14:49:29 -04:00
|
|
|
|
2023-05-05 12:31:24 -04:00
|
|
|
if (isCode) {
|
|
|
|
plainTextContent = plainTextContent.replace(codePattern, '');
|
|
|
|
}
|
|
|
|
// Remove anything enclosed in brackets
|
|
|
|
plainTextContent = plainTextContent.replace(/ *\([^)]*\) */g, '');
|
2023-05-05 10:55:29 -04:00
|
|
|
if (plainTextContent.length > MAX_CONTENT_LENGTH) {
|
|
|
|
plainTextContent = plainTextContent.substring(0, MAX_CONTENT_LENGTH) + '...';
|
|
|
|
}
|
2023-05-05 12:32:46 -04:00
|
|
|
response += `Content: ${plainTextContent.trim()}`;
|
2023-05-05 10:55:29 -04:00
|
|
|
}
|
|
|
|
response += `URL: ${url}`;
|
|
|
|
|
2023-05-05 14:49:29 -04:00
|
|
|
// Get the index of the last message in the array
|
|
|
|
const lastMessageIndex = conversation.messages.length - 1;
|
2023-05-05 10:55:29 -04:00
|
|
|
|
2023-05-05 14:49:29 -04:00
|
|
|
// Append a new line and the new content to the existing content of the last message
|
|
|
|
conversation.messages[lastMessageIndex].content += "\n" + response;
|
2023-05-05 20:32:10 -04:00
|
|
|
|
2023-05-05 10:55:29 -04:00
|
|
|
console.log("A URL was provided, response: " + response)
|
|
|
|
|
|
|
|
} catch (err) {
|
|
|
|
console.error(err);
|
2023-05-05 12:12:10 -04:00
|
|
|
return sendRand(errorMessages);
|
2023-05-05 10:55:29 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-05-05 20:32:10 -04:00
|
|
|
|
|
|
|
|
|
|
|
|
2023-04-09 19:49:51 -04:00
|
|
|
const controller = new AbortController();
|
|
|
|
const timeout = setTimeout(() => {
|
|
|
|
controller.abort();
|
|
|
|
}, 900000);
|
|
|
|
|
2023-04-09 20:53:37 -04:00
|
|
|
const messagesCopy = [...conversation.messages]; // create a copy of the messages array
|
|
|
|
|
2023-04-16 20:07:41 -04:00
|
|
|
let botMessage; // define a variable to hold the message object
|
2023-04-16 21:56:09 -04:00
|
|
|
let time = 0
|
2023-04-16 20:07:41 -04:00
|
|
|
// define a function that shows the system load percentage and updates the message
|
|
|
|
const showSystemLoad = async () => {
|
2023-05-02 08:38:57 -04:00
|
|
|
time = Number(time) + Number(process.env.REFRESH_INTERVAL);
|
2023-05-05 10:55:29 -04:00
|
|
|
cpuStat.usagePercent(function (err, percent, seconds) {
|
|
|
|
if (err) {
|
|
|
|
return console.log(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
const systemLoad = percent;
|
|
|
|
const freeMemory = os.freemem() / 1024 / 1024 / 1024;
|
|
|
|
const totalMemory = os.totalmem() / 1024 / 1024 / 1024;
|
|
|
|
const usedMemory = totalMemory - freeMemory;
|
|
|
|
|
|
|
|
const embedData = {
|
|
|
|
color: 0x0099ff,
|
|
|
|
title: 'Please wait.. I am thinking...',
|
|
|
|
fields: [
|
|
|
|
{
|
|
|
|
name: 'System Load',
|
|
|
|
value: `${systemLoad.toFixed(2)}%`,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: 'Memory Usage',
|
|
|
|
value: `${usedMemory.toFixed(2)} GB / ${totalMemory.toFixed(2)} GB`,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: 'Time',
|
|
|
|
value: `~${time} seconds.`,
|
|
|
|
},
|
|
|
|
],
|
|
|
|
};
|
|
|
|
|
|
|
|
// if the message object doesn't exist, create it
|
|
|
|
if (!botMessage) {
|
|
|
|
(async () => {
|
|
|
|
botMessage = await message.channel.send({ embeds: [embedData] });
|
|
|
|
})();
|
|
|
|
} else {
|
|
|
|
botMessage.edit({ embeds: [embedData] }); // otherwise, update the message
|
|
|
|
}
|
2023-04-28 10:44:07 -04:00
|
|
|
});
|
2023-05-05 10:55:29 -04:00
|
|
|
};
|
2023-04-16 20:07:41 -04:00
|
|
|
|
|
|
|
// call the function initially
|
|
|
|
await showSystemLoad();
|
|
|
|
|
2023-05-02 08:15:45 -04:00
|
|
|
// Grab the REFRESH_INTERVAL from ENV if not exist, lets use 7 (seconds)
|
|
|
|
const refreshInterval = setInterval(showSystemLoad, (process.env.REFRESH_INTERVAL || 7) * 1000);
|
2023-04-11 11:38:47 -04:00
|
|
|
|
2023-04-09 19:49:51 -04:00
|
|
|
try {
|
2023-04-09 20:10:02 -04:00
|
|
|
const response = await fetch(`http://${process.env.ROOT_IP}:${process.env.ROOT_PORT}/v1/chat/completions`, {
|
2023-04-09 19:49:51 -04:00
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
2023-05-05 10:55:29 -04:00
|
|
|
'accept': 'application/json',
|
|
|
|
'Content-Type': 'application/json'
|
2023-04-09 19:49:51 -04:00
|
|
|
},
|
|
|
|
body: JSON.stringify({
|
2023-05-05 10:55:29 -04:00
|
|
|
messages: messagesCopy,
|
|
|
|
max_tokens: Number(process.env.MAX_TOKENS) // add the max_tokens parameter here
|
2023-04-09 19:49:51 -04:00
|
|
|
}),
|
|
|
|
signal: controller.signal
|
2023-05-05 10:55:29 -04:00
|
|
|
});
|
2023-04-09 19:49:51 -04:00
|
|
|
|
|
|
|
const responseData = await response.json();
|
2023-04-16 20:07:41 -04:00
|
|
|
console.log(JSON.stringify(responseData));
|
2023-04-09 19:49:51 -04:00
|
|
|
const choice = responseData.choices[0];
|
|
|
|
|
2023-04-16 20:07:41 -04:00
|
|
|
const responseText = choice.message.content;
|
|
|
|
|
|
|
|
// clear the interval, replace the "please wait" message with the response, and update the message
|
|
|
|
clearInterval(refreshInterval);
|
|
|
|
console.log(responseText);
|
|
|
|
botMessage.delete()
|
|
|
|
|
2023-04-16 10:22:57 -04:00
|
|
|
return responseText;
|
2023-04-16 20:07:41 -04:00
|
|
|
|
2023-04-09 19:49:51 -04:00
|
|
|
} catch (err) {
|
2023-04-09 20:53:37 -04:00
|
|
|
throw err;
|
2023-04-09 19:49:51 -04:00
|
|
|
} finally {
|
|
|
|
clearTimeout(timeout);
|
2023-04-16 21:56:09 -04:00
|
|
|
time = 0
|
2023-04-09 19:49:51 -04:00
|
|
|
}
|
2023-04-09 12:07:32 -04:00
|
|
|
}
|
|
|
|
|
2023-04-09 19:49:51 -04:00
|
|
|
client.login(process.env.THE_TOKEN); // Replace with your bot token
|