formatting

This commit is contained in:
artie 2025-02-17 23:21:49 +01:00
parent 0a628b9dd9
commit 433df9364f
24 changed files with 114 additions and 127 deletions

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"arrowParens": "avoid",
"trailingComma": "es5"
}

View File

@ -43,7 +43,7 @@ export class ArtemisClient extends Client {
const rest = new REST().setToken(env.DISCORD_TOKEN);
this.api = new API(rest);
this.on("error", (err) => {
this.on("error", err => {
logger.error(err);
});
}
@ -56,15 +56,15 @@ export class ArtemisClient extends Client {
const commandsDir = path.join(import.meta.dir, "commands");
const categories = await fs
.readdir(commandsDir)
.then((categories) =>
categories.filter((category) => !category.includes("."))
.then(categories =>
categories.filter(category => !category.includes("."))
);
const promises: Promise<void>[] = [];
for (const category of categories) {
const files = await fs
.readdir(path.join(commandsDir, category))
.then((files) => files.filter((file) => file.endsWith(".ts")));
.then(files => files.filter(file => file.endsWith(".ts")));
for (const file of files) {
promises.push(
@ -90,7 +90,7 @@ export class ArtemisClient extends Client {
const eventsDir = path.join(import.meta.dir, "events");
const files = await fs
.readdir(eventsDir)
.then((files) => files.filter((file) => file !== "index.ts"));
.then(files => files.filter(file => file !== "index.ts"));
for (const file of files) {
const { default: event } = await import(path.join(eventsDir, file));
@ -107,8 +107,8 @@ export class ArtemisClient extends Client {
}
const publicCommands = this.commands
.filter((command) => !command.isOwnerOnly)
.map((command) =>
.filter(command => !command.isOwnerOnly)
.map(command =>
command.data
.setIntegrationTypes(
ApplicationIntegrationType.GuildInstall,
@ -122,8 +122,8 @@ export class ArtemisClient extends Client {
.toJSON()
);
const ownerCommands = this.commands
.filter((command) => command.isOwnerOnly)
.map((command) =>
.filter(command => command.isOwnerOnly)
.map(command =>
command.data
.setIntegrationTypes(ApplicationIntegrationType.GuildInstall)
.toJSON()
@ -138,7 +138,7 @@ export class ArtemisClient extends Client {
...publicCommands,
...ownerCommands,
])
.then((res) => (guildCount += res.length));
.then(res => (guildCount += res.length));
} else {
await this.api.applicationCommands
.bulkOverwriteGuildCommands(
@ -146,10 +146,10 @@ export class ArtemisClient extends Client {
env.DEV_GUILD_ID,
ownerCommands
)
.then((res) => (guildCount += res.length));
.then(res => (guildCount += res.length));
await this.api.applicationCommands
.bulkOverwriteGlobalCommands(env.APPLICATION_ID, publicCommands)
.then((res) => (globalCount += res.length));
.then(res => (globalCount += res.length));
}
logger.info(

View File

@ -27,10 +27,10 @@ export async function translateAutocompleteImpl(
? await getSourceLanguages()
: await getTargetLanguages();
const choices = languages
.filter((language) =>
.filter(language =>
language.name.toLowerCase().includes(option.value.toLowerCase())
)
.map((language) => ({
.map(language => ({
name: language.name,
value: language.code,
}))
@ -109,19 +109,19 @@ export default defineCommand({
.setDescription(
"Translates text using DeepL or Google Translate as fallback"
)
.addStringOption((option) =>
.addStringOption(option =>
option
.setName("text")
.setDescription("The text to translate")
.setRequired(true)
)
.addStringOption((option) =>
.addStringOption(option =>
option
.setName("source")
.setDescription("Source language of the text")
.setAutocomplete(true)
)
.addStringOption((option) =>
.addStringOption(option =>
option
.setName("target")
.setDescription("Target language of the text")

View File

@ -13,36 +13,29 @@ import { translateImpl } from "./translate";
import { findFuzzyLanguage } from "../../utils/deepl";
export function buildTranslateModal() {
const modal = new ModalBuilder()
return new ModalBuilder()
.setTitle("Translate")
.setCustomId("translate-modal");
const sourceInput = new TextInputBuilder()
.setLabel("Source language")
.setCustomId("source")
.setStyle(TextInputStyle.Short)
.setMaxLength(20)
.setPlaceholder("en, pl, hungarian, japanese...")
.setRequired(false);
const targetInput = new TextInputBuilder()
.setLabel("Target language")
.setCustomId("target")
.setStyle(TextInputStyle.Short)
.setMaxLength(20)
.setPlaceholder("en, pl, hungarian, japanese...")
.setRequired(false);
const sourceRow =
new ActionRowBuilder<ModalActionRowComponentBuilder>().addComponents(
sourceInput
.setCustomId("translate-modal")
.addComponents(
new ActionRowBuilder<ModalActionRowComponentBuilder>().addComponents(
new TextInputBuilder()
.setLabel("Source language")
.setCustomId("source")
.setStyle(TextInputStyle.Short)
.setMaxLength(20)
.setPlaceholder("en, pl, hungarian, japanese...")
.setRequired(false)
),
new ActionRowBuilder<ModalActionRowComponentBuilder>().addComponents(
new TextInputBuilder()
.setLabel("Target language")
.setCustomId("target")
.setStyle(TextInputStyle.Short)
.setMaxLength(20)
.setPlaceholder("en, pl, hungarian, japanese...")
.setRequired(false)
)
);
const targetRow =
new ActionRowBuilder<ModalActionRowComponentBuilder>().addComponents(
targetInput
);
return modal.addComponents(sourceRow, targetRow);
}
export default defineCommand({
@ -61,10 +54,10 @@ export default defineCommand({
await interaction
.awaitModalSubmit({
filter: (i) => i.customId === "translate-modal",
filter: i => i.customId === "translate-modal",
time: 60000 * 5,
})
.then(async (interaction) => {
.then(async interaction => {
await interaction.deferReply();
const sourceField =
@ -75,15 +68,11 @@ export default defineCommand({
const source =
sourceField === "auto"
? null
: await findFuzzyLanguage(sourceField, "source").then(
(l) => l?.code
);
: await findFuzzyLanguage(sourceField, "source").then(l => l?.code);
const target =
targetField === "en-US"
? targetField
: await findFuzzyLanguage(targetField, "target").then(
(l) => l?.code
);
: await findFuzzyLanguage(targetField, "target").then(l => l?.code);
if (source === undefined) {
abort("Source language not found");

View File

@ -12,7 +12,7 @@ export default defineCommand({
data: new SlashCommandBuilder()
.setName("wiktionary")
.setDescription("Looks up a term on Wiktionary")
.addStringOption((option) =>
.addStringOption(option =>
option
.setName("term")
.setDescription("The term to look up")
@ -33,12 +33,12 @@ export default defineCommand({
return;
}
suggestions.forEach((suggestion) => {
suggestions.forEach(suggestion => {
titleCache.set(suggestion.key, suggestion.title);
});
const choices = suggestions
.map((suggestion) => ({
.map(suggestion => ({
name: suggestion.title,
value: `:${suggestion.key}`,
}))
@ -69,17 +69,17 @@ export default defineCommand({
const title = titleCache.get(term) ?? term;
const msg = new PaginatedMessage();
msg.setSelectMenuOptions((i) => ({
msg.setSelectMenuOptions(i => ({
label: definitions[i - 1].language,
description: `Page ${i}`,
}));
definitions.forEach((definition) => {
definitions.forEach(definition => {
const description = definition.entries
.map((entry) => {
.map(entry => {
const name = entry.partOfSpeech;
const definitions = entry.definitions
.filter((def) => def.definition)
.filter(def => def.definition)
.map((def, i) => {
const prefix = inlineCode(`${i + 1}.`);
const definition = stripHtml(def.definition);
@ -91,7 +91,7 @@ export default defineCommand({
})
.join("\n\n");
msg.addPageEmbed((embed) =>
msg.addPageEmbed(embed =>
embed
.setAuthor({
name: `Wiktionary - ${definition.language}`,

View File

@ -102,10 +102,10 @@ export default defineCommand({
data: new SlashCommandBuilder()
.setName("ocr")
.setDescription("OCR an image using Google Lens or Yandex as fallback")
.addAttachmentOption((option) =>
.addAttachmentOption(option =>
option.setName("image").setDescription("The image to OCR")
)
.addStringOption((option) =>
.addStringOption(option =>
option.setName("url").setDescription("The image URL to OCR")
),

View File

@ -15,19 +15,19 @@ export default defineCommand({
.setDescription(
"OCR an image using Google Lens or Yandex and translate the result using DeepL or Google Translate"
)
.addAttachmentOption((option) =>
.addAttachmentOption(option =>
option.setName("image").setDescription("The image to OCR")
)
.addStringOption((option) =>
.addStringOption(option =>
option.setName("url").setDescription("The image URL to OCR")
)
.addStringOption((option) =>
.addStringOption(option =>
option
.setName("source")
.setDescription("Source language of the text")
.setAutocomplete(true)
)
.addStringOption((option) =>
.addStringOption(option =>
option
.setName("target")
.setDescription("Target language of the text")

View File

@ -22,10 +22,10 @@ export default defineCommand({
await interaction
.awaitModalSubmit({
filter: (i) => i.customId === "translate-modal",
filter: i => i.customId === "translate-modal",
time: 60000 * 5,
})
.then(async (interaction) => {
.then(async interaction => {
await interaction.deferReply();
const sourceField =
@ -36,15 +36,11 @@ export default defineCommand({
const source =
sourceField === null
? sourceField
: await findFuzzyLanguage(sourceField, "source").then(
(l) => l?.code
);
: await findFuzzyLanguage(sourceField, "source").then(l => l?.code);
const target =
targetField === "en-US"
? targetField
: await findFuzzyLanguage(targetField, "target").then(
(l) => l?.code
);
: await findFuzzyLanguage(targetField, "target").then(l => l?.code);
if (source === undefined) {
abort("Source language not found");

View File

@ -12,7 +12,7 @@ import { defineCommand } from "..";
import { client } from "../../client";
import { abort } from "../../utils/error";
import { restart as restartBot } from "../../utils/restart";
import { shell } from "../../utils/functions";
import { noop, shell } from "../../utils/functions";
export async function sync(interaction: ChatInputCommandInteraction) {
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
@ -39,7 +39,7 @@ export async function restart(interaction: ChatInputCommandInteraction) {
}
export async function update(interaction: ChatInputCommandInteraction) {
const response = await interaction.deferReply({ withResponse: true });
const reply = await interaction.deferReply();
const result = await shell`git pull`;
const output = result.stdout + result.stderr;
@ -63,14 +63,14 @@ export async function update(interaction: ChatInputCommandInteraction) {
});
if (!isUpToDate && !result.failed) {
response.resource?.message
?.awaitMessageComponent({
await reply
.awaitMessageComponent({
componentType: ComponentType.Button,
time: 30000,
filter: (i) => i.user.id === interaction.user.id,
filter: i => i.user.id === interaction.user.id,
dispose: true,
})
.then(async (interaction) => {
.then(async interaction => {
await interaction.update({
components: [],
});
@ -81,7 +81,8 @@ export async function update(interaction: ChatInputCommandInteraction) {
channelId: interaction.message.channelId,
},
});
});
})
.catch(noop);
}
}
@ -89,13 +90,13 @@ export default defineCommand({
data: new SlashCommandBuilder()
.setName("dev")
.setDescription("Owner commands")
.addSubcommand((subcommand) =>
.addSubcommand(subcommand =>
subcommand.setName("sync").setDescription("Sync application commands")
)
.addSubcommand((subcommand) =>
.addSubcommand(subcommand =>
subcommand.setName("restart").setDescription("Restarts the bot")
)
.addSubcommand((subcommand) =>
.addSubcommand(subcommand =>
subcommand.setName("update").setDescription("Updates the bot")
),
isOwnerOnly: true,

View File

@ -7,7 +7,7 @@ export default defineCommand({
data: new SlashCommandBuilder()
.setName("charinfo")
.setDescription("Unicode character info for given text")
.addStringOption((option) =>
.addStringOption(option =>
option
.setName("text")
.setDescription("The text to get info for")

View File

@ -14,7 +14,7 @@ export default defineCommand({
data: new SlashCommandBuilder()
.setName("httpcat")
.setDescription("Sends a cat for the given HTTP code")
.addIntegerOption((option) =>
.addIntegerOption(option =>
option
.setName("code")
.setDescription("HTTP code")

View File

@ -10,7 +10,7 @@ export default defineCommand({
data: new SlashCommandBuilder()
.setName("isdown")
.setDescription("URL healthcheck")
.addStringOption((option) =>
.addStringOption(option =>
option.setName("url").setDescription("The URL to check").setRequired(true)
),

View File

@ -15,19 +15,20 @@ export default defineCommand({
);
}
const msg = (
await interaction.reply({
await interaction
.reply({
content: `:ping_pong: Pong!\nWebSocket latency is ${inlineCode(
Math.round(client.ws.ping).toString()
)} ms.`,
withResponse: true,
})
).resource!.message!;
await msg.edit(
`${msg.content}\nAPI roundtrip latency is ${inlineCode(
(msg.createdTimestamp - interaction.createdTimestamp).toString()
)}ms.`
);
.then(reply => {
const msg = reply.resource?.message;
return msg?.edit(
`${msg?.content}\nAPI roundtrip latency is ${inlineCode(
(msg?.createdTimestamp - interaction.createdTimestamp).toString()
)}ms.`
);
});
},
});

View File

@ -6,7 +6,7 @@ export default defineCommand({
data: new SlashCommandBuilder()
.setName("whois")
.setDescription("Look up IP or domain info")
.addStringOption((option) =>
.addStringOption(option =>
option.setName("query").setDescription("IP or domain").setRequired(true)
),

View File

@ -15,13 +15,13 @@ export default defineCommand({
data: new SlashCommandBuilder()
.setName("wikipedia")
.setDescription("Looks up a thing on Wikipedia")
.addStringOption((option) =>
.addStringOption(option =>
option
.setName("query")
.setDescription("The thing to look up")
.setAutocomplete(true)
)
.addStringOption((option) =>
.addStringOption(option =>
option
.setName("language")
.setDescription("The Wikipedia language edition to use")
@ -37,11 +37,11 @@ export default defineCommand({
const editions = await getWikipediaEditions();
const choices = editions
.filter(
(edition) =>
edition =>
edition.subdomain.toLowerCase() === value ||
edition.language.toLowerCase().includes(value)
)
.map((edition) => ({
.map(edition => ({
name: `${edition.language} (${edition.subdomain})`,
value: `:${edition.subdomain}`,
}))
@ -57,7 +57,7 @@ export default defineCommand({
option.value
);
const choices = suggestions
.map((suggestion) => ({
.map(suggestion => ({
name: suggestion,
value: `:${suggestion}`,
}))
@ -77,10 +77,9 @@ export default defineCommand({
} else {
const editions = await getWikipediaEditions();
const edition =
editions.find((endpoint) => endpoint.subdomain === language) ||
editions.find(endpoint => endpoint.subdomain === language) ||
editions.find(
(endpoint) =>
endpoint.language.toLowerCase() === language.toLowerCase()
endpoint => endpoint.language.toLowerCase() === language.toLowerCase()
);
if (!edition) {
abort("No such Wikipedia language edition");

View File

@ -3,12 +3,12 @@ import { client } from "./client";
import { logger } from "./utils/logger";
import { DiscordAPIError } from "discord.js";
process.on("unhandledRejection", (err) => {
process.on("unhandledRejection", err => {
if (err instanceof DiscordAPIError && err.status >= 500) return;
logger.error(err);
});
process.on("uncaughtException", (err) => {
process.on("uncaughtException", err => {
logger.error(err);
process.exit(1);
});

View File

@ -21,8 +21,8 @@ type InferInteraction<B> = B extends
| SlashCommandSubcommandsOnlyBuilder
? ChatInputCommandInteraction
: B extends ContextMenuCommandBuilder
? MessageContextMenuCommandInteraction | UserContextMenuCommandInteraction
: never;
? MessageContextMenuCommandInteraction | UserContextMenuCommandInteraction
: never;
export interface Command<B extends CommandBuilder = SlashCommandBuilder> {
data: B;

View File

@ -21,19 +21,16 @@ export async function confirmPrompt(
.setStyle(ButtonStyle.Danger)
);
const msg = (
await interaction.reply({
content: message,
components: [row],
withResponse: true,
})
).resource!.message!;
const reply = await interaction.reply({
content: message,
components: [row],
});
const confirmation = await msg
const confirmation = await reply
.awaitMessageComponent({
componentType: ComponentType.Button,
time: 60000,
filter: (i) => i.user.id === interaction.user.id,
filter: i => i.user.id === interaction.user.id,
dispose: true,
})
.catch(() => {

View File

@ -62,7 +62,7 @@ export async function getUsage() {
export async function isSourceLanguage(code: string) {
const sourceLanguages = await getSourceLanguages();
return (
sourceLanguages.find((l) => l.code.toLowerCase() === code.toLowerCase()) !==
sourceLanguages.find(l => l.code.toLowerCase() === code.toLowerCase()) !==
undefined
);
}
@ -70,7 +70,7 @@ export async function isSourceLanguage(code: string) {
export async function isTargetLanguage(code: string) {
const targetLanguages = await getTargetLanguages();
return (
targetLanguages.find((l) => l.code.toLowerCase() === code.toLowerCase()) !==
targetLanguages.find(l => l.code.toLowerCase() === code.toLowerCase()) !==
undefined
);
}

View File

@ -16,7 +16,7 @@ export function pickRandom<T>(arr: T[]): T {
}
export function sleep(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
return new Promise<void>(resolve => setTimeout(resolve, ms));
}
export function chunk<T>(arr: T[], size: number): T[][];

View File

@ -20,7 +20,7 @@ const languageCodes = lazy(
);
export const getLanguages = lazy(() =>
languageCodes().map((code) => ({
languageCodes().map(code => ({
code,
name: languageCodeToName(code),
}))
@ -51,7 +51,7 @@ export async function translate(
return {
translatedText: sentences
.map((s) => s?.trans)
.map(s => s?.trans)
.filter(Boolean)
.join(""),
detectedSourceLang: src,

View File

@ -18,7 +18,7 @@ export async function lensOcr(resource: string | Buffer): Promise<OCRResult> {
}
return {
text: result.segments.map((s) => s.text).join("\n"),
text: result.segments.map(s => s.text).join("\n"),
language: result.language ?? "n/a",
model: "google",
};

View File

@ -52,7 +52,7 @@ export async function maybeSendRestarted() {
if (!channel) return;
await silently(
channel.messages.fetch(state.message.id).then((msg) => msg.react("☑️"))
channel.messages.fetch(state.message.id).then(msg => msg.react("☑️"))
);
}

View File

@ -50,7 +50,7 @@ export const getWikipediaEditions = lazy(async () => {
subdomain: $(el).find("> td:nth-child(5)").text(),
}))
.toArray()
.filter((edition) => edition.language && edition.subdomain);
.filter(edition => edition.language && edition.subdomain);
});
export async function searchWikipedia(client: KyInstance, query: string) {