-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
176 lines (141 loc) · 5.96 KB
/
index.js
File metadata and controls
176 lines (141 loc) · 5.96 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
// All helper functions for index.js
const express = require('express')
const app = express()
const fs = require('fs')
require("dotenv").config()
const { OpenAI } = require("openai");
const openai = new OpenAI({
apiKey: process.env.OPEN_AI_TOKEN,
});
const discord = require('discord.js')
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.MessageMentions
]
});
var saveData = load(saveData);
app.get('/', (req, res) => {
res.send("hello world!")
})
app.listen(3001, () => { console.log("YappingBot Ready!") });
function load() {
try {
var saveData = JSON.parse(fs.readFileSync('./save-data.json', 'utf8'));
} catch (e) {
// init if no data found
var saveData = {
"Warnings": ["Send a message telling the users to move the conversation to the \"yapping\" channel"],
"YappingRegister": {},
"BirthdayRegister": {}
};
}
return saveData;
}
function save(saveData){
fs.writeFileSync('./save-data.json', JSON.stringify(saveData));
}
async function askAIYap(prompt){
const response = await openai.chat.completions.create({
messages: [
{ role: "system", content: "You are a warning system for a discord server that keeps users from talking too much (yapping) in the wrong channels and directs them to instead move the conversation to the right channel, the \"yapping\" channel. Keep all following responses to a very short, concise paragraph." },
{ role: "user", content: prompt + " (be sure to be passive aggressive, mildly insulting, witty, and snarky in your response)" }
],
model: "gpt-3.5-turbo",
});
return response.choices[0].message.content;
}
async function askAIBirthday(username){
const response = await openai.chat.completions.create({
messages: [
{ role: "system", content: "You are a birthday congradulations AI for a discord server! Keep all following responses to a very short, concise paragraph." },
{ role: "user", content: "Say happy birthday to " + username + " with many well-wishes and a cheerful tone!" }
],
model: "gpt-3.5-turbo",
});
return response.choices[0].message.content;
}
client.on('ready', () => {
console.log("YappingBot is up and running");
});
client.on('messageCreate', async msg => {
if (msg.author === client.user || msg.author.bot) {
return;
}
// !help-yapping command
if (msg.content.toLowerCase().includes("!help-yapping")) {
msg.channel.send(
`Hi! I'm YappingBot, and I let y'all know when you are yapping too much and \"gently encourage\" you to move to the yapping channel instead with a \"fun\" AI message.
(Current settings: Trigger on ${process.env.YAPPING_AMOUNT_TRIGGER} messages sent in a channel within ${process.env.YAPPING_MINUTES_TRIGGER} minutes)
You can use the command "!add-yap-warning-prompt" followed by your prompt to add an AI yapping warning prompt to the random prompt list.`
);
}
// !add-yap-warning-prompt command
if (msg.content.toLowerCase().includes("!add-yap-warning-prompt")) {
var warning = msg.content.substring(23).trim();
if (warning.length < 1) {
msg.channel.send("Please provide a yapping prompt.");
return;
}
if (warning.length > Number(process.env.MAX_WARNING_LENGTH)) {
msg.channel.send(`The warning is too long. Please limit it to ${process.env.MAX_WARNING_LENGTH} characters.`);
return;
}
saveData = load(saveData);
if (!Array.isArray(saveData["Warnings"])) {
saveData["Warnings"] = [];
}
const duplicateWarning = saveData["Warnings"].some(existingWarning => existingWarning.toLowerCase() === warning.toLowerCase());
if (duplicateWarning) {
msg.channel.send("This yap warning prompt already exists.");
} else {
saveData["Warnings"].push(warning);
msg.channel.send("New yap warning prompt successfully added :thumbsup:");
}
save(saveData);
}
// Yapping logic
else if (("" + msg.channel) != process.env.YAPPING_CHANNEL_ID) {
const nowInMinutes = Math.ceil(Date.now() / (60 * 1000));
const expiryTime = nowInMinutes + Number(process.env.YAPPING_MINUTES_TRIGGER);
const channelId = msg.channel.id;
if (!saveData["YappingRegister"][channelId]) {
saveData["YappingRegister"][channelId] = [];
}
saveData["YappingRegister"][channelId].push(expiryTime);
saveData["YappingRegister"][channelId] = saveData["YappingRegister"][channelId].filter(yapExpiry => yapExpiry > nowInMinutes);
if (saveData["YappingRegister"][channelId].length >= process.env.YAPPING_AMOUNT_TRIGGER) {
const randomWarningPrompt = saveData["Warnings"][Math.floor(Math.random() * saveData["Warnings"].length)];
saveData["YappingRegister"][channelId] = [];
askAIYap(randomWarningPrompt)
.then(response => msg.channel.send(response));
}
}
// Birthday recognition
if (msg.mentions.users.size > 0 && /(happy\s*(b(?:ir)?thday|b-?day)|hbd|feliz cumpleaños|congratulations on your birthday|congradulations|congrats|grats)/i.test(msg.content)) {
const now = Date.now();
const dayInMs = 24 * 60 * 60 * 1000;
saveData = load(saveData);
msg.mentions.users.forEach(user => {
const userId = user.id;
if (!saveData["BirthdayRegister"][userId]) {
saveData["BirthdayRegister"][userId] = [];
}
saveData["BirthdayRegister"][userId].push(now);
saveData["BirthdayRegister"][userId] = saveData["BirthdayRegister"][userId].filter(time => now - time <= dayInMs);
if (saveData["BirthdayRegister"][userId].length > 3) {
askAIBirthday(randomWarningPrompt)
.then(response => msg.channel.send(response));
msg.channel.send(`🎉 Happy Birthday to <@${userId}>! 🎉`);
saveData["BirthdayRegister"][userId] = [];
}
});
save(saveData);
}
save(saveData);
});
client.login(process.env.TOKEN);