Files
no-twitter-bot/src/main.ts
Lucid df433c1951
All checks were successful
Main / build-and-push-docker-image (20.x) (push) Successful in 4m58s
Added cache exchange urq, fixed eslint, added prettier, upgraded yarn, added statsSite command.
2026-01-02 10:10:20 -05:00

126 lines
2.9 KiB
TypeScript

#!/usr/bin/env tsx
import type { PollingConfig, WebhookConfig } from "#root/config.js";
import type { RunnerHandle } from "@grammyjs/runner";
import process from "node:process";
import { createBot } from "#root/bot/index.js";
import { config } from "#root/config.js";
import { logger } from "#root/logger.js";
import { createServer, createServerManager } from "#root/server/index.js";
import { run } from "@grammyjs/runner";
import { cacheExchange, Client, fetchExchange } from "@urql/core";
async function startPolling(config: PollingConfig) {
const bot = createBot(config.botToken, {
config,
logger
});
// eslint-disable-next-line prefer-const
let runner: undefined | RunnerHandle;
// graceful shutdown
onShutdown(async () => {
logger.info("Shutdown");
await runner?.stop();
});
await Promise.all([bot.init(), bot.api.deleteWebhook()]);
// start bot
runner = run(bot, {
runner: {
fetch: {
allowed_updates: config.botAllowedUpdates
}
}
});
logger.info({
msg: "Bot running...",
username: bot.botInfo.username
});
}
async function startWebhook(config: WebhookConfig) {
const bot = createBot(config.botToken, {
config,
logger
});
const server = createServer({
bot,
config,
logger
});
const serverManager = createServerManager(server, {
host: config.serverHost,
port: config.serverPort
});
// graceful shutdown
onShutdown(async () => {
logger.info("Shutdown");
await serverManager.stop();
});
// to prevent receiving updates before the bot is ready
await bot.init();
const setWebhook = async (): Promise<void> => {
// set webhook
return await bot.api
.setWebhook(config.botWebhook, {
allowed_updates: config.botAllowedUpdates,
secret_token: config.botWebhookSecret
})
.then(() => {
logger.info({
msg: "Webhook was set",
url: config.botWebhook
});
});
};
// start server
const info = await serverManager.start().then(async info => {
logger.info({
msg: "Server started",
url: info.url
});
setTimeout(async () => {
await setWebhook();
}, 10000);
});
}
try {
if (config.isWebhookMode) await startWebhook(config);
else if (config.isPollingMode) await startPolling(config);
} catch (error) {
logger.error(error);
process.exit(1);
}
// Utils
function onShutdown(cleanUp: () => Promise<void>) {
let isShuttingDown = false;
const handleShutdown = async () => {
if (isShuttingDown) return;
isShuttingDown = true;
await cleanUp();
};
process.on("SIGINT", handleShutdown);
process.on("SIGTERM", handleShutdown);
}
export const urql = new Client({
url: process.env.GRAPHQL_URL || "",
exchanges: [fetchExchange, cacheExchange],
fetchOptions: {
headers: {
"x-api-key": process.env?.GRAPHQL_API_TOKEN || ""
}
}
});