chz-telegram-bot 0.3.13 → 0.3.14

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
@@ -26,13 +26,13 @@ botFramework is a TypeScript library that provides a structured approach to buil
26
26
 
27
27
  ```bash
28
28
  # Using npm
29
- npm install chz-bot-framework
29
+ npm install chz-telegram-bot
30
30
 
31
31
  # Using yarn
32
- yarn add chz-bot-framework
32
+ yarn add chz-telegram-bot
33
33
 
34
34
  # Using bun
35
- bun add chz-bot-framework
35
+ bun add chz-telegram-bot
36
36
  ```
37
37
 
38
38
  ## Quick Start
@@ -59,6 +59,7 @@ import {
59
59
  startBot,
60
60
  stopBots,
61
61
  CommandActionBuilder,
62
+ MessageType,
62
63
  Seconds
63
64
  } from 'chz-telegram-bot';
64
65
 
@@ -66,31 +67,52 @@ import {
66
67
  const commands = [
67
68
  new CommandActionBuilder('HelloWorld')
68
69
  .on('/hello')
69
- .do(async (ctx) => {
70
- ctx.replyWithText('Hello, world!');
70
+ .do((ctx) => {
71
+ ctx.reply.withText('Hello, world!');
72
+ })
73
+ .build(),
74
+
75
+ new CommandActionBuilder('Welcome')
76
+ .on(MessageType.NewChatMember)
77
+ .do((ctx) => {
78
+ ctx.reply, withText('Welcome to the group!');
71
79
  })
72
80
  .build()
73
81
  ];
74
82
 
75
- // Define scheduled actions (if needed)
76
- const scheduled = [];
77
-
78
83
  async function main() {
79
- // Start the bot
80
- startBot({
81
- name: 'MyFirstBot',
82
- tokenFilePath: './token.txt',
83
- commands: commands,
84
- scheduled: scheduled,
85
- chats: {
86
- MyChat: -1001234567890 // Replace with your actual chat ID,
87
- },
88
- scheduledPeriod: (60 * 5) as Seconds
89
- });
90
-
91
- // Set up graceful shutdown
92
- process.on('SIGINT', () => stopBots('SIGINT'));
93
- process.on('SIGTERM', () => stopBots('SIGTERM'));
84
+ try {
85
+ // Start the bot
86
+ const bot = await startBot({
87
+ name: 'MyFirstBot',
88
+ tokenFilePath: './token.txt',
89
+ commands,
90
+ scheduled: [], // Add scheduled actions if needed
91
+ chats: {
92
+ MyChat: -1001234567890 // Replace with your chat ID
93
+ },
94
+ scheduledPeriod: (60 * 5) as Seconds,
95
+ // Optional settings
96
+ storagePath: './data',
97
+ verboseLoggingForIncomingMessage: false
98
+ });
99
+
100
+ // Proper cleanup on shutdown
101
+ const cleanup = async (signal: string) => {
102
+ console.log(`Received ${signal}, cleaning up...`);
103
+ await stopBots(signal);
104
+ process.exit(0);
105
+ };
106
+
107
+ process.on('SIGINT', () => cleanup('SIGINT'));
108
+ process.on('SIGTERM', () => cleanup('SIGTERM'));
109
+
110
+ console.log('Bot started successfully!');
111
+ return bot;
112
+ } catch (error) {
113
+ console.error('Failed to start bot:', error);
114
+ process.exit(1);
115
+ }
94
116
  }
95
117
 
96
118
  main().catch(console.error);
@@ -113,21 +135,21 @@ import { CommandActionBuilder } from 'chz-telegram-bot';
113
135
 
114
136
  const myCommand = new CommandActionBuilder('StartCommand')
115
137
  .on('/start')
116
- .do(async (ctx) => {
117
- ctx.replyWithText('Welcome to my bot!');
138
+ .do((ctx) => {
139
+ ctx.reply.withText('Welcome to my bot!');
118
140
  })
119
141
  .build();
120
142
  ```
121
143
 
122
- Message types are also can trigger commands:
144
+ Message types can also trigger commands:
123
145
 
124
146
  ```typescript
125
147
  import { CommandActionBuilder, MessageType } from 'chz-telegram-bot';
126
148
 
127
149
  const myCommand = new CommandActionBuilder('WelcomeMessage')
128
150
  .on(MessageType.NewChatMember)
129
- .do(async (ctx) => {
130
- ctx.replyWithText('Welcome to my group chat!');
151
+ .do((ctx) => {
152
+ ctx.reply.withText('Welcome to my group chat!');
131
153
  })
132
154
  .build();
133
155
  ```
@@ -141,38 +163,38 @@ import { ScheduledActionBuilder, Hours } from 'chz-telegram-bot';
141
163
 
142
164
  const dailyNotification = new ScheduledActionBuilder('GM')
143
165
  .runAt(9 as Hours) // Run at 9 AM
144
- .do(async (ctx) => {
145
- ctx.sendTextToChat('Good morning!');
166
+ .do((ctx) => {
167
+ ctx.send.text('Good morning!');
146
168
  })
147
169
  .build();
148
170
  ```
149
171
 
150
172
  ### Replies and message sending
151
173
 
152
- Depending on a type of action, you will have access to following interaction options:
174
+ Depending on the type of action, you will have access to the following interaction options:
153
175
 
154
- | Method | Action type | Description |
155
- | ----------------- | ----------- | ------------------------------------------------------------ |
156
- | `sendTextToChat` | Both | Send text to chat as a standalone message |
157
- | `sendImageToChat` | Both | Send image to chat as a standalone message |
158
- | `sendVideoToChat` | Both | Send video/gif to chat as a standalone message |
159
- | `unpinMessage` | Both | Unpins message by its ID |
160
- | `wait` | Both | Delays next replies from this action by given amount of ms |
161
- | `replyWithText` | Command | Replies with text to a message that triggered an action |
162
- | `replyWithImage` | Command | Replies with image to a message that triggered an action |
163
- | `replyWithVideo` | Command | Replies with video/gif to a message that triggered an action |
164
- | `react` | Command | Sets an emoji reaction to a message that triggered an action |
176
+ | Method | Action type | Description |
177
+ | -------------------- | ----------- | ------------------------------------------------------------ |
178
+ | `send.text` | Both | Send text to chat as a standalone message |
179
+ | `send.image` | Both | Send image to chat as a standalone message |
180
+ | `send.video` | Both | Send video/gif to chat as a standalone message |
181
+ | `unpinMessage` | Both | Unpins message by its ID |
182
+ | `wait` | Both | Delays next replies from this action by given amount of ms |
183
+ | `reply.withText` | Command | Replies with text to a message that triggered an action |
184
+ | `reply.withImage` | Command | Replies with image to a message that triggered an action |
185
+ | `reply.withVideo` | Command | Replies with video/gif to a message that triggered an action |
186
+ | `reply.withReaction` | Command | Sets an emoji reaction to a message that triggered an action |
165
187
 
166
- Keep in mind that reply sending is deferred until action execution finished and will be done in order of calling in action handler.
167
- Ex:
188
+ Keep in mind that reply sending is deferred until action execution finishes and will be done in order of calling in the action handler.
189
+ Example:
168
190
 
169
191
  ```typescript
170
- ctx.sendTextToChat('Message 1');
192
+ ctx.send.text('Message 1');
171
193
  ctx.wait(5000 as Millisecond);
172
- ctx.sendTextToChat('Message 2');
194
+ ctx.send.text('Message 2');
173
195
  ```
174
196
 
175
- This will result in `Message 1` text being send, followed by `Message 2` after 5 second delay.
197
+ This will result in `Message 1` being sent, followed by `Message 2` after a 5 second delay.
176
198
 
177
199
  ## Configuration Options
178
200
 
@@ -182,27 +204,19 @@ When starting a bot, you can provide the following configuration:
182
204
  | ----------------- | ------------------------ | --------------------------- | ----------------------------------------------------------------------------------------- |
183
205
  | `name` | `string` | Yes | Bot name used in logging |
184
206
  | `tokenFilePath` | `string` | Yes | Path to file containing Telegram Bot token |
185
- | `actions` | | Yes | Object containing actions to be executed by bot |
207
+ | `commands` | `CommandAction[] ` | Yes (can be empty) | Collection of command actions |
208
+ | `scheduled` | `ScheduledAction[]` | Yes (can be empty) | Collection of scheduled actions |
186
209
  | `chats` | `Record<string, number>` | Yes | Object containing chat name-id pairs. Used for logging and execution of scheduled action. |
187
210
  | `storagePath` | `string` | No | Custom storage path for default JsonFileStorage client |
188
211
  | `scheduledPeriod` | `Seconds` | No (will default to 1 hour) | Period between scheduled action executions |
189
212
  | `services` | | No | Custom services to be used instead of default ones |
190
213
 
191
- Actions object should have following structure:
192
-
193
- | Option | Type | Required | Description |
194
- | --------------- | --------------------- | ------------------ | ---------------------------------- |
195
- | `commands` | `CommandAction[] ` | Yes (can be empty) | Collection of command actions |
196
- | `scheduled` | `ScheduledAction[]` | Yes (can be empty) | Collection of scheduled actions |
197
- | `inlineQueries` | `InlineQueryAction[]` | Yes (can be empty) | Collection of inline query actions |
198
-
199
214
  Services object should have following structure:
200
-
201
- | Option | Type | Required | Description |
202
- | --------------- | ---------------- | ------------------------------------------- | ---------------------------------- |
203
- | `storageClient` | `IStorageClient` | No (will default to `JsonFileStorage`) | Persistance state provide |
204
- | `logger` | `ILogger` | No (will default to `JsonLogger`) | Logger service |
205
- | `scheduler` | `IScheduler` | No (will default to `NodeTimeoutScheduler`) | Scheduler used to scheduled action |
215
+ | Option | Type | Required | Description |
216
+ |------------------|--------------------------|----------|---------------------------------------------------------------|
217
+ | `storageClient` | `IStorageClient` | No (will default to `JsonFileStorage`) | Persistance state provide |
218
+ | `logger` | `ILogger` | No (will default to `JsonLogger`) | Logger service |
219
+ | `scheduler` | `IScheduler` | No (will default to `NodeTimeoutScheduler`) | Scheduler used to scheduled action|
206
220
 
207
221
  ## Advanced Usage
208
222
 
@@ -224,7 +238,7 @@ const counterCommand = new CommandActionBuilderWithState<MyCustomState>(
224
238
  .on('/count')
225
239
  .do(async (ctx, state) => {
226
240
  state.counter++;
227
- ctx.replyWithText(`Count: ${state.counter}`);
241
+ ctx.reply.withText(`Count: ${state.counter}`);
228
242
  })
229
243
  .build();
230
244
  ```
@@ -239,15 +253,20 @@ The framework provides support for handling inline queries with type-safe builde
239
253
  import { InlineQueryActionBuilder } from 'chz-telegram-bot';
240
254
 
241
255
  const searchCommand = new InlineQueryActionBuilder('Search')
242
- .do(async (ctx) => {
256
+ .do((ctx) => {
243
257
  const query = ctx.queryText;
244
258
  // Process the query and return inline results
245
- ctx.showInlineQueryResult({
246
- id: '1',
247
- type: 'article',
248
- title: `Search results for: ${query}`,
249
- description: 'Click to send'
250
- });
259
+ ctx.showInlineQueryResult([
260
+ {
261
+ id: '1',
262
+ type: 'article',
263
+ title: `Search results for: ${query}`,
264
+ description: 'Click to send',
265
+ input_message_content: {
266
+ message_text: `Search result for: ${query}`
267
+ }
268
+ }
269
+ ]);
251
270
  })
252
271
  .build();
253
272
  ```
@@ -257,9 +276,9 @@ const searchCommand = new InlineQueryActionBuilder('Search')
257
276
  The framework includes a response processing queue that ensures reliable message delivery and proper ordering of responses:
258
277
 
259
278
  ```typescript
260
- ctx.sendTextToChat('First message');
261
- ctx.sendImageToChat('image.jpg');
262
- ctx.react('👍');
279
+ await ctx.send.text('First message');
280
+ await ctx.send.image('image');
281
+ await ctx.reply.withReaction('👍');
263
282
  ```
264
283
 
265
284
  All responses are queued and processed in order, ensuring proper sequencing of messages and reactions.
Binary file
@@ -1 +1 @@
1
- {"version":3,"file":"commandAction.d.ts","sourceRoot":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ction {
84
84
  }
85
85
  }
86
86
  checkIfShouldBeExecuted(ctx, trigger, state) {
87
+ const triggerCheckResult = this.checkTrigger(ctx, trigger);
88
+ if (!triggerCheckResult.shouldExecute)
89
+ return triggerCheckResult;
87
90
  if (!ctx.fromUserId)
88
91
  return commandTriggerCheckResult_1.CommandTriggerCheckResult.DontTriggerAndSkipCooldown('UserIdMissing');
89
92
  const isUserAllowed = this.allowedUsers.length == 0 ||
@@ -98,7 +101,7 @@ class CommandAction {
98
101
  const isCustomConditionMet = this.condition(ctx, state);
99
102
  if (!isCustomConditionMet)
100
103
  return commandTriggerCheckResult_1.CommandTriggerCheckResult.DontTriggerAndSkipCooldown('CustomConditionNotMet');
101
- return this.checkTrigger(ctx, trigger);
104
+ return triggerCheckResult;
102
105
  }
103
106
  checkTrigger(ctx, trigger) {
104
107
  if (trigger == messageTypes_1.MessageType.Any || trigger == ctx.messageType)
@@ -149,6 +149,10 @@ export class CommandAction<TActionState extends IActionState>
149
149
  trigger: CommandTrigger,
150
150
  state: TActionState
151
151
  ) {
152
+ const triggerCheckResult = this.checkTrigger(ctx, trigger);
153
+
154
+ if (!triggerCheckResult.shouldExecute) return triggerCheckResult;
155
+
152
156
  if (!ctx.fromUserId)
153
157
  return CommandTriggerCheckResult.DontTriggerAndSkipCooldown(
154
158
  'UserIdMissing'
@@ -179,7 +183,7 @@ export class CommandAction<TActionState extends IActionState>
179
183
  'CustomConditionNotMet'
180
184
  );
181
185
 
182
- return this.checkTrigger(ctx, trigger);
186
+ return triggerCheckResult;
183
187
  }
184
188
 
185
189
  private checkTrigger(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chz-telegram-bot",
3
- "version": "0.3.13",
3
+ "version": "0.3.14",
4
4
  "type": "module",
5
5
  "dependencies": {
6
6
  "async-sema": "^3.1.1",