initial commit

This commit is contained in:
2024-10-13 14:50:19 +00:00
commit dbdbf16bfe
34 changed files with 3035 additions and 0 deletions

131
.gitignore vendored Normal file
View File

@@ -0,0 +1,131 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

10
Dockerfile Normal file
View File

@@ -0,0 +1,10 @@
FROM node:22.4-slim AS build
WORKDIR /work
COPY . /work
RUN npm ci && npm run build
FROM gcr.io/distroless/nodejs22-debian12
WORKDIR /work
COPY --from=build /work /work
CMD ["index.js"]

23
classes/command.ts Normal file
View File

@@ -0,0 +1,23 @@
import {
SlashCommandBuilder,
SlashCommandSubcommandsOnlyBuilder,
CommandInteraction
} from 'discord.js';
export interface Component{
execute(interaction: unknown): Promise<void>;
build(): unknown;
};
export abstract class Command implements Component{
abstract get name(): string;
abstract get description(): string;
abstract execute(interaction: CommandInteraction): Promise<void>;
build():
SlashCommandBuilder | SlashCommandSubcommandsOnlyBuilder |
Omit<SlashCommandBuilder, "addSubcommand" | "addSubcommandGroup">{
return new SlashCommandBuilder()
.setName(this.name)
.setDescription(this.description);
}
};

22
classes/extendedclient.ts Normal file
View File

@@ -0,0 +1,22 @@
import {
Client,
Collection,
ClientOptions,
} from 'discord.js';
import {Command} from './command'
export function isExtendedClient(client: Client): client is ExtendedClient{
return (client as ExtendedClient).commands !== undefined;
}
export class ExtendedClient extends Client{
public commands: Collection<string, Command>;
constructor(
opts: ClientOptions,
cmds = new Collection<string, Command>()
){
super(opts);
this.commands = cmds;
}
};

View File

@@ -0,0 +1,152 @@
import discord, {
CommandInteraction,
CommandInteractionOptionResolver,
SlashCommandBuilder,
SlashCommandRoleOption,
SlashCommandStringOption,
SlashCommandIntegerOption,
SlashCommandSubcommandBuilder,
EmbedBuilder,
InteractionResponse,
SlashCommandSubcommandsOnlyBuilder,
} from 'discord.js';
import {HydratedDocument} from 'mongoose';
import {Command} from '../../classes/command';
import {logger} from '../../logger';
import {config} from '../../config';
import {Guild, guildModel} from '../../models/Guild';
import {GiveawayMsg, giveawayMsgModel} from '../../models/GiveawayMsg';
type CIOR = CommandInteractionOptionResolver;
async function add(interaction: CommandInteraction): Promise<void>{
const message: string | null =
(interaction.options as CIOR).getString('message');
if(!message)
throw Error('message not exist');
const embed = new EmbedBuilder()
.setTitle('New Giveaway')
.setDescription(`@everyone\n${message}`);
if(!interaction.guildId)
throw Error('guildId not exist');
if(!interaction.channelId)
throw Error('channelId not exist');
let msg: discord.Message =
await (await interaction.reply({embeds: [embed]})).fetch();
await msg.react(config.giveaway.emoji);
if(!interaction.guild || !interaction.guild.id)
throw Error('guild not exist');
const guild: HydratedDocument<Guild> | null =
await guildModel.findOneAndUpdate(
{id: interaction.guild.id},
{$set: {name: interaction.guild.name}},
{upsert: true, new: true}
);
if(!guild)
throw Error('guild not exist');
const giveawayMsg: HydratedDocument<GiveawayMsg> | null =
await giveawayMsgModel.findOneAndUpdate(
{guild: guild, messageId: msg.id, authorId: interaction.user.id},
{}, {upsert: true, new: true}
);
if(!giveawayMsg)
throw Error('giveawayMsg not exist');
await msg.edit({embeds: [new EmbedBuilder()
.setColor(Math.floor(Math.random()*16777215))
.setTitle('Giveaway')
.setDescription(message)
.setFooter({text: `id: ${msg.id}`})
]});
}
async function pick(interaction: CommandInteraction): Promise<void>{
const messageId: string | null =
(interaction.options as CIOR).getString('message');
if(!messageId)
throw Error('message not exist');
const num: number | null =
(interaction.options as CIOR).getInteger('number');
if(!num)
throw Error('number not exist');
const dbGiveawayMsg: HydratedDocument<GiveawayMsg> | null =
await giveawayMsgModel.findOneAndDelete({
messageId: messageId, authorId: interaction.user.id
});
if(!dbGiveawayMsg){
await interaction.reply({
content: logger.log(`Giveaway didn't exist or the author didn't match.`),
ephemeral: true
});
return;
}
for(let i = dbGiveawayMsg.userIds.length - 1; i > 0; i--){
let j = Math.floor(Math.random() * (i + 1));
[dbGiveawayMsg.userIds[i], dbGiveawayMsg.userIds[j]]
= [dbGiveawayMsg.userIds[j], dbGiveawayMsg.userIds[i]];
}
let content: string = '### Giveaway Result\n';
for(let i = 0; i < num; i++)
content += `1. ${await interaction.client.users.fetch(dbGiveawayMsg.userIds[i])}\n`;
content += `will obtain the prize for giveaway, id: ${dbGiveawayMsg.messageId}`;
await interaction.reply({content: content});
}
class Giveaway extends Command{
get name(){return 'giveaway';}
get description(){return 'Setup a Giveaway message.';}
async execute(interaction: CommandInteraction): Promise<void>{
try{
const subcommand: string | null =
(interaction.options as CIOR).getSubcommand();
switch(subcommand){
case 'add':
await add(interaction); break;
case 'pick':
await pick(interaction); break;
default:
throw Error('subcommand not exist');
}
}catch(err: unknown){
let message;
if(err instanceof Error) message = err.message;
else message = String(message);
logger.error(`While executing "/giveaway", ${message}`);
await interaction.reply({content: `While executing "/giveaway", ${message}`});
}
}
override build(): SlashCommandSubcommandsOnlyBuilder{
return new SlashCommandBuilder()
.setName(this.name)
.setDescription(this.description)
.addSubcommand((subcommand: SlashCommandSubcommandBuilder) => subcommand
.setName('add')
.setDescription('Construct a giveaway')
.addStringOption((option: SlashCommandStringOption) => option
.setName('message')
.setDescription('The message displayed with the giveaway message.')
.setRequired(true)
)
)
.addSubcommand((subcommand: SlashCommandSubcommandBuilder) => subcommand
.setName('pick')
.setDescription('Random pick a number of user in a giveaway')
.addStringOption((option: SlashCommandStringOption) => option
.setName('message')
.setDescription('The message id of the giveaway (Shown in the footer)')
.setRequired(true)
)
.addIntegerOption((option: SlashCommandIntegerOption) => option
.setName('number')
.setDescription('The number of member to choose.')
.setRequired(true)
)
)
}
};
export const command = new Giveaway();

221
commands/images/image.ts Normal file
View File

@@ -0,0 +1,221 @@
import discord, {
CommandInteraction,
CommandInteractionOptionResolver,
SlashCommandBuilder,
SlashCommandStringOption,
SlashCommandAttachmentOption,
SlashCommandSubcommandBuilder,
EmbedBuilder,
InteractionResponse,
SlashCommandSubcommandsOnlyBuilder,
Attachment
} from 'discord.js';
import { HydratedDocument } from 'mongoose';
import fs from 'fs';
import path from 'path';
import axios from 'axios';
import { Client } from 'minio';
import { Command } from '../../classes/command';
import { logger } from '../../logger';
import { config } from '../../config';
import { reactPreprocess } from '../../functions/react-preprocess';
import { Image, imageModel } from '../../models/Image';
import { Alias, aliasModel } from '../../models/Alias';
import { Guild, guildModel } from '../../models/Guild';
import { Token, tokenModel } from '../../models/Token';
type CIOR = CommandInteractionOptionResolver;
const client = new Client(config.minio.client);
async function download(url: string, file: string): Promise<void>{
const saveFile = await axios({
url: url, method: 'GET', responseType: 'arraybuffer'
});
if(!await client.bucketExists(config.minio.bucket))
await client.makeBucket(config.minio.bucket);
await client.putObject(config.minio.bucket, file, saveFile.data);
}
async function upload(interaction: CommandInteraction): Promise<void>{
if(!interaction.guildId)
throw Error('guildId not exist');
const file: discord.Attachment | null =
(interaction.options as CIOR).getAttachment('file');
if(!file)
throw Error('file not exist');
const fileExt: string = path.extname(file.name);
const image: HydratedDocument<Image> | null =
await (new imageModel({extension: fileExt})).save();
if(!image)
throw Error('image not exist');
await download(file.url, `${String(image._id)}${fileExt}`);
const publicUrl: string = `${config.httpServer.external.url}/${String(image._id)}${fileExt}`;
await interaction.reply({
content: logger.log(`Image saved with id: ${image._id}.`),
});
if(interaction.channel)
await interaction.channel.send({content: publicUrl});
}
async function link(interaction: CommandInteraction): Promise<void>{
if(!interaction.guildId)
throw Error('guildId not exist');
let aliasText: string | null =
(interaction.options as CIOR).getString('alias');
if(!aliasText)
throw Error('aliasText not exist');
const imageId: string | null =
(interaction.options as CIOR).getString('image');
if(!imageId)
throw Error('imageId not exist');
aliasText = reactPreprocess(aliasText);
if(!interaction.guild || !interaction.guild.id || !interaction.guild.name)
throw Error('guild not exist');
const guild: HydratedDocument<Guild> | null =
await guildModel.findOneAndUpdate(
{id: interaction.guild.id},
{$set: {name: interaction.guild.name}},
{new: true, upsert: true}
);
if(!guild)
throw Error('guild not exist');
const image: HydratedDocument<Image> | null =
await imageModel.findById(imageId);
if(!image)
throw Error('image not exist');
const alias: HydratedDocument<Alias> | null =
await aliasModel.findOneAndUpdate(
{guild: guild, text: aliasText, images: {$nin: image}},
{$push: {images: image}},
{new: true, upsert: true}
);
if(!alias)
throw Error('alias update failed');
await interaction.reply({
content: logger.log(`Alias ${aliasText} has linked to image id: ${imageId}.`)
});
}
async function unlink(interaction: CommandInteraction): Promise<void>{
if(!interaction.guildId)
throw Error('guildId not exist');
let aliasText: string | null =
(interaction.options as CIOR).getString('alias');
if(!aliasText)
throw Error('aliasText not exist');
aliasText = reactPreprocess(aliasText);
if(!interaction.guild || !interaction.guild.id)
throw Error('guild not exist');
const guild: HydratedDocument<Guild> | null =
await guildModel.findOne({id: interaction.guild.id});
if(!guild)
throw Error('guild not exist');
const res = await aliasModel.deleteOne(
{guild: guild, text: aliasText}
);
if(!res)
logger.warning('alias not exist');
await interaction.reply({
content: logger.log(`All the image have been unlinked to alias ${aliasText}.`)
});
}
async function list(interaction: CommandInteraction): Promise<void>{
const token: string = String(Math.floor(Math.random() * 100000000));
if(!interaction.guild || !interaction.guild.id)
throw Error('guild not exist');
await tokenModel.create({
token: token,
guildId: interaction.guild.id,
exp: Date.now() + config.tokenTimeLimit
});
const embed = new EmbedBuilder()
.setColor(0x1f1e33)
.setTitle('Autoreact Image List')
.setDescription('experimental function')
.addFields({
name: 'One Time Link:',
value: `[open in browser](https://amane.konchin.com/auth?token=${token})`
});
await interaction.reply({embeds: [embed], ephemeral: true});
}
class ImageCmd extends Command{
get name(){return "image";}
get description(){return "Modify the reacting image database.";}
async execute(interaction: CommandInteraction): Promise<void>{
try{
const subcommand: string | null =
(interaction.options as CIOR).getSubcommand();
switch(subcommand){
case 'upload':
await upload(interaction); break;
case 'link':
await link(interaction); break;
case 'unlink':
await unlink(interaction); break;
case 'list':
await list(interaction); break;
default:
throw Error('subcommand not exist');
}
}catch(err: unknown){
let message;
if(err instanceof Error) message = err.message;
else message = String(message);
logger.error(`While executing "/image", ${message}`);
await interaction.reply({content: `While executing "/image", ${message}`});
}
}
override build(): SlashCommandSubcommandsOnlyBuilder{
return new SlashCommandBuilder()
.setName(this.name)
.setDescription(this.description)
.addSubcommand((subcommand: SlashCommandSubcommandBuilder) => subcommand
.setName('upload')
.setDescription('Upload an image.')
.addAttachmentOption((option: SlashCommandAttachmentOption) => option
.setName('file')
.setDescription('The image file that you want to upload.')
.setRequired(true)
)
)
.addSubcommand((subcommand: SlashCommandSubcommandBuilder) => subcommand
.setName('link')
.setDescription('Link an alias to an image')
.addStringOption((option: SlashCommandStringOption) => option
.setName('alias')
.setDescription('The alias to be linked.')
.setRequired(true)
)
.addStringOption((option: SlashCommandStringOption) => option
.setName('image')
.setDescription('The image to be linked, as id.')
.setRequired(true)
)
)
.addSubcommand((subcommand: SlashCommandSubcommandBuilder) => subcommand
.setName('unlink')
.setDescription('Unlink an alias to an image')
.addStringOption((option: SlashCommandStringOption) => option
.setName('alias')
.setDescription('The alias to be unlinked.')
.setRequired(true)
)
)
.addSubcommand((subcommand: SlashCommandSubcommandBuilder) => subcommand
.setName('list')
.setDescription('Show the image list')
)
}
};
export const command = new ImageCmd();

View File

@@ -0,0 +1,90 @@
import discord, {
CommandInteraction,
CommandInteractionOptionResolver,
SlashCommandBuilder,
SlashCommandRoleOption,
SlashCommandStringOption,
InteractionResponse,
} from 'discord.js';
import {HydratedDocument} from 'mongoose';
import {Command} from '../../classes/command';
import {logger} from '../../logger';
import {AutoroleMsg, autoroleMsgModel} from '../../models/AutoroleMsg';
import {Guild, guildModel} from '../../models/Guild';
type CIOR = CommandInteractionOptionResolver;
class Autorole extends Command{
get name(){return "autorole";}
get description(){return "Setup a autorole message.";}
async execute(interaction: CommandInteraction): Promise<void>{
try{
let role = (interaction.options as CIOR).getRole('role');
if(!role)
throw Error('role not exist');
const title: string | null =
(interaction.options as CIOR).getString('title');
if(!title)
throw Error('title not exist');
const message: string | null =
(interaction.options as CIOR).getString('message');
if(!message)
throw Error('message not exist');
if(!interaction.guild || !interaction.guild.id || !interaction.guild.name)
throw Error('guildId not exist');
if(!interaction.channelId)
throw Error('channelId not exist');
let content: string = `>> **Auto Role: ${title}** <<\n`;
content += '*React to give yourself a role.*\n\n';
content += `${message}`;
let msg: discord.Message =
await (await interaction.reply({content: content})).fetch();
const guild: HydratedDocument<Guild> | null =
await guildModel.findOneAndUpdate(
{id: interaction.guild.id},
{$set: {name: interaction.guild.name}},
{upsert: true, new: true}
);
if(!guild)
throw Error('guild not exist');
const autoroleMsg: HydratedDocument<AutoroleMsg> | null =
await autoroleMsgModel.findOneAndUpdate(
{guild: guild, messageId: msg.id, roleId: role.id},
{}, {upsert: true, new: true}
);
if(!autoroleMsg)
throw Error('autoroleMsg not exist');
}catch(err: unknown){
let message;
if(err instanceof Error) message = err.message;
else message = String(message);
logger.error(`While executing "/autorole", ${message}`);
await interaction.reply({content: `While executing "/autorole", ${message}`});
}
}
override build(): SlashCommandBuilder |
Omit<SlashCommandBuilder, "addSubcommand" | "addSubcommandGroup">{
return new SlashCommandBuilder()
.setName(this.name)
.setDescription(this.description)
.addRoleOption((option: SlashCommandRoleOption) => option
.setName('role')
.setDescription('The role that autorole gives when reacted.')
.setRequired(true)
)
.addStringOption((option: SlashCommandStringOption) => option
.setName('title')
.setDescription('The title displayed with the autorole message.')
.setRequired(true)
)
.addStringOption((option: SlashCommandStringOption) => option
.setName('message')
.setDescription('The additional message displayed with the autorole message.')
.setRequired(true)
)
}
};
export const command = new Autorole();

10
commands/tests/test.ts Normal file
View File

@@ -0,0 +1,10 @@
import {CommandInteraction} from 'discord.js';
import {Command} from '../../classes/command';
class Test extends Command{
get name(){return "test";}
get description(){return "Testing some features.";}
async execute(interaction: CommandInteraction): Promise<void>{}
};
// export const command = new Test();

29
commands/utils/help.ts Normal file
View File

@@ -0,0 +1,29 @@
import {CommandInteraction, EmbedBuilder} from 'discord.js';
import {Command} from '../../classes/command';
import {logger} from '../../logger';
import {config} from '../../config';
class Help extends Command{
get name(){return "help";}
get description(){return "Help messages.";}
async execute(interaction: CommandInteraction): Promise<void>{
const embed = new EmbedBuilder()
.setTitle("Help message")
.setDescription(`Report issues on [this page](${config.urls.issue})`)
.setColor(0x1f1e33)
.setAuthor({
name: 'Ian Shih (konchin)',
url: config.urls.author,
iconURL: config.urls.icon
})
.setFields(
{name: 'Read the documentation', value: config.urls.help},
{name: 'Read the source code', value: config.urls.git}
);
await interaction.reply({embeds: [embed], ephemeral: true});
logger.log(`Command: help`);
}
};
export const command = new Help();

19
commands/utils/ping.ts Normal file
View File

@@ -0,0 +1,19 @@
import {CommandInteraction} from 'discord.js';
import {Command} from '../../classes/command';
class Ping extends Command{
get name(){return "ping";}
get description(){return "Reply with the RTT of this bot.";}
async execute(interaction: CommandInteraction): Promise<void>{
const sent = await interaction.reply({
content: "Pinging...",
ephemeral: true,
fetchReply: true,
});
await interaction.editReply(`Roundtrip latency: ${
sent.createdTimestamp - interaction.createdTimestamp
}ms`);
}
};
export const command = new Ping();

104
commands/utils/set.ts Normal file
View File

@@ -0,0 +1,104 @@
import discord, {
CommandInteraction,
CommandInteractionOptionResolver,
SlashCommandBuilder,
SlashCommandSubcommandBuilder,
SlashCommandStringOption,
SlashCommandChannelOption,
InteractionResponse,
SlashCommandSubcommandsOnlyBuilder,
} from 'discord.js';
import {HydratedDocument} from 'mongoose';
import {Command} from '../../classes/command';
import {logger} from '../../logger';
import {Guild, guildModel} from '../../models/Guild';
type CIOR = CommandInteractionOptionResolver;
async function log(interaction: CommandInteraction): Promise<void>{
const feature: string | null =
(interaction.options as CIOR).getString('feature');
if(!feature)
throw Error('feature not exist');
const logChannel = (interaction.options as CIOR).getChannel('channel');
if(!logChannel || !('send' in logChannel))
throw Error('logChannel not exist or illegal');
if(!interaction.guild || !interaction.guild.id || !interaction.guild.name)
throw Error('guild not exist');
let guild: HydratedDocument<Guild> | null = null;
switch(feature){
case 'giveaway':
await guildModel.findOneAndUpdate(
{id: interaction.guild.id},
{$set: {
name: interaction.guild.name,
giveawayLogChannelId: logChannel.id
}},
{new: true, upsert: true}
);
break;
case 'autorole':
await guildModel.findOneAndUpdate(
{id: interaction.guild.id},
{$set: {
name: interaction.guild.name,
autoroleLogChannelId: logChannel.id
}},
{new: true, upsert: true}
);
break;
}
await interaction.reply({
content: logger.log(`The log channel of ${feature} has been set to ${logChannel}`)
});
;
}
class SetVariables extends Command{
get name(){return "set";}
get description(){return "Set guild variables.";}
async execute(interaction: CommandInteraction): Promise<void>{
try{
const subcommand: string =
(interaction.options as CIOR).getSubcommand();
switch(subcommand){
case 'log':
await log(interaction); break;
default:
throw Error('subcommand not exist');
}
}catch(err: unknown){
let message;
if(err instanceof Error) message = err.message;
else message = String(message);
logger.error(`While executing "/set", ${message}`);
await interaction.reply({content: `While executing "/set", ${message}`});
}
}
override build(): SlashCommandSubcommandsOnlyBuilder{
return new SlashCommandBuilder()
.setName(this.name)
.setDescription(this.description)
.addSubcommand((subcommand: SlashCommandSubcommandBuilder) => subcommand
.setName('log')
.setDescription('Set log of features.')
.addStringOption((option: SlashCommandStringOption) => option
.setName('feature')
.setDescription('Specify the to be set feature.')
.setRequired(true)
.addChoices(
{name: 'giveaway', value: 'giveaway'},
{name: 'autorole', value: 'autorole'},
)
)
.addChannelOption((option: SlashCommandChannelOption) => option
.setName('channel')
.setDescription('The channel that log send to.')
.setRequired(true)
)
)
}
};
export const command = new SetVariables();

51
config.ts Normal file
View File

@@ -0,0 +1,51 @@
import dotenv from 'dotenv';
dotenv.config();
export const config = {
token: process.env.DC_TOKEN!,
clientId: process.env.DC_CLIENTID!,
adminId: process.env.ADMIN_ID ?? '',
nickname: '谷風 天音',
data: '.',
urls: {
author: 'https://hello.konchin.com',
icon: 'https://secure.gravatar.com/avatar/c35f2cb664f366e3e3365b9c22216834?d=identicon&s=512',
help: 'https://md.konchin.com/s/u7qUK4oY4',
git: 'https://git.konchin.com/discord-bot/Tanikaze-Amane',
issue: 'https://git.konchin.com/discord-bot/Tanikaze-Amane/issues'
},
giveaway: {
emoji: '✋',
},
logger: {
logFile: 'test.log',
},
httpServer: {
local: {
port: process.env.PORT ?? 8082,
},
external: {
url: 'https://amane.konchin.com/img'
},
},
mongodb: {
host: process.env.MONGODB_HOST ?? '127.0.0.1',
port: process.env.MONGODB_PORT ?? 27017,
db: process.env.MONGODB_DB ?? 'amanev2',
user: process.env.MONGODB_USER ?? 'amane',
pass: process.env.MONGODB_PASS!,
reset: process.env.DB_RESET ?? 'false',
},
tokenTimeLimit: 60 * 1000,
minio: {
bucket: 'amane-img',
client: {
endPoint: process.env.MINIO_ENDPOINT ?? 'minio.konchin.com',
useSSL: (process.env.MINIO_USESSL == 'true') ?? false,
port: (process.env.MINIO_PORT as unknown as number) ?? 9000,
accessKey: process.env.MINIO_ACCESSKEY ?? '',
secretKey: process.env.MINIO_SECRETKEY ?? '',
}
}
};

101
events/handle-auto-roles.ts Normal file
View File

@@ -0,0 +1,101 @@
import discord, {
MessageReaction, PartialMessageReaction,
User, PartialUser,
} from 'discord.js';
import {HydratedDocument} from 'mongoose';
import {logger} from '../logger';
import {config} from '../config';
import {Guild, guildModel} from '../models/Guild';
import {AutoroleMsg, autoroleMsgModel} from '../models/AutoroleMsg';
function isMessageReaction(reaction: MessageReaction | PartialMessageReaction): reaction is MessageReaction{
return reaction.partial === false;
}
function isUser(user: User | PartialUser): user is User{
return user.partial === false;
}
async function handleRole(
reaction: MessageReaction | PartialMessageReaction,
user: User | PartialUser,
action: string
): Promise<void>{
try{
if(config.clientId === user.id) return;
if(reaction.partial)
reaction = await reaction.fetch();
if(user.partial)
user = await user.fetch();
if(!isMessageReaction(reaction))
throw Error('type mismatch: reaction.partial');
if(!isUser(user))
throw Error('type mismatch: user.partial');
if(!reaction.emoji)
throw Error('reaction.emoji not exist');
const dbAutoroleMsg: HydratedDocument<AutoroleMsg> | null =
await autoroleMsgModel.findOneAndUpdate(
{messageId: reaction.message.id},
{$set: {emoji: reaction.emoji.toString()}},
{new: true}
);
if(!dbAutoroleMsg || dbAutoroleMsg.emoji !== reaction.emoji.toString())
return;
if(!reaction.me)
await reaction.react();
const dbGuild: HydratedDocument<Guild> | null =
await guildModel.findById(dbAutoroleMsg.guild._id);
if(!dbGuild)
throw Error('dbGuild not exist');
const guild: discord.Guild | null =
await reaction.client.guilds.resolve(dbGuild.id);
if(!guild)
throw Error('guild not exist');
const role: discord.Role | null =
await guild.roles.resolve(dbAutoroleMsg.roleId);
if(!role)
throw Error('role not exist');
switch(action){
case 'add': await guild.members.addRole({
user: user.id, role: role.id
}); break;
case 'remove': await guild.members.removeRole({
user: user.id, role: role.id
}); break;
}
logger.log(`${user} has been ${action === 'add'?'given':'removed'} ${role} role.`);
if('autoroleLogChannelId' in dbGuild && dbGuild.autoroleLogChannelId){
const autoroleChannel: discord.Channel | null =
await guild.channels.resolve(dbGuild.autoroleLogChannelId);
if(autoroleChannel === null || !autoroleChannel.isTextBased())
throw Error('autoroleChannel not exist or autoroleChannel isn\'t text based');
await autoroleChannel.send({content:
`${user} has been ${action === 'add'?'given':'removed'} ${role} role.`
});
}
}catch(err: unknown){
let message;
if(err instanceof Error) message = err.message;
else message = String(message);
logger.error(`While executing "handle-autorole", ${message}`);
}
}
export async function handleRoleAdd(
reaction: MessageReaction | PartialMessageReaction, user: User | PartialUser
): Promise<void>{
await handleRole(reaction, user, 'add');
}
export async function handleRoleRemove(
reaction: MessageReaction | PartialMessageReaction, user: User | PartialUser
): Promise<void>{
await handleRole(reaction, user, 'remove');
}

31
events/handle-commands.ts Normal file
View File

@@ -0,0 +1,31 @@
import {Interaction} from 'discord.js';
import {isExtendedClient} from '../classes/extendedclient';
import {logger} from '../logger';
export async function handleCommands(interaction: Interaction): Promise<void>{
if(!interaction.isChatInputCommand()) return;
if(interaction.commandName === null)
throw logger.error('interaction.commandName not exist');
if(!isExtendedClient(interaction.client))
throw logger.error(`Type Error in function "handleCommands"`);
const command = interaction.client.commands.get(interaction.commandName);
if(!command)
throw logger.error(`No command matching ${interaction.commandName} was found.`);
try{
if('execute' in command)
await command.execute(interaction);
else{
logger.error(`The command (${interaction.commandName}) is missing a require "execute" function`);
return;
}
}catch(err: unknown){
if(interaction.replied || interaction.deferred)
await interaction.followUp({content: 'There was an error while executing this command!', ephemeral: true});
else
await interaction.reply({content: 'There was an error while executing this command!', ephemeral: true});
throw logger.error(`While handling "${interaction.commandName}, ${err}"`);
}
}

88
events/handle-giveaway.ts Normal file
View File

@@ -0,0 +1,88 @@
import discord, {
MessageReaction, PartialMessageReaction,
User, PartialUser,
} from 'discord.js';
import {HydratedDocument} from 'mongoose';
import {logger} from '../logger';
import {config} from '../config';
import {Guild, guildModel} from '../models/Guild';
import {GiveawayMsg, giveawayMsgModel} from '../models/GiveawayMsg';
function isMessageReaction(reaction: MessageReaction | PartialMessageReaction): reaction is MessageReaction{
return reaction.partial === false;
}
function isUser(user: User | PartialUser): user is User{
return user.partial === false;
}
export async function handleGiveaway(
reaction: MessageReaction | PartialMessageReaction,
user: User | PartialUser
): Promise<void>{
try{
// fetch data
if(config.clientId === user.id) return;
if(reaction.partial){
reaction = await reaction.fetch();
logger.debug('reaction in handleRole has fetched');
}
if(user.partial){
user = await user.fetch();
logger.debug('user in handleRole has fetched');
}
if(!isMessageReaction(reaction))
throw Error('type mismatch: reaction.partial');
if(!isUser(user))
throw Error('type mismatch: user.partial');
if(!reaction.emoji)
throw Error('reaction.emoji not exist');
if(reaction.emoji.toString() !== config.giveaway.emoji) return;
let dbGiveawayMsg: HydratedDocument<GiveawayMsg> | null =
await giveawayMsgModel.findOne(
{messageId: reaction.message.id}
);
if(!dbGiveawayMsg) return;
if(dbGiveawayMsg.userIds.includes(user.id)){
logger.info(`${user} has already in giveaway userIds`);
return;
}
const dbGuild: HydratedDocument<Guild> | null =
await guildModel.findById(dbGiveawayMsg.guild._id);
if(!dbGuild)
throw Error('dbGuild not exist');
const guild: discord.Guild = await reaction.client.guilds.resolve(dbGuild.id);
if(!guild)
throw Error('guild not exist');
// record
dbGiveawayMsg = await giveawayMsgModel.findOneAndUpdate(
{messageId: dbGiveawayMsg.messageId},
{$push: {userIds: user.id}}, {new: true}
);
if(!dbGiveawayMsg)
throw Error('dbGiveawayMsg not exist');
// notify
logger.log(`${user} has been reacted to giveaway, id: ${dbGiveawayMsg.messageId}.`);
if(!dbGuild.giveawayLogChannelId){
const author: discord.User | null =
await reaction.client.users.fetch(dbGiveawayMsg.authorId);
if(!author)
throw Error(`author ${author} not exist`);
await author.send({content: `user ${user} has reacted to giveaway, id: ${dbGiveawayMsg.messageId}`});
}else{
const logChannel: discord.Channel | null =
await guild.channels.resolve(dbGuild.giveawayLogChannelId);
if(!logChannel || !logChannel.isTextBased())
throw Error('logChannel not exist or logChannel isn\'t text based');
await logChannel.send({content: `user ${user} has reacted to giveaway, id: ${dbGiveawayMsg.messageId}`});
}
}catch(err: unknown){
let message;
if(err instanceof Error) message = err.message;
else message = String(message);
logger.error(`While executing "handleGiveaway", ${message}`);
}
}

View File

@@ -0,0 +1,40 @@
import discord from 'discord.js';
import {HydratedDocument} from 'mongoose';
import {logger} from '../logger';
import {config} from '../config';
import {reactPreprocess} from '../functions/react-preprocess';
import {Alias, aliasModel} from '../models/Alias';
import {Guild, guildModel} from '../models/Guild';
import {Image, imageModel} from '../models/Image';
export async function handleReactImage(message: discord.Message): Promise<void>{
try{
if(!message.guild || !message.guild.id || !message.content) return;
const guild: HydratedDocument<Guild> | null =
await guildModel.findOne({id: message.guild.id});
if(!guild) return; // not in guild
const alias: HydratedDocument<Alias> | null =
await aliasModel.findOne(
{guild: guild, text: reactPreprocess(message.content)}
);
if(!alias) return; // alias not exist
if(!alias.images.length) return; // alias not linked
const chosenImage: Image =
alias.images[Math.floor(Math.random() * alias.images.length)];
const image: HydratedDocument<Image> | null =
await imageModel.findById(chosenImage._id);
if(!image)
throw Error('image not exist');
await message.channel.send({
content: `${config.httpServer.external.url}/${image._id}${image.extension}`
});
}catch(err: unknown){
let errMsg;
if(err instanceof Error) errMsg = err.message;
else errMsg = String(errMsg);
logger.error(`While executing "handleReactImage", ${errMsg}`);
}
}

View File

@@ -0,0 +1,3 @@
export function reactPreprocess(str: string){
return str.toLowerCase().replaceAll(' ', '');
}

97
index.ts Normal file
View File

@@ -0,0 +1,97 @@
import {Events, GatewayIntentBits, Partials, ActivityType} from 'discord.js';
import {createServer} from 'http';
// Global config
import {config} from './config';
// Classes
import {ExtendedClient} from './classes/extendedclient'
// Initialization functions
import {setNickname} from './init/set-nickname';
import {loadCommands} from './init/load-commands';
import {registerCommands} from './init/register-commands';
import {sendReadyDM} from './init/ready-dm';
// Event-handling functions
import {handleCommands} from './events/handle-commands';
import {handleGiveaway} from './events/handle-giveaway';
import {handleRoleAdd, handleRoleRemove} from './events/handle-auto-roles';
import {handleReactImage} from './events/handle-react-image';
// Sub-services
import {logger} from './logger';
import {runMongo} from './mongo';
const client = new ExtendedClient({
intents:[
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildWebhooks,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildScheduledEvents,
GatewayIntentBits.AutoModerationConfiguration,
GatewayIntentBits.AutoModerationExecution,
],
partials:[
Partials.User,
Partials.Channel,
Partials.GuildMember,
Partials.Message,
Partials.Reaction,
Partials.GuildScheduledEvent,
Partials.ThreadMember,
]
});
client.login(config.token);
// Event handling
client.on(Events.InteractionCreate, handleCommands);
client.on(Events.MessageReactionAdd, handleGiveaway);
client.on(Events.MessageReactionAdd, handleRoleAdd);
client.on(Events.MessageReactionRemove, handleRoleRemove);
client.on(Events.MessageCreate, handleReactImage);
// Initialization
client.once(Events.ClientReady, async c => {
logger.info(`Logged in as ${c.user.tag}`);
if(client.user){
client.user.setPresence({
activities: [{
name: '天使☆騒々 RE-BOOT!',
type: ActivityType.Playing,
}],
status: 'online'
});
logger.info('Set status done');
}
await setNickname(client);
logger.info(`Set nickname as ${config.nickname}`);
const commands = await loadCommands(client);
logger.info(`${commands.length} commands loaded.`);
const regCmdCnt = await registerCommands(commands);
logger.info(`${regCmdCnt} commands registered.`);
await runMongo();
logger.info(`Database ready`);
logger.info(`Ready!`);
await sendReadyDM(client, config.adminId);
});

25
init/load-commands.ts Normal file
View File

@@ -0,0 +1,25 @@
import path from 'path';
import {readdirSync} from 'fs';
import {ExtendedClient} from '../classes/extendedclient';
import {logger} from '../logger';
export async function loadCommands(client: ExtendedClient): Promise<Array<string>>{
const foldersPath = path.join(__dirname, '../commands');
const commandFolders = readdirSync(foldersPath);
const commands: Array<string> = [];
for(const folder of commandFolders){
const commandsPath = path.join(foldersPath, folder);
const commandsFiles = readdirSync(commandsPath).filter(file => file.endsWith('.ts'));
for(const file of commandsFiles){
const filePath = path.join(commandsPath, file);
const data = await import(filePath);
if(data.command !== undefined){
client.commands.set(data.command.name, data.command);
commands.push(data.command.build().toJSON());
}else
logger.warning(`The command at ${filePath} is missing required properties.`);
}
}
return commands;
}

11
init/ready-dm.ts Normal file
View File

@@ -0,0 +1,11 @@
import {logger} from '../logger';
import {ExtendedClient} from '../classes/extendedclient';
export async function sendReadyDM(client: ExtendedClient, adminId: string): Promise<void>{
try{
await (await client.users.fetch(adminId)).send(`service up at ${new Date()}`);
logger.log('Service up message sent');
}catch(err: unknown){
logger.warning('sendReadyDM failed.');
}
}

26
init/register-commands.ts Normal file
View File

@@ -0,0 +1,26 @@
import {REST, Routes} from 'discord.js';
import {config} from '../config';
import {logger} from '../logger';
function isArray<T>(data: unknown): data is Array<T>{
return (data as Array<T>).length !== undefined;
}
export async function registerCommands(commands: Array<string>): Promise<number>{
const rest = new REST().setToken(config.token);
try{
const data = await rest.put(
Routes.applicationCommands(config.clientId),
{body: commands},
);
if(!isArray(data)) throw Error('Type error');
return data.length;
}catch(err: unknown){
let message;
if(err instanceof Error) message = err.message;
else message = String(message);
logger.error(`While executing "registerCommands", ${message}`);
return -1;
}
}

22
init/set-nickname.ts Normal file
View File

@@ -0,0 +1,22 @@
import {Guild} from 'discord.js';
import {ExtendedClient} from '../classes/extendedclient';
import {config} from '../config';
import {logger} from '../logger';
export async function setNickname(client: ExtendedClient): Promise<void>{
await client.guilds.cache.forEach(async (guild: Guild): Promise<void> => {
try{
// console.log(guild.members);
const self = await guild.members.fetch({user: config.clientId, force: true});
if(!self) throw Error('self not exist');
await self.setNickname(config.nickname);
logger.log(`Nickname had changed in guild: ${guild.name}`);
}catch(err: unknown){
let message;
if(err instanceof Error) message = err.message;
else message = String(message);
logger.error(`While executing setNickname, ${message}`);
}
});
}

View File

@@ -0,0 +1,64 @@
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: amane-dcbot
namespace: amane-tanikaze
labels:
app: amane-dcbot
spec:
replicas: 1
selector:
matchLabels:
app: amane-dcbot
template:
metadata:
labels:
app: amane-dcbot
spec:
containers:
- name: dcbot
image: 'gitea.konchin.com/services/amane-tanikaze-dcbot:latest'
env:
- name: DC_TOKEN
valueFrom:
secretKeyRef:
name: amane-dcbot
key: DC_TOKEN
- name: DC_CLIENTID
valueFrom:
secretKeyRef:
name: amane-dcbot
key: DC_CLIENTID
- name: ADMIN_ID
valueFrom:
secretKeyRef:
name: amane-dcbot
key: ADMIN_ID
- name: MONGODB_HOST
valueFrom:
secretKeyRef:
name: amane-dcbot
key: MONGODB_HOST
- name: MONGODB_USER
valueFrom:
secretKeyRef:
name: amane-dcbot
key: MONGODB_USER
- name: MONGODB_PASS
valueFrom:
secretKeyRef:
name: amane-dcbot
key: MONGODB_PASS
- name: MINIO_ACCESSKEY
valueFrom:
secretKeyRef:
name: amane-dcbot
key: MINIO_ACCESSKEY
- name: MINIO_SECRETKEY
valueFrom:
secretKeyRef:
name: amane-dcbot
key: MINIO_SECRETKEY
imagePullSecrets:
- name: regcred

45
logger.ts Normal file
View File

@@ -0,0 +1,45 @@
import {appendFileSync} from 'fs';
import moment from 'moment-timezone';
import {config} from './config';
enum LogLevel{
ERROR = 'ERROR',
WARNING = 'WARNING',
DEBUG = 'DEBUG',
LOG = 'LOG',
INFO = 'INFO',
}
class Logger{
constructor(readonly logFile?: string){
this.debug('logger initialized');
}
private currentTime(): string{
return '[' + moment().tz('Asia/Taipei').format('YYYY/MM/DD hh:mm:ss') + ']';
}
private writeLog(content: string, logLevel: LogLevel): void{
const line = `${this.currentTime()} ${logLevel}: ${content}`;
console.log(line);
if(this.logFile !== undefined){
appendFileSync(this.logFile, line + '\n');
}
}
error(content: string): Error{
this.writeLog(content, LogLevel.ERROR); return Error(content);
}
warning(content: string): string{
this.writeLog(content, LogLevel.WARNING); return content;
}
debug(content: string): string{
this.writeLog(content, LogLevel.DEBUG); return content;
}
log(content: string): string{
this.writeLog(content, LogLevel.LOG); return content;
}
info(content: string): string{
this.writeLog(content, LogLevel.INFO); return content;
}
}
export const logger = new Logger(`${config.data}/${config.logger.logFile}`);

21
models/Alias.ts Normal file
View File

@@ -0,0 +1,21 @@
import {Schema, Types, model} from 'mongoose';
import {Image} from './Image';
import {Guild} from './Guild';
export interface Alias{
_id: Types.ObjectId;
guild: Guild;
text: string;
images: Image[];
}
const aliasSchema = new Schema<Alias>({
guild: {type: Schema.Types.ObjectId, ref: 'Guild', required: true},
text: {type: String, required: true},
images: {type: [{type: Schema.Types.ObjectId, ref: 'Image'}], default: []},
});
export const aliasModel = model<Alias>(
'aliasModel', aliasSchema
);

22
models/AutoroleMsg.ts Normal file
View File

@@ -0,0 +1,22 @@
import {Schema, Types, model} from 'mongoose';
import {Guild} from './Guild';
export interface AutoroleMsg{
_id: Types.ObjectId;
guild: Guild;
messageId: string;
emoji: string;
roleId: string;
}
const autoroleMsgSchema = new Schema<AutoroleMsg>({
guild: {type: Schema.Types.ObjectId, required: true},
messageId: {type: String, required: true},
emoji: {type: String, required: false},
roleId: {type: String, required: true},
});
export const autoroleMsgModel = model<AutoroleMsg>(
'autoroleMsgModel', autoroleMsgSchema
);

22
models/GiveawayMsg.ts Normal file
View File

@@ -0,0 +1,22 @@
import {Schema, Types, model} from 'mongoose';
import {Guild} from './Guild';
export interface GiveawayMsg{
_id: Types.ObjectId;
guild: Guild;
messageId: string;
authorId: string;
userIds: string[];
}
const giveawayMsgSchema = new Schema<GiveawayMsg>({
guild: {type: Schema.Types.ObjectId, required: true},
messageId: {type: String, required: true},
authorId: {type: String, required: true},
userIds: {type: [{type: String}], default: []}
});
export const giveawayMsgModel = model<GiveawayMsg>(
'giveawayMsgModel', giveawayMsgSchema
);

23
models/Guild.ts Normal file
View File

@@ -0,0 +1,23 @@
import {Schema, Types, model} from 'mongoose';
import {GiveawayMsg} from './GiveawayMsg';
import {AutoroleMsg} from './AutoroleMsg';
export interface Guild{
_id: Types.ObjectId;
id: string;
name: string;
giveawayLogChannelId: string;
autoroleLogChannelId: string;
}
const guildSchema = new Schema<Guild>({
id: {type: String, required: true},
name: {type: String, required: true},
giveawayLogChannelId: {type: String, required: false},
autoroleLogChannelId: {type: String, required: false},
});
export const guildModel = model<Guild>(
'guildModel', guildSchema
);

14
models/Image.ts Normal file
View File

@@ -0,0 +1,14 @@
import {Schema, Types, model} from 'mongoose';
export interface Image{
_id: Types.ObjectId; // act as random generated filename
extension: string;
}
const imageSchema = new Schema<Image>({
extension: {type: String, required: true}
});
export const imageModel = model<Image>(
'imageModel', imageSchema
);

18
models/Token.ts Normal file
View File

@@ -0,0 +1,18 @@
import {Schema, Types, model} from 'mongoose';
export interface Token{
_id: Types.ObjectId;
token: string;
guildId: string;
exp: number;
};
const tokenSchema = new Schema<Token>({
token: {type: String, required: true},
guildId: {type: String, required: true},
exp: {type: Number, required: true}
});
export const tokenModel = model<Token>(
'tokenModel', tokenSchema
);

45
mongo.ts Normal file
View File

@@ -0,0 +1,45 @@
import mongoose from 'mongoose';
import {config} from './config';
import {guildModel} from './models/Guild';
import {autoroleMsgModel} from './models/AutoroleMsg';
import {giveawayMsgModel} from './models/GiveawayMsg';
import {imageModel} from './models/Image';
import {aliasModel} from './models/Alias';
async function resetMongo(): Promise<void> {
try{
await guildModel.deleteMany({});
await autoroleMsgModel.deleteMany({});
await giveawayMsgModel.deleteMany({});
await imageModel.deleteMany({});
await aliasModel.deleteMany({});
}catch(err: unknown){
throw new Error(`MongoDB reset failed. ${err}`);
}
}
async function initializeMongo(): Promise<void> {
try{
if(config.mongodb.reset === 'true') await resetMongo();
}catch(err: unknown){
throw new Error(`MongoDB initialize failed. ${err}`);
}
}
export async function runMongo(): Promise<void> {
try {
mongoose.set('strictQuery', false);
const auth: string = `${config.mongodb.user}:${config.mongodb.pass}`;
const server: string = `${config.mongodb.host}:${config.mongodb.port}`
const uri: string = `mongodb://${auth}@${server}/${config.mongodb.db}`;
await mongoose.connect(uri);
} catch(err: unknown) {
throw new Error(`MongoDB connection failed. ${err}`);
}
try {
await initializeMongo();
} catch(err: unknown) {
throw new Error(`Initialize MongoDB data failed. ${err}`);
}
}

1312
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

34
package.json Normal file
View File

@@ -0,0 +1,34 @@
{
"name": "tanikaze-amane",
"version": "1.0.1",
"main": "index.ts",
"scripts": {
"test": "ts-node index.ts",
"build": "npx tsc --build",
"clean": "npx tsc --build --clean"
},
"repository": {
"type": "git",
"url": "git+https://github.com/konchinshih/Tanikaze-Amane.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/konchinshih/Tanikaze-Amane/issues"
},
"homepage": "https://github.com/konchinshih/Tanikaze-Amane#readme",
"dependencies": {
"@types/node": "^20.3.2",
"axios": "^1.6.2",
"discord.js": "^14.11.0",
"dotenv": "^16.3.1",
"fs": "^0.0.1-security",
"minio": "^8.0.1",
"moment-timezone": "^0.5.43",
"mongodb": "^5.6.0",
"mongoose": "^8.0.1",
"path": "^0.12.7",
"typescript": "^5.1.3"
},
"description": ""
}

109
tsconfig.json Normal file
View File

@@ -0,0 +1,109 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonJS", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}