@grammyjs/commands 0.0.1 → 0.3.0

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.
package/README.md CHANGED
@@ -1,12 +1,10 @@
1
1
  ## grammY Commands Plugin
2
2
 
3
- This plugin provides a convenient way to define and manage commands for your grammY bot. It simplifies the process of
4
- setting up commands with scopes and localization.
3
+ This plugin provides a convenient way to define and manage commands for your grammY bot. It simplifies the process of setting up commands with scopes and localization.
5
4
 
6
5
  ## Installation
7
6
 
8
- On NPM, this plugin is available as `@grammyjs/commands`, and on Deno it's available at
9
- [deno.land/x/grammy_commands](https://deno.land/x/grammy_commands).
7
+ On NPM, this plugin is available as `@grammyjs/commands`, and on Deno it's available at [deno.land/x/grammy_commands](https://deno.land/x/grammy_commands).
10
8
 
11
9
  You can install it for Node.js with this command:
12
10
 
@@ -14,165 +12,61 @@ You can install it for Node.js with this command:
14
12
  npm i @grammyjs/commands
15
13
  ```
16
14
 
17
- ## Core Concepts
18
-
19
- ### The `Commands` class
20
-
21
- The `Commands` class is the foundation of this plugin. It allows you to create commands by specifying their names and
22
- descriptions, along with additional attributes such as scopes and localization.
23
-
24
- ### The `ctx.setMyCommands` method
25
-
26
- The `ctx.setMyCommands` method, provided by the plugin, offers a convenient way to dynamically set the available
27
- commands for the current chat. By invoking this method and passing an instance of the `Commands` class, you can override
28
- the default command scopes and make all commands accessible within the current chat. This feature is particularly useful
29
- when you need to customize the command set for specific chat contexts, ignoring the predefined scopes, which allows for
30
- a more tailored and context-aware usage of bot commands.
31
15
 
32
16
  ## Usage
33
17
 
34
- ### Managing Commands For Multiple Scopes
18
+ The main functionality of this plugin is to define your commands, localize them, and give them handlers for each [scope](https://core.telegram.org/bots/api#botcommandscope), like so:
35
19
 
36
- To manage commands for multiple scopes at once, create an instance of the `Commands` class, add your commands to it, and
37
- then call the `setFor` method of the class instance. Check out this example:
38
20
 
39
21
  ```typescript
40
22
  import { Bot } from "https://deno.land/x/grammy/mod.ts";
41
23
  import { Commands } from "https://deno.land/x/grammy_commands/mod.ts";
42
24
 
43
- const bot = new Bot("<your_bot_token>");
44
- const cmds = new Commands();
45
-
46
- // Define your commands...
47
-
48
- await cmds.setFor(bot);
49
- ```
50
-
51
- ### Managing Commands For The Current Chat
52
-
53
- To set the commands for the current chat, you can use the `ctx.setMyCommands` method of the `Context` object. For that,
54
- you will need to install the `CommandsFlavor` to your context, and create an instance of the `Commands` class, to which
55
- you add your commands to and then pass to `ctx.setMyCommands`. This will override the predefined scopes and make all
56
- commands available to the current chat. Here's an example:
57
-
58
- > Please note that this only works in updates which have a `chat` object. If `ctx.chat` is not defined, an error will be
59
- > thrown ar runtime.
60
-
61
- ```typescript
62
- import { Bot, Context } from "https://deno.land/x/grammy/mod.ts";
63
- import { Commands, CommandsFlavor } from "https://deno.land/x/grammy_commands/mod.ts";
25
+ const bot = new Bot("<telegram token>");
64
26
 
65
- type MyContext = CommandsFlavor<Context>;
66
- const bot = new Bot<MyContext>("<your_bot_token>");
67
-
68
- bot.on(":text", async (ctx: Context) => {
69
- const cmds = new Commands();
70
-
71
- // Define your commands...
72
-
73
- await ctx.setMyCommands(cmds);
74
- });
75
- ```
76
-
77
- ### Defining Commands
78
-
79
- To define a command, use the `command` method of the `CommandsPlugin` instance. The `command` method takes two
80
- arguments: the command name and the command description. Here's an example:
81
-
82
- ```typescript
83
- commands.command("help", "Sends help");
84
- ```
27
+ const myCommands = new Commands();
85
28
 
86
- ### Setting handlers
29
+ myCommands.command("start", "Initializes bot configuration")
30
+ .localize("pt", "start", "Inicializa as configurações do bot")
31
+ .addToScope({ type: "all_private_chats" }, (ctx) => ctx.reply(`Hello, ${ctx.chat.first_name}!`))
32
+ .addToScope({ type: "all_group_chats" }, (ctx) => ctx.reply(`Hello, members of ${ctx.chat.title}!`));
87
33
 
88
- The underlying class returned by the `.command()` method extends the grammY `Composer` class. That means you can use
89
- `.use`, `.filter`, `.branch`, `.chatType` and every other `Composer` method you already know and love. Alternatively,
90
- you can pass your middleware as a third parameter to the `.command()` method. You can also use the `onChatType` method
91
- of the `Command` class to define middleware specific to that chat type. Here are some examples:
34
+ // Calls `setMyCommands`
35
+ await myCommands.setCommands(bot);
92
36
 
93
- #### Example 1
37
+ // Registers the command handlers
38
+ bot.use(myCommands);
94
39
 
95
- ```typescript
96
- commands.command("start", "Starts the bot", (ctx) => {
97
- ctx.reply(`Hello, ${ctx.chat?.first_name ?? "there"}!`);
98
- });
40
+ bot.start();
99
41
  ```
100
42
 
101
- #### Example 2
43
+ It is very important that you call `bot.use` with your instance of the `Commands` class.
44
+ Otherwise, the command handlers will not be registered, and your bot will not respond to those commands.
102
45
 
103
- ```typescript
104
- commands.command("start", "Starts the bot")
105
- .onChatType("private", (ctx) => ctx.reply(`Hello ${ctx.chat.first_name}!`))
106
- .onChatType(["group", "supergroup", "channel"], (ctx) => ctx.reply(`Hello members of ${ctx.chat.title}!`))
107
- .addToScope("default");
108
- ```
46
+ ### Context shortcuts
109
47
 
110
- ### Localization
111
-
112
- You can localize command names and descriptions using the `localize` method. The `localize` method takes the language
113
- code, the localized command name, and the localized command description. Here's an example:
48
+ This plugin provides a shortcut for setting the commands for the current chat.
49
+ To use it, you need to install the commands flavor and the plugin itself, like so:
114
50
 
115
51
  ```typescript
116
- commands.command("help", "Sends help")
117
- .localize("de-DE", "hilfe", "Sendet Hilfe");
118
- ```
52
+ import { Bot, Context } from "https://deno.land/x/grammy/mod.ts";
53
+ import { Commands, CommandsFlavor, commands } from "https://deno.land/x/grammy_commands/mod.ts";
119
54
 
120
- ### Scopes
55
+ type BotContext = CommandsFlavor;
121
56
 
122
- Scopes determine the availability of each command, enabling you to control whether a command can be accessed in all
123
- group chats, private chats, or limited to chat administrators. Commands can be assigned to different scopes using the
124
- `addToScope` method. Here's an example:
57
+ const bot = new Bot<BotContext>("<telegram_token>");
58
+ bot.use(commands());
125
59
 
126
- ```typescript
127
- commands.command("help", "Sends help")
128
- .addToScope("default")
129
- .addToScope("all_group_chats")
130
- .addToScope("all_private_chats")
131
- .addToScope("all_chat_administrators")
132
- .addToScope("chat_administrators", "@grammyjs")
133
- .addToScope("chat", "@SpecificUserChat");
134
- ```
60
+ bot.on("message", async (ctx) => {
61
+ const cmds = new Commands();
135
62
 
136
- ### Setting Commands for Current Chat
63
+ cmds.command("start", "Initializes bot configuration")
64
+ .localize("pt", "start", "Inicializa as configurações do bot");
137
65
 
138
- To set the commands for the current chat, you can use the `setMyCommands` method of the `Context` object. This will
139
- override the defined scopes and make all commands available to the current chat. Here's an example:
66
+ await ctx.setMyCommands(cmds);
140
67
 
141
- ```typescript
142
- bot.on(":text", async (ctx) => {
143
- await ctx.setMyCommands(commands);
68
+ return ctx.reply("Commands set!");
144
69
  });
145
- ```
146
-
147
- This will set all commands defined in the `commands` instance for the current chat.
148
-
149
- ## Examples
150
-
151
- ### Example 1: Help Command
152
-
153
- This example shows how to define a basic help command:
154
-
155
- ```typescript
156
- commands.command("help", "Sends help")
157
- .localize("de-DE", "hilfe", "Sendet Hilfe")
158
- .addToScope("default")
159
- .addToScope("all_group_chats")
160
- .addToScope("all_private_chats")
161
- .addToScope("all_chat_administrators")
162
- .addToScope("chat_administrators", "@grammyjs")
163
- .addToScope("chat", "@LWJerri");
164
- ```
165
-
166
- ### Example 2: Stats Command
167
-
168
- This example shows how to define a stats command for group chats:
169
-
170
- ```typescript
171
- commands.command("stats", "Sends group stats")
172
- .addToScope("all_group_chats")
173
- .addToScope("all_chat_administrators")
174
- .addToScope("chat_administrators", "@grammyjs")
175
- .addToScope("chat", "@LWJerri");
176
- ```
177
70
 
178
- Feel free to add more commands and customize them according to your bot's needs.
71
+ bot.start()
72
+ ```
package/out/command.d.ts CHANGED
@@ -1,22 +1,26 @@
1
- import { BotCommand, BotCommandScope, Chat, ChatTypeContext, CommandMiddleware, Composer, Context, Middleware } from "./deps.node.js";
1
+ import { type BotCommand, type BotCommandScope, type BotCommandScopeAllChatAdministrators, type BotCommandScopeAllGroupChats, type BotCommandScopeAllPrivateChats, type ChatTypeMiddleware, type Context, type Middleware, type MiddlewareObj } from "./deps.node.js";
2
2
  export type MaybeArray<T> = T | T[];
3
- export declare class Command<C extends Context = Context> extends Composer<C> {
4
- #private;
5
- constructor(name: string, description: string, ...middleware: Array<Middleware<C>>);
3
+ type BotCommandGroupsScope = BotCommandScopeAllGroupChats | BotCommandScopeAllChatAdministrators;
4
+ export declare class Command<C extends Context = Context> implements MiddlewareObj<C> {
5
+ private _scopes;
6
+ private _languages;
7
+ private _composer;
8
+ constructor(name: string, description: string);
9
+ get scopes(): BotCommandScope[];
6
10
  get languages(): Map<string, {
7
11
  name: string;
8
12
  description: string;
9
13
  }>;
10
- get scopes(): BotCommandScope[];
14
+ get names(): string[];
11
15
  get name(): string;
12
16
  get description(): string;
13
- addToScope(type: "default" | "all_private_chats" | "all_group_chats" | "all_chat_administrators"): this;
14
- addToScope(type: "chat", chatId: string | number): this;
15
- addToScope(type: "chat_member", chatId: string | number, userId: number): this;
16
- addToScope(type: "chat_administrators", chatId: string | number): this;
17
+ addToScope(scope: BotCommandGroupsScope, ...middleware: ChatTypeMiddleware<C, "group" | "supergroup">[]): this;
18
+ addToScope(scope: BotCommandScopeAllPrivateChats, ...middleware: ChatTypeMiddleware<C, "private">[]): this;
19
+ addToScope(scope: BotCommandScope, ...middleware: Array<Middleware<C>>): this;
17
20
  localize(languageCode: string, name: string, description: string): this;
18
21
  getLocalizedName(languageCode: string): string;
19
22
  getLocalizedDescription(languageCode: string): string;
20
- onChatType<T extends Chat["type"]>(chatType: MaybeArray<T>, ...middleware: Array<CommandMiddleware<ChatTypeContext<C, T>>>): this;
21
23
  toObject(languageCode?: string): BotCommand;
24
+ middleware(): import("grammy").MiddlewareFn<C>;
22
25
  }
26
+ export {};
package/out/command.js CHANGED
@@ -1,62 +1,54 @@
1
1
  "use strict";
2
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
- };
7
- var _Command_scopes, _Command_languages;
8
2
  Object.defineProperty(exports, "__esModule", { value: true });
9
3
  exports.Command = void 0;
10
4
  const deps_node_js_1 = require("./deps.node.js");
11
- class Command extends deps_node_js_1.Composer {
12
- constructor(name, description, ...middleware) {
13
- super();
14
- _Command_scopes.set(this, []);
15
- _Command_languages.set(this, new Map());
16
- if (!name.match(/[a-z0-9_]{1,32}/)) {
17
- throw new Error(`${name} is not a valid command name`);
18
- }
19
- __classPrivateFieldGet(this, _Command_languages, "f").set("default", { name, description });
20
- this.command(name, ...middleware);
5
+ const isAdmin = (ctx) => ctx.getAuthor().then((author) => ["administrator", "creator"].includes(author.status));
6
+ class Command {
7
+ constructor(name, description) {
8
+ this._scopes = [];
9
+ this._languages = new Map();
10
+ this._composer = new deps_node_js_1.Composer();
11
+ this._languages.set("default", { name, description });
12
+ }
13
+ get scopes() {
14
+ return this._scopes;
21
15
  }
22
16
  get languages() {
23
- return __classPrivateFieldGet(this, _Command_languages, "f");
17
+ return this._languages;
24
18
  }
25
- get scopes() {
26
- return __classPrivateFieldGet(this, _Command_scopes, "f");
19
+ get names() {
20
+ return Array.from(this._languages.values()).map(({ name }) => name);
27
21
  }
28
22
  get name() {
29
- return __classPrivateFieldGet(this, _Command_languages, "f").get("default").name;
23
+ return this._languages.get("default").name;
30
24
  }
31
25
  get description() {
32
- return __classPrivateFieldGet(this, _Command_languages, "f").get("default").description;
33
- }
34
- addToScope(type, chatId, userId) {
35
- const scope = (0, deps_node_js_1.match)({ type, chatId, userId })
36
- .with({ type: "default" }, { type: "all_chat_administrators" }, { type: "all_group_chats" }, { type: "all_private_chats" }, ({ type }) => ({ type }))
37
- .with({ type: deps_node_js_1.P.union("chat", "chat_administrators"), chatId: deps_node_js_1.P.not(deps_node_js_1.P.nullish) }, ({ type, chatId }) => ({ type, chat_id: chatId }))
38
- .with({ type: "chat_member", chatId: deps_node_js_1.P.not(deps_node_js_1.P.nullish), userId: deps_node_js_1.P.not(deps_node_js_1.P.nullish) }, ({ type, chatId, userId }) => ({ type, chat_id: chatId, user_id: userId }))
39
- .otherwise(() => null);
40
- if (scope)
41
- __classPrivateFieldGet(this, _Command_scopes, "f").push(scope);
26
+ return this._languages.get("default").description;
27
+ }
28
+ addToScope(scope, ...middleware) {
29
+ (0, deps_node_js_1.match)(scope)
30
+ .with({ type: "default" }, () => this._composer.command(this.names, ...middleware))
31
+ .with({ type: "all_chat_administrators" }, () => this._composer.filter(isAdmin).command(this.names, ...middleware))
32
+ .with({ type: "all_private_chats" }, () => this._composer.chatType("private").command(this.names, ...middleware))
33
+ .with({ type: "all_group_chats" }, () => this._composer.chatType(["group", "supergroup"]).command(this.names, ...middleware))
34
+ .with({ type: deps_node_js_1.P.union("chat", "chat_administrators"), chat_id: deps_node_js_1.P.not(deps_node_js_1.P.nullish).select() }, (chatId) => this._composer.filter((ctx) => { var _a; return ((_a = ctx.chat) === null || _a === void 0 ? void 0 : _a.id) === chatId; }).filter(isAdmin).command(this.names, ...middleware))
35
+ .with({ type: "chat_member", chat_id: deps_node_js_1.P.not(deps_node_js_1.P.nullish).select("chatId"), user_id: deps_node_js_1.P.not(deps_node_js_1.P.nullish).select("userId") }, ({ chatId, userId }) => this._composer.filter((ctx) => { var _a; return ((_a = ctx.chat) === null || _a === void 0 ? void 0 : _a.id) === chatId; })
36
+ .filter((ctx) => { var _a; return ((_a = ctx.from) === null || _a === void 0 ? void 0 : _a.id) === userId; })
37
+ .command(this.names, ...middleware));
38
+ this._scopes.push(scope);
42
39
  return this;
43
40
  }
44
41
  localize(languageCode, name, description) {
45
- __classPrivateFieldGet(this, _Command_languages, "f").set(languageCode, { name, description });
42
+ this._languages.set(languageCode, { name, description });
46
43
  return this;
47
44
  }
48
45
  getLocalizedName(languageCode) {
49
46
  var _a, _b;
50
- return (_b = (_a = __classPrivateFieldGet(this, _Command_languages, "f").get(languageCode)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : this.name;
47
+ return (_b = (_a = this._languages.get(languageCode)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : this.name;
51
48
  }
52
49
  getLocalizedDescription(languageCode) {
53
50
  var _a, _b;
54
- return (_b = (_a = __classPrivateFieldGet(this, _Command_languages, "f").get(languageCode)) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : this.description;
55
- }
56
- onChatType(chatType, ...middleware) {
57
- const names = Array.from(__classPrivateFieldGet(this, _Command_languages, "f").values()).map(({ name }) => name);
58
- this.chatType(chatType).command(names, ...middleware);
59
- return this;
51
+ return (_b = (_a = this._languages.get(languageCode)) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : this.description;
60
52
  }
61
53
  toObject(languageCode = "default") {
62
54
  return {
@@ -64,6 +56,8 @@ class Command extends deps_node_js_1.Composer {
64
56
  description: this.getLocalizedDescription(languageCode),
65
57
  };
66
58
  }
59
+ middleware() {
60
+ return this._composer.middleware();
61
+ }
67
62
  }
68
63
  exports.Command = Command;
69
- _Command_scopes = new WeakMap(), _Command_languages = new WeakMap();
@@ -1,3 +1,3 @@
1
- export { Bot, type ChatTypeContext, type CommandMiddleware, Composer, Context, type Middleware, type NextFunction, } from "grammy";
2
- export type { BotCommand, BotCommandScope, Chat } from "grammy/types";
1
+ export { Api, Bot, type ChatTypeContext, type ChatTypeMiddleware, type CommandMiddleware, Composer, Context, type Middleware, type MiddlewareObj, type NextFunction, } from "grammy";
2
+ export type { BotCommand, BotCommandScope, BotCommandScopeAllChatAdministrators, BotCommandScopeAllGroupChats, BotCommandScopeAllPrivateChats, Chat, } from "grammy/types";
3
3
  export { match, P } from "ts-pattern";
package/out/deps.node.js CHANGED
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.P = exports.match = exports.Context = exports.Composer = exports.Bot = void 0;
3
+ exports.P = exports.match = exports.Context = exports.Composer = exports.Bot = exports.Api = void 0;
4
4
  // TODO: Replace with official deno module, once it arrives (https://github.com/gvergnaud/ts-pattern/pull/108)
5
5
  var grammy_1 = require("grammy");
6
+ Object.defineProperty(exports, "Api", { enumerable: true, get: function () { return grammy_1.Api; } });
6
7
  Object.defineProperty(exports, "Bot", { enumerable: true, get: function () { return grammy_1.Bot; } });
7
8
  Object.defineProperty(exports, "Composer", { enumerable: true, get: function () { return grammy_1.Composer; } });
8
9
  Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return grammy_1.Context; } });
package/out/plugin.d.ts CHANGED
@@ -1,18 +1,27 @@
1
1
  import { Command } from "./command.js";
2
- import { Bot, BotCommand, BotCommandScope, Context, Middleware } from "./deps.node.js";
2
+ import { Api, BotCommand, BotCommandScope, Context } from "./deps.node.js";
3
3
  type SetMyCommandsParams = {
4
4
  scope?: BotCommandScope;
5
5
  language_code?: string;
6
6
  commands: BotCommand[];
7
7
  };
8
8
  export declare class Commands<C extends Context> {
9
- #private;
9
+ private _languages;
10
+ private _scopes;
11
+ private _commands;
12
+ private _composer;
10
13
  constructor(commands?: Command<C>[]);
11
- command(name: string, description: string, ...middleware: Array<Middleware<C>>): Command<C>;
14
+ private _addCommandToScope;
15
+ private _populateComposer;
16
+ private _populateMetadata;
17
+ command(name: string, description: string): Command<C>;
12
18
  toArgs(): SetMyCommandsParams[];
13
19
  toSingleScopeArgs(scope: BotCommandScope): SetMyCommandsParams[];
14
- setFor<C extends Context>(bot: Bot<C>): Promise<true[]>;
20
+ setCommands({ api }: {
21
+ api: Api;
22
+ }): Promise<void>;
15
23
  toJSON(): SetMyCommandsParams[];
16
24
  toString(): string;
25
+ middleware(): import("grammy").MiddlewareFn<C>;
17
26
  }
18
27
  export {};
package/out/plugin.js CHANGED
@@ -1,38 +1,50 @@
1
1
  "use strict";
2
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
- };
7
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
8
- if (kind === "m") throw new TypeError("Private method is not writable");
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
11
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
12
- };
13
- var _Commands_instances, _Commands_languages, _Commands_scopes, _Commands_commands, _Commands_addCommandToScope, _Commands_populate;
14
2
  Object.defineProperty(exports, "__esModule", { value: true });
15
3
  exports.Commands = void 0;
16
4
  const command_js_1 = require("./command.js");
17
5
  const deps_node_js_1 = require("./deps.node.js");
18
6
  class Commands {
19
7
  constructor(commands = []) {
20
- _Commands_instances.add(this);
21
- _Commands_languages.set(this, new Set());
22
- _Commands_scopes.set(this, new Map());
23
- _Commands_commands.set(this, []);
24
- commands.forEach((command) => __classPrivateFieldGet(this, _Commands_commands, "f").push(command));
8
+ this._languages = new Set();
9
+ this._scopes = new Map();
10
+ this._commands = [];
11
+ this._composer = new deps_node_js_1.Composer();
12
+ commands.forEach((command) => this._commands.push(command));
25
13
  }
26
- command(name, description, ...middleware) {
27
- const command = new command_js_1.Command(name, description, ...middleware);
28
- __classPrivateFieldGet(this, _Commands_commands, "f").push(command);
14
+ _addCommandToScope(scope, command) {
15
+ var _a;
16
+ const commands = (_a = this._scopes.get(JSON.stringify(scope))) !== null && _a !== void 0 ? _a : [];
17
+ this._scopes.set(JSON.stringify(scope), commands.concat([command]));
18
+ }
19
+ _populateComposer() {
20
+ for (const command of this._commands) {
21
+ for (const args of command.languages.values()) {
22
+ this._composer.command(args.name, command.middleware());
23
+ }
24
+ }
25
+ }
26
+ _populateMetadata() {
27
+ this._languages.clear();
28
+ this._scopes.clear();
29
+ this._commands.forEach((command) => {
30
+ for (const scope of command.scopes) {
31
+ this._addCommandToScope(scope, command);
32
+ }
33
+ for (const language of command.languages.keys()) {
34
+ this._languages.add(language);
35
+ }
36
+ });
37
+ }
38
+ command(name, description) {
39
+ const command = new command_js_1.Command(name, description);
40
+ this._commands.push(command);
29
41
  return command;
30
42
  }
31
43
  toArgs() {
32
- __classPrivateFieldGet(this, _Commands_instances, "m", _Commands_populate).call(this);
44
+ this._populateMetadata();
33
45
  const params = [];
34
- for (const [scope, commands] of __classPrivateFieldGet(this, _Commands_scopes, "f").entries()) {
35
- for (const language of __classPrivateFieldGet(this, _Commands_languages, "f")) {
46
+ for (const [scope, commands] of this._scopes.entries()) {
47
+ for (const language of this._languages) {
36
48
  params.push({
37
49
  scope: JSON.parse(scope),
38
50
  language_code: language === "default" ? undefined : language,
@@ -43,23 +55,21 @@ class Commands {
43
55
  return params.filter((params) => params.commands.length > 0);
44
56
  }
45
57
  toSingleScopeArgs(scope) {
46
- __classPrivateFieldGet(this, _Commands_instances, "m", _Commands_populate).call(this);
58
+ this._populateMetadata();
47
59
  const params = [];
48
- for (const language of __classPrivateFieldGet(this, _Commands_languages, "f")) {
60
+ for (const language of this._languages) {
49
61
  params.push({
50
62
  scope,
51
- language_code: (0, deps_node_js_1.match)(language).with("default", () => undefined).otherwise((value) => value),
52
- commands: __classPrivateFieldGet(this, _Commands_commands, "f")
63
+ language_code: language === "default" ? undefined : language,
64
+ commands: this._commands
53
65
  .filter((command) => command.scopes.length)
54
66
  .map((command) => command.toObject(language)),
55
67
  });
56
68
  }
57
69
  return params;
58
70
  }
59
- setFor(bot) {
60
- const argsArray = this.toArgs();
61
- const promises = argsArray.map((args) => bot.api.raw.setMyCommands(args));
62
- return Promise.all(promises);
71
+ async setCommands({ api }) {
72
+ await Promise.all(this.toArgs().map((args) => api.raw.setMyCommands(args)));
63
73
  }
64
74
  toJSON() {
65
75
  return this.toArgs();
@@ -67,18 +77,11 @@ class Commands {
67
77
  toString() {
68
78
  return JSON.stringify(this);
69
79
  }
70
- [(_Commands_languages = new WeakMap(), _Commands_scopes = new WeakMap(), _Commands_commands = new WeakMap(), _Commands_instances = new WeakSet(), _Commands_addCommandToScope = function _Commands_addCommandToScope(scope, command) {
71
- var _a;
72
- const commands = (_a = __classPrivateFieldGet(this, _Commands_scopes, "f").get(JSON.stringify(scope))) !== null && _a !== void 0 ? _a : [];
73
- __classPrivateFieldGet(this, _Commands_scopes, "f").set(JSON.stringify(scope), commands.concat([command]));
74
- }, _Commands_populate = function _Commands_populate() {
75
- __classPrivateFieldSet(this, _Commands_languages, new Set(), "f");
76
- __classPrivateFieldSet(this, _Commands_scopes, new Map(), "f");
77
- __classPrivateFieldGet(this, _Commands_commands, "f").forEach((command) => {
78
- command.scopes.forEach((scope) => __classPrivateFieldGet(this, _Commands_instances, "m", _Commands_addCommandToScope).call(this, scope, command));
79
- Array.from(command.languages.keys()).forEach((language) => __classPrivateFieldGet(this, _Commands_languages, "f").add(language));
80
- });
81
- }, Symbol.for("Deno.customInspect"))]() {
80
+ middleware() {
81
+ this._populateComposer();
82
+ return this._composer.middleware();
83
+ }
84
+ [Symbol.for("Deno.customInspect")]() {
82
85
  return this.toString();
83
86
  }
84
87
  [Symbol.for("nodejs.util.inspect.custom")]() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grammyjs/commands",
3
- "version": "0.0.1",
3
+ "version": "0.3.0",
4
4
  "description": "grammY Commands Plugin",
5
5
  "main": "out/mod.js",
6
6
  "scripts": {
@@ -21,5 +21,7 @@
21
21
  "devDependencies": {
22
22
  "typescript": "^5.1.6"
23
23
  },
24
- "files": ["out"]
24
+ "files": [
25
+ "out"
26
+ ]
25
27
  }