@mtkruto/node 0.1.115 → 0.1.117

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.
@@ -5,7 +5,7 @@ export declare const PUBLIC_KEYS: PublicKeys;
5
5
  export declare const VECTOR_CONSTRUCTOR = 481674261;
6
6
  export declare const INITIAL_DC: DC;
7
7
  export declare const LAYER = 166;
8
- export declare const APP_VERSION = "MTKruto 0.1.115";
8
+ export declare const APP_VERSION = "MTKruto 0.1.117";
9
9
  export declare const DEVICE_MODEL: string;
10
10
  export declare const LANG_CODE: string;
11
11
  export declare const LANG_PACK = "";
@@ -54,7 +54,7 @@ export const PUBLIC_KEYS = Object.freeze([
54
54
  export const VECTOR_CONSTRUCTOR = 0x1CB5C415;
55
55
  export const INITIAL_DC = "2";
56
56
  export const LAYER = 166;
57
- export const APP_VERSION = "MTKruto 0.1.115";
57
+ export const APP_VERSION = "MTKruto 0.1.117";
58
58
  // @ts-ignore: lib
59
59
  export const DEVICE_MODEL = typeof dntShim.Deno === "undefined" ? typeof navigator === "undefined" ? typeof process === "undefined" ? "Unknown" : process.platform + "-" + process.arch : navigator.userAgent.split(" ")[0] : dntShim.Deno.build.os + "-" + dntShim.Deno.build.arch;
60
60
  export const LANG_CODE = typeof navigator === "undefined" ? "en" : navigator.language.split("-")[0];
@@ -9,3 +9,4 @@ export declare function isChannelPtsUpdate(v: types.TypeUpdate | types.TypeUpdat
9
9
  export type FileSource = string | URL | Uint8Array;
10
10
  export declare function getFileContents(source: FileSource, fileName?: string): Promise<readonly [Uint8Array, string]>;
11
11
  export declare function isHttpUrl(string: string): boolean;
12
+ export declare function getUsername(string: string): string;
@@ -2,6 +2,7 @@ import * as dntShim from "../_dnt.shims.js";
2
2
  import { path } from "../0_deps.js";
3
3
  import { UNREACHABLE } from "../1_utilities.js";
4
4
  import { types } from "../2_tl.js";
5
+ import { Username } from "../tl/2_types.js";
5
6
  export const resolve = () => Promise.resolve();
6
7
  export function isPtsUpdate(v) {
7
8
  return v instanceof types.UpdateShortMessage ||
@@ -74,3 +75,66 @@ export function isHttpUrl(string) {
74
75
  return false;
75
76
  }
76
77
  }
78
+ function isAlpha(string) {
79
+ const c = string.charCodeAt(0) | 0x20;
80
+ return "a".charCodeAt(0) <= c && c <= "z".charCodeAt(0);
81
+ }
82
+ function isDigit(string) {
83
+ const c = string.charCodeAt(0);
84
+ return "0".charCodeAt(0) <= c && c <= "9".charCodeAt(0);
85
+ }
86
+ const errInvalidUsername = (u) => new Error("Invalid username: " + u);
87
+ function validateUsername(string, ignoreAt = false) {
88
+ string = string.trim();
89
+ if (ignoreAt && string.startsWith("@")) {
90
+ string = string.slice(1);
91
+ }
92
+ if (string.length == 0 || string.length > 32) {
93
+ throw errInvalidUsername(string);
94
+ }
95
+ if (!isAlpha(string[0])) {
96
+ throw errInvalidUsername(string);
97
+ }
98
+ for (const c of string) {
99
+ if (!isAlpha(c) && !isDigit(c) && c != "_") {
100
+ throw errInvalidUsername(string);
101
+ }
102
+ }
103
+ if (string[Username.length - 1] == "_") {
104
+ throw errInvalidUsername(string);
105
+ }
106
+ for (let i = 1; i < string.length; ++i) {
107
+ if (string[i - 1] == "_" && string[i] == "_") {
108
+ throw errInvalidUsername(string);
109
+ }
110
+ }
111
+ return string;
112
+ }
113
+ export function getUsername(string) {
114
+ let url = null;
115
+ try {
116
+ url = new URL(string);
117
+ }
118
+ catch {
119
+ try {
120
+ url = new URL("https://" + string);
121
+ }
122
+ catch {
123
+ //
124
+ }
125
+ }
126
+ if (url === null || (url.protocol != "http:" && url.protocol != "https:")) {
127
+ return validateUsername(string, true);
128
+ }
129
+ if (url.hostname != "telegram.dog" && url.hostname != "telegram.me" && url.hostname != "t.me" && !url.hostname.endsWith(".t.me")) {
130
+ return validateUsername(string, true);
131
+ }
132
+ if (url.hostname == "telegram.dog" || url.hostname == "telegram.me" || url.hostname == "t.me") {
133
+ return validateUsername(url.pathname.split("/")[1]);
134
+ }
135
+ const parts = url.hostname.split(".");
136
+ if (parts.length != 3) {
137
+ return validateUsername(string);
138
+ }
139
+ return validateUsername(parts[0]);
140
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,7 +1,6 @@
1
1
  import { MaybePromise } from "../1_utilities.js";
2
2
  import { functions, types } from "../2_tl.js";
3
3
  import { BotCommandScope, CallbackQuery, ChatID, ForceReply, InlineKeyboardMarkup, InlineQuery, InlineQueryResultButton, Message, MessageEntity, ReplyKeyboardMarkup, ReplyKeyboardRemove } from "../3_types.js";
4
- import { With } from "./0_utilities.js";
5
4
  import { ClientPlainParams } from "./2_client_plain.js";
6
5
  import { ParseMode } from "../3_types.js";
7
6
  export interface ClientParams extends ClientPlainParams {
@@ -314,6 +313,10 @@ export interface InvokeErrorHandler<C> {
314
313
  n: number;
315
314
  }, next: NextFn<boolean>): MaybePromise<boolean>;
316
315
  }
317
- export type FilterUpdate<U extends Update, T extends keyof U, F extends (keyof NonNullable<U[T]>) | null> = With<U, T> & Pick<{
318
- [P in T]-?: F extends keyof NonNullable<U[T]> ? With<NonNullable<U[T]>, F> : NonNullable<U[T]>;
319
- }, T>;
316
+ type Update_ = Update;
317
+ export type FilterUpdate<Update extends Update_, Type extends keyof Update_, Field extends string, TypeType extends NonNullable<Update_[Type]> = NonNullable<Update_[Type]>> = Update & {
318
+ [Type_ in Type]-?: TypeType & {
319
+ [Field_ in Field]-?: Field extends keyof TypeType ? NonNullable<TypeType[Field]> : never;
320
+ };
321
+ };
322
+ export {};
@@ -1,4 +1,8 @@
1
- import { FilterableUpdates, FilterUpdate, Update } from "./3_types.js";
1
+ import { User } from "../3_types.js";
2
+ import { FilterableUpdates, FilterUpdate, Update as Update_ } from "./3_types.js";
3
+ interface Update extends Update_ {
4
+ me: undefined extends this["connectionState"] ? undefined extends this["authorizationState"] ? User : (User | undefined) : (User | undefined);
5
+ }
2
6
  type MaybePromise<T> = T | Promise<T>;
3
7
  export type NextFunction = () => Promise<void>;
4
8
  export type MiddlewareFn<C extends Update = Update> = (ctx: C, next: NextFunction) => MaybePromise<unknown>;
@@ -17,6 +21,7 @@ export declare class Composer<C extends Update> implements MiddlewareObj<C> {
17
21
  branch(predicate: (ctx: C) => MaybePromise<boolean>, trueHandler_: Middleware<C>, falseHandler_: Middleware<C>): Composer<C>;
18
22
  filter<D extends C>(predicate: (ctx: C) => ctx is D, ...middleware: Middleware<D>[]): Composer<D>;
19
23
  filter(predicate: (ctx: C) => MaybePromise<boolean>, ...middleware: Middleware<C>[]): Composer<C>;
20
- on<T extends keyof Update, F extends keyof NonNullable<Update[T]>>(filter: T extends FilterableUpdates ? T | [T, F, ...F[]] : T, ...middleawre: Middleware<FilterUpdate<C, T, F>>[]): Composer<FilterUpdate<C, T, F>>;
24
+ on<T extends keyof Update_, F extends string>(filter: T extends FilterableUpdates ? T | [T, F, ...F[]] : T, ...middleawre: Middleware<FilterUpdate<C, T, F>>[]): Composer<FilterUpdate<C, T, F>>;
25
+ command(commands: string | RegExp | (string | RegExp)[], ...middleawre: Middleware<FilterUpdate<C, "message", "text">>[]): Composer<FilterUpdate<C, "message", "text">>;
21
26
  }
22
27
  export {};
@@ -54,7 +54,9 @@ export class Composer {
54
54
  });
55
55
  }
56
56
  filter(predicate, ...middleware) {
57
- return this.branch(predicate, middleware.length == 0 ? skip : middleware.map(flatten).reduce(concat), skip);
57
+ const composer = new Composer(...middleware);
58
+ this.branch(predicate, composer, skip);
59
+ return composer;
58
60
  }
59
61
  on(filter, ...middleawre) {
60
62
  const type = typeof filter === "string" ? filter : filter[0];
@@ -77,5 +79,31 @@ export class Composer {
77
79
  }
78
80
  }, ...middleawre);
79
81
  }
82
+ command(commands, ...middleawre) {
83
+ const commands_ = Array.isArray(commands) ? commands : [commands];
84
+ return this.on(["message", "text"]).filter((ctx) => {
85
+ const botCommand = ctx.message.entities?.find((v) => v.type == "botCommand");
86
+ if (!botCommand) {
87
+ return false;
88
+ }
89
+ const cmd = ctx.message.text.slice(botCommand.offset, botCommand.offset + botCommand.length);
90
+ if (cmd.includes("@")) {
91
+ const username = cmd.split("@")[1];
92
+ if (username.toLowerCase() !== ctx.me.username?.toLowerCase()) {
93
+ return false;
94
+ }
95
+ }
96
+ const command_ = cmd.split("@")[0].split("/")[1].toLowerCase();
97
+ for (const command of commands_) {
98
+ if (typeof command === "string" && (command.toLowerCase() == command_)) {
99
+ return true;
100
+ }
101
+ else if (command instanceof RegExp && command.test(command_)) {
102
+ return true;
103
+ }
104
+ }
105
+ return false;
106
+ }, ...middleawre);
107
+ }
80
108
  }
81
109
  _Composer_handle = new WeakMap();
@@ -15,6 +15,7 @@ declare const getMessageWithReply: unique symbol;
15
15
  export interface Context extends Update {
16
16
  /** The client that received the update. */
17
17
  client: Client;
18
+ me: undefined extends this["connectionState"] ? undefined extends this["authorizationState"] ? User : (User | undefined) : (User | undefined);
18
19
  /** Resolves to `ctx.message ?? ctx.editedMessage ?? ctx.callbackQuery?.message`. */
19
20
  msg: undefined extends this["message"] ? undefined extends this["editedMessage"] ? undefined extends this["callbackQuery"] ? never : this["callbackQuery"] extends With<CallbackQuery, "message"> ? this["callbackQuery"]["message"] : this["callbackQuery"] extends With<CallbackQuery, "inlineMessageId"> ? never : (Message | undefined) : this["editedMessage"] : this["message"];
20
21
  /** Resolves to `effectiveMessage?.chat`. */
@@ -282,9 +283,10 @@ export declare class Client<C extends Context = Context> extends ClientAbstract
282
283
  answerInlineQuery(id: string, results: InlineQueryResult[], params?: AnswerInlineQueryParams): Promise<void>;
283
284
  use(...middleware: Middleware<C>[]): Composer<C>;
284
285
  branch(predicate: (ctx: C) => MaybePromise<boolean>, trueHandler_: Middleware<C>, falseHandler_: Middleware<C>): Composer<C>;
285
- filter<D extends C>(predicate: (ctx: C) => ctx is D, ...middleware: Middleware<D>[]): void;
286
- filter(predicate: (ctx: C) => MaybePromise<boolean>, ...middleware: Middleware<C>[]): void;
287
- on<T extends keyof Update, F extends keyof NonNullable<Update[T]>>(filter: T extends FilterableUpdates ? T | [T, F, ...F[]] : T, ...middleawre: Middleware<FilterUpdate<C, T, F>>[]): void;
286
+ filter<D extends C>(predicate: (ctx: C) => ctx is D, ...middleware: Middleware<D>[]): Composer<D>;
287
+ filter(predicate: (ctx: C) => MaybePromise<boolean>, ...middleware: Middleware<C>[]): Composer<C>;
288
+ on<T extends keyof Update, F extends string>(filter: T extends FilterableUpdates ? T | [T, F, ...F[]] : T, ...middleawre: Middleware<FilterUpdate<C, T, F>>[]): Composer<FilterUpdate<C, T, F>>;
289
+ command(commands: string | RegExp | (string | RegExp)[], ...middleawre: Middleware<FilterUpdate<C, "message", "text">>[]): Composer<FilterUpdate<C, "message", "text">>;
288
290
  /**
289
291
  * Set the bot's description in the given language. Bot-only.
290
292
  *
@@ -9,9 +9,9 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  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");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _Client_instances, _a, _Client_auth, _Client_sessionId, _Client_state, _Client_promises, _Client_toAcknowledge, _Client_updateState, _Client_publicKeys, _Client_autoStart, _Client_ignoreOutgoing, _Client_constructContext, _Client_propagateConnectionState, _Client_lastPropagatedConnectionState, _Client_storageInited, _Client_setAuth, _Client_authKeyWasCreated, _Client_connectMutex, _Client_assertUser, _Client_assertBot, _Client_fetchState, _Client_connectionInited, _Client_initConnection, _Client_lastPropagatedAuthorizationState, _Client_propagateAuthorizationState, _Client_selfId, _Client_getSelfId, _Client_receiveLoop, _Client_pingInterval, _Client_pingLoop, _Client_pingLoopStarted, _Client_autoStarted, _Client_lastMsgId, _Client_invoke, _Client_handleInvokeError, _Client_processChats, _Client_processUsers, _Client_handleUpdateQueue, _Client_processUpdatesQueue, _Client_checkChannelGap, _Client_processUpdates, _Client_setUpdateStateDate, _Client_getLocalState, _Client_recoverUpdateGap, _Client_recoverChannelUpdateGap, _Client_getChannelAccessHash, _Client_getInputPeerInner, _Client_updatesToMessages, _Client_resolveSendAs, _Client_parseText, _Client_getMessagesInner, _Client_downloadInner, _Client_handleUpdate, _Client_usernameResolver, _Client_constructReplyMarkup, _Client_assertMsgHas, _Client_handle, _Client_setMyInfo, _Client_getMyInfo;
12
+ var _Client_instances, _a, _Client_auth, _Client_sessionId, _Client_state, _Client_promises, _Client_toAcknowledge, _Client_updateState, _Client_publicKeys, _Client_autoStart, _Client_ignoreOutgoing, _Client_constructContext, _Client_propagateConnectionState, _Client_lastPropagatedConnectionState, _Client_storageInited, _Client_setAuth, _Client_authKeyWasCreated, _Client_connectMutex, _Client_assertUser, _Client_assertBot, _Client_fetchState, _Client_connectionInited, _Client_initConnection, _Client_lastPropagatedAuthorizationState, _Client_propagateAuthorizationState, _Client_selfId, _Client_getSelfId, _Client_receiveLoop, _Client_pingInterval, _Client_pingLoop, _Client_pingLoopStarted, _Client_autoStarted, _Client_lastMsgId, _Client_invoke, _Client_handleInvokeError, _Client_processChats, _Client_processUsers, _Client_handleUpdateQueue, _Client_processUpdatesQueue, _Client_checkChannelGap, _Client_processUpdates, _Client_setUpdateStateDate, _Client_getLocalState, _Client_recoverUpdateGap, _Client_recoverChannelUpdateGap, _Client_getChannelAccessHash, _Client_getInputPeerInner, _Client_updatesToMessages, _Client_resolveSendAs, _Client_parseText, _Client_getMessagesInner, _Client_downloadInner, _Client_lastGetMe, _Client_getMe, _Client_handleUpdate, _Client_usernameResolver, _Client_constructReplyMarkup, _Client_assertMsgHas, _Client_handle, _Client_setMyInfo, _Client_getMyInfo;
13
13
  import { debug, gunzip, Mutex } from "../0_deps.js";
14
- import { bigIntFromBuffer, drop, getRandomBigInt, getRandomId, mod, mustPrompt, mustPromptOneOf, Queue, sha1, UNREACHABLE } from "../1_utilities.js";
14
+ import { bigIntFromBuffer, cleanObject, drop, getRandomBigInt, getRandomId, mod, mustPrompt, mustPromptOneOf, Queue, sha1, UNREACHABLE } from "../1_utilities.js";
15
15
  import { as, functions, getChannelChatId, Message_, MessageContainer, peerToChatId, RPCResult, TLError, TLReader, types } from "../2_tl.js";
16
16
  import { StorageMemory } from "../3_storage.js";
17
17
  import { botCommandScopeToTlObject, constructCallbackQuery, constructInlineQuery, constructMessage, constructUser, FileID, FileType, inlineQueryResultToTlObject, messageEntityToTlObject, replyMarkupToTlObject, ThumbnailSource } from "../3_types.js";
@@ -20,7 +20,7 @@ import { AuthKeyUnregistered, FloodWait, Migrate, PasswordHashInvalid, PhoneNumb
20
20
  import { parseHtml } from "./0_html.js";
21
21
  import { decryptMessage, encryptMessage, getMessageId } from "./0_message.js";
22
22
  import { checkPassword } from "./0_password.js";
23
- import { getFileContents, isChannelPtsUpdate, isHttpUrl, isPtsUpdate, resolve } from "./0_utilities.js";
23
+ import { getFileContents, getUsername, isChannelPtsUpdate, isHttpUrl, isPtsUpdate, resolve } from "./0_utilities.js";
24
24
  import { ClientAbstract } from "./1_client_abstract.js";
25
25
  import { ClientPlain } from "./2_client_plain.js";
26
26
  import { Composer, concat, flatten, skip } from "./4_composer.js";
@@ -120,7 +120,7 @@ export class Client extends ClientAbstract {
120
120
  _Client_publicKeys.set(this, void 0);
121
121
  _Client_autoStart.set(this, void 0);
122
122
  _Client_ignoreOutgoing.set(this, void 0);
123
- _Client_constructContext.set(this, (update) => {
123
+ _Client_constructContext.set(this, async (update) => {
124
124
  const msg = update.message ?? update.editedMessage ?? update.callbackQuery?.message;
125
125
  const mustGetMsg = () => {
126
126
  if (msg !== undefined) {
@@ -138,9 +138,11 @@ export class Client extends ClientAbstract {
138
138
  const replyToMessageId = shouldQuote ? effectiveMessage.id : undefined;
139
139
  return replyToMessageId;
140
140
  };
141
- return {
141
+ const me = update.connectionState !== undefined ? __classPrivateFieldGet(this, _Client_lastGetMe, "f") : (update.authorizationState !== undefined && !update.authorizationState.authorized) ? __classPrivateFieldGet(this, _Client_lastGetMe, "f") : await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getMe).call(this);
142
+ return cleanObject({
142
143
  ...update,
143
144
  client: this,
145
+ me: me == null ? undefined : me,
144
146
  msg,
145
147
  chat,
146
148
  from,
@@ -217,7 +219,7 @@ export class Client extends ClientAbstract {
217
219
  get toJSON() {
218
220
  return () => update;
219
221
  },
220
- };
222
+ });
221
223
  });
222
224
  _Client_lastPropagatedConnectionState.set(this, null);
223
225
  Object.defineProperty(this, "stateChangeHandler", {
@@ -277,6 +279,7 @@ export class Client extends ClientAbstract {
277
279
  });
278
280
  _Client_handleUpdateQueue.set(this, new Queue("handleUpdate"));
279
281
  _Client_processUpdatesQueue.set(this, new Queue("processUpdates"));
282
+ _Client_lastGetMe.set(this, null);
280
283
  _Client_usernameResolver.set(this, async (v) => {
281
284
  const inputPeer = await this.getInputPeer(v).then((v) => v[as](types.InputPeerUser));
282
285
  return new types.InputUser({ userId: inputPeer.userId, accessHash: inputPeer.accessHash });
@@ -403,9 +406,9 @@ export class Client extends ClientAbstract {
403
406
  release();
404
407
  }
405
408
  }
406
- async [(_Client_auth = new WeakMap(), _Client_sessionId = new WeakMap(), _Client_state = new WeakMap(), _Client_promises = new WeakMap(), _Client_toAcknowledge = new WeakMap(), _Client_updateState = new WeakMap(), _Client_publicKeys = new WeakMap(), _Client_autoStart = new WeakMap(), _Client_ignoreOutgoing = new WeakMap(), _Client_constructContext = new WeakMap(), _Client_lastPropagatedConnectionState = new WeakMap(), _Client_storageInited = new WeakMap(), _Client_authKeyWasCreated = new WeakMap(), _Client_connectMutex = new WeakMap(), _Client_connectionInited = new WeakMap(), _Client_lastPropagatedAuthorizationState = new WeakMap(), _Client_selfId = new WeakMap(), _Client_pingInterval = new WeakMap(), _Client_pingLoopStarted = new WeakMap(), _Client_autoStarted = new WeakMap(), _Client_lastMsgId = new WeakMap(), _Client_handleInvokeError = new WeakMap(), _Client_handleUpdateQueue = new WeakMap(), _Client_processUpdatesQueue = new WeakMap(), _Client_usernameResolver = new WeakMap(), _Client_handle = new WeakMap(), _Client_instances = new WeakSet(), _Client_propagateConnectionState = function _Client_propagateConnectionState(connectionState) {
409
+ async [(_Client_auth = new WeakMap(), _Client_sessionId = new WeakMap(), _Client_state = new WeakMap(), _Client_promises = new WeakMap(), _Client_toAcknowledge = new WeakMap(), _Client_updateState = new WeakMap(), _Client_publicKeys = new WeakMap(), _Client_autoStart = new WeakMap(), _Client_ignoreOutgoing = new WeakMap(), _Client_constructContext = new WeakMap(), _Client_lastPropagatedConnectionState = new WeakMap(), _Client_storageInited = new WeakMap(), _Client_authKeyWasCreated = new WeakMap(), _Client_connectMutex = new WeakMap(), _Client_connectionInited = new WeakMap(), _Client_lastPropagatedAuthorizationState = new WeakMap(), _Client_selfId = new WeakMap(), _Client_pingInterval = new WeakMap(), _Client_pingLoopStarted = new WeakMap(), _Client_autoStarted = new WeakMap(), _Client_lastMsgId = new WeakMap(), _Client_handleInvokeError = new WeakMap(), _Client_handleUpdateQueue = new WeakMap(), _Client_processUpdatesQueue = new WeakMap(), _Client_lastGetMe = new WeakMap(), _Client_usernameResolver = new WeakMap(), _Client_handle = new WeakMap(), _Client_instances = new WeakSet(), _Client_propagateConnectionState = function _Client_propagateConnectionState(connectionState) {
407
410
  __classPrivateFieldGet(this, _Client_handleUpdateQueue, "f").add(async () => {
408
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { connectionState }), resolve);
411
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { connectionState }), resolve);
409
412
  });
410
413
  }, _Client_setAuth = async function _Client_setAuth(key) {
411
414
  const hash = await sha1(key);
@@ -684,7 +687,7 @@ export class Client extends ClientAbstract {
684
687
  }
685
688
  }, _Client_propagateAuthorizationState = async function _Client_propagateAuthorizationState(authorized) {
686
689
  if (__classPrivateFieldGet(this, _Client_lastPropagatedAuthorizationState, "f") != authorized) {
687
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { authorizationState: { authorized } }), resolve);
690
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { authorizationState: { authorized } }), resolve);
688
691
  __classPrivateFieldSet(this, _Client_lastPropagatedAuthorizationState, authorized, "f");
689
692
  }
690
693
  }, _Client_getSelfId = async function _Client_getSelfId() {
@@ -1157,52 +1160,44 @@ export class Client extends ClientAbstract {
1157
1160
  return channels.chats[0][as](types.Channel).accessHash ?? 0n;
1158
1161
  }, _Client_getInputPeerInner = async function _Client_getInputPeerInner(id) {
1159
1162
  if (typeof id === "string") {
1160
- if (!id.startsWith("@")) {
1161
- throw new Error("Expected username to start with @");
1162
- }
1163
- else {
1164
- id = id.slice(1);
1165
- if (!id) {
1166
- throw new Error("Empty username");
1167
- }
1168
- let userId = 0n;
1169
- let channelId = 0n;
1170
- const maybeUsername = await this.storage.getUsername(id);
1171
- if (maybeUsername != null && Date.now() - maybeUsername[2].getTime() < USERNAME_TTL) {
1172
- const [type, id] = maybeUsername;
1173
- if (type == "user") {
1174
- userId = id;
1175
- }
1176
- else {
1177
- channelId = id;
1178
- }
1163
+ id = getUsername(id);
1164
+ let userId = 0n;
1165
+ let channelId = 0n;
1166
+ const maybeUsername = await this.storage.getUsername(id);
1167
+ if (maybeUsername != null && Date.now() - maybeUsername[2].getTime() < USERNAME_TTL) {
1168
+ const [type, id] = maybeUsername;
1169
+ if (type == "user") {
1170
+ userId = id;
1179
1171
  }
1180
1172
  else {
1181
- const resolved = await this.invoke(new functions.ContactsResolveUsername({ username: id }));
1182
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChats).call(this, resolved.chats);
1183
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUsers).call(this, resolved.users);
1184
- if (resolved.peer instanceof types.PeerUser) {
1185
- userId = resolved.peer.userId;
1186
- }
1187
- else if (resolved.peer instanceof types.PeerChannel) {
1188
- channelId = resolved.peer.channelId;
1189
- }
1190
- else {
1191
- UNREACHABLE();
1192
- }
1173
+ channelId = id;
1193
1174
  }
1194
- if (userId) {
1195
- const accessHash = await this.storage.getUserAccessHash(userId);
1196
- return new types.InputPeerUser({ userId, accessHash: accessHash ?? 0n });
1175
+ }
1176
+ else {
1177
+ const resolved = await this.invoke(new functions.ContactsResolveUsername({ username: id }));
1178
+ await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChats).call(this, resolved.chats);
1179
+ await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUsers).call(this, resolved.users);
1180
+ if (resolved.peer instanceof types.PeerUser) {
1181
+ userId = resolved.peer.userId;
1197
1182
  }
1198
- else if (channelId) {
1199
- const accessHash = await this.storage.getChannelAccessHash(channelId);
1200
- return new types.InputPeerChannel({ channelId, accessHash: accessHash ?? 0n });
1183
+ else if (resolved.peer instanceof types.PeerChannel) {
1184
+ channelId = resolved.peer.channelId;
1201
1185
  }
1202
1186
  else {
1203
1187
  UNREACHABLE();
1204
1188
  }
1205
1189
  }
1190
+ if (userId) {
1191
+ const accessHash = await this.storage.getUserAccessHash(userId);
1192
+ return new types.InputPeerUser({ userId, accessHash: accessHash ?? 0n });
1193
+ }
1194
+ else if (channelId) {
1195
+ const accessHash = await this.storage.getChannelAccessHash(channelId);
1196
+ return new types.InputPeerChannel({ channelId, accessHash: accessHash ?? 0n });
1197
+ }
1198
+ else {
1199
+ UNREACHABLE();
1200
+ }
1206
1201
  }
1207
1202
  else if (id > 0) {
1208
1203
  const id_ = BigInt(id);
@@ -1585,7 +1580,9 @@ export class Client extends ClientAbstract {
1585
1580
  if (users.length < 1) {
1586
1581
  UNREACHABLE();
1587
1582
  }
1588
- return constructUser(users[0][as](types.User));
1583
+ const user = constructUser(users[0][as](types.User));
1584
+ __classPrivateFieldSet(this, _Client_lastGetMe, user, "f");
1585
+ return user;
1589
1586
  }
1590
1587
  /**
1591
1588
  * Answer a callback query. Bot-only.
@@ -1856,7 +1853,9 @@ export class Client extends ClientAbstract {
1856
1853
  });
1857
1854
  }
1858
1855
  filter(predicate, ...middleware) {
1859
- return this.branch(predicate, middleware.length == 0 ? skip : middleware.map(flatten).reduce(concat), skip);
1856
+ const composer = new Composer(...middleware);
1857
+ this.branch(predicate, composer, skip);
1858
+ return composer;
1860
1859
  }
1861
1860
  on(filter, ...middleawre) {
1862
1861
  const type = typeof filter === "string" ? filter : filter[0];
@@ -1879,6 +1878,32 @@ export class Client extends ClientAbstract {
1879
1878
  }
1880
1879
  }, ...middleawre);
1881
1880
  }
1881
+ command(commands, ...middleawre) {
1882
+ const commands_ = Array.isArray(commands) ? commands : [commands];
1883
+ return this.on(["message", "text"]).filter((ctx) => {
1884
+ const botCommand = ctx.message.entities?.find((v) => v.type == "botCommand");
1885
+ if (!botCommand) {
1886
+ return false;
1887
+ }
1888
+ const cmd = ctx.message.text.slice(botCommand.offset, botCommand.offset + botCommand.length);
1889
+ if (cmd.includes("@")) {
1890
+ const username = cmd.split("@")[1];
1891
+ if (username.toLowerCase() !== ctx.me.username?.toLowerCase()) {
1892
+ return false;
1893
+ }
1894
+ }
1895
+ const command_ = cmd.split("@")[0].split("/")[1].toLowerCase();
1896
+ for (const command of commands_) {
1897
+ if (typeof command === "string" && (command.toLowerCase() == command_)) {
1898
+ return true;
1899
+ }
1900
+ else if (command instanceof RegExp && command.test(command_)) {
1901
+ return true;
1902
+ }
1903
+ }
1904
+ return false;
1905
+ }, ...middleawre);
1906
+ }
1882
1907
  /**
1883
1908
  * Set the bot's description in the given language. Bot-only.
1884
1909
  *
@@ -2032,7 +2057,16 @@ export class Client extends ClientAbstract {
2032
2057
  return __classPrivateFieldGet(Client, _a, "m", _Client_assertMsgHas).call(Client, message, "photo");
2033
2058
  }
2034
2059
  }
2035
- _a = Client, _Client_handleUpdate =
2060
+ _a = Client, _Client_getMe = async function _Client_getMe() {
2061
+ if (__classPrivateFieldGet(this, _Client_lastGetMe, "f") != null) {
2062
+ return __classPrivateFieldGet(this, _Client_lastGetMe, "f");
2063
+ }
2064
+ else {
2065
+ const user = await this.getMe();
2066
+ __classPrivateFieldSet(this, _Client_lastGetMe, user, "f");
2067
+ return user;
2068
+ }
2069
+ }, _Client_handleUpdate =
2036
2070
  // TODO: log errors
2037
2071
  async function _Client_handleUpdate(update) {
2038
2072
  if (update instanceof types.UpdateShortMessage) {
@@ -2097,7 +2131,7 @@ async function _Client_handleUpdate(update) {
2097
2131
  }
2098
2132
  if (!shouldIgnore) {
2099
2133
  const message = await constructMessage(update.message, this[getEntity].bind(this), this.getMessage.bind(this), this[getStickerSetName].bind(this));
2100
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { [key]: message }), resolve);
2134
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { [key]: message }), resolve);
2101
2135
  }
2102
2136
  }
2103
2137
  }
@@ -2114,7 +2148,7 @@ async function _Client_handleUpdate(update) {
2114
2148
  }
2115
2149
  }
2116
2150
  if (deletedMessages.length > 0) {
2117
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages: deletedMessages }), resolve);
2151
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages: deletedMessages }), resolve);
2118
2152
  }
2119
2153
  }
2120
2154
  else if (update instanceof types.UpdateDeleteChannelMessages) {
@@ -2128,14 +2162,14 @@ async function _Client_handleUpdate(update) {
2128
2162
  await this.storage.setMessage(chatId, messageId, null);
2129
2163
  }
2130
2164
  if (deletedMessages.length > 0) {
2131
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages: deletedMessages }), resolve);
2165
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages: deletedMessages }), resolve);
2132
2166
  }
2133
2167
  }
2134
2168
  if (update instanceof types.UpdateBotCallbackQuery || update instanceof types.UpdateInlineBotCallbackQuery) {
2135
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { callbackQuery: await constructCallbackQuery(update, this[getEntity].bind(this), this[getMessageWithReply].bind(this)) }), resolve);
2169
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { callbackQuery: await constructCallbackQuery(update, this[getEntity].bind(this), this[getMessageWithReply].bind(this)) }), resolve);
2136
2170
  }
2137
2171
  else if (update instanceof types.UpdateBotInlineQuery) {
2138
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { inlineQuery: await constructInlineQuery(update, this[getEntity].bind(this)) }), resolve);
2172
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { inlineQuery: await constructInlineQuery(update, this[getEntity].bind(this)) }), resolve);
2139
2173
  }
2140
2174
  }, _Client_constructReplyMarkup = async function _Client_constructReplyMarkup(params) {
2141
2175
  if (params?.replyMarkup) {
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "module": "./esm/mod.js",
3
3
  "main": "./script/mod.js",
4
4
  "name": "@mtkruto/node",
5
- "version": "0.1.115",
5
+ "version": "0.1.117",
6
6
  "description": "MTKruto for Node.js",
7
7
  "author": "Roj <rojvv@icloud.com>",
8
8
  "license": "LGPL-3.0-or-later",
@@ -5,7 +5,7 @@ export declare const PUBLIC_KEYS: PublicKeys;
5
5
  export declare const VECTOR_CONSTRUCTOR = 481674261;
6
6
  export declare const INITIAL_DC: DC;
7
7
  export declare const LAYER = 166;
8
- export declare const APP_VERSION = "MTKruto 0.1.115";
8
+ export declare const APP_VERSION = "MTKruto 0.1.117";
9
9
  export declare const DEVICE_MODEL: string;
10
10
  export declare const LANG_CODE: string;
11
11
  export declare const LANG_PACK = "";
@@ -80,7 +80,7 @@ exports.PUBLIC_KEYS = Object.freeze([
80
80
  exports.VECTOR_CONSTRUCTOR = 0x1CB5C415;
81
81
  exports.INITIAL_DC = "2";
82
82
  exports.LAYER = 166;
83
- exports.APP_VERSION = "MTKruto 0.1.115";
83
+ exports.APP_VERSION = "MTKruto 0.1.117";
84
84
  // @ts-ignore: lib
85
85
  exports.DEVICE_MODEL = typeof dntShim.Deno === "undefined" ? typeof navigator === "undefined" ? typeof process === "undefined" ? "Unknown" : process.platform + "-" + process.arch : navigator.userAgent.split(" ")[0] : dntShim.Deno.build.os + "-" + dntShim.Deno.build.arch;
86
86
  exports.LANG_CODE = typeof navigator === "undefined" ? "en" : navigator.language.split("-")[0];
@@ -9,3 +9,4 @@ export declare function isChannelPtsUpdate(v: types.TypeUpdate | types.TypeUpdat
9
9
  export type FileSource = string | URL | Uint8Array;
10
10
  export declare function getFileContents(source: FileSource, fileName?: string): Promise<readonly [Uint8Array, string]>;
11
11
  export declare function isHttpUrl(string: string): boolean;
12
+ export declare function getUsername(string: string): string;
@@ -23,11 +23,12 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.isHttpUrl = exports.getFileContents = exports.isChannelPtsUpdate = exports.isPtsUpdate = exports.resolve = void 0;
26
+ exports.getUsername = exports.isHttpUrl = exports.getFileContents = exports.isChannelPtsUpdate = exports.isPtsUpdate = exports.resolve = void 0;
27
27
  const dntShim = __importStar(require("../_dnt.shims.js"));
28
28
  const _0_deps_js_1 = require("../0_deps.js");
29
29
  const _1_utilities_js_1 = require("../1_utilities.js");
30
30
  const _2_tl_js_1 = require("../2_tl.js");
31
+ const _2_types_js_1 = require("../tl/2_types.js");
31
32
  const resolve = () => Promise.resolve();
32
33
  exports.resolve = resolve;
33
34
  function isPtsUpdate(v) {
@@ -105,3 +106,67 @@ function isHttpUrl(string) {
105
106
  }
106
107
  }
107
108
  exports.isHttpUrl = isHttpUrl;
109
+ function isAlpha(string) {
110
+ const c = string.charCodeAt(0) | 0x20;
111
+ return "a".charCodeAt(0) <= c && c <= "z".charCodeAt(0);
112
+ }
113
+ function isDigit(string) {
114
+ const c = string.charCodeAt(0);
115
+ return "0".charCodeAt(0) <= c && c <= "9".charCodeAt(0);
116
+ }
117
+ const errInvalidUsername = (u) => new Error("Invalid username: " + u);
118
+ function validateUsername(string, ignoreAt = false) {
119
+ string = string.trim();
120
+ if (ignoreAt && string.startsWith("@")) {
121
+ string = string.slice(1);
122
+ }
123
+ if (string.length == 0 || string.length > 32) {
124
+ throw errInvalidUsername(string);
125
+ }
126
+ if (!isAlpha(string[0])) {
127
+ throw errInvalidUsername(string);
128
+ }
129
+ for (const c of string) {
130
+ if (!isAlpha(c) && !isDigit(c) && c != "_") {
131
+ throw errInvalidUsername(string);
132
+ }
133
+ }
134
+ if (string[_2_types_js_1.Username.length - 1] == "_") {
135
+ throw errInvalidUsername(string);
136
+ }
137
+ for (let i = 1; i < string.length; ++i) {
138
+ if (string[i - 1] == "_" && string[i] == "_") {
139
+ throw errInvalidUsername(string);
140
+ }
141
+ }
142
+ return string;
143
+ }
144
+ function getUsername(string) {
145
+ let url = null;
146
+ try {
147
+ url = new URL(string);
148
+ }
149
+ catch {
150
+ try {
151
+ url = new URL("https://" + string);
152
+ }
153
+ catch {
154
+ //
155
+ }
156
+ }
157
+ if (url === null || (url.protocol != "http:" && url.protocol != "https:")) {
158
+ return validateUsername(string, true);
159
+ }
160
+ if (url.hostname != "telegram.dog" && url.hostname != "telegram.me" && url.hostname != "t.me" && !url.hostname.endsWith(".t.me")) {
161
+ return validateUsername(string, true);
162
+ }
163
+ if (url.hostname == "telegram.dog" || url.hostname == "telegram.me" || url.hostname == "t.me") {
164
+ return validateUsername(url.pathname.split("/")[1]);
165
+ }
166
+ const parts = url.hostname.split(".");
167
+ if (parts.length != 3) {
168
+ return validateUsername(string);
169
+ }
170
+ return validateUsername(parts[0]);
171
+ }
172
+ exports.getUsername = getUsername;
@@ -0,0 +1 @@
1
+ export {};
@@ -1,7 +1,6 @@
1
1
  import { MaybePromise } from "../1_utilities.js";
2
2
  import { functions, types } from "../2_tl.js";
3
3
  import { BotCommandScope, CallbackQuery, ChatID, ForceReply, InlineKeyboardMarkup, InlineQuery, InlineQueryResultButton, Message, MessageEntity, ReplyKeyboardMarkup, ReplyKeyboardRemove } from "../3_types.js";
4
- import { With } from "./0_utilities.js";
5
4
  import { ClientPlainParams } from "./2_client_plain.js";
6
5
  import { ParseMode } from "../3_types.js";
7
6
  export interface ClientParams extends ClientPlainParams {
@@ -314,6 +313,10 @@ export interface InvokeErrorHandler<C> {
314
313
  n: number;
315
314
  }, next: NextFn<boolean>): MaybePromise<boolean>;
316
315
  }
317
- export type FilterUpdate<U extends Update, T extends keyof U, F extends (keyof NonNullable<U[T]>) | null> = With<U, T> & Pick<{
318
- [P in T]-?: F extends keyof NonNullable<U[T]> ? With<NonNullable<U[T]>, F> : NonNullable<U[T]>;
319
- }, T>;
316
+ type Update_ = Update;
317
+ export type FilterUpdate<Update extends Update_, Type extends keyof Update_, Field extends string, TypeType extends NonNullable<Update_[Type]> = NonNullable<Update_[Type]>> = Update & {
318
+ [Type_ in Type]-?: TypeType & {
319
+ [Field_ in Field]-?: Field extends keyof TypeType ? NonNullable<TypeType[Field]> : never;
320
+ };
321
+ };
322
+ export {};
@@ -1,4 +1,8 @@
1
- import { FilterableUpdates, FilterUpdate, Update } from "./3_types.js";
1
+ import { User } from "../3_types.js";
2
+ import { FilterableUpdates, FilterUpdate, Update as Update_ } from "./3_types.js";
3
+ interface Update extends Update_ {
4
+ me: undefined extends this["connectionState"] ? undefined extends this["authorizationState"] ? User : (User | undefined) : (User | undefined);
5
+ }
2
6
  type MaybePromise<T> = T | Promise<T>;
3
7
  export type NextFunction = () => Promise<void>;
4
8
  export type MiddlewareFn<C extends Update = Update> = (ctx: C, next: NextFunction) => MaybePromise<unknown>;
@@ -17,6 +21,7 @@ export declare class Composer<C extends Update> implements MiddlewareObj<C> {
17
21
  branch(predicate: (ctx: C) => MaybePromise<boolean>, trueHandler_: Middleware<C>, falseHandler_: Middleware<C>): Composer<C>;
18
22
  filter<D extends C>(predicate: (ctx: C) => ctx is D, ...middleware: Middleware<D>[]): Composer<D>;
19
23
  filter(predicate: (ctx: C) => MaybePromise<boolean>, ...middleware: Middleware<C>[]): Composer<C>;
20
- on<T extends keyof Update, F extends keyof NonNullable<Update[T]>>(filter: T extends FilterableUpdates ? T | [T, F, ...F[]] : T, ...middleawre: Middleware<FilterUpdate<C, T, F>>[]): Composer<FilterUpdate<C, T, F>>;
24
+ on<T extends keyof Update_, F extends string>(filter: T extends FilterableUpdates ? T | [T, F, ...F[]] : T, ...middleawre: Middleware<FilterUpdate<C, T, F>>[]): Composer<FilterUpdate<C, T, F>>;
25
+ command(commands: string | RegExp | (string | RegExp)[], ...middleawre: Middleware<FilterUpdate<C, "message", "text">>[]): Composer<FilterUpdate<C, "message", "text">>;
21
26
  }
22
27
  export {};
@@ -60,7 +60,9 @@ class Composer {
60
60
  });
61
61
  }
62
62
  filter(predicate, ...middleware) {
63
- return this.branch(predicate, middleware.length == 0 ? exports.skip : middleware.map(flatten).reduce(concat), exports.skip);
63
+ const composer = new Composer(...middleware);
64
+ this.branch(predicate, composer, exports.skip);
65
+ return composer;
64
66
  }
65
67
  on(filter, ...middleawre) {
66
68
  const type = typeof filter === "string" ? filter : filter[0];
@@ -83,6 +85,32 @@ class Composer {
83
85
  }
84
86
  }, ...middleawre);
85
87
  }
88
+ command(commands, ...middleawre) {
89
+ const commands_ = Array.isArray(commands) ? commands : [commands];
90
+ return this.on(["message", "text"]).filter((ctx) => {
91
+ const botCommand = ctx.message.entities?.find((v) => v.type == "botCommand");
92
+ if (!botCommand) {
93
+ return false;
94
+ }
95
+ const cmd = ctx.message.text.slice(botCommand.offset, botCommand.offset + botCommand.length);
96
+ if (cmd.includes("@")) {
97
+ const username = cmd.split("@")[1];
98
+ if (username.toLowerCase() !== ctx.me.username?.toLowerCase()) {
99
+ return false;
100
+ }
101
+ }
102
+ const command_ = cmd.split("@")[0].split("/")[1].toLowerCase();
103
+ for (const command of commands_) {
104
+ if (typeof command === "string" && (command.toLowerCase() == command_)) {
105
+ return true;
106
+ }
107
+ else if (command instanceof RegExp && command.test(command_)) {
108
+ return true;
109
+ }
110
+ }
111
+ return false;
112
+ }, ...middleawre);
113
+ }
86
114
  }
87
115
  exports.Composer = Composer;
88
116
  _Composer_handle = new WeakMap();
@@ -15,6 +15,7 @@ declare const getMessageWithReply: unique symbol;
15
15
  export interface Context extends Update {
16
16
  /** The client that received the update. */
17
17
  client: Client;
18
+ me: undefined extends this["connectionState"] ? undefined extends this["authorizationState"] ? User : (User | undefined) : (User | undefined);
18
19
  /** Resolves to `ctx.message ?? ctx.editedMessage ?? ctx.callbackQuery?.message`. */
19
20
  msg: undefined extends this["message"] ? undefined extends this["editedMessage"] ? undefined extends this["callbackQuery"] ? never : this["callbackQuery"] extends With<CallbackQuery, "message"> ? this["callbackQuery"]["message"] : this["callbackQuery"] extends With<CallbackQuery, "inlineMessageId"> ? never : (Message | undefined) : this["editedMessage"] : this["message"];
20
21
  /** Resolves to `effectiveMessage?.chat`. */
@@ -282,9 +283,10 @@ export declare class Client<C extends Context = Context> extends ClientAbstract
282
283
  answerInlineQuery(id: string, results: InlineQueryResult[], params?: AnswerInlineQueryParams): Promise<void>;
283
284
  use(...middleware: Middleware<C>[]): Composer<C>;
284
285
  branch(predicate: (ctx: C) => MaybePromise<boolean>, trueHandler_: Middleware<C>, falseHandler_: Middleware<C>): Composer<C>;
285
- filter<D extends C>(predicate: (ctx: C) => ctx is D, ...middleware: Middleware<D>[]): void;
286
- filter(predicate: (ctx: C) => MaybePromise<boolean>, ...middleware: Middleware<C>[]): void;
287
- on<T extends keyof Update, F extends keyof NonNullable<Update[T]>>(filter: T extends FilterableUpdates ? T | [T, F, ...F[]] : T, ...middleawre: Middleware<FilterUpdate<C, T, F>>[]): void;
286
+ filter<D extends C>(predicate: (ctx: C) => ctx is D, ...middleware: Middleware<D>[]): Composer<D>;
287
+ filter(predicate: (ctx: C) => MaybePromise<boolean>, ...middleware: Middleware<C>[]): Composer<C>;
288
+ on<T extends keyof Update, F extends string>(filter: T extends FilterableUpdates ? T | [T, F, ...F[]] : T, ...middleawre: Middleware<FilterUpdate<C, T, F>>[]): Composer<FilterUpdate<C, T, F>>;
289
+ command(commands: string | RegExp | (string | RegExp)[], ...middleawre: Middleware<FilterUpdate<C, "message", "text">>[]): Composer<FilterUpdate<C, "message", "text">>;
288
290
  /**
289
291
  * Set the bot's description in the given language. Bot-only.
290
292
  *
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  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");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _Client_instances, _a, _Client_auth, _Client_sessionId, _Client_state, _Client_promises, _Client_toAcknowledge, _Client_updateState, _Client_publicKeys, _Client_autoStart, _Client_ignoreOutgoing, _Client_constructContext, _Client_propagateConnectionState, _Client_lastPropagatedConnectionState, _Client_storageInited, _Client_setAuth, _Client_authKeyWasCreated, _Client_connectMutex, _Client_assertUser, _Client_assertBot, _Client_fetchState, _Client_connectionInited, _Client_initConnection, _Client_lastPropagatedAuthorizationState, _Client_propagateAuthorizationState, _Client_selfId, _Client_getSelfId, _Client_receiveLoop, _Client_pingInterval, _Client_pingLoop, _Client_pingLoopStarted, _Client_autoStarted, _Client_lastMsgId, _Client_invoke, _Client_handleInvokeError, _Client_processChats, _Client_processUsers, _Client_handleUpdateQueue, _Client_processUpdatesQueue, _Client_checkChannelGap, _Client_processUpdates, _Client_setUpdateStateDate, _Client_getLocalState, _Client_recoverUpdateGap, _Client_recoverChannelUpdateGap, _Client_getChannelAccessHash, _Client_getInputPeerInner, _Client_updatesToMessages, _Client_resolveSendAs, _Client_parseText, _Client_getMessagesInner, _Client_downloadInner, _Client_handleUpdate, _Client_usernameResolver, _Client_constructReplyMarkup, _Client_assertMsgHas, _Client_handle, _Client_setMyInfo, _Client_getMyInfo;
13
+ var _Client_instances, _a, _Client_auth, _Client_sessionId, _Client_state, _Client_promises, _Client_toAcknowledge, _Client_updateState, _Client_publicKeys, _Client_autoStart, _Client_ignoreOutgoing, _Client_constructContext, _Client_propagateConnectionState, _Client_lastPropagatedConnectionState, _Client_storageInited, _Client_setAuth, _Client_authKeyWasCreated, _Client_connectMutex, _Client_assertUser, _Client_assertBot, _Client_fetchState, _Client_connectionInited, _Client_initConnection, _Client_lastPropagatedAuthorizationState, _Client_propagateAuthorizationState, _Client_selfId, _Client_getSelfId, _Client_receiveLoop, _Client_pingInterval, _Client_pingLoop, _Client_pingLoopStarted, _Client_autoStarted, _Client_lastMsgId, _Client_invoke, _Client_handleInvokeError, _Client_processChats, _Client_processUsers, _Client_handleUpdateQueue, _Client_processUpdatesQueue, _Client_checkChannelGap, _Client_processUpdates, _Client_setUpdateStateDate, _Client_getLocalState, _Client_recoverUpdateGap, _Client_recoverChannelUpdateGap, _Client_getChannelAccessHash, _Client_getInputPeerInner, _Client_updatesToMessages, _Client_resolveSendAs, _Client_parseText, _Client_getMessagesInner, _Client_downloadInner, _Client_lastGetMe, _Client_getMe, _Client_handleUpdate, _Client_usernameResolver, _Client_constructReplyMarkup, _Client_assertMsgHas, _Client_handle, _Client_setMyInfo, _Client_getMyInfo;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.Client = exports.ConnectionError = exports.restartAuth = exports.skipInvoke = exports.handleMigrationError = void 0;
16
16
  const _0_deps_js_1 = require("../0_deps.js");
@@ -125,7 +125,7 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
125
125
  _Client_publicKeys.set(this, void 0);
126
126
  _Client_autoStart.set(this, void 0);
127
127
  _Client_ignoreOutgoing.set(this, void 0);
128
- _Client_constructContext.set(this, (update) => {
128
+ _Client_constructContext.set(this, async (update) => {
129
129
  const msg = update.message ?? update.editedMessage ?? update.callbackQuery?.message;
130
130
  const mustGetMsg = () => {
131
131
  if (msg !== undefined) {
@@ -143,9 +143,11 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
143
143
  const replyToMessageId = shouldQuote ? effectiveMessage.id : undefined;
144
144
  return replyToMessageId;
145
145
  };
146
- return {
146
+ const me = update.connectionState !== undefined ? __classPrivateFieldGet(this, _Client_lastGetMe, "f") : (update.authorizationState !== undefined && !update.authorizationState.authorized) ? __classPrivateFieldGet(this, _Client_lastGetMe, "f") : await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getMe).call(this);
147
+ return (0, _1_utilities_js_1.cleanObject)({
147
148
  ...update,
148
149
  client: this,
150
+ me: me == null ? undefined : me,
149
151
  msg,
150
152
  chat,
151
153
  from,
@@ -222,7 +224,7 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
222
224
  get toJSON() {
223
225
  return () => update;
224
226
  },
225
- };
227
+ });
226
228
  });
227
229
  _Client_lastPropagatedConnectionState.set(this, null);
228
230
  Object.defineProperty(this, "stateChangeHandler", {
@@ -282,6 +284,7 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
282
284
  });
283
285
  _Client_handleUpdateQueue.set(this, new _1_utilities_js_1.Queue("handleUpdate"));
284
286
  _Client_processUpdatesQueue.set(this, new _1_utilities_js_1.Queue("processUpdates"));
287
+ _Client_lastGetMe.set(this, null);
285
288
  _Client_usernameResolver.set(this, async (v) => {
286
289
  const inputPeer = await this.getInputPeer(v).then((v) => v[_2_tl_js_1.as](_2_tl_js_1.types.InputPeerUser));
287
290
  return new _2_tl_js_1.types.InputUser({ userId: inputPeer.userId, accessHash: inputPeer.accessHash });
@@ -408,9 +411,9 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
408
411
  release();
409
412
  }
410
413
  }
411
- async [(_Client_auth = new WeakMap(), _Client_sessionId = new WeakMap(), _Client_state = new WeakMap(), _Client_promises = new WeakMap(), _Client_toAcknowledge = new WeakMap(), _Client_updateState = new WeakMap(), _Client_publicKeys = new WeakMap(), _Client_autoStart = new WeakMap(), _Client_ignoreOutgoing = new WeakMap(), _Client_constructContext = new WeakMap(), _Client_lastPropagatedConnectionState = new WeakMap(), _Client_storageInited = new WeakMap(), _Client_authKeyWasCreated = new WeakMap(), _Client_connectMutex = new WeakMap(), _Client_connectionInited = new WeakMap(), _Client_lastPropagatedAuthorizationState = new WeakMap(), _Client_selfId = new WeakMap(), _Client_pingInterval = new WeakMap(), _Client_pingLoopStarted = new WeakMap(), _Client_autoStarted = new WeakMap(), _Client_lastMsgId = new WeakMap(), _Client_handleInvokeError = new WeakMap(), _Client_handleUpdateQueue = new WeakMap(), _Client_processUpdatesQueue = new WeakMap(), _Client_usernameResolver = new WeakMap(), _Client_handle = new WeakMap(), _Client_instances = new WeakSet(), _Client_propagateConnectionState = function _Client_propagateConnectionState(connectionState) {
414
+ async [(_Client_auth = new WeakMap(), _Client_sessionId = new WeakMap(), _Client_state = new WeakMap(), _Client_promises = new WeakMap(), _Client_toAcknowledge = new WeakMap(), _Client_updateState = new WeakMap(), _Client_publicKeys = new WeakMap(), _Client_autoStart = new WeakMap(), _Client_ignoreOutgoing = new WeakMap(), _Client_constructContext = new WeakMap(), _Client_lastPropagatedConnectionState = new WeakMap(), _Client_storageInited = new WeakMap(), _Client_authKeyWasCreated = new WeakMap(), _Client_connectMutex = new WeakMap(), _Client_connectionInited = new WeakMap(), _Client_lastPropagatedAuthorizationState = new WeakMap(), _Client_selfId = new WeakMap(), _Client_pingInterval = new WeakMap(), _Client_pingLoopStarted = new WeakMap(), _Client_autoStarted = new WeakMap(), _Client_lastMsgId = new WeakMap(), _Client_handleInvokeError = new WeakMap(), _Client_handleUpdateQueue = new WeakMap(), _Client_processUpdatesQueue = new WeakMap(), _Client_lastGetMe = new WeakMap(), _Client_usernameResolver = new WeakMap(), _Client_handle = new WeakMap(), _Client_instances = new WeakSet(), _Client_propagateConnectionState = function _Client_propagateConnectionState(connectionState) {
412
415
  __classPrivateFieldGet(this, _Client_handleUpdateQueue, "f").add(async () => {
413
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { connectionState }), _0_utilities_js_1.resolve);
416
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { connectionState }), _0_utilities_js_1.resolve);
414
417
  });
415
418
  }, _Client_setAuth = async function _Client_setAuth(key) {
416
419
  const hash = await (0, _1_utilities_js_1.sha1)(key);
@@ -689,7 +692,7 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
689
692
  }
690
693
  }, _Client_propagateAuthorizationState = async function _Client_propagateAuthorizationState(authorized) {
691
694
  if (__classPrivateFieldGet(this, _Client_lastPropagatedAuthorizationState, "f") != authorized) {
692
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { authorizationState: { authorized } }), _0_utilities_js_1.resolve);
695
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { authorizationState: { authorized } }), _0_utilities_js_1.resolve);
693
696
  __classPrivateFieldSet(this, _Client_lastPropagatedAuthorizationState, authorized, "f");
694
697
  }
695
698
  }, _Client_getSelfId = async function _Client_getSelfId() {
@@ -1162,52 +1165,44 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
1162
1165
  return channels.chats[0][_2_tl_js_1.as](_2_tl_js_1.types.Channel).accessHash ?? 0n;
1163
1166
  }, _Client_getInputPeerInner = async function _Client_getInputPeerInner(id) {
1164
1167
  if (typeof id === "string") {
1165
- if (!id.startsWith("@")) {
1166
- throw new Error("Expected username to start with @");
1167
- }
1168
- else {
1169
- id = id.slice(1);
1170
- if (!id) {
1171
- throw new Error("Empty username");
1172
- }
1173
- let userId = 0n;
1174
- let channelId = 0n;
1175
- const maybeUsername = await this.storage.getUsername(id);
1176
- if (maybeUsername != null && Date.now() - maybeUsername[2].getTime() < _4_constants_js_1.USERNAME_TTL) {
1177
- const [type, id] = maybeUsername;
1178
- if (type == "user") {
1179
- userId = id;
1180
- }
1181
- else {
1182
- channelId = id;
1183
- }
1168
+ id = (0, _0_utilities_js_1.getUsername)(id);
1169
+ let userId = 0n;
1170
+ let channelId = 0n;
1171
+ const maybeUsername = await this.storage.getUsername(id);
1172
+ if (maybeUsername != null && Date.now() - maybeUsername[2].getTime() < _4_constants_js_1.USERNAME_TTL) {
1173
+ const [type, id] = maybeUsername;
1174
+ if (type == "user") {
1175
+ userId = id;
1184
1176
  }
1185
1177
  else {
1186
- const resolved = await this.invoke(new _2_tl_js_1.functions.ContactsResolveUsername({ username: id }));
1187
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChats).call(this, resolved.chats);
1188
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUsers).call(this, resolved.users);
1189
- if (resolved.peer instanceof _2_tl_js_1.types.PeerUser) {
1190
- userId = resolved.peer.userId;
1191
- }
1192
- else if (resolved.peer instanceof _2_tl_js_1.types.PeerChannel) {
1193
- channelId = resolved.peer.channelId;
1194
- }
1195
- else {
1196
- (0, _1_utilities_js_1.UNREACHABLE)();
1197
- }
1178
+ channelId = id;
1198
1179
  }
1199
- if (userId) {
1200
- const accessHash = await this.storage.getUserAccessHash(userId);
1201
- return new _2_tl_js_1.types.InputPeerUser({ userId, accessHash: accessHash ?? 0n });
1180
+ }
1181
+ else {
1182
+ const resolved = await this.invoke(new _2_tl_js_1.functions.ContactsResolveUsername({ username: id }));
1183
+ await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChats).call(this, resolved.chats);
1184
+ await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUsers).call(this, resolved.users);
1185
+ if (resolved.peer instanceof _2_tl_js_1.types.PeerUser) {
1186
+ userId = resolved.peer.userId;
1202
1187
  }
1203
- else if (channelId) {
1204
- const accessHash = await this.storage.getChannelAccessHash(channelId);
1205
- return new _2_tl_js_1.types.InputPeerChannel({ channelId, accessHash: accessHash ?? 0n });
1188
+ else if (resolved.peer instanceof _2_tl_js_1.types.PeerChannel) {
1189
+ channelId = resolved.peer.channelId;
1206
1190
  }
1207
1191
  else {
1208
1192
  (0, _1_utilities_js_1.UNREACHABLE)();
1209
1193
  }
1210
1194
  }
1195
+ if (userId) {
1196
+ const accessHash = await this.storage.getUserAccessHash(userId);
1197
+ return new _2_tl_js_1.types.InputPeerUser({ userId, accessHash: accessHash ?? 0n });
1198
+ }
1199
+ else if (channelId) {
1200
+ const accessHash = await this.storage.getChannelAccessHash(channelId);
1201
+ return new _2_tl_js_1.types.InputPeerChannel({ channelId, accessHash: accessHash ?? 0n });
1202
+ }
1203
+ else {
1204
+ (0, _1_utilities_js_1.UNREACHABLE)();
1205
+ }
1211
1206
  }
1212
1207
  else if (id > 0) {
1213
1208
  const id_ = BigInt(id);
@@ -1590,7 +1585,9 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
1590
1585
  if (users.length < 1) {
1591
1586
  (0, _1_utilities_js_1.UNREACHABLE)();
1592
1587
  }
1593
- return (0, _3_types_js_1.constructUser)(users[0][_2_tl_js_1.as](_2_tl_js_1.types.User));
1588
+ const user = (0, _3_types_js_1.constructUser)(users[0][_2_tl_js_1.as](_2_tl_js_1.types.User));
1589
+ __classPrivateFieldSet(this, _Client_lastGetMe, user, "f");
1590
+ return user;
1594
1591
  }
1595
1592
  /**
1596
1593
  * Answer a callback query. Bot-only.
@@ -1861,7 +1858,9 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
1861
1858
  });
1862
1859
  }
1863
1860
  filter(predicate, ...middleware) {
1864
- return this.branch(predicate, middleware.length == 0 ? _4_composer_js_1.skip : middleware.map(_4_composer_js_1.flatten).reduce(_4_composer_js_1.concat), _4_composer_js_1.skip);
1861
+ const composer = new _4_composer_js_1.Composer(...middleware);
1862
+ this.branch(predicate, composer, _4_composer_js_1.skip);
1863
+ return composer;
1865
1864
  }
1866
1865
  on(filter, ...middleawre) {
1867
1866
  const type = typeof filter === "string" ? filter : filter[0];
@@ -1884,6 +1883,32 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
1884
1883
  }
1885
1884
  }, ...middleawre);
1886
1885
  }
1886
+ command(commands, ...middleawre) {
1887
+ const commands_ = Array.isArray(commands) ? commands : [commands];
1888
+ return this.on(["message", "text"]).filter((ctx) => {
1889
+ const botCommand = ctx.message.entities?.find((v) => v.type == "botCommand");
1890
+ if (!botCommand) {
1891
+ return false;
1892
+ }
1893
+ const cmd = ctx.message.text.slice(botCommand.offset, botCommand.offset + botCommand.length);
1894
+ if (cmd.includes("@")) {
1895
+ const username = cmd.split("@")[1];
1896
+ if (username.toLowerCase() !== ctx.me.username?.toLowerCase()) {
1897
+ return false;
1898
+ }
1899
+ }
1900
+ const command_ = cmd.split("@")[0].split("/")[1].toLowerCase();
1901
+ for (const command of commands_) {
1902
+ if (typeof command === "string" && (command.toLowerCase() == command_)) {
1903
+ return true;
1904
+ }
1905
+ else if (command instanceof RegExp && command.test(command_)) {
1906
+ return true;
1907
+ }
1908
+ }
1909
+ return false;
1910
+ }, ...middleawre);
1911
+ }
1887
1912
  /**
1888
1913
  * Set the bot's description in the given language. Bot-only.
1889
1914
  *
@@ -2038,7 +2063,16 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
2038
2063
  }
2039
2064
  }
2040
2065
  exports.Client = Client;
2041
- _a = Client, _Client_handleUpdate =
2066
+ _a = Client, _Client_getMe = async function _Client_getMe() {
2067
+ if (__classPrivateFieldGet(this, _Client_lastGetMe, "f") != null) {
2068
+ return __classPrivateFieldGet(this, _Client_lastGetMe, "f");
2069
+ }
2070
+ else {
2071
+ const user = await this.getMe();
2072
+ __classPrivateFieldSet(this, _Client_lastGetMe, user, "f");
2073
+ return user;
2074
+ }
2075
+ }, _Client_handleUpdate =
2042
2076
  // TODO: log errors
2043
2077
  async function _Client_handleUpdate(update) {
2044
2078
  if (update instanceof _2_tl_js_1.types.UpdateShortMessage) {
@@ -2103,7 +2137,7 @@ async function _Client_handleUpdate(update) {
2103
2137
  }
2104
2138
  if (!shouldIgnore) {
2105
2139
  const message = await (0, _3_types_js_1.constructMessage)(update.message, this[getEntity].bind(this), this.getMessage.bind(this), this[getStickerSetName].bind(this));
2106
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { [key]: message }), _0_utilities_js_1.resolve);
2140
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { [key]: message }), _0_utilities_js_1.resolve);
2107
2141
  }
2108
2142
  }
2109
2143
  }
@@ -2120,7 +2154,7 @@ async function _Client_handleUpdate(update) {
2120
2154
  }
2121
2155
  }
2122
2156
  if (deletedMessages.length > 0) {
2123
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages: deletedMessages }), _0_utilities_js_1.resolve);
2157
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages: deletedMessages }), _0_utilities_js_1.resolve);
2124
2158
  }
2125
2159
  }
2126
2160
  else if (update instanceof _2_tl_js_1.types.UpdateDeleteChannelMessages) {
@@ -2134,14 +2168,14 @@ async function _Client_handleUpdate(update) {
2134
2168
  await this.storage.setMessage(chatId, messageId, null);
2135
2169
  }
2136
2170
  if (deletedMessages.length > 0) {
2137
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages: deletedMessages }), _0_utilities_js_1.resolve);
2171
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages: deletedMessages }), _0_utilities_js_1.resolve);
2138
2172
  }
2139
2173
  }
2140
2174
  if (update instanceof _2_tl_js_1.types.UpdateBotCallbackQuery || update instanceof _2_tl_js_1.types.UpdateInlineBotCallbackQuery) {
2141
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { callbackQuery: await (0, _3_types_js_1.constructCallbackQuery)(update, this[getEntity].bind(this), this[getMessageWithReply].bind(this)) }), _0_utilities_js_1.resolve);
2175
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { callbackQuery: await (0, _3_types_js_1.constructCallbackQuery)(update, this[getEntity].bind(this), this[getMessageWithReply].bind(this)) }), _0_utilities_js_1.resolve);
2142
2176
  }
2143
2177
  else if (update instanceof _2_tl_js_1.types.UpdateBotInlineQuery) {
2144
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { inlineQuery: await (0, _3_types_js_1.constructInlineQuery)(update, this[getEntity].bind(this)) }), _0_utilities_js_1.resolve);
2178
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { inlineQuery: await (0, _3_types_js_1.constructInlineQuery)(update, this[getEntity].bind(this)) }), _0_utilities_js_1.resolve);
2145
2179
  }
2146
2180
  }, _Client_constructReplyMarkup = async function _Client_constructReplyMarkup(params) {
2147
2181
  if (params?.replyMarkup) {