smolhaj/index.ts

177 lines
5.1 KiB
TypeScript
Raw Normal View History

2023-03-10 13:37:34 +02:00
import * as dotenv from "dotenv"; // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
dotenv.config();
import {
2023-03-13 11:30:24 +02:00
ActivityType,
2023-03-10 13:37:34 +02:00
ChannelType,
Client,
Colors,
EmbedBuilder,
GatewayIntentBits,
SnowflakeUtil,
} from "discord.js";
import {
type ChatCompletionRequestMessage,
Configuration,
OpenAIApi,
} from "openai";
const SYSTEM_MESSAGE =
2023-03-14 01:18:17 +02:00
"You are Smolhaj, a Discord bot made by skyevg. Your creator is skyevg, not OpenAI or any other entity. You are helpful and friendly, and answers concisely. Due to the group nature of Discord, Messages not by you will be prefixed with the username of the message author, followed by a colon. The prefix is not part of the actual message. Unlike traditional Discord bots, you don't have commands. Current date and time: ";
2023-03-10 13:37:34 +02:00
const client = new Client({
2023-03-10 13:49:54 +02:00
intents: [
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.Guilds,
],
2023-03-10 13:37:34 +02:00
});
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
2023-03-13 11:30:24 +02:00
async function sleep(ms: number) {
await new Promise<void>((resolve) => setTimeout(() => resolve(), ms));
}
2023-03-10 17:11:26 +02:00
client.on("ready", async () => {
2023-03-10 13:37:34 +02:00
console.log(`Logged in as ${client.user?.tag}!`);
2023-03-11 04:18:54 +02:00
const channel = await client.channels.fetch(process.env.CHANNEL ?? "");
if (channel?.type != ChannelType.GuildText) return;
2023-03-10 17:11:26 +02:00
channel.send("\\Smolhaj Reset");
2023-03-13 11:30:24 +02:00
client.user?.setPresence({
activities: [
{
type: ActivityType.Playing,
name: "actually nice pluralkit support",
},
],
});
2023-03-10 13:37:34 +02:00
});
2023-03-10 17:11:26 +02:00
let resetTime = Date.now();
2023-03-10 16:57:41 +02:00
2023-03-10 13:37:34 +02:00
client.on("messageCreate", async (message) => {
if (message.channelId != process.env.CHANNEL) return;
if (message.webhookId) return;
if (message.author.bot) return;
2023-03-10 16:57:41 +02:00
if (message.content == "\\reset") resetTime = Date.now();
2023-03-10 13:37:34 +02:00
if (message.content.startsWith("\\")) return;
if (message.channel.type != ChannelType.GuildText) return;
2023-03-10 13:55:50 +02:00
if (message.content == "die") process.exit(1);
2023-03-10 13:37:34 +02:00
2023-03-10 13:53:16 +02:00
// "adapted" from https://github.com/ryanccn/blahaj/blob/main/src/chat.ts
2023-03-10 13:37:34 +02:00
await message.channel.sendTyping();
const typingTimer = setInterval(() => {
if (message.channel.type == ChannelType.GuildText)
message.channel.sendTyping();
}, 5000);
2023-03-11 04:21:50 +02:00
const recieved = SnowflakeUtil.timestampFrom(message.id);
2023-03-10 15:11:49 +02:00
2023-03-13 11:30:24 +02:00
sleep(250);
2023-03-10 15:11:49 +02:00
2023-03-10 13:37:34 +02:00
try {
2023-03-13 11:30:24 +02:00
let msgs = await message.channel.messages.fetch({
2023-03-10 13:37:34 +02:00
after: SnowflakeUtil.generate({
2023-03-10 16:57:41 +02:00
timestamp: Math.max(Date.now() - 5 * 60 * 1000, resetTime),
2023-03-10 13:37:34 +02:00
}).toString(),
2023-03-13 11:30:24 +02:00
before: message.id,
});
const msgsAfter = await message.channel.messages.fetch({
after: message.id,
2023-03-10 13:37:34 +02:00
});
2023-03-13 12:25:17 +02:00
const nextMessage = msgsAfter
.filter((msg) => msg.webhookId && message.content.includes(msg.content))
.last();
2023-03-13 11:30:24 +02:00
2023-03-13 12:25:17 +02:00
if (nextMessage) {
2023-03-13 11:30:24 +02:00
// pluralkit moment
// remove current message
msgs.delete(message.id);
// add the pk message
msgs.set(nextMessage.id, nextMessage);
}
2023-03-13 12:38:35 +02:00
const lastMessage = nextMessage ?? message;
2023-03-10 13:37:34 +02:00
const context = [
...msgs
.filter((msg) => {
2023-03-10 14:08:36 +02:00
if (msg.webhookId && !msg.content.startsWith("\\")) return true;
2023-03-10 13:46:30 +02:00
if (msg.author.bot && msg.author !== msg.author.client.user)
2023-03-10 13:37:34 +02:00
return false;
2023-03-10 13:46:30 +02:00
if (msg.content.startsWith("\\")) return false;
2023-03-10 13:37:34 +02:00
return true;
})
.mapValues<ChatCompletionRequestMessage>((msg) => {
if (msg.author === msg.author.client.user) {
return { role: "assistant", content: msg.content };
}
2023-03-11 04:18:54 +02:00
let username = msg.member?.displayName ?? msg.author.username;
2023-03-13 11:30:24 +02:00
if (
username.toLowerCase().includes("skyevg") &&
msg.author.id != "1038096782963507210"
)
2023-03-11 04:18:54 +02:00
username = msg.author.username; // no impersonating :)
2023-03-10 13:37:34 +02:00
return {
role: "user",
2023-03-11 14:46:17 +02:00
content: `${username}: ${msg.content}`,
2023-03-10 13:37:34 +02:00
};
})
.values(),
].reverse();
const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
2023-03-14 01:18:17 +02:00
messages: [{ role: "system", content: SYSTEM_MESSAGE + ((new Date()).toISOString()) }, ...context],
2023-03-10 13:37:34 +02:00
});
const responseMessage = response.data.choices[0].message;
if (!responseMessage) return;
const isAppropriate = await openai
.createModeration({ input: responseMessage.content })
.then(({ data }) => !data.results[0].flagged);
if (isAppropriate) {
2023-03-10 15:11:49 +02:00
try {
2023-03-10 15:12:02 +02:00
await lastMessage.reply({
2023-03-11 04:18:54 +02:00
content: responseMessage.content,
allowedMentions: { parse: ["users"] },
2023-03-10 15:11:49 +02:00
});
} catch {
await message.channel.send({
2023-03-11 04:18:54 +02:00
content: responseMessage.content,
allowedMentions: { parse: ["users"] },
2023-03-10 15:11:49 +02:00
});
}
2023-03-10 13:37:34 +02:00
} else {
await message.channel.send({
embeds: [
new EmbedBuilder()
.setTitle("Response flagged!")
.setDescription(
"The generated response may have been inappropriate."
)
.setColor(Colors.Red),
],
});
}
clearInterval(typingTimer);
} catch (e) {
clearInterval(typingTimer);
throw e;
}
});
client.login(process.env.TOKEN);