@pikokr/command.ts 5.0.0-dev.a0bc517 → 5.0.0-dev.c0902b8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/.github/workflows/codeql-analysis.yml +3 -3
  2. package/.github/workflows/docs.yml +2 -2
  3. package/dist/index.d.ts +125 -34
  4. package/dist/index.js +1 -1
  5. package/dist/index.js.map +1 -1
  6. package/package.json +17 -14
  7. package/publish-version.js +10 -0
  8. package/renovate.json +5 -0
  9. package/scripts/docs.ts +8 -8
  10. package/src/applicationCommand/ApplicationCommand.ts +14 -18
  11. package/src/applicationCommand/ApplicationCommandExtension.ts +169 -0
  12. package/src/applicationCommand/ApplicationCommandOption.ts +9 -2
  13. package/src/applicationCommand/index.ts +8 -0
  14. package/src/core/components/BaseComponent.ts +42 -14
  15. package/src/core/components/ComponentArgument.ts +8 -0
  16. package/src/core/components/ComponentArgumentDecorator.ts +8 -0
  17. package/src/core/components/decoratorCreator.ts +17 -3
  18. package/src/core/components/index.ts +13 -3
  19. package/src/core/converter/index.ts +16 -0
  20. package/src/core/extensions/CTSExtension.ts +17 -0
  21. package/src/core/extensions/Extension.ts +62 -0
  22. package/src/core/extensions/index.ts +9 -0
  23. package/src/core/hooks/componentHook.ts +40 -0
  24. package/src/core/hooks/index.ts +11 -1
  25. package/src/core/hooks/moduleHook.ts +11 -3
  26. package/src/core/index.ts +13 -1
  27. package/src/core/listener/index.ts +22 -2
  28. package/src/core/structures/CommandClient.ts +68 -4
  29. package/src/core/structures/Registry.ts +29 -5
  30. package/src/core/structures/index.ts +8 -0
  31. package/src/core/symbols.ts +13 -4
  32. package/src/core/utils/checks.ts +27 -0
  33. package/src/core/utils/errors.ts +9 -0
  34. package/src/core/utils/index.ts +10 -0
  35. package/src/index.ts +11 -10
  36. package/src/textCommand/TextCommand.ts +20 -0
  37. package/src/textCommand/TextCommandExtension.ts +128 -0
  38. package/src/textCommand/index.ts +11 -0
  39. package/src/textCommand/parameters.ts +14 -0
  40. package/test/index.ts +51 -27
  41. package/tsconfig.prod.json +1 -0
  42. package/tsup.config.ts +8 -8
@@ -0,0 +1,169 @@
1
+ /*
2
+ * File: ApplicationCommandExtension.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
9
+ import chalk from 'chalk'
10
+ import {
11
+ ApplicationCommandData,
12
+ ApplicationCommandType,
13
+ ChatInputCommandInteraction,
14
+ Interaction,
15
+ InteractionType,
16
+ MessageContextMenuCommandInteraction,
17
+ Snowflake,
18
+ UserContextMenuCommandInteraction,
19
+ } from 'discord.js'
20
+ import { ApplicationCommandComponent } from './ApplicationCommand'
21
+ import { ApplicationCommandOption } from './ApplicationCommandOption'
22
+ import { moduleHook } from '../core/hooks'
23
+ import { listener } from '../core/listener'
24
+ import { CommandClient } from '../core/structures'
25
+ import { argConverter } from '../core/converter'
26
+ import { CTSExtension } from '../core/extensions/CTSExtension'
27
+
28
+ export type ApplicationCommandExtensionConfig = {
29
+ guilds?: Snowflake[]
30
+ }
31
+
32
+ export class ApplicationCommandExtension extends CTSExtension {
33
+ constructor(public config: ApplicationCommandExtensionConfig) {
34
+ super()
35
+ }
36
+
37
+ @listener({ event: 'interactionCreate' })
38
+ async interactionCreate(i: Interaction) {
39
+ if (i.type !== InteractionType.ApplicationCommand) return
40
+
41
+ let cmd: ApplicationCommandComponent | null = null
42
+ let ext: object | null = null
43
+
44
+ const extensions = this.commandClient.registry.extensions
45
+
46
+ for (const extension of extensions) {
47
+ const components = this.commandClient.registry.getComponentsWithType(extension, ApplicationCommandComponent)
48
+
49
+ for (const command of components) {
50
+ if (command.options.name === i.commandName) {
51
+ ext = extension
52
+ cmd = command
53
+ }
54
+ }
55
+ }
56
+
57
+ if (cmd && ext) {
58
+ const argList: unknown[] = []
59
+
60
+ await this.convertArguments(ApplicationCommandComponent, argList, cmd.argTypes, () => [i])
61
+
62
+ for (const [idx, arg] of cmd.argTypes) {
63
+ let value: unknown = null
64
+
65
+ for (const decorator of arg.decorators) {
66
+ if (decorator instanceof ApplicationCommandOption) {
67
+ value = i.options.get(decorator.options.name, false)?.value
68
+ break
69
+ }
70
+ }
71
+
72
+ if (value) {
73
+ argList[idx] = value
74
+ }
75
+ }
76
+
77
+ try {
78
+ await cmd.execute(ext, argList, [i])
79
+ } catch (e) {
80
+ this.logger.error(e)
81
+ this.commandClient.emit('applicationCommandInvokeError', e, i)
82
+ }
83
+ }
84
+ }
85
+
86
+ @moduleHook('load')
87
+ async load() {}
88
+
89
+ async sync() {
90
+ const client = CommandClient.getFromModule(this)
91
+
92
+ this.logger.info('Trying to sync commands...')
93
+
94
+ const commands: ApplicationCommandData[] = []
95
+
96
+ for (const command of client.registry.getComponentsWithTypeGlobal(ApplicationCommandComponent)) {
97
+ const cmd: ApplicationCommandData = { ...command.options }
98
+
99
+ if (cmd.type === ApplicationCommandType.ChatInput) {
100
+ cmd.options = []
101
+
102
+ for (const [, arg] of command.argTypes) {
103
+ const option = arg.decorators.find((x) => x.constructor === ApplicationCommandOption) as ApplicationCommandOption
104
+
105
+ if (option) {
106
+ cmd.options.push(option.options)
107
+ }
108
+ }
109
+ }
110
+
111
+ commands.push(cmd)
112
+ }
113
+
114
+ this.logger.info(`Processing ${chalk.green(commands.length)} commands(${commands.map((x) => chalk.blue(x.name)).join(', ')})`)
115
+
116
+ if (this.config.guilds) {
117
+ for (const guild of this.config.guilds) {
118
+ try {
119
+ const g = await this.client.guilds.fetch(guild)
120
+ await g.fetch()
121
+ this.logger.info(`Registering commands for guild ${chalk.green(g.name)}(${chalk.blue(g.id)})`)
122
+
123
+ await g.commands.set(commands)
124
+
125
+ this.logger.info(`Successfully registered commands for guild ${chalk.green(g.name)}(${chalk.blue(g.id)})`)
126
+ } catch (e) {
127
+ this.logger.error(`Failed to register commands to guild ${chalk.green(guild)}: ${(e as Error).message}`)
128
+ }
129
+ }
130
+ } else {
131
+ try {
132
+ this.logger.info(`Registering commands globally...`)
133
+
134
+ await this.client.application!.commands.set(commands)
135
+
136
+ this.logger.info('Successfully registered commands.')
137
+ } catch (e) {
138
+ this.logger.error(`Failed to register commands to global: ${(e as Error).message}`)
139
+ }
140
+ }
141
+ }
142
+
143
+ @argConverter({
144
+ component: ApplicationCommandComponent,
145
+ parameterless: true,
146
+ type: ChatInputCommandInteraction,
147
+ })
148
+ async chatInteraction(i: ChatInputCommandInteraction) {
149
+ return i
150
+ }
151
+
152
+ @argConverter({
153
+ component: ApplicationCommandComponent,
154
+ parameterless: true,
155
+ type: MessageContextMenuCommandInteraction,
156
+ })
157
+ async messageInteraction(i: MessageContextMenuCommandInteraction) {
158
+ return i
159
+ }
160
+
161
+ @argConverter({
162
+ component: ApplicationCommandComponent,
163
+ parameterless: true,
164
+ type: UserContextMenuCommandInteraction,
165
+ })
166
+ async userInteraction(i: UserContextMenuCommandInteraction) {
167
+ return i
168
+ }
169
+ }
@@ -1,6 +1,13 @@
1
+ /*
2
+ * File: ApplicationCommandOption.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
1
9
  import { APIApplicationCommandOption } from 'discord.js'
2
- import { createArgumentDecorator } from '../core'
3
- import { ComponentArgumentDecorator } from '../core/components/ComponentArgumentDecorator'
10
+ import { createArgumentDecorator, ComponentArgumentDecorator } from '../core'
4
11
 
5
12
  type Options = APIApplicationCommandOption
6
13
 
@@ -1,2 +1,10 @@
1
+ /*
2
+ * File: index.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
1
9
  export * from './ApplicationCommand'
2
10
  export { option } from './ApplicationCommandOption'
@@ -1,22 +1,28 @@
1
+ /*
2
+ * File: BaseComponent.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
1
9
  import { Collection } from 'discord.js'
2
10
  import _ from 'lodash'
11
+ import type { ComponentHookStore } from '../hooks'
3
12
  import { ComponentArgument } from './ComponentArgument'
4
13
 
5
- export class BaseComponent<Options = unknown, RequiredOptions = unknown> {
6
- options: Options & RequiredOptions
14
+ export class BaseComponent<Options = unknown, OptionsArg = Options> {
15
+ options: Options
7
16
 
8
17
  method: Function
9
18
 
19
+ hooks: ComponentHookStore = new Collection()
20
+
10
21
  argTypes: Collection<number, ComponentArgument> = new Collection()
11
22
 
12
- constructor(options: Partial<Options> & RequiredOptions, method: Function, argTypes: unknown[]) {
13
- if (typeof options === 'object') {
14
- this.options = _.merge(this.defaultOptions(), options)
15
- } else if (typeof options === 'string') {
16
- this.options = options as this['options']
17
- } else {
18
- this.options = null as unknown as this['options']
19
- }
23
+ constructor(options: OptionsArg, method: Function, argTypes: unknown[]) {
24
+ this.options = this.convertOptions(options)
25
+
20
26
  this.method = method
21
27
  for (let i = 0; i < argTypes.length; i++) {
22
28
  const element = argTypes[i]
@@ -24,11 +30,33 @@ export class BaseComponent<Options = unknown, RequiredOptions = unknown> {
24
30
  }
25
31
  }
26
32
 
27
- defaultOptions(): Options & Partial<RequiredOptions> {
28
- return {} as unknown as ReturnType<this['defaultOptions']>
33
+ convertOptions(options: OptionsArg): Options {
34
+ return options as unknown as Options
29
35
  }
30
36
 
31
- execute(target: object, args: unknown[]) {
32
- return this.method.apply(target, args)
37
+ async executeHook(target: object, name: string, args: unknown[]) {
38
+ const hook = this.hooks.get(name)
39
+
40
+ if (!hook) return
41
+
42
+ const { CommandClient } = await import('../structures/CommandClient')
43
+
44
+ for (const fn of hook) {
45
+ await fn.call(null, CommandClient.getFromModule(target), ...args)
46
+ }
47
+ }
48
+
49
+ async execute(target: object, args: unknown[], beforeCallArgs: unknown[] = args) {
50
+ await this.executeHook(target, 'beforeCall', beforeCallArgs)
51
+ let result
52
+ try {
53
+ result = await this.method.call(target, ...args)
54
+ } catch (e) {
55
+ await this.executeHook(target, 'invokeError', [e])
56
+ throw e
57
+ }
58
+ await this.executeHook(target, 'afterCall', [result])
59
+
60
+ return result
33
61
  }
34
62
  }
@@ -1,3 +1,11 @@
1
+ /*
2
+ * File: ComponentArgument.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
1
9
  import { ComponentArgumentDecorator } from './ComponentArgumentDecorator'
2
10
 
3
11
  export class ComponentArgument {
@@ -1,3 +1,11 @@
1
+ /*
2
+ * File: ComponentArgumentDecorator.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
1
9
  import _ from 'lodash'
2
10
 
3
11
  export class ComponentArgumentDecorator<Options = unknown> {
@@ -1,4 +1,14 @@
1
+ /*
2
+ * File: decoratorCreator.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
1
9
  import { Collection } from 'discord.js'
10
+ import { ComponentHookStore } from '../hooks'
11
+ import { getComponentHookStore } from '../hooks/componentHook'
2
12
  import { ComponentStoreSymbol } from '../symbols'
3
13
  import { BaseComponent } from './BaseComponent'
4
14
  import { ComponentArgumentDecorator } from './ComponentArgumentDecorator'
@@ -24,10 +34,14 @@ export const getComponent = (target: object, key: string | symbol) => {
24
34
  return store.get(key)
25
35
  }
26
36
 
27
- export const createComponentDecorator = <Options, RequiredOptions>(type: typeof BaseComponent<Options, RequiredOptions>) => {
28
- return (options: Partial<Options> & RequiredOptions): MethodDecorator => {
37
+ export const createComponentDecorator = <Options, OptionArgs>(type: typeof BaseComponent<Options, OptionArgs>) => {
38
+ return (options: OptionArgs): MethodDecorator => {
29
39
  return (target, key) => {
30
- var component: BaseComponent<Options> = new type(options, Reflect.get(target, key), Reflect.getMetadata('design:paramtypes', target, key))
40
+ var component: BaseComponent<Options, OptionArgs> = new type(options, Reflect.get(target, key), Reflect.getMetadata('design:paramtypes', target, key))
41
+
42
+ const componentHookStore: ComponentHookStore = getComponentHookStore(target, key)
43
+
44
+ component.hooks = componentHookStore
31
45
 
32
46
  const store = getComponentStore(target)
33
47
 
@@ -1,3 +1,13 @@
1
- import 'reflect-metadata'
2
- export * from './BaseComponent'
3
- export * from './decoratorCreator'
1
+ /*
2
+ * File: index.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
9
+ import 'reflect-metadata'
10
+ export * from './decoratorCreator'
11
+ export * from './ComponentArgument'
12
+ export * from './ComponentArgumentDecorator'
13
+ export * from './BaseComponent'
@@ -0,0 +1,16 @@
1
+ /*
2
+ * File: index.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
9
+ import { BaseComponent } from '../components/BaseComponent'
10
+ import { createComponentDecorator } from '../components/decoratorCreator'
11
+
12
+ type Options = { component: typeof BaseComponent<unknown>; type: Function; parameterless: boolean }
13
+
14
+ export class ConverterComponent extends BaseComponent<Options, Omit<Options, 'parameterless'> & { parameterless?: boolean }> {}
15
+
16
+ export const argConverter = createComponentDecorator(ConverterComponent)
@@ -0,0 +1,17 @@
1
+ /*
2
+ * File: CTSExtension.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
9
+ import chalk from 'chalk'
10
+ import { Extension } from './Extension'
11
+
12
+ export class CTSExtension extends Extension {
13
+ protected get logger() {
14
+ if (!this._logger) this._logger = this.commandClient.ctsLogger.getChildLogger({ prefix: [chalk.green(`[${this.constructor.name}]`)], displayFunctionName: false })
15
+ return this._logger
16
+ }
17
+ }
@@ -0,0 +1,62 @@
1
+ /*
2
+ * File: Extension.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
9
+ import chalk from 'chalk'
10
+ import { Collection } from 'discord.js'
11
+ import { Logger } from 'tslog'
12
+ import { BaseComponent } from '../components'
13
+ import { ComponentArgument } from '../components/ComponentArgument'
14
+ import { ConverterComponent } from '../converter'
15
+ import { CommandClient } from '../structures'
16
+
17
+ export class Extension {
18
+ protected get commandClient() {
19
+ return CommandClient.getFromModule(this)
20
+ }
21
+
22
+ protected get client() {
23
+ return this.commandClient.discord
24
+ }
25
+
26
+ protected _logger?: Logger
27
+
28
+ protected get logger() {
29
+ if (!this._logger) this._logger = this.commandClient.logger.getChildLogger({ prefix: [chalk.green(`[${this.constructor.name}]`)], displayFunctionName: false })
30
+ return this._logger
31
+ }
32
+
33
+ protected async convertArguments(
34
+ component: typeof BaseComponent<unknown>,
35
+ argList: unknown[],
36
+ args: Collection<number, ComponentArgument>,
37
+ getConverterArgs: (arg: ComponentArgument, index: number, converter: ConverterComponent) => unknown[] | Promise<unknown[]>,
38
+ ) {
39
+ const items = new Collection<unknown, { ext: object; component: ConverterComponent }>()
40
+
41
+ for (const extension of this.commandClient.registry.extensions) {
42
+ for (const converter of this.commandClient.registry.getComponentsWithType(extension, ConverterComponent)) {
43
+ if (converter.options.component != component) continue
44
+
45
+ items.set(converter.options.type, { component: converter, ext: extension })
46
+ }
47
+ }
48
+
49
+ for (const [index, arg] of args) {
50
+ const converter = items.get(arg.type)
51
+
52
+ if (!converter) {
53
+ argList[index] = undefined
54
+ continue
55
+ }
56
+
57
+ const converterArgs = await getConverterArgs(arg, index, converter.component)
58
+
59
+ argList[index] = await converter.component.execute(converter.ext, converterArgs)
60
+ }
61
+ }
62
+ }
@@ -0,0 +1,9 @@
1
+ /*
2
+ * File: index.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
9
+ export * from './Extension'
@@ -0,0 +1,40 @@
1
+ /*
2
+ * File: componentHook.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
9
+ import { Collection } from 'discord.js'
10
+ import { ComponentHookSymbol } from '../symbols'
11
+
12
+ export type ComponentHookFn = (...args: any[]) => void | Promise<void>
13
+
14
+ export type ComponentHookStore = Collection<string, ComponentHookFn[]>
15
+
16
+ export const getComponentHookStore = (target: object, property: string | symbol): ComponentHookStore => {
17
+ let data = Reflect.getMetadata(ComponentHookSymbol, target, property) as ComponentHookStore
18
+
19
+ if (!data) {
20
+ data = new Collection()
21
+ Reflect.defineMetadata(ComponentHookSymbol, data, target, property)
22
+ }
23
+
24
+ return data
25
+ }
26
+
27
+ export const createComponentHook = (name: string, fn: ComponentHookFn): MethodDecorator => {
28
+ return (target, key) => {
29
+ const store = getComponentHookStore(target, key)
30
+
31
+ let hooks = store.get(name)
32
+
33
+ if (!hooks) {
34
+ hooks = []
35
+ store.set(name, hooks)
36
+ }
37
+
38
+ hooks.push(fn)
39
+ }
40
+ }
@@ -1 +1,11 @@
1
- export * from './moduleHook'
1
+ /*
2
+ * File: index.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
9
+ export * from './moduleHook'
10
+ export { createComponentHook } from './componentHook'
11
+ export type { ComponentHookStore } from './componentHook'
@@ -1,7 +1,15 @@
1
+ /*
2
+ * File: moduleHook.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
1
9
  import { Collection } from 'discord.js'
2
10
  import { ModuleHookStoreSymbol } from '../symbols'
3
11
 
4
- type ModuleHookStore = Collection<string | symbol, Function[]>
12
+ type ModuleHookStore = Collection<string, Function[]>
5
13
 
6
14
  export const getModuleHookStore = (target: object) => {
7
15
  let result: ModuleHookStore | null = Reflect.getMetadata(ModuleHookStoreSymbol, target)
@@ -19,11 +27,11 @@ export const moduleHook = (name: string): MethodDecorator => {
19
27
  return (target, key) => {
20
28
  const store = getModuleHookStore(target)
21
29
 
22
- let v = store.get(key)
30
+ let v = store.get(name)
23
31
 
24
32
  if (!v) {
25
33
  v = []
26
- store.set(key, v)
34
+ store.set(name, v)
27
35
  }
28
36
 
29
37
  v.push(Reflect.get(target, key))
package/src/core/index.ts CHANGED
@@ -1,3 +1,15 @@
1
+ /*
2
+ * File: index.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
1
9
  export * from './components'
2
- export * from './structures'
3
10
  export * from './hooks'
11
+ export * from './converter'
12
+ export * from './utils'
13
+ export * from './listener'
14
+ export * from './structures'
15
+ export * from './extensions'
@@ -1,9 +1,29 @@
1
- import { BaseComponent, createComponentDecorator } from '../components'
1
+ /*
2
+ * File: index.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
9
+ import { BaseComponent } from '../components/BaseComponent'
10
+ import { createComponentDecorator } from '../components/decoratorCreator'
2
11
 
3
- export class ListenerComponent extends BaseComponent<{ emitter: string }, { event: string }> {
12
+ export class ListenerComponent extends BaseComponent<{ emitter: string; event: string }, { emitter?: string; event: string }> {
4
13
  defaultOptions() {
5
14
  return { emitter: 'discord' }
6
15
  }
16
+
17
+ constructor(options: ListenerComponent['options'], method: Function, argTypes: unknown[]) {
18
+ super(
19
+ {
20
+ event: options.event,
21
+ emitter: options.emitter ?? 'discord',
22
+ },
23
+ method,
24
+ argTypes,
25
+ )
26
+ }
7
27
  }
8
28
 
9
29
  export const listener = createComponentDecorator(ListenerComponent)
@@ -1,14 +1,78 @@
1
- import { Client } from 'discord.js'
1
+ /*
2
+ * File: CommandClient.ts
3
+ *
4
+ * Copyright (c) 2022-2022 pikokr
5
+ *
6
+ * Licensed under MIT License. Please see more defails in LICENSE file.
7
+ */
8
+
9
+ import chalk from 'chalk'
10
+ import { Client, Snowflake, Team, User } from 'discord.js'
2
11
  import EventEmitter from 'events'
12
+ import { Logger } from 'tslog'
13
+ import { ApplicationCommandExtension, ApplicationCommandExtensionConfig } from '../../applicationCommand/ApplicationCommandExtension'
14
+ import { TextCommandConfig } from '../../textCommand'
15
+ import { TextCommandExtension } from '../../textCommand/TextCommandExtension'
16
+ import { CommandClientSymbol } from '../symbols'
3
17
  import { Registry } from './Registry'
4
-
5
18
  export class CommandClient extends EventEmitter {
6
- registry = new Registry()
19
+ ctsLogger: Logger
20
+ registry: Registry
21
+
22
+ owners: Set<Snowflake> = new Set()
7
23
 
8
- constructor(public discord: Client) {
24
+ constructor(public discord: Client, public logger: Logger = new Logger({ dateTimeTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone })) {
9
25
  super()
10
26
 
27
+ this.ctsLogger = logger.getChildLogger({ prefix: [chalk.blue('[command.ts]')], displayFilePath: 'hidden', displayFunctionName: false })
28
+
29
+ this.registry = new Registry(this.ctsLogger, this)
30
+
11
31
  this.registry.registerEventEmitter('cts', this)
12
32
  this.registry.registerEventEmitter('discord', this.discord)
13
33
  }
34
+
35
+ async fetchOwners() {
36
+ if (!this.discord.application) throw new Error('The client is not logged in.')
37
+
38
+ this.ctsLogger.info('Fetching owners...')
39
+
40
+ await this.discord.application.fetch()
41
+
42
+ const owner = this.discord.application.owner
43
+
44
+ if (!owner) throw new Error('Cannot find application owner')
45
+
46
+ const owners: string[] = []
47
+
48
+ if (owner instanceof User) {
49
+ this.owners.add(owner.id)
50
+ owners.push(owner.tag)
51
+ } else if (owner instanceof Team) {
52
+ for (const [id, member] of owner.members) {
53
+ this.owners.add(id)
54
+ owners.push(member.user.tag)
55
+ }
56
+ }
57
+
58
+ this.ctsLogger.info(`Fetched ${chalk.green(owners.length)} owners(${owners.map((x) => chalk.blue(x)).join(', ')})`)
59
+ }
60
+
61
+ async enableApplicationCommandsExtension(config: ApplicationCommandExtensionConfig) {
62
+ await this.registry.registerModule(new ApplicationCommandExtension(config))
63
+ this.ctsLogger.info('Application command extension enabled.')
64
+ }
65
+
66
+ async enableTextCommandsExtension(config: TextCommandConfig) {
67
+ await this.registry.registerModule(new TextCommandExtension(config))
68
+ this.ctsLogger.info('Text command extension enabled.')
69
+ }
70
+
71
+ getApplicationCommandsExtension() {
72
+ return this.registry.extensions.find((x) => x.constructor === ApplicationCommandExtension) as ApplicationCommandExtension | undefined
73
+ }
74
+
75
+ static getFromModule(ext: object): CommandClient {
76
+ return Reflect.getMetadata(CommandClientSymbol, ext)
77
+ }
14
78
  }