Update talko and backend to support saving colors

This commit is contained in:
Hri7566 2024-10-14 01:37:36 -04:00
parent ca89644205
commit a50af8abfe
8 changed files with 154 additions and 62 deletions

View File

@ -17438,6 +17438,7 @@ var TalkomaticBot = class extends import_node_events.EventEmitter {
}, },
autoConnect: false autoConnect: false
}); });
this.bindEventListeners();
} }
client; client;
b = new import_node_events.EventEmitter(); b = new import_node_events.EventEmitter();
@ -17449,8 +17450,7 @@ var TalkomaticBot = class extends import_node_events.EventEmitter {
async start() { async start() {
this.logger.info("Starting"); this.logger.info("Starting");
this.client.connect(); this.client.connect();
this.bindEventListeners(); let data = await this.findChannel(this.config.channel.name) || await this.createChannel(this.config.channel.name, "private");
let data = await this.findChannel(this.config.channel.name) || await this.createChannel(this.config.channel.name);
this.logger.debug(data); this.logger.debug(data);
if (typeof data !== "undefined") { if (typeof data !== "undefined") {
try { try {
@ -17494,32 +17494,48 @@ var TalkomaticBot = class extends import_node_events.EventEmitter {
); );
this.client.on( this.client.on(
"udpateRoom", "udpateRoom",
(msg) => { async (msg) => {
if (!Array.isArray(msg.users)) return; if (!Array.isArray(msg.users)) return;
try { try {
for (const user of msg.users) { for (const user of msg.users) {
let color = (await this.trpc.getUserColor.query({
userId: user.id
})).color;
this.logger.debug(
"(updateRoom) user color from api:",
color
);
const p = ppl[user.id] || { const p = ppl[user.id] || {
name: user.username, name: user.username,
id: user.id, id: user.id,
color: "#abe3d6", color,
typingFlag: false typingFlag: false
}; };
ppl[user.id] = p; ppl[user.id] = p;
} }
} catch (err) { } catch (err) {
this.logger.warn("Unable to set user data:", err);
} }
} }
); );
this.client.on( this.client.on(
"roomUsers", "roomUsers",
(msg) => { async (msg) => {
if (!Array.isArray(msg.users)) return; if (!Array.isArray(msg.users)) return;
try { try {
for (const user of msg.users) { for (const user of msg.users) {
let color = (await this.trpc.getUserColor.query({
userId: user.id
})).color;
if (!color) color = this.defaultColor;
this.logger.debug(
"(roomUsers) user color from api:",
color
);
const p = ppl[user.id] || { const p = ppl[user.id] || {
name: user.username, name: user.username,
id: user.id, id: user.id,
color: "#abe3d6", color,
typingFlag: false typingFlag: false
}; };
ppl[user.id] = p; ppl[user.id] = p;
@ -17542,12 +17558,16 @@ var TalkomaticBot = class extends import_node_events.EventEmitter {
let usedPrefix = prefixes.find( let usedPrefix = prefixes.find(
(pr) => msg.text.startsWith(pr) (pr) => msg.text.startsWith(pr)
); );
let color = (await this.trpc.getUserColor.query({
userId: msg.userId
})).color;
if (!color) color = this.defaultColor;
if (!usedPrefix) return; if (!usedPrefix) return;
const args = msg.text.split(" "); const args = msg.text.split(" ");
let part = ppl[msg.userId] || { let part = ppl[msg.userId] || {
name: "<unknown user>", name: "<unknown user>",
id: msg.userId, id: msg.userId,
color: this.defaultColor, color,
typingFlag: false typingFlag: false
}; };
this.logger.info(`${part.name}: ${msg.text}`); this.logger.info(`${part.name}: ${msg.text}`);
@ -17592,12 +17612,17 @@ var TalkomaticBot = class extends import_node_events.EventEmitter {
return; return;
} }
}, 1e3 / 20); }, 1e3 / 20);
this.b.on("color", (msg) => { this.b.on("color", async (msg) => {
if (typeof msg.color !== "string" || typeof msg.id !== "string") if (typeof msg.color !== "string" || typeof msg.id !== "string")
return; return;
try { try {
ppl[msg.id].color = msg.color; ppl[msg.id].color = msg.color;
await this.trpc.saveColor.query({
userId: msg.id,
color: msg.color
});
} catch (err) { } catch (err) {
this.logger.warn("Unable to save user color:", err);
} }
}); });
this.b.on( this.b.on(
@ -17612,8 +17637,9 @@ var TalkomaticBot = class extends import_node_events.EventEmitter {
} }
oldText = ""; oldText = "";
sendChat(text, reply, id) { sendChat(text, reply, id) {
if (this.oldText.split("\n").reverse()[0].toLowerCase().includes("autofish")) const fixedOld = this.oldText.split("\n")[-1];
text = [this.oldText, text].join("\n").split("\n").slice(-5).join("\n"); if (text.toLowerCase().includes("autofish"))
text = `${fixedOld ? fixedOld + "\n" : ""}${text}`;
const msg = { const msg = {
roomId: this.channelId, roomId: this.channelId,
// text: text.split("sack").join("ʂасκ"), // text: text.split("sack").join("ʂасκ"),

View File

@ -2,6 +2,7 @@ import { getBacks, flushBacks } from "@server/backs";
import { commandGroups } from "@server/commands/groups"; import { commandGroups } from "@server/commands/groups";
import { handleCommand } from "@server/commands/handler"; import { handleCommand } from "@server/commands/handler";
import { prefixes } from "@server/commands/prefixes"; import { prefixes } from "@server/commands/prefixes";
import { kvGet, kvSet } from "@server/data/keyValueStore";
import { checkToken, tokenToID } from "@server/data/token"; import { checkToken, tokenToID } from "@server/data/token";
import { TRPCError, initTRPC } from "@trpc/server"; import { TRPCError, initTRPC } from "@trpc/server";
import { Logger } from "@util/Logger"; import { Logger } from "@util/Logger";
@ -117,7 +118,40 @@ export const appRouter = router({
logger.error(err); logger.error(err);
return undefined; return undefined;
} }
}) }),
saveColor: privateProcedure
.input(
z.object({
userId: z.string(),
color: z.string()
})
)
.query(async opts => {
const { id, json } = await kvSet(`usercolor~${opts.input.userId}`, {
color: opts.input.color
});
return {
success: true,
id,
json
};
}),
getUserColor: privateProcedure
.input(
z.object({
userId: z.string()
})
)
.query(async opts => {
const color = await kvGet(`usercolor~${opts.input.userId}`);
return {
color
};
})
}); });
export type AppRouter = typeof appRouter; export type AppRouter = typeof appRouter;

View File

@ -1,13 +0,0 @@
import Command from "@server/commands/Command";
export const group = new Command(
"group",
["group"],
"Get user group",
"group",
"command.util.group",
async props => {
return JSON.stringify(props);
},
false
);

View File

@ -1 +1 @@
export const prefixes = ["/", "fishing"]; export const prefixes = ["/", "fish/", "fishing/", "f/", "fosh/", "foshong/"];

View File

@ -22,7 +22,7 @@ export async function claimDailyPokemon(userID: string) {
} }
} }
logger.debug("Time remaining:", Date.now() - timestamp); // logger.debug("Time remaining:", Date.now() - timestamp);
// Check if it has been over a day // Check if it has been over a day
if (Date.now() - timestamp > oneDay) { if (Date.now() - timestamp > oneDay) {

View File

@ -27,11 +27,12 @@ const user = {
(globalThis as unknown as any).rl = rl; (globalThis as unknown as any).rl = rl;
rl.setPrompt("> "); rl.setPrompt("> ");
rl.prompt(); rl.prompt();
setPrompt(); await setPrompt();
function setPrompt() { async function setPrompt() {
const color = new CosmicColor(user.color); let color = await trpc.getUserColor.query({ userId: user._id });
rl.setPrompt(`\x1b[38;2;${color.r};${color.g};${color.b}m> `); const c = new CosmicColor(user.color);
rl.setPrompt(`\x1b[38;2;${c.r};${c.g};${c.b}m> `);
} }
rl.on("line", async line => { rl.on("line", async line => {
@ -98,10 +99,17 @@ setInterval(async () => {
} }
}, 1000 / 20); }, 1000 / 20);
b.on("color", msg => { b.on("color", async msg => {
if (typeof msg.color !== "string" || typeof msg.id !== "string") return; if (typeof msg.color !== "string" || typeof msg.id !== "string") return;
user.color = msg.color; user.color = msg.color;
setPrompt();
trpc.saveColor.query({
userId: user._id,
color: msg.color
});
await setPrompt();
}); });
b.on("sendchat", msg => { b.on("sendchat", msg => {

View File

@ -9,6 +9,7 @@ const convertMarkdownToUnicode = require("markdown-to-unicode");
export interface TalkomaticBotConfig { export interface TalkomaticBotConfig {
channel: { channel: {
name: string; name: string;
type: "public" | "private";
}; };
} }
@ -33,13 +34,8 @@ export class TalkomaticBot extends EventEmitter {
constructor(public config: TalkomaticBotConfig) { constructor(public config: TalkomaticBotConfig) {
super(); super();
this.logger = new Logger("Talkomatic - " + config.channel.name);
// this.client = new Client(config.uri, token);
// this.client = io(
// "wss://talkomatic.co/socket.io/?EIO=4&transport=websocket&sid=f_X4Z5LB8lKBlybNAdj8"
// );
// this.logger.debug(process.env.TALKOMATIC_SID); this.logger = new Logger("Talkomatic - " + config.channel.name);
this.client = io("https://talkomatic.co/", { this.client = io("https://talkomatic.co/", {
extraHeaders: { extraHeaders: {
@ -47,17 +43,21 @@ export class TalkomaticBot extends EventEmitter {
}, },
autoConnect: false autoConnect: false
}); });
this.bindEventListeners();
} }
public async start() { public async start() {
this.logger.info("Starting"); this.logger.info("Starting");
this.client.connect(); this.client.connect();
// this.client.io.engine.on("packetCreate", this.logger.debug); // this.client.io.engine.on("packetCreate", this.logger.debug);
this.bindEventListeners();
let data = let data =
(await this.findChannel(this.config.channel.name)) || (await this.findChannel(this.config.channel.name)) ||
(await this.createChannel(this.config.channel.name)); (await this.createChannel(
this.config.channel.name,
this.config.channel.type
));
this.logger.debug(data); this.logger.debug(data);
if (typeof data !== "undefined") { if (typeof data !== "undefined") {
@ -113,7 +113,7 @@ export class TalkomaticBot extends EventEmitter {
this.client.on( this.client.on(
"udpateRoom", "udpateRoom",
(msg: { async (msg: {
users: { users: {
id: string; id: string;
username: string; username: string;
@ -125,22 +125,35 @@ export class TalkomaticBot extends EventEmitter {
if (!Array.isArray(msg.users)) return; if (!Array.isArray(msg.users)) return;
try { try {
for (const user of msg.users) { for (const user of msg.users) {
let color = (
await this.trpc.getUserColor.query({
userId: user.id
})
).color;
this.logger.debug(
"(updateRoom) user color from api:",
color
);
const p = ppl[user.id] || { const p = ppl[user.id] || {
name: user.username, name: user.username,
id: user.id, id: user.id,
color: "#abe3d6", color,
typingFlag: false typingFlag: false
}; };
ppl[user.id] = p; ppl[user.id] = p;
} }
} catch (err) {} } catch (err) {
this.logger.warn("Unable to set user data:", err);
}
} }
); );
this.client.on( this.client.on(
"roomUsers", "roomUsers",
(msg: { async (msg: {
users: { users: {
id: string; id: string;
username: string; username: string;
@ -153,10 +166,23 @@ export class TalkomaticBot extends EventEmitter {
if (!Array.isArray(msg.users)) return; if (!Array.isArray(msg.users)) return;
try { try {
for (const user of msg.users) { for (const user of msg.users) {
let color = (
await this.trpc.getUserColor.query({
userId: user.id
})
).color;
if (!color) color = this.defaultColor;
this.logger.debug(
"(roomUsers) user color from api:",
color
);
const p = ppl[user.id] || { const p = ppl[user.id] || {
name: user.username, name: user.username,
id: user.id, id: user.id,
color: "#abe3d6", color,
typingFlag: false typingFlag: false
}; };
@ -183,6 +209,13 @@ export class TalkomaticBot extends EventEmitter {
msg.text.startsWith(pr) msg.text.startsWith(pr)
); );
let color = (
await this.trpc.getUserColor.query({
userId: msg.userId
})
).color;
if (!color) color = this.defaultColor;
if (!usedPrefix) return; if (!usedPrefix) return;
const args = msg.text.split(" "); const args = msg.text.split(" ");
@ -190,7 +223,7 @@ export class TalkomaticBot extends EventEmitter {
let part: TalkomaticParticipant = ppl[msg.userId] || { let part: TalkomaticParticipant = ppl[msg.userId] || {
name: "<unknown user>", name: "<unknown user>",
id: msg.userId, id: msg.userId,
color: this.defaultColor, color,
typingFlag: false typingFlag: false
}; };
@ -248,13 +281,21 @@ export class TalkomaticBot extends EventEmitter {
} }
}, 1000 / 20); }, 1000 / 20);
this.b.on("color", msg => { this.b.on("color", async msg => {
if (typeof msg.color !== "string" || typeof msg.id !== "string") if (typeof msg.color !== "string" || typeof msg.id !== "string")
return; return;
// this.textColor = msg.color; // this.textColor = msg.color;
try { try {
ppl[msg.id].color = msg.color; ppl[msg.id].color = msg.color;
} catch (err) {}
await this.trpc.saveColor.query({
userId: msg.id,
color: msg.color
});
} catch (err) {
this.logger.warn("Unable to save user color:", err);
}
}); });
this.b.on( this.b.on(
@ -274,18 +315,10 @@ export class TalkomaticBot extends EventEmitter {
private oldText: string = ""; private oldText: string = "";
public sendChat(text: string, reply?: string, id?: string) { public sendChat(text: string, reply?: string, id?: string) {
if ( const fixedOld = this.oldText.split("\n")[-1];
this.oldText
.split("\n") if (text.toLowerCase().includes("autofish"))
.reverse()[0] text = `${fixedOld ? fixedOld + "\n" : ""}${text}`;
.toLowerCase()
.includes("autofish")
)
text = [this.oldText, text]
.join("\n")
.split("\n")
.slice(-5)
.join("\n");
const msg = { const msg = {
roomId: this.channelId, roomId: this.channelId,

View File

@ -2,9 +2,13 @@ import { kvGet, kvSet } from "@server/data/keyValueStore";
import { test, expect } from "bun:test"; import { test, expect } from "bun:test";
test("Key value store saves, loads, and deletes", async () => { test("Key value store saves, loads, and deletes", async () => {
await kvSet("test", 1); const stuff = {
potatoes: 30
};
await kvSet("test", stuff);
const val = await kvGet("test"); const val = await kvGet("test");
expect(val).toBe(1); expect(val.potatoes).toBe(30);
await kvSet("test", undefined); await kvSet("test", undefined);
const val2 = await kvGet("test"); const val2 = await kvGet("test");