Files
ts3gotify/src/app.ts
Timo Behrendt 990e7b1dbe
Some checks failed
CD / Test (push) Successful in 1m0s
CD / Build and push (amd64) (push) Has been cancelled
CD / Build and push (arm64) (push) Has been cancelled
refactor: better env handling (#5)
Reviewed-on: #5
Co-authored-by: Timo Behrendt <t.behrendt@t00n.de>
Co-committed-by: Timo Behrendt <t.behrendt@t00n.de>
2025-01-07 19:46:32 +01:00

137 lines
2.8 KiB
TypeScript

import { Gotify } from "gotify";
import {
QueryProtocol,
TeamSpeak,
TextMessageTargetMode,
} from "ts3-nodejs-library";
import { createLogger, transports, format } from "winston";
import {
GOTIFY_TITLE,
GOTIFY_TOKEN,
GOTIFY_URL,
LOG_LEVEL,
MODE,
TS3_HOST,
TS3_NICKNAME,
TS3_PASSWORD,
TS3_QUERY_PORT,
TS3_SERVER_PORT,
TS3_USERNAME,
} from "./env";
import type { Mode } from "./types";
const logger = createLogger({
level: LOG_LEVEL,
transports: [new transports.Console()],
format: format.combine(format.colorize(), format.timestamp()),
});
const gotify = new Gotify({
server: GOTIFY_URL,
});
const gotifyConfig = {
app: GOTIFY_TOKEN,
title: GOTIFY_TITLE,
};
function getModes(): {
[key in Mode]: boolean;
} {
const modes = MODE.map((mode) => {
return { [mode]: true };
});
return Object.assign(
{
connect: false,
disconnect: false,
moved: false,
message: false,
},
...modes
);
}
function sendNotification(message: string) {
gotify
.send({
...gotifyConfig,
message: message,
})
.catch((error: Error) => {
logger.error(`Error sending message to gotify: ${error.message}`);
});
}
function resolveMessageTarget(target: TextMessageTargetMode): string {
if (target === 1) {
return "Client";
} else if (target === 2) {
return "Channel";
} else {
return "Server";
}
}
function handleMessage(message: string) {
logger.debug(message);
sendNotification(message);
}
TeamSpeak.connect({
host: TS3_HOST,
queryport: TS3_QUERY_PORT,
serverport: TS3_SERVER_PORT,
protocol: QueryProtocol.RAW,
username: TS3_USERNAME,
password: TS3_PASSWORD,
nickname: TS3_NICKNAME,
}).then((teamspeak) => {
const mode = getModes();
logger.info("connected to TS3");
if (mode.connect) {
teamspeak.on("clientconnect", (event) => {
handleMessage(`${event.client.nickname} connected`);
});
}
if (mode.disconnect) {
teamspeak.on("clientdisconnect", (event) => {
handleMessage(`${event.client?.nickname} disconnected`);
});
}
if (mode.message) {
teamspeak.on("textmessage", (event) => {
handleMessage(
`${event.invoker.nickname} wrote ${
event.msg
} to a ${resolveMessageTarget(event.targetmode)}`
);
});
}
if (mode.moved) {
teamspeak.on("clientmoved", (event) => {
handleMessage(
`${event.client.nickname} got moved to ${event.channel.name}`
);
});
}
teamspeak.on("close", async () => {
logger.debug("disconnected, trying to reconnect...");
await teamspeak.reconnect(5, 1000);
logger.info("reconnected!");
});
teamspeak.on("error", (error: Error) => {
logger.error(`Error connecting to TS3 server: ${error.message}`);
process.exit(1);
});
});