Skip to content

Commit

Permalink
updated bot.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
GhomKrosmonaute committed Oct 27, 2024
1 parent ba2a27e commit c97f954
Show file tree
Hide file tree
Showing 13 changed files with 123 additions and 98 deletions.
90 changes: 45 additions & 45 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,60 +10,60 @@ import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all
});

export default [
...compat.extends("eslint:recommended", "plugin:@typescript-eslint/recommended"),
{
plugins: {
"@typescript-eslint": typescriptEslint,
import: fixupPluginRules(_import),
},
...compat.extends("eslint:recommended", "plugin:@typescript-eslint/recommended"),
{
plugins: {
"@typescript-eslint": typescriptEslint,
import: fixupPluginRules(_import),
},

languageOptions: {
parser: tsParser,
},
languageOptions: {
parser: tsParser,
},

settings: {
"import/resolver": {
alias: {
map: [
["#tables", "./src/tables"],
["#buttons", "./src/buttons"],
["#src", "./src"]
],
extensions: [".ts", ".js", ".jsx", ".tsx"],
},
settings: {
"import/resolver": {
alias: {
map: [
["#tables", "./src/tables"],
["#buttons", "./src/buttons"],
["#src", "./src"]
],
extensions: [".ts", ".js", ".jsx", ".tsx"],
},

node: {
extensions: [".js", ".jsx", ".ts", ".tsx"],
moduleDirectory: ["node_modules", "src/"],
},
},
node: {
extensions: [".js", ".jsx", ".ts", ".tsx"],
moduleDirectory: ["node_modules", "src/"],
},
},
},

rules: {
"import/extensions": ["error", "ignorePackages", {
js: "always",
ts: "always",
mjs: "never",
jsx: "never",
tsx: "never",
}],
rules: {
"import/extensions": ["error", "ignorePackages", {
js: "always",
ts: "always",
mjs: "never",
jsx: "never",
tsx: "never",
}],

"import/no-unresolved": ["error", {
ignore: ["^#app$", "^#config$", "^#env$", "^#client$", "^#logger$", "^#database$", "^@ghom/orm$"],
}],
"import/no-unresolved": ["error", {
ignore: ["^#app$", "^#config$", "^#env$", "^#client$", "^#logger$", "^#database$", "^@ghom/orm$"],
}],

"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/no-explicit-any": "off",
"no-prototype-builtins": "off",
"no-control-regex": "off",
"no-misleading-character-class": "off",
"no-empty": "off",
},
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/no-explicit-any": "off",
"no-prototype-builtins": "off",
"no-control-regex": "off",
"no-misleading-character-class": "off",
"no-empty": "off",
},
},
];
38 changes: 19 additions & 19 deletions src/app/button.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ export interface IButton {
* The parameters that the button will receive.
* @example
* ```ts
* export type BuyButtonParams = [article: string, quantity: number]
* export type BuyButtonParams = { article: string, quantity: number }
* ```
*/
export type ButtonParams = (string | number | boolean)[]
export type ButtonParams = Record<string, string | boolean | number> | null

export interface ButtonOptions<Params extends ButtonParams> {
key: string
Expand All @@ -85,54 +85,54 @@ export interface ButtonOptions<Params extends ButtonParams> {
adminOnly?: boolean
botOwnerOnly?: boolean
cooldown?: util.Cooldown
builder?: (button: discord.ButtonBuilder, ...params: Params) => unknown
builder?: (button: discord.ButtonBuilder, params: Params) => unknown
run: (
this: ButtonOptions<Params>,
interaction: ButtonSystemInteraction,
...params: Params
params: Params,
) => unknown
}

/**
* Represents a button handler. <br>
* See the {@link https://ghom.gitbook.io/bot.ts/usage/create-a-button guide} for more information.
*/
export class Button<Params extends ButtonParams> {
export class Button<Params extends ButtonParams = null> {
filepath?: string
native = false

constructor(public options: ButtonOptions<Params>) {}

public create(...params: Params): discord.ButtonBuilder {
return createButton(this, ...params)
public create(): discord.ButtonBuilder
public create(params: Params): discord.ButtonBuilder
public create(params?: Params): discord.ButtonBuilder {
return createButton(this, params!)
}
}

export function decodeButtonCustomId(
customId: string,
): [string, ...ButtonParams] {
return customId.split(";").map(decodeURIComponent) as [
string,
...ButtonParams,
]
export const BUTTON_CODE_SEPARATOR = ";://i//?;"

export function decodeButtonCustomId(customId: string): [string, ButtonParams] {
const [key, params] = customId.split(BUTTON_CODE_SEPARATOR)
return [key, JSON.parse(params)]
}

export function encodeButtonCustomId(
key: string,
...params: ButtonParams
params: ButtonParams,
): string {
return `${key};${params.map(encodeURIComponent).join(";")}`
return `${key}${BUTTON_CODE_SEPARATOR}${JSON.stringify(params)}`
}

export function createButton<Params extends ButtonParams>(
handler: Button<Params>,
...params: Params
params: Params,
): discord.ButtonBuilder {
const button = new discord.ButtonBuilder()
.setCustomId(encodeButtonCustomId(handler.options.key, ...params))
.setCustomId(encodeButtonCustomId(handler.options.key, params))
.setStyle(discord.ButtonStyle.Primary)

handler.options.builder?.(button, ...params)
handler.options.builder?.(button, params)

return button
}
Expand Down
2 changes: 1 addition & 1 deletion src/app/pagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export abstract class Paginator {
new discord.ActionRowBuilder<discord.MessageActionRowComponentBuilder>().addComponents(
Paginator.keys.map((key) => {
const button = paginationButton
.create(key)
.create({ key })
.setStyle(
this.options.buttonStyle ??
Paginator.defaults.buttonStyle ??
Expand Down
15 changes: 10 additions & 5 deletions src/app/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,9 +490,9 @@ export type SystemMessageType = "default" | keyof SystemEmojis

export interface GetSystemMessageOptions {
/**
* js, json, ts, etc.
* if given, a formatted code clock will be displayed
* if true, the code block will be displayed without lang
* js, json, ts, etc. <br>
* If given, a formatted code clock will be displayed <br>
* If true, the code block will be displayed without lang
*/
code?: boolean | string

Expand Down Expand Up @@ -549,8 +549,13 @@ export async function getSystemMessage(
output.embeds = [
new discord.EmbedBuilder()
.setColor(systemColors[type])
.setTitle(message.header ?? null)
.setDescription(output.content!)
.setDescription(
message.header
? `### ${
type === "default" ? "" : getSystemEmoji(type)
} ${message.header}\n${output.content}`.trim()
: output.content!,
)
.setFooter(message.footer ? { text: message.footer } : null)
.setTimestamp(message.date ?? null)
.toJSON(),
Expand Down
23 changes: 13 additions & 10 deletions src/buttons/givePoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@ import * as app from "#app"
import points from "#tables/point.ts"
import helping from "#tables/helping.ts"

export type GivePointsButtonParams = [toId: string, amount: number]
export type GivePointsButtonParams = []

export default new app.Button<GivePointsButtonParams>({
export default new app.Button<{
targetId: string
amount: number
}>({
key: "givePoints",
description: "Gives some helping points to a user",
guildOnly: true,
builder: (builder) => builder.setEmoji("👍"),
async run(interaction, toId, amount) {
async run(interaction, { targetId, amount }) {
if (!interaction.channel?.isThread()) return

await interaction.deferReply({ ephemeral: true })
Expand All @@ -21,7 +24,7 @@ export default new app.Button<GivePointsButtonParams>({

const fromId = interaction.user.id

if (fromId === toId)
if (fromId === targetId)
return await interaction.editReply({
content: `${app.emote(
interaction,
Expand All @@ -37,7 +40,7 @@ export default new app.Button<GivePointsButtonParams>({
})

const fromUser = await app.getUser({ id: fromId }, true)
const toUser = await app.getUser({ id: toId }, true)
const toUser = await app.getUser({ id: targetId }, true)

await points.query.insert({
from_id: fromUser._id,
Expand All @@ -48,16 +51,16 @@ export default new app.Button<GivePointsButtonParams>({

await app.sendLog(
interaction.guild!,
`${interaction.user} gave **${amount}** points to ${app.userMention(toId)} in ${interaction.channel}.`,
`${interaction.user} gave **${amount}** points to ${app.userMention(targetId)} in ${interaction.channel}.`,
)

await interaction.editReply({
content: `${app.emote(interaction, "CheckMark")} Successfully thanked ${app.userMention(
toId,
targetId,
)}`,
})

const target = await interaction.client.users.fetch(toId, {
const target = await interaction.client.users.fetch(targetId, {
cache: false,
force: true,
})
Expand All @@ -78,8 +81,8 @@ export default new app.Button<GivePointsButtonParams>({
await helping.query.where("id", interaction.channel.id).update({
rewarded_helper_ids:
state && state.rewarded_helper_ids !== ""
? [...state.rewarded_helper_ids.split(";"), toId].join(";")
: toId,
? [...state.rewarded_helper_ids.split(";"), targetId].join(";")
: targetId,
})

await app.refreshHelpingFooter(interaction.channel)
Expand Down
8 changes: 4 additions & 4 deletions src/buttons/pagination.native.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import * as button from "#src/app/button.ts"
import type * as pagination from "#src/app/pagination.ts"

export type PaginationButtonParams = [key: pagination.PaginatorKey]

export default new button.Button<PaginationButtonParams>({
export default new button.Button<{
key: pagination.PaginatorKey
}>({
key: "pagination",
description: "The pagination button",
async run(interaction, key) {
async run(interaction, { key }) {
const app = await import("#app")

const paginator = app.Paginator.getByMessage(interaction.message)
Expand Down
4 changes: 2 additions & 2 deletions src/buttons/resolveTopic.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import * as app from "#app"
import helping from "#tables/helping.ts"

export default new app.Button<[]>({
export default new app.Button({
key: "resolveTopic",
description: "Mark the topic as resolved",
guildOnly: true,
builder: (builder) =>
builder.setLabel("Résolu").setStyle(app.ButtonStyle.Success).setEmoji("✅"),
async run(interaction /*, ...params */) {
async run(interaction) {
if (!interaction.channel?.isThread()) return

await interaction.deferReply({ ephemeral: true })
Expand Down
4 changes: 2 additions & 2 deletions src/buttons/upTopic.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as app from "#app"

export default new app.Button<[]>({
export default new app.Button({
key: "upTopic",
description: "Up the topic in the help forum",
guildOnly: true,
Expand All @@ -13,7 +13,7 @@ export default new app.Button<[]>({
.setLabel("Remonter")
.setEmoji("🆙")
.setStyle(app.ButtonStyle.Secondary),
async run(interaction /*, ...params */) {
async run(interaction) {
if (!interaction.channel?.isThread()) return

await interaction.deferUpdate()
Expand Down
22 changes: 19 additions & 3 deletions src/commands/terminal.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,16 @@ export default new app.Command({
message.triggerCooldown()

const toEdit = await message.channel.send(
await app.getSystemMessage("loading", "The process is running..."),
await app.getSystemMessage(
"loading",
{
header: "The process is running...",
body: message.rest,
},
{
code: "bash",
},
),
)

let systemMessage: app.SystemMessage
Expand All @@ -39,9 +48,16 @@ export default new app.Command({
"success",
{
header: "The process is done",
body: output.split("").reverse().slice(0, 2000).reverse().join(""),
body:
output
.split("")
.reverse()
.slice(0, 2000)
.reverse()
.join("")
.trim() || "void",
},
{ code: true },
{ code: "js" },
)
} catch (error: any) {
systemMessage = await app.getSystemMessage(
Expand Down
Loading

0 comments on commit c97f954

Please sign in to comment.