Skip to content
This repository was archived by the owner on Apr 24, 2024. It is now read-only.

Commit b7c5012

Browse files
committed
feat: load balancer
1 parent 2494460 commit b7c5012

File tree

8 files changed

+139
-37
lines changed

8 files changed

+139
-37
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "turing-bot",
3-
"version": "0.0.9",
3+
"version": "0.1.0",
44
"description": "",
55
"main": "src/index.js",
66
"type": "module",

src/commands/bot.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ export default {
6464
},
6565
{
6666
name: "Version",
67-
value: `v0.0.9`,
67+
value: `v0.1.0`,
6868
},
6969
])
7070
.setFooter({

src/commands/chat.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export default {
3737
});
3838
if (user.credits <= 0) {
3939
await interaction.editReply(
40-
`You don't have enough credits for this acction.`
40+
`You don't have enough credits for this acction. If you want more credits, please join us in [dsc.gg/turing](https://dsc.gg/turing)`
4141
);
4242
return;
4343
}

src/commands/sessiontoken.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { SlashCommandBuilder, time } from "discord.js";
22
import { getUser } from "../modules/user.js";
3+
import { addToken } from "../modules/loadbalancer.js";
34

45
export default {
56
data: new SlashCommandBuilder()
@@ -14,6 +15,13 @@ export default {
1415
.setRequired(true)
1516
),
1617
async execute(interaction, client) {
18+
var token = interaction.options.getString("sessiontoken");
19+
interaction.reply({
20+
content: `Adding your session token...`,
21+
ephemeral: true,
22+
});
23+
await addToken(token);
24+
interaction.editReply("Token added successfully");
1725
return;
1826
},
1927
};

src/index.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,9 @@ import {
1313
REST,
1414
Routes,
1515
} from "discord.js";
16-
import { initChat } from "./modules/gpt-api.js";
16+
import "dotenv/config";
1717
import supabase from "./modules/supabase.js";
18-
import * as dotenv from "dotenv"; // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
19-
dotenv.config();
18+
import { initTokens, reloadTokens } from "./modules/loadbalancer.js";
2019
import "./modules/status.js";
2120

2221
// Create a new client instance
@@ -84,6 +83,11 @@ for (const file of commandFiles) {
8483
// When the client is ready, run this code (only once)
8584
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
8685
client.once(Events.ClientReady, async (c) => {
86+
await reloadTokens();
87+
setInterval(async () => {
88+
await reloadTokens();
89+
}, ms("10m"));
90+
await initTokens();
8791
console.log(
8892
chalk.white(`Ready! Logged in as `) + chalk.blue.bold(c.user.tag)
8993
);
@@ -107,14 +111,10 @@ client.once(Events.ClientReady, async (c) => {
107111
.from("conversations")
108112
.delete()
109113
.eq("abled", true);
110-
await initChat();
111-
setInterval(async () => {
112-
await initChat();
113-
}, ms("50m"));
114114
if (process.env.NODE_ENV != "production") {
115115
client.user.setPresence({
116116
activities: [
117-
{ name: `v0.0.9 | dsc.gg/turing`, type: ActivityType.Playing },
117+
{ name: `maintenance | dsc.gg/turing`, type: ActivityType.Playing },
118118
],
119119
status: "online",
120120
});

src/modules/gpt-api.js

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,16 @@
11
//import { chatgptToken } from "chatgpt-token/module";
22
import * as dotenv from "dotenv"; // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
3-
import Client from "justbrowse.io";
43
import delay from "delay";
54
dotenv.config();
65
import chalk from "chalk";
6+
import { useToken, addMessage, removeMessage } from "./loadbalancer.js";
77

8-
var client = "loading";
98
var abled = false;
109

11-
async function initChat() {
12-
try {
13-
client = new Client(process.env.SESSION_TOKEN, process.env.API_TOKEN);
14-
await client.init();
15-
abled = false;
16-
} catch (err) {
17-
console.error(err);
18-
client = "loading";
19-
}
20-
console.log("loaded");
21-
}
2210
async function getStatus() {
2311
return abled;
2412
}
25-
async function checkId() {
13+
async function checkId(client) {
2614
try {
2715
if (client != "loading") {
2816
var status = await client.status();
@@ -110,27 +98,25 @@ async function conversationSendMessage(conversationId, message) {
11098
}
11199

112100
async function chat(message) {
101+
var token = await useToken();
102+
console.log(token);
103+
113104
if (!abled) {
114-
var check = await checkId();
105+
var check = await checkId(token.client);
115106
if (!check) {
116107
return `Wait 1-2 mins the bot is reloading.\nFor more information join our discord: [dsc.gg/turing](https://dsc.gg/turing)`;
117108
}
118109
await delay(1000);
119110
}
120-
console.log(message);
121111
try {
122-
var response = await client.chat(message);
112+
await addMessage(token.token);
113+
var response = await token.client.chat(message);
114+
await removeMessage(token.token);
123115
return response;
124116
} catch (err) {
125117
console.log(err);
126118
return `Something wrong happened, please wait we are solving this issue [dsc.gg/turing](https://dsc.gg/turing)`;
127119
}
128120
}
129121

130-
export {
131-
initChat,
132-
createConversation,
133-
chat,
134-
getStatus,
135-
conversationSendMessage,
136-
};
122+
export { createConversation, chat, getStatus, conversationSendMessage };

src/modules/loadbalancer.js

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import ms from "ms";
22
import supabase from "./supabase.js";
3+
import Client from "justbrowse.io";
4+
var clients = [];
35

46
async function getTokens() {
57
let { data: sessiontokens, error } = await supabase
@@ -9,7 +11,104 @@ async function getTokens() {
911

1012
return sessiontokens;
1113
}
14+
async function initChat(token) {
15+
try {
16+
var client = new Client(token, process.env.API_TOKEN);
17+
await client.init();
18+
clients.push({ client, token });
19+
} catch (err) {
20+
console.error(err);
21+
}
22+
console.log("loaded");
23+
}
24+
25+
async function useToken() {
26+
var tokens = await getTokens();
27+
var t = tokens
28+
.filter((x) => x.lastUse == null && x.messages <= 2)
29+
.sort((a, b) => {
30+
if (a.messages > b.messages) {
31+
return 1;
32+
}
33+
if (a.messages < b.messages) {
34+
return -1;
35+
}
36+
if (a.messages == b.messages) {
37+
return 0;
38+
}
39+
});
40+
var token = t[getRndInteger(0, t.length)];
41+
var client = clients.find((x) => x.token == token.sessionToken);
1242

43+
return client;
44+
}
45+
function getRndInteger(min, max) {
46+
return Math.floor(Math.random() * (max - min + 1)) + min;
47+
}
48+
async function addMessage(token) {
49+
let { data: sessiontokens, error } = await supabase
50+
.from("sessiontokens")
51+
.select("*")
52+
.eq("sessionToken", token);
53+
var tokenObj = sessiontokens[0];
54+
if (tokenObj) {
55+
if (tokenObj.totalMessages >= 30) {
56+
const { data, error } = await supabase
57+
.from("sessiontokens")
58+
.update({
59+
messages: tokenObj.messages + 1,
60+
totalMessages: tokenObj.totalMessages + 1,
61+
lastUse: Date.now(),
62+
})
63+
.eq("sessionToken", token);
64+
var index = clients.findIndex((x) => x.token == tokenObj.sessionToken);
65+
clients.splice(index, 1); // 2nd parameter means remove one item only
66+
} else {
67+
const { data, error } = await supabase
68+
.from("sessiontokens")
69+
.update({
70+
messages: tokenObj.messages + 1,
71+
totalMessages: tokenObj.totalMessages + 1,
72+
})
73+
.eq("sessionToken", token);
74+
}
75+
}
76+
}
77+
async function removeMessage(token) {
78+
let { data: sessiontokens, error } = await supabase
79+
.from("sessiontokens")
80+
.select("*")
81+
.eq("sessionToken", token);
82+
var tokenObj = sessiontokens[0];
83+
if (tokenObj) {
84+
const { data, error } = await supabase
85+
.from("sessiontokens")
86+
.update({ messages: tokenObj.messages - 1 })
87+
.eq("sessionToken", token);
88+
}
89+
}
90+
91+
async function initTokens() {
92+
var tokens = await getTokens();
93+
for (var i = 0; i < tokens.length; i++) {
94+
var token = tokens[i];
95+
await initChat(token.sessionToken);
96+
}
97+
}
98+
async function addToken(sessionToken) {
99+
const { data, error } = await supabase.from("sessiontokens").insert([
100+
{
101+
sessionToken: sessionToken,
102+
messages: 0,
103+
totalMessages: 0,
104+
lastUse: null,
105+
},
106+
]);
107+
if (error) {
108+
return error.message;
109+
}
110+
await initChat(sessionToken);
111+
}
13112
async function reloadTokens() {
14113
var tokens = await getTokens();
15114
var t = tokens.filter((x) => x.lastUse != null);
@@ -22,6 +121,15 @@ async function reloadTokens() {
22121
.from("sessiontokens")
23122
.update({ lastUse: null, messages: 0, totalMessages: 0 })
24123
.eq("id", t.id);
124+
await initChat(sessionToken);
25125
}
26126
}
27127
}
128+
export {
129+
addToken,
130+
initTokens,
131+
addMessage,
132+
removeMessage,
133+
useToken,
134+
reloadTokens,
135+
};

src/modules/user.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ async function getUser(discordUser) {
1616
const { data, error } = await supabase.from("users").insert([
1717
{
1818
id: discordUser.id,
19-
credits: 5,
19+
credits: 20,
2020
created_at: new Date(),
2121
},
2222
]);
@@ -27,7 +27,7 @@ async function getUser(discordUser) {
2727
id: discordUser.id,
2828
username: discordUser.username,
2929
discriminator: discordUser.discriminator,
30-
credits: 5,
30+
credits: 20,
3131
created_at: new Date(),
3232
};
3333
}

0 commit comments

Comments
 (0)