fix/types: bot admin checking fixes, other misc fixes, add types

This commit is contained in:
Aidan 2025-04-26 14:54:02 -04:00
parent a192681d18
commit ede26386be
3 changed files with 77 additions and 32 deletions

View File

@ -4,6 +4,7 @@ import spamwatchMiddlewareModule from '../spamwatch/Middleware';
import os from 'os'; import os from 'os';
import { exec } from 'child_process'; import { exec } from 'child_process';
import { error } from 'console'; import { error } from 'console';
import { Context, Telegraf } from 'telegraf';
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch); const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
@ -31,7 +32,7 @@ function updateBot() {
}); });
} }
function formatUptime(uptime) { function formatUptime(uptime: number) {
const hours = Math.floor(uptime / 3600); const hours = Math.floor(uptime / 3600);
const minutes = Math.floor((uptime % 3600) / 60); const minutes = Math.floor((uptime % 3600) / 60);
const seconds = Math.floor(uptime % 60); const seconds = Math.floor(uptime % 60);
@ -52,152 +53,190 @@ function getSystemInfo() {
`*Uptime:* \`${formatUptime(uptime())}\`\n\n`; `*Uptime:* \`${formatUptime(uptime())}\`\n\n`;
} }
async function handleAdminCommand(ctx, action, successMessage, errorMessage) { async function handleAdminCommand(ctx: Context & { message: { text: string } }, action: () => Promise<void>, successMessage: string, errorMessage: string) {
const Strings = getStrings(ctx.from.language_code); const Strings = getStrings(ctx.from?.language_code);
const userId = ctx.from.id; const userId = ctx.from?.id;
const adminArray = JSON.parse("[" + process.env.botAdmins + "]"); const adminArray = process.env.botAdmins ? process.env.botAdmins.split(',').map(id => parseInt(id.trim())) : [];
if (adminArray.includes(userId)) { if (userId && adminArray.includes(userId)) {
try { try {
await action(); await action();
if (successMessage) {
ctx.reply(successMessage, { ctx.reply(successMessage, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
}
} catch (error) { } catch (error) {
ctx.reply(errorMessage.replace(/{error}/g, error.message), { ctx.reply(errorMessage.replace(/{error}/g, error.message), {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
} }
} else { } else {
ctx.reply(Strings.noPermission, { ctx.reply(Strings.noPermission, {
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
} }
} }
export default (bot) => { export default (bot: Telegraf<Context>) => {
bot.command('getbotstats', spamwatchMiddleware, async (ctx) => { bot.command('getbotstats', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
const Strings = getStrings(ctx.from.language_code); const Strings = getStrings(ctx.from?.language_code);
handleAdminCommand(ctx, async () => { handleAdminCommand(ctx, async () => {
const stats = getSystemInfo(); const stats = getSystemInfo();
await ctx.reply(stats, { await ctx.reply(stats, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
}, '', Strings.errorRetrievingStats); }, '', Strings.errorRetrievingStats);
}); });
bot.command('getbotcommit', spamwatchMiddleware, async (ctx) => { bot.command('getbotcommit', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
const Strings = getStrings(ctx.from.language_code); const Strings = getStrings(ctx.from?.language_code);
handleAdminCommand(ctx, async () => { handleAdminCommand(ctx, async () => {
try { try {
const commitHash = await getGitCommitHash(); const commitHash = await getGitCommitHash();
await ctx.reply(Strings.gitCurrentCommit.replace(/{commitHash}/g, commitHash), { await ctx.reply(Strings.gitCurrentCommit.replace(/{commitHash}/g, commitHash), {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
} catch (error) { } catch (error) {
ctx.reply(Strings.gitErrRetrievingCommit.replace(/{error}/g, error), { ctx.reply(Strings.gitErrRetrievingCommit.replace(/{error}/g, error), {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
} }
}, '', Strings.gitErrRetrievingCommit); }, '', Strings.gitErrRetrievingCommit);
}); });
bot.command('updatebot', spamwatchMiddleware, async (ctx) => { bot.command('updatebot', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
const Strings = getStrings(ctx.from.language_code); const Strings = getStrings(ctx.from?.language_code);
handleAdminCommand(ctx, async () => { handleAdminCommand(ctx, async () => {
try { try {
const result = await updateBot(); const result = await updateBot();
await ctx.reply(Strings.botUpdated.replace(/{result}/g, result), { await ctx.reply(Strings.botUpdated.replace(/{result}/g, result), {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
} catch (error) { } catch (error) {
ctx.reply(Strings.errorUpdatingBot.replace(/{error}/g, error), { ctx.reply(Strings.errorUpdatingBot.replace(/{error}/g, error), {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
} }
}, '', Strings.errorUpdatingBot); }, '', Strings.errorUpdatingBot);
}); });
bot.command('setbotname', spamwatchMiddleware, async (ctx) => { bot.command('setbotname', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
const Strings = getStrings(ctx.from.language_code); const Strings = getStrings(ctx.from?.language_code);
const botName = ctx.message.text.split(' ').slice(1).join(' '); const botName = ctx.message.text.split(' ').slice(1).join(' ');
handleAdminCommand(ctx, async () => { handleAdminCommand(ctx, async () => {
await ctx.telegram.setMyName(botName); await ctx.telegram.setMyName(botName);
}, Strings.botNameChanged.replace(/{botName}/g, botName), Strings.botNameErr.replace(/{error}/g, error)); }, Strings.botNameChanged.replace(/{botName}/g, botName), Strings.botNameErr.replace(/{error}/g, error));
}); });
bot.command('setbotdesc', spamwatchMiddleware, async (ctx) => { bot.command('setbotdesc', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
const Strings = getStrings(ctx.from.language_code); const Strings = getStrings(ctx.from?.language_code);
const botDesc = ctx.message.text.split(' ').slice(1).join(' '); const botDesc = ctx.message.text.split(' ').slice(1).join(' ');
handleAdminCommand(ctx, async () => { handleAdminCommand(ctx, async () => {
await ctx.telegram.setMyDescription(botDesc); await ctx.telegram.setMyDescription(botDesc);
}, Strings.botDescChanged.replace(/{botDesc}/g, botDesc), Strings.botDescErr.replace(/{error}/g, error)); }, Strings.botDescChanged.replace(/{botDesc}/g, botDesc), Strings.botDescErr.replace(/{error}/g, error));
}); });
bot.command('botkickme', spamwatchMiddleware, async (ctx) => { bot.command('botkickme', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
const Strings = getStrings(ctx.from.language_code); const Strings = getStrings(ctx.from?.language_code);
handleAdminCommand(ctx, async () => { handleAdminCommand(ctx, async () => {
if (!ctx.chat) {
ctx.reply(Strings.chatNotFound, {
parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id
});
return;
}
ctx.reply(Strings.kickingMyself, { ctx.reply(Strings.kickingMyself, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
await ctx.telegram.leaveChat(ctx.chat.id); await ctx.telegram.leaveChat(ctx.chat.id);
}, '', Strings.kickingMyselfErr); }, '', Strings.kickingMyselfErr);
}); });
bot.command('getfile', spamwatchMiddleware, async (ctx) => { bot.command('getfile', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
const Strings = getStrings(ctx.from.language_code); const Strings = getStrings(ctx.from?.language_code);
const botFile = ctx.message.text.split(' ').slice(1).join(' '); const botFile = ctx.message.text.split(' ').slice(1).join(' ');
if (!botFile) {
ctx.reply(Strings.noFileProvided, {
parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id
});
return;
}
handleAdminCommand(ctx, async () => { handleAdminCommand(ctx, async () => {
try { try {
await ctx.replyWithDocument({ await ctx.replyWithDocument({
// @ts-ignore
source: botFile, source: botFile,
caption: botFile caption: botFile
}, {
// @ts-ignore
reply_to_message_id: ctx.message.message_id
}); });
} catch (error) { } catch (error) {
ctx.reply(Strings.unexpectedErr.replace(/{error}/g, error.message), { ctx.reply(Strings.unexpectedErr.replace(/{error}/g, error.message), {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
} }
}, '', Strings.unexpectedErr); }, '', Strings.unexpectedErr);
}); });
bot.command('run', spamwatchMiddleware, async (ctx) => { bot.command('run', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
const command = ctx.message.text.split(' ').slice(1).join(' '); const command = ctx.message.text.split(' ').slice(1).join(' ');
handleAdminCommand(ctx, async () => { handleAdminCommand(ctx, async () => {
if (!command) { if (!command) {
return ctx.reply('Por favor, forneça um comando para executar.'); ctx.reply('Por favor, forneça um comando para executar.');
return;
} }
exec(command, (error, stdout, stderr) => { exec(command, (error, stdout, stderr) => {
if (error) { if (error) {
return ctx.reply(`\`${error.message}\``, { return ctx.reply(`\`${error.message}\``, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
} }
if (stderr) { if (stderr) {
return ctx.reply(`\`${stderr}\``, { return ctx.reply(`\`${stderr}\``, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
} }
ctx.reply(`\`${stdout}\``, { ctx.reply(`\`${stdout}\``, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
}); });
}, '', "Nope!"); }, '', "Nope!");
}); });
bot.command('eval', spamwatchMiddleware, async (ctx) => { bot.command('eval', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
const code = ctx.message.text.split(' ').slice(1).join(' '); const code = ctx.message.text.split(' ').slice(1).join(' ');
if (!code) { if (!code) {
return ctx.reply('Por favor, forneça um código para avaliar.'); return ctx.reply('Por favor, forneça um código para avaliar.');
@ -207,19 +246,21 @@ export default (bot) => {
const result = eval(code); const result = eval(code);
ctx.reply(`Result: ${result}`, { ctx.reply(`Result: ${result}`, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
} catch (error) { } catch (error) {
ctx.reply(`Error: ${error.message}`, { ctx.reply(`Error: ${error.message}`, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
// @ts-ignore
reply_to_message_id: ctx.message.message_id reply_to_message_id: ctx.message.message_id
}); });
} }
}); });
bot.command('crash', spamwatchMiddleware, async (ctx) => { bot.command('crash', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
handleAdminCommand(ctx, async () => { handleAdminCommand(ctx, async () => {
ctx.reply(null); ctx.reply('Crashed!');
}, '', "Nope!"); }, '', "Nope!");
}); });
}; };

View File

@ -112,5 +112,7 @@
"notFound": "Phone not found.", "notFound": "Phone not found.",
"resultMsg": "*Name:* `{name}`\n*Brand:* `{brand}`\n*Model:* `{model}`\n*Codename:* `{codename}`", "resultMsg": "*Name:* `{name}`\n*Brand:* `{brand}`\n*Model:* `{model}`\n*Codename:* `{codename}`",
"apiErr": "An error occurred while fetching data from the API.\n\n`{err}`" "apiErr": "An error occurred while fetching data from the API.\n\n`{err}`"
} },
"chatNotFound": "Chat not found.",
"noFileProvided": "Please provide a file to send."
} }

View File

@ -112,5 +112,7 @@
"notFound": "Celular não encontrado.", "notFound": "Celular não encontrado.",
"resultMsg": "*Nome:* `{name}`\n*Marca:* `{brand}`\n*Modelo:* `{model}`\n*Codinome:* `{codename}`", "resultMsg": "*Nome:* `{name}`\n*Marca:* `{brand}`\n*Modelo:* `{model}`\n*Codinome:* `{codename}`",
"apiErr": "Ocorreu um erro ao buscar os dados da API.\n\n`{err}`" "apiErr": "Ocorreu um erro ao buscar os dados da API.\n\n`{err}`"
} },
"chatNotFound": "Chat não encontrado.",
"noFileProvided": "Por favor, forneça um arquivo para enviar."
} }