Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d2fba3883 | ||
|
|
77aa924161 | ||
|
|
b4b6f42a1a | ||
|
|
dd0b7cde36 | ||
|
|
162708812d | ||
|
|
71c9d1635b | ||
|
|
07f9b5c581 |
@@ -1 +1,7 @@
|
||||
# monke-bot
|
||||
# Legica Bot
|
||||
|
||||
Discord bot that scrapes the https://sib.net.hr/legica-dana website and posts the latest legica-dana post to all discord text channels it has permissions to.
|
||||
|
||||
## Documentation
|
||||
|
||||
[Documentation](https://legica.jurmanovic.com/swagger)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "legica-dana",
|
||||
"version": "2.0.0",
|
||||
"version": "2.0.3",
|
||||
"main": "src/app.ts",
|
||||
"scripts": {
|
||||
"start": "bun src/app.ts"
|
||||
@@ -8,20 +8,23 @@
|
||||
"author": "Fran Jurmanović <fjurma12@outlook.com>",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@elysiajs/cron": "^0.7.0",
|
||||
"@elysiajs/static": "^0.7.1",
|
||||
"@elysiajs/swagger": "^0.7.3",
|
||||
"axios": "^0.26.0",
|
||||
"body-parser": "^1.20.2",
|
||||
"cheerio": "^1.0.0-rc.10",
|
||||
"cron": "^3.0.0",
|
||||
"dayjs": "^1.11.10",
|
||||
"discord.js": "^12.5.1",
|
||||
"dotenv": "^8.2.0",
|
||||
"elysia": "^0.7.15",
|
||||
"lodash-es": "^4.17.21",
|
||||
"minimatch": "^9.0.3",
|
||||
"pino": "^8.15.4",
|
||||
"typescript": "^4.1.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/lodash-es": "^4.17.9",
|
||||
"@types/node": "^20.8.2",
|
||||
"@typescript-eslint/eslint-plugin": "^6.7.4",
|
||||
"@typescript-eslint/parser": "^6.7.4",
|
||||
|
||||
2
process-env.d.ts
vendored
2
process-env.d.ts
vendored
@@ -5,6 +5,8 @@ declare global {
|
||||
PORT: string;
|
||||
CRON_LEGICA: string;
|
||||
PASSWORD: string;
|
||||
TIMEZONE: string;
|
||||
LEGICA_DATE_FORMAT: string;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
188
src/app.ts
188
src/app.ts
@@ -1,12 +1,12 @@
|
||||
import { Client } from "discord.js";
|
||||
import { config } from "@constants";
|
||||
import { CronJob } from "cron";
|
||||
import { sendDiscordMessage, sendNextMessage } from "@common";
|
||||
import { Elysia, t } from "elysia";
|
||||
import { swagger } from "@elysiajs/swagger";
|
||||
import { basicAuth } from "@core";
|
||||
import { basicAuth, BasicAuthError } from "@core";
|
||||
import pino from "pino";
|
||||
import staticPlugin from "@elysiajs/static";
|
||||
import cron from "@elysiajs/cron";
|
||||
|
||||
const client: Client = new Client();
|
||||
|
||||
@@ -22,28 +22,48 @@ const logger = pino(
|
||||
fileTransport
|
||||
);
|
||||
|
||||
const taskPlugin = new Elysia({ prefix: "/job" })
|
||||
.state("job", null as CronJob | null)
|
||||
.onStart(({ store }) => {
|
||||
client.on("ready", (): void => {
|
||||
if (store.job) {
|
||||
store.job.stop();
|
||||
async function jobRunner() {
|
||||
try {
|
||||
await sendNextMessage(client);
|
||||
} catch (err) {
|
||||
logger.error(err);
|
||||
}
|
||||
store.job = new CronJob(
|
||||
config.CRON_LEGICA,
|
||||
() => sendNextMessage(client),
|
||||
null,
|
||||
true,
|
||||
"utc"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const taskPlugin = new Elysia({ prefix: "/job" })
|
||||
.use(
|
||||
cron({
|
||||
name: "job",
|
||||
pattern: config.CRON_LEGICA,
|
||||
run: jobRunner,
|
||||
paused: true,
|
||||
timezone: config.TIMEZONE,
|
||||
})
|
||||
.onBeforeHandle(({ store: { job }, set }) => {
|
||||
if (!job) {
|
||||
)
|
||||
.onStart(
|
||||
({
|
||||
store: {
|
||||
cron: { job },
|
||||
},
|
||||
}) => {
|
||||
client.on("ready", (): void => {
|
||||
job.resume();
|
||||
});
|
||||
}
|
||||
)
|
||||
.onBeforeHandle(
|
||||
({
|
||||
store: {
|
||||
cron: { job },
|
||||
},
|
||||
set,
|
||||
}) => {
|
||||
if (job.isStopped()) {
|
||||
set.status = 400;
|
||||
return "Job is not running.";
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
.use(
|
||||
basicAuth({
|
||||
users: [
|
||||
@@ -55,26 +75,65 @@ const taskPlugin = new Elysia({ prefix: "/job" })
|
||||
errorMessage: "Unauthorized",
|
||||
})
|
||||
)
|
||||
.get("/", ({ store: { job } }) => ({
|
||||
running: job?.running ?? false,
|
||||
next: job?.nextDate().toISO(),
|
||||
}))
|
||||
.post("/", ({ store: { job }, set }) => {
|
||||
if (job?.running) {
|
||||
set.status = 400;
|
||||
return "Task already running";
|
||||
.get(
|
||||
"/",
|
||||
({
|
||||
store: {
|
||||
cron: { job },
|
||||
},
|
||||
}) => ({
|
||||
running: job.isRunning() ?? false,
|
||||
stopped: job.isStopped() ?? false,
|
||||
next: job.nextRun()?.toISOString(),
|
||||
}),
|
||||
{
|
||||
detail: {
|
||||
summary: "Get CRON job status",
|
||||
},
|
||||
}
|
||||
job?.start();
|
||||
return "Task started";
|
||||
})
|
||||
.delete("/", ({ store: { job }, set }) => {
|
||||
if (!job?.running) {
|
||||
)
|
||||
.post(
|
||||
"/",
|
||||
({
|
||||
store: {
|
||||
cron: { job },
|
||||
},
|
||||
set,
|
||||
}) => {
|
||||
if (job.isRunning()) {
|
||||
set.status = 400;
|
||||
return "Task already stopped";
|
||||
return "Job already running";
|
||||
}
|
||||
job?.stop();
|
||||
return "Task stopped";
|
||||
})
|
||||
job.resume();
|
||||
return "Job started";
|
||||
},
|
||||
{
|
||||
detail: {
|
||||
summary: "Start CRON job if it is not running",
|
||||
},
|
||||
}
|
||||
)
|
||||
.delete(
|
||||
"/",
|
||||
({
|
||||
store: {
|
||||
cron: { job },
|
||||
},
|
||||
set,
|
||||
}) => {
|
||||
if (!job.isRunning()) {
|
||||
set.status = 400;
|
||||
return "Job already paused";
|
||||
}
|
||||
job.pause();
|
||||
return "Job paused";
|
||||
},
|
||||
{
|
||||
detail: {
|
||||
summary: "Pause CRON job if it is not paused",
|
||||
},
|
||||
}
|
||||
)
|
||||
.post(
|
||||
"/send",
|
||||
async ({ set, body }) => {
|
||||
@@ -92,21 +151,47 @@ const taskPlugin = new Elysia({ prefix: "/job" })
|
||||
}
|
||||
},
|
||||
{
|
||||
body: t.Object({
|
||||
url: t.String(),
|
||||
}),
|
||||
body: t.Optional(
|
||||
t.Object({
|
||||
url: t.Optional(t.String()),
|
||||
})
|
||||
),
|
||||
detail: {
|
||||
summary: "Send legica-dana post to discord channels",
|
||||
},
|
||||
}
|
||||
)
|
||||
.get("/log", () => Bun.file("app.log"));
|
||||
|
||||
client.login(config.TOKEN);
|
||||
|
||||
.get("/log", () => Bun.file("app.log"), {
|
||||
detail: {
|
||||
summary: "Get the error log",
|
||||
},
|
||||
});
|
||||
const app = new Elysia()
|
||||
.onError(({ error }) => {
|
||||
.error({ BASIC_AUTH_ERROR: BasicAuthError })
|
||||
.onError(({ error, code }) => {
|
||||
switch (code) {
|
||||
case "BASIC_AUTH_ERROR":
|
||||
return new Response(error.message, {
|
||||
status: 401,
|
||||
headers: {
|
||||
"WWW-Authenticate": `Basic${
|
||||
config.realm ? ` realm="${config.realm}"` : ""
|
||||
}`,
|
||||
},
|
||||
});
|
||||
case "NOT_FOUND":
|
||||
return new Response(error.message, {
|
||||
status: 404,
|
||||
});
|
||||
default:
|
||||
logger.error(error);
|
||||
return new Response(error.toString());
|
||||
}
|
||||
})
|
||||
.get("/", () => config.APP_VERSION, {
|
||||
detail: {
|
||||
summary: "Get current API version",
|
||||
},
|
||||
})
|
||||
.get("/", () => config.APP_VERSION)
|
||||
.use(
|
||||
swagger({
|
||||
documentation: {
|
||||
@@ -114,6 +199,14 @@ const app = new Elysia()
|
||||
title: "Legica Bot",
|
||||
version: config.APP_VERSION,
|
||||
},
|
||||
security: [
|
||||
{
|
||||
type: ["basic"],
|
||||
},
|
||||
],
|
||||
},
|
||||
swaggerOptions: {
|
||||
withCredentials: true,
|
||||
},
|
||||
})
|
||||
)
|
||||
@@ -121,6 +214,7 @@ const app = new Elysia()
|
||||
.use(taskPlugin)
|
||||
.listen(config.PORT);
|
||||
|
||||
client.login(config.TOKEN);
|
||||
console.log(
|
||||
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
|
||||
`🦊 Elysia is running at http://${app.server?.hostname}:${app.server?.port}`
|
||||
);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { config } from "@constants";
|
||||
import axios from "axios";
|
||||
import cheerio from "cheerio";
|
||||
|
||||
export async function getFirstHtml(): Promise<string> {
|
||||
const response = await axios.get("https://sib.net.hr/legica-dana");
|
||||
const response = await axios.get(config.LEGICA_URL);
|
||||
const html = response.data;
|
||||
const $ = cheerio.load(html);
|
||||
const { href } = $(".News-link.c-def")?.attr() || {};
|
||||
|
||||
@@ -1,13 +1,31 @@
|
||||
import { getFirstHtml, getImgTitle } from "@common";
|
||||
import { config } from "@constants";
|
||||
import dayjs from "dayjs";
|
||||
import customParseFormat from "dayjs/plugin/customParseFormat";
|
||||
import { Client, MessageEmbed, TextChannel } from "discord.js";
|
||||
|
||||
dayjs.extend(customParseFormat);
|
||||
|
||||
export async function sendDiscordMessage(
|
||||
client: Client,
|
||||
url: string
|
||||
url: string,
|
||||
dateCheck?: dayjs.Dayjs
|
||||
): Promise<void> {
|
||||
if (!url) return;
|
||||
const { img, title } = await getImgTitle(url);
|
||||
|
||||
if (dateCheck) {
|
||||
const dateRegex = /\d{1,2}.\d{1,2}.\d{4}/g;
|
||||
const date = dateRegex.exec(title)?.[0];
|
||||
const dayjsDate = dayjs(date, config.LEGICA_DATE_FORMAT);
|
||||
if (!dateCheck.isSame(dayjsDate, "D"))
|
||||
throw new Error(
|
||||
`Post failed date check, date from post ${date}, date checked ${dateCheck.format(
|
||||
config.LEGICA_DATE_FORMAT
|
||||
)}`
|
||||
);
|
||||
}
|
||||
|
||||
client.channels.cache.forEach(async (channel) => {
|
||||
try {
|
||||
if (channel.type !== "text") return null;
|
||||
@@ -39,10 +57,6 @@ export async function sendDiscordMessage(
|
||||
}
|
||||
|
||||
export async function sendNextMessage(client: Client): Promise<void> {
|
||||
try {
|
||||
const href = await getFirstHtml();
|
||||
await sendDiscordMessage(client, href);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
await sendDiscordMessage(client, href, dayjs());
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ const config: ProjectConfig = {
|
||||
CRON_LEGICA: process.env.CRON_LEGICA || "0 9 * * *",
|
||||
APP_VERSION: version,
|
||||
LEGICA_URL: "https://sib.net.hr/legica-dana",
|
||||
TIMEZONE: process.env.TIMEZONE || "utc",
|
||||
LEGICA_DATE_FORMAT: process.env.LEGICA_DATE_FORMAT || "DD.MM.YYYY",
|
||||
};
|
||||
|
||||
export { config };
|
||||
|
||||
@@ -22,7 +22,6 @@ export interface BasicAuthConfig {
|
||||
|
||||
export const basicAuth = (config: BasicAuthConfig) =>
|
||||
new Elysia({ name: "basic-auth", seed: config })
|
||||
.error({ BASIC_AUTH_ERROR: BasicAuthError })
|
||||
.derive((ctx) => {
|
||||
const authorization = ctx.headers?.authorization;
|
||||
if (!authorization) return { basicAuth: { isAuthed: false, username: "" } };
|
||||
@@ -40,19 +39,8 @@ export const basicAuth = (config: BasicAuthConfig) =>
|
||||
!isPathExcluded(ctx.path, config.exclude) &&
|
||||
ctx.request &&
|
||||
ctx.request.method !== "OPTIONS"
|
||||
)
|
||||
) {
|
||||
throw new BasicAuthError(config.errorMessage ?? "Unauthorized");
|
||||
})
|
||||
.onError((ctx) => {
|
||||
if (ctx.code === "BASIC_AUTH_ERROR") {
|
||||
return new Response(ctx.error.message, {
|
||||
status: 401,
|
||||
headers: {
|
||||
"WWW-Authenticate": `Basic${
|
||||
config.realm ? ` realm="${config.realm}"` : ""
|
||||
}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
export { basicAuth } from "./basicAuth";
|
||||
export { basicAuth, BasicAuthError } from "./basicAuth";
|
||||
|
||||
Reference in New Issue
Block a user