teleproto 203.0.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.
Files changed (224) hide show
  1. package/CryptoFile.d.ts +2 -0
  2. package/CryptoFile.js +23 -0
  3. package/Helpers.d.ts +151 -0
  4. package/Helpers.js +477 -0
  5. package/LICENSE +23 -0
  6. package/Password.d.ts +15 -0
  7. package/Password.js +271 -0
  8. package/README.md +111 -0
  9. package/Utils.d.ts +228 -0
  10. package/Utils.js +1248 -0
  11. package/Version.d.ts +1 -0
  12. package/Version.js +4 -0
  13. package/client/2fa.d.ts +48 -0
  14. package/client/2fa.js +109 -0
  15. package/client/TelegramClient.d.ts +1042 -0
  16. package/client/TelegramClient.js +1167 -0
  17. package/client/account.d.ts +0 -0
  18. package/client/account.js +1 -0
  19. package/client/auth.d.ts +93 -0
  20. package/client/auth.js +375 -0
  21. package/client/bots.d.ts +6 -0
  22. package/client/bots.js +24 -0
  23. package/client/buttons.d.ts +4 -0
  24. package/client/buttons.js +87 -0
  25. package/client/chats.d.ts +46 -0
  26. package/client/chats.js +350 -0
  27. package/client/dialogs.d.ts +52 -0
  28. package/client/dialogs.js +174 -0
  29. package/client/downloads.d.ts +157 -0
  30. package/client/downloads.js +598 -0
  31. package/client/fs.d.ts +1 -0
  32. package/client/fs.js +13 -0
  33. package/client/index.d.ts +15 -0
  34. package/client/index.js +50 -0
  35. package/client/messageParse.d.ts +17 -0
  36. package/client/messageParse.js +191 -0
  37. package/client/messages.d.ts +259 -0
  38. package/client/messages.js +804 -0
  39. package/client/os.d.ts +2 -0
  40. package/client/os.js +23 -0
  41. package/client/path.d.ts +2 -0
  42. package/client/path.js +7 -0
  43. package/client/telegramBaseClient.d.ts +238 -0
  44. package/client/telegramBaseClient.js +368 -0
  45. package/client/updates.d.ts +31 -0
  46. package/client/updates.js +254 -0
  47. package/client/uploads.d.ts +137 -0
  48. package/client/uploads.js +514 -0
  49. package/client/users.d.ts +29 -0
  50. package/client/users.js +491 -0
  51. package/crypto/AuthKey.d.ts +20 -0
  52. package/crypto/AuthKey.js +76 -0
  53. package/crypto/CTR.d.ts +6 -0
  54. package/crypto/CTR.js +35 -0
  55. package/crypto/Factorizator.d.ts +19 -0
  56. package/crypto/Factorizator.js +74 -0
  57. package/crypto/IGE.d.ts +18 -0
  58. package/crypto/IGE.js +34 -0
  59. package/crypto/RSA.d.ts +15 -0
  60. package/crypto/RSA.js +70 -0
  61. package/crypto/converters.d.ts +19 -0
  62. package/crypto/converters.js +52 -0
  63. package/crypto/crypto.d.ts +27 -0
  64. package/crypto/crypto.js +117 -0
  65. package/crypto/words.d.ts +6 -0
  66. package/crypto/words.js +48 -0
  67. package/define.d.ts +77 -0
  68. package/entityCache.d.ts +7 -0
  69. package/entityCache.js +79 -0
  70. package/errors/Common.d.ts +72 -0
  71. package/errors/Common.js +122 -0
  72. package/errors/RPCBaseErrors.d.ts +84 -0
  73. package/errors/RPCBaseErrors.js +134 -0
  74. package/errors/RPCErrorList.d.ts +37 -0
  75. package/errors/RPCErrorList.js +117 -0
  76. package/errors/index.d.ts +11 -0
  77. package/errors/index.js +29 -0
  78. package/events/Album.d.ts +36 -0
  79. package/events/Album.js +104 -0
  80. package/events/CallbackQuery.d.ts +74 -0
  81. package/events/CallbackQuery.js +193 -0
  82. package/events/DeletedMessage.d.ts +45 -0
  83. package/events/DeletedMessage.js +63 -0
  84. package/events/EditedMessage.d.ts +30 -0
  85. package/events/EditedMessage.js +41 -0
  86. package/events/NewMessage.d.ts +89 -0
  87. package/events/NewMessage.js +182 -0
  88. package/events/Raw.d.ts +29 -0
  89. package/events/Raw.js +43 -0
  90. package/events/common.d.ts +66 -0
  91. package/events/common.js +141 -0
  92. package/events/index.d.ts +2 -0
  93. package/events/index.js +8 -0
  94. package/extensions/AsyncQueue.d.ts +10 -0
  95. package/extensions/AsyncQueue.js +32 -0
  96. package/extensions/BinaryReader.d.ts +100 -0
  97. package/extensions/BinaryReader.js +242 -0
  98. package/extensions/BinaryWriter.d.ts +7 -0
  99. package/extensions/BinaryWriter.js +15 -0
  100. package/extensions/Deferred.d.ts +8 -0
  101. package/extensions/Deferred.js +16 -0
  102. package/extensions/Logger.d.ts +56 -0
  103. package/extensions/Logger.js +107 -0
  104. package/extensions/MessagePacker.d.ts +22 -0
  105. package/extensions/MessagePacker.js +154 -0
  106. package/extensions/PendingState.d.ts +12 -0
  107. package/extensions/PendingState.js +29 -0
  108. package/extensions/PromisedNetSockets.d.ts +25 -0
  109. package/extensions/PromisedNetSockets.js +178 -0
  110. package/extensions/PromisedWebSockets.d.ts +19 -0
  111. package/extensions/PromisedWebSockets.js +124 -0
  112. package/extensions/html.d.ts +5 -0
  113. package/extensions/html.js +213 -0
  114. package/extensions/index.d.ts +7 -0
  115. package/extensions/index.js +17 -0
  116. package/extensions/markdown.d.ts +5 -0
  117. package/extensions/markdown.js +76 -0
  118. package/extensions/markdownv2.d.ts +5 -0
  119. package/extensions/markdownv2.js +51 -0
  120. package/extensions/net.d.ts +1 -0
  121. package/extensions/net.js +13 -0
  122. package/extensions/socks.d.ts +1 -0
  123. package/extensions/socks.js +13 -0
  124. package/index.d.ts +14 -0
  125. package/index.js +48 -0
  126. package/inspect.d.ts +1 -0
  127. package/inspect.js +5 -0
  128. package/network/Authenticator.d.ts +12 -0
  129. package/network/Authenticator.js +193 -0
  130. package/network/MTProtoPlainSender.d.ts +19 -0
  131. package/network/MTProtoPlainSender.js +74 -0
  132. package/network/MTProtoSender.d.ts +291 -0
  133. package/network/MTProtoSender.js +854 -0
  134. package/network/MTProtoState.d.ts +103 -0
  135. package/network/MTProtoState.js +267 -0
  136. package/network/RequestState.d.ts +19 -0
  137. package/network/RequestState.js +35 -0
  138. package/network/connection/Connection.d.ts +71 -0
  139. package/network/connection/Connection.js +157 -0
  140. package/network/connection/TCPAbridged.d.ts +20 -0
  141. package/network/connection/TCPAbridged.js +58 -0
  142. package/network/connection/TCPFull.d.ts +17 -0
  143. package/network/connection/TCPFull.js +61 -0
  144. package/network/connection/TCPMTProxy.d.ts +50 -0
  145. package/network/connection/TCPMTProxy.js +121 -0
  146. package/network/connection/TCPObfuscated.d.ts +19 -0
  147. package/network/connection/TCPObfuscated.js +78 -0
  148. package/network/connection/index.d.ts +4 -0
  149. package/network/connection/index.js +11 -0
  150. package/network/index.d.ts +11 -0
  151. package/network/index.js +23 -0
  152. package/package.json +69 -0
  153. package/requestIter.d.ts +24 -0
  154. package/requestIter.js +107 -0
  155. package/sessions/Abstract.d.ts +103 -0
  156. package/sessions/Abstract.js +6 -0
  157. package/sessions/CacheApiSession.d.ts +18 -0
  158. package/sessions/CacheApiSession.js +99 -0
  159. package/sessions/Memory.d.ts +38 -0
  160. package/sessions/Memory.js +272 -0
  161. package/sessions/StoreSession.d.ts +14 -0
  162. package/sessions/StoreSession.js +77 -0
  163. package/sessions/StringSession.d.ts +33 -0
  164. package/sessions/StringSession.js +116 -0
  165. package/sessions/index.d.ts +4 -0
  166. package/sessions/index.js +13 -0
  167. package/sessions/localStorage.d.ts +1 -0
  168. package/sessions/localStorage.js +4 -0
  169. package/tl/AllTLObjects.d.ts +3 -0
  170. package/tl/AllTLObjects.js +17 -0
  171. package/tl/MTProtoRequest.d.ts +19 -0
  172. package/tl/MTProtoRequest.js +38 -0
  173. package/tl/api.d.ts +31425 -0
  174. package/tl/api.js +507 -0
  175. package/tl/apiTl.d.ts +2 -0
  176. package/tl/apiTl.js +2142 -0
  177. package/tl/core/GZIPPacked.d.ts +16 -0
  178. package/tl/core/GZIPPacked.js +51 -0
  179. package/tl/core/MessageContainer.d.ts +12 -0
  180. package/tl/core/MessageContainer.js +42 -0
  181. package/tl/core/RPCResult.d.ts +15 -0
  182. package/tl/core/RPCResult.js +32 -0
  183. package/tl/core/TLMessage.d.ts +10 -0
  184. package/tl/core/TLMessage.js +14 -0
  185. package/tl/core/index.d.ts +6 -0
  186. package/tl/core/index.js +16 -0
  187. package/tl/custom/button.d.ts +25 -0
  188. package/tl/custom/button.js +78 -0
  189. package/tl/custom/chatGetter.d.ts +30 -0
  190. package/tl/custom/chatGetter.js +114 -0
  191. package/tl/custom/dialog.d.ts +31 -0
  192. package/tl/custom/dialog.js +40 -0
  193. package/tl/custom/draft.d.ts +22 -0
  194. package/tl/custom/draft.js +48 -0
  195. package/tl/custom/file.d.ts +22 -0
  196. package/tl/custom/file.js +68 -0
  197. package/tl/custom/forward.d.ts +16 -0
  198. package/tl/custom/forward.js +47 -0
  199. package/tl/custom/index.d.ts +1 -0
  200. package/tl/custom/index.js +5 -0
  201. package/tl/custom/inlineResult.d.ts +33 -0
  202. package/tl/custom/inlineResult.js +87 -0
  203. package/tl/custom/inlineResults.d.ts +21 -0
  204. package/tl/custom/inlineResults.js +26 -0
  205. package/tl/custom/message.d.ts +428 -0
  206. package/tl/custom/message.js +702 -0
  207. package/tl/custom/messageButton.d.ts +55 -0
  208. package/tl/custom/messageButton.js +152 -0
  209. package/tl/custom/senderGetter.d.ts +29 -0
  210. package/tl/custom/senderGetter.js +55 -0
  211. package/tl/generateModule.d.ts +1 -0
  212. package/tl/generateModule.js +17 -0
  213. package/tl/generationHelpers.d.ts +12 -0
  214. package/tl/generationHelpers.js +289 -0
  215. package/tl/index.d.ts +3 -0
  216. package/tl/index.js +10 -0
  217. package/tl/patched/index.d.ts +2 -0
  218. package/tl/patched/index.js +77 -0
  219. package/tl/schemaTl.d.ts +2 -0
  220. package/tl/schemaTl.js +64 -0
  221. package/tl/types-generator/generate.d.ts +1 -0
  222. package/tl/types-generator/generate.js +84 -0
  223. package/tl/types-generator/template.d.ts +6 -0
  224. package/tl/types-generator/template.js +257 -0
File without changes
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,93 @@
1
+ /// <reference types="node" />
2
+ import { Api } from "../tl";
3
+ import type { TelegramClient } from "./TelegramClient";
4
+ /**
5
+ * For when you want to login as a {@link Api.User}<br/>
6
+ * this should handle all needed steps for authorization as a user.<br/>
7
+ * to stop the operation at any point just raise and error with the message `AUTH_USER_CANCEL`.
8
+ */
9
+ export interface UserAuthParams {
10
+ /** Either a string or a callback that returns a string for the phone to use to login. */
11
+ phoneNumber: string | (() => Promise<string>);
12
+ /** callback that should return the login code that telegram sent.<br/>
13
+ * has optional bool `isCodeViaApp` param for whether the code was sent through the app (true) or an SMS (false). */
14
+ phoneCode: (isCodeViaApp?: boolean) => Promise<string>;
15
+ /** optional string or callback that should return the 2FA password if present.<br/>
16
+ * the password hint will be sent in the hint param */
17
+ password?: (hint?: string) => Promise<string>;
18
+ /** in case of a new account creation this callback should return a first name and last name `[first,last]`. */
19
+ firstAndLastNames?: () => Promise<[string, string?]>;
20
+ /** a qrCode token for login through qrCode.<br/>
21
+ * this would need a QR code that you should scan with another app to login with. */
22
+ qrCode?: (qrCode: {
23
+ token: Buffer;
24
+ expires: number;
25
+ }) => Promise<void>;
26
+ /** when an error happens during auth this function will be called with the error.<br/>
27
+ * if this returns true the auth operation will stop. */
28
+ onError: (err: Error) => Promise<boolean> | void;
29
+ /** whether to send the code through SMS or not. */
30
+ forceSMS?: boolean;
31
+ }
32
+ export interface UserPasswordAuthParams {
33
+ /** optional string or callback that should return the 2FA password if present.<br/>
34
+ * the password hint will be sent in the hint param */
35
+ password?: (hint?: string) => Promise<string>;
36
+ /** when an error happens during auth this function will be called with the error.<br/>
37
+ * if this returns true the auth operation will stop. */
38
+ onError: (err: Error) => Promise<boolean> | void;
39
+ }
40
+ export interface QrCodeAuthParams extends UserPasswordAuthParams {
41
+ /** a qrCode token for login through qrCode.<br/>
42
+ * this would need a QR code that you should scan with another app to login with. */
43
+ qrCode?: (qrCode: {
44
+ token: Buffer;
45
+ expires: number;
46
+ }) => Promise<void>;
47
+ /** when an error happens during auth this function will be called with the error.<br/>
48
+ * if this returns true the auth operation will stop. */
49
+ onError: (err: Error) => Promise<boolean> | void;
50
+ }
51
+ interface ReturnString {
52
+ (): string;
53
+ }
54
+ /**
55
+ * For when you want as a normal bot created by https://t.me/Botfather.<br/>
56
+ * Logging in as bot is simple and requires no callbacks
57
+ */
58
+ export interface BotAuthParams {
59
+ /**
60
+ * the bot token to use.
61
+ */
62
+ botAuthToken: string | ReturnString;
63
+ }
64
+ /**
65
+ * Credential needed for the authentication. you can get theses from https://my.telegram.org/auth<br/>
66
+ * Note: This is required for both logging in as a bot and a user.<br/>
67
+ */
68
+ export interface ApiCredentials {
69
+ /** The app api id. */
70
+ apiId: number;
71
+ /** the app api hash */
72
+ apiHash: string;
73
+ }
74
+ /** @hidden */
75
+ export declare function start(client: TelegramClient, authParams: UserAuthParams | BotAuthParams): Promise<void>;
76
+ /** @hidden */
77
+ export declare function checkAuthorization(client: TelegramClient): Promise<boolean>;
78
+ /** @hidden */
79
+ export declare function signInUser(client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams): Promise<Api.TypeUser>;
80
+ /** @hidden */
81
+ export declare function signInUserWithQrCode(client: TelegramClient, apiCredentials: ApiCredentials, authParams: QrCodeAuthParams): Promise<Api.TypeUser>;
82
+ /** @hidden */
83
+ export declare function sendCode(client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS?: boolean): Promise<{
84
+ phoneCodeHash: string;
85
+ isCodeViaApp: boolean;
86
+ }>;
87
+ /** @hidden */
88
+ export declare function signInWithPassword(client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserPasswordAuthParams): Promise<Api.TypeUser>;
89
+ /** @hidden */
90
+ export declare function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams): Promise<Api.TypeUser>;
91
+ /** @hidden */
92
+ export declare function _authFlow(client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams | BotAuthParams): Promise<void>;
93
+ export {};
package/client/auth.js ADDED
@@ -0,0 +1,375 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports._authFlow = exports.signInBot = exports.signInWithPassword = exports.sendCode = exports.signInUserWithQrCode = exports.signInUser = exports.checkAuthorization = exports.start = void 0;
23
+ const tl_1 = require("../tl");
24
+ const utils = __importStar(require("../Utils"));
25
+ const Helpers_1 = require("../Helpers");
26
+ const Password_1 = require("../Password");
27
+ const QR_CODE_TIMEOUT = 30000;
28
+ // region public methods
29
+ /** @hidden */
30
+ async function start(client, authParams) {
31
+ if (!client.connected) {
32
+ await client.connect();
33
+ }
34
+ if (await client.checkAuthorization()) {
35
+ return;
36
+ }
37
+ const apiCredentials = {
38
+ apiId: client.apiId,
39
+ apiHash: client.apiHash,
40
+ };
41
+ await _authFlow(client, apiCredentials, authParams);
42
+ }
43
+ exports.start = start;
44
+ /** @hidden */
45
+ async function checkAuthorization(client) {
46
+ try {
47
+ await client.invoke(new tl_1.Api.updates.GetState());
48
+ return true;
49
+ }
50
+ catch (e) {
51
+ return false;
52
+ }
53
+ }
54
+ exports.checkAuthorization = checkAuthorization;
55
+ /** @hidden */
56
+ async function signInUser(client, apiCredentials, authParams) {
57
+ let phoneNumber;
58
+ let phoneCodeHash;
59
+ let isCodeViaApp = false;
60
+ while (1) {
61
+ try {
62
+ if (typeof authParams.phoneNumber === "function") {
63
+ try {
64
+ phoneNumber = await authParams.phoneNumber();
65
+ }
66
+ catch (err) {
67
+ if (err.errorMessage === "RESTART_AUTH_WITH_QR") {
68
+ return client.signInUserWithQrCode(apiCredentials, authParams);
69
+ }
70
+ throw err;
71
+ }
72
+ }
73
+ else {
74
+ phoneNumber = authParams.phoneNumber;
75
+ }
76
+ const sendCodeResult = await client.sendCode(apiCredentials, phoneNumber, authParams.forceSMS);
77
+ phoneCodeHash = sendCodeResult.phoneCodeHash;
78
+ isCodeViaApp = sendCodeResult.isCodeViaApp;
79
+ if (typeof phoneCodeHash !== "string") {
80
+ throw new Error("Failed to retrieve phone code hash");
81
+ }
82
+ break;
83
+ }
84
+ catch (err) {
85
+ if (typeof authParams.phoneNumber !== "function") {
86
+ throw err;
87
+ }
88
+ const shouldWeStop = await authParams.onError(err);
89
+ if (shouldWeStop) {
90
+ throw new Error("AUTH_USER_CANCEL");
91
+ }
92
+ }
93
+ }
94
+ let phoneCode;
95
+ let isRegistrationRequired = false;
96
+ let termsOfService;
97
+ while (1) {
98
+ try {
99
+ try {
100
+ phoneCode = await authParams.phoneCode(isCodeViaApp);
101
+ }
102
+ catch (err) {
103
+ // This is the support for changing phone number from the phone code screen.
104
+ if (err.errorMessage === "RESTART_AUTH") {
105
+ return client.signInUser(apiCredentials, authParams);
106
+ }
107
+ }
108
+ if (!phoneCode) {
109
+ throw new Error("Code is empty");
110
+ }
111
+ // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,
112
+ // PhoneCodeHashEmptyError or PhoneCodeInvalidError.
113
+ const result = await client.invoke(new tl_1.Api.auth.SignIn({
114
+ phoneNumber,
115
+ phoneCodeHash,
116
+ phoneCode,
117
+ }));
118
+ if (result instanceof tl_1.Api.auth.AuthorizationSignUpRequired) {
119
+ isRegistrationRequired = true;
120
+ termsOfService = result.termsOfService;
121
+ break;
122
+ }
123
+ return result.user;
124
+ }
125
+ catch (err) {
126
+ if (err.errorMessage === "SESSION_PASSWORD_NEEDED") {
127
+ return client.signInWithPassword(apiCredentials, authParams);
128
+ }
129
+ else {
130
+ const shouldWeStop = await authParams.onError(err);
131
+ if (shouldWeStop) {
132
+ throw new Error("AUTH_USER_CANCEL");
133
+ }
134
+ }
135
+ }
136
+ }
137
+ if (isRegistrationRequired) {
138
+ while (1) {
139
+ try {
140
+ let lastName;
141
+ let firstName = "first name";
142
+ if (authParams.firstAndLastNames) {
143
+ const result = await authParams.firstAndLastNames();
144
+ firstName = result[0];
145
+ lastName = result[1];
146
+ }
147
+ if (!firstName) {
148
+ throw new Error("First name is required");
149
+ }
150
+ const { user } = (await client.invoke(new tl_1.Api.auth.SignUp({
151
+ phoneNumber,
152
+ phoneCodeHash,
153
+ firstName,
154
+ lastName,
155
+ })));
156
+ if (termsOfService) {
157
+ // This is a violation of Telegram rules: the user should be presented with and accept TOS.
158
+ await client.invoke(new tl_1.Api.help.AcceptTermsOfService({
159
+ id: termsOfService.id,
160
+ }));
161
+ }
162
+ return user;
163
+ }
164
+ catch (err) {
165
+ const shouldWeStop = await authParams.onError(err);
166
+ if (shouldWeStop) {
167
+ throw new Error("AUTH_USER_CANCEL");
168
+ }
169
+ }
170
+ }
171
+ }
172
+ await authParams.onError(new Error("Auth failed"));
173
+ return client.signInUser(apiCredentials, authParams);
174
+ }
175
+ exports.signInUser = signInUser;
176
+ /** @hidden */
177
+ async function signInUserWithQrCode(client, apiCredentials, authParams) {
178
+ let isScanningComplete = false;
179
+ if (authParams.qrCode == undefined) {
180
+ throw new Error("qrCode callback not defined");
181
+ }
182
+ const inputPromise = (async () => {
183
+ while (1) {
184
+ if (isScanningComplete) {
185
+ break;
186
+ }
187
+ const result = await client.invoke(new tl_1.Api.auth.ExportLoginToken({
188
+ apiId: Number(apiCredentials.apiId),
189
+ apiHash: apiCredentials.apiHash,
190
+ exceptIds: [],
191
+ }));
192
+ if (!(result instanceof tl_1.Api.auth.LoginToken)) {
193
+ throw new Error("Unexpected");
194
+ }
195
+ const { token, expires } = result;
196
+ await Promise.race([
197
+ authParams.qrCode({ token, expires }),
198
+ (0, Helpers_1.sleep)(QR_CODE_TIMEOUT),
199
+ ]);
200
+ await (0, Helpers_1.sleep)(QR_CODE_TIMEOUT);
201
+ }
202
+ })();
203
+ const updatePromise = new Promise((resolve) => {
204
+ client.addEventHandler((update) => {
205
+ if (update instanceof tl_1.Api.UpdateLoginToken) {
206
+ resolve(undefined);
207
+ }
208
+ });
209
+ });
210
+ try {
211
+ await Promise.race([updatePromise, inputPromise]);
212
+ }
213
+ catch (err) {
214
+ throw err;
215
+ }
216
+ finally {
217
+ isScanningComplete = true;
218
+ }
219
+ try {
220
+ const result2 = await client.invoke(new tl_1.Api.auth.ExportLoginToken({
221
+ apiId: Number(apiCredentials.apiId),
222
+ apiHash: apiCredentials.apiHash,
223
+ exceptIds: [],
224
+ }));
225
+ if (result2 instanceof tl_1.Api.auth.LoginTokenSuccess &&
226
+ result2.authorization instanceof tl_1.Api.auth.Authorization) {
227
+ return result2.authorization.user;
228
+ }
229
+ else if (result2 instanceof tl_1.Api.auth.LoginTokenMigrateTo) {
230
+ await client._switchDC(result2.dcId);
231
+ const migratedResult = await client.invoke(new tl_1.Api.auth.ImportLoginToken({
232
+ token: result2.token,
233
+ }));
234
+ if (migratedResult instanceof tl_1.Api.auth.LoginTokenSuccess &&
235
+ migratedResult.authorization instanceof tl_1.Api.auth.Authorization) {
236
+ return migratedResult.authorization.user;
237
+ }
238
+ else {
239
+ client._log.error(`Received unknown result while scanning QR ${result2.className}`);
240
+ throw new Error(`Received unknown result while scanning QR ${result2.className}`);
241
+ }
242
+ }
243
+ else {
244
+ client._log.error(`Received unknown result while scanning QR ${result2.className}`);
245
+ throw new Error(`Received unknown result while scanning QR ${result2.className}`);
246
+ }
247
+ }
248
+ catch (err) {
249
+ if (err.errorMessage === "SESSION_PASSWORD_NEEDED") {
250
+ return client.signInWithPassword(apiCredentials, authParams);
251
+ }
252
+ throw err;
253
+ }
254
+ await authParams.onError(new Error("QR auth failed"));
255
+ throw new Error("QR auth failed");
256
+ }
257
+ exports.signInUserWithQrCode = signInUserWithQrCode;
258
+ /** @hidden */
259
+ async function sendCode(client, apiCredentials, phoneNumber, forceSMS = false) {
260
+ try {
261
+ const { apiId, apiHash } = apiCredentials;
262
+ const sendResult = await client.invoke(new tl_1.Api.auth.SendCode({
263
+ phoneNumber,
264
+ apiId,
265
+ apiHash,
266
+ settings: new tl_1.Api.CodeSettings({}),
267
+ }));
268
+ if (sendResult instanceof tl_1.Api.auth.SentCodeSuccess)
269
+ throw new Error("logged in right after sending the code");
270
+ if (!(sendResult instanceof tl_1.Api.auth.SentCode)) {
271
+ return {
272
+ phoneCodeHash: sendResult.phoneCodeHash,
273
+ isCodeViaApp: false,
274
+ };
275
+ }
276
+ // If we already sent a SMS, do not resend the phoneCode (hash may be empty)
277
+ if (!forceSMS || sendResult.type instanceof tl_1.Api.auth.SentCodeTypeSms) {
278
+ return {
279
+ phoneCodeHash: sendResult.phoneCodeHash,
280
+ isCodeViaApp: sendResult.type instanceof tl_1.Api.auth.SentCodeTypeApp,
281
+ };
282
+ }
283
+ const resendResult = await client.invoke(new tl_1.Api.auth.ResendCode({
284
+ phoneNumber,
285
+ phoneCodeHash: sendResult.phoneCodeHash,
286
+ }));
287
+ if (resendResult instanceof tl_1.Api.auth.SentCodeSuccess)
288
+ throw new Error("logged in right after resending the code");
289
+ if (!(resendResult instanceof tl_1.Api.auth.SentCode)) {
290
+ return {
291
+ phoneCodeHash: resendResult.phoneCodeHash,
292
+ isCodeViaApp: false,
293
+ };
294
+ }
295
+ return {
296
+ phoneCodeHash: resendResult.phoneCodeHash,
297
+ isCodeViaApp: resendResult.type instanceof tl_1.Api.auth.SentCodeTypeApp,
298
+ };
299
+ }
300
+ catch (err) {
301
+ if (err.errorMessage === "AUTH_RESTART") {
302
+ return client.sendCode(apiCredentials, phoneNumber, forceSMS);
303
+ }
304
+ else {
305
+ throw err;
306
+ }
307
+ }
308
+ }
309
+ exports.sendCode = sendCode;
310
+ /** @hidden */
311
+ async function signInWithPassword(client, apiCredentials, authParams) {
312
+ let emptyPassword = false;
313
+ while (1) {
314
+ try {
315
+ const passwordSrpResult = await client.invoke(new tl_1.Api.account.GetPassword());
316
+ if (!authParams.password) {
317
+ emptyPassword = true;
318
+ break;
319
+ }
320
+ const password = await authParams.password(passwordSrpResult.hint);
321
+ if (!password) {
322
+ throw new Error("Password is empty");
323
+ }
324
+ const passwordSrpCheck = await (0, Password_1.computeCheck)(passwordSrpResult, password);
325
+ const { user } = (await client.invoke(new tl_1.Api.auth.CheckPassword({
326
+ password: passwordSrpCheck,
327
+ })));
328
+ return user;
329
+ }
330
+ catch (err) {
331
+ const shouldWeStop = await authParams.onError(err);
332
+ if (shouldWeStop) {
333
+ throw new Error("AUTH_USER_CANCEL");
334
+ }
335
+ }
336
+ }
337
+ if (emptyPassword) {
338
+ throw new Error("Account has 2FA enabled.");
339
+ }
340
+ return undefined; // Never reached (TypeScript fix)
341
+ }
342
+ exports.signInWithPassword = signInWithPassword;
343
+ /** @hidden */
344
+ async function signInBot(client, apiCredentials, authParams) {
345
+ const { apiId, apiHash } = apiCredentials;
346
+ let { botAuthToken } = authParams;
347
+ if (!botAuthToken) {
348
+ throw new Error("a valid BotToken is required");
349
+ }
350
+ if (typeof botAuthToken === "function") {
351
+ let token;
352
+ while (true) {
353
+ token = await botAuthToken();
354
+ if (token) {
355
+ botAuthToken = token;
356
+ break;
357
+ }
358
+ }
359
+ }
360
+ const { user } = (await client.invoke(new tl_1.Api.auth.ImportBotAuthorization({
361
+ apiId,
362
+ apiHash,
363
+ botAuthToken,
364
+ })));
365
+ return user;
366
+ }
367
+ exports.signInBot = signInBot;
368
+ /** @hidden */
369
+ async function _authFlow(client, apiCredentials, authParams) {
370
+ const me = "phoneNumber" in authParams
371
+ ? await client.signInUser(apiCredentials, authParams)
372
+ : await client.signInBot(apiCredentials, authParams);
373
+ client._log.info("Signed in successfully as " + utils.getDisplayName(me));
374
+ }
375
+ exports._authFlow = _authFlow;
@@ -0,0 +1,6 @@
1
+ import type { EntityLike } from "../define";
2
+ import { Api } from "../tl";
3
+ import { InlineResults } from "../tl/custom/inlineResults";
4
+ import type { TelegramClient } from "./TelegramClient";
5
+ /** @hidden */
6
+ export declare function inlineQuery(client: TelegramClient, bot: EntityLike, query: string, entity?: Api.InputPeerSelf, offset?: string, geoPoint?: Api.TypeInputGeoPoint): Promise<InlineResults>;
package/client/bots.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.inlineQuery = void 0;
4
+ const tl_1 = require("../tl");
5
+ const inlineResults_1 = require("../tl/custom/inlineResults");
6
+ var GetInlineBotResults = tl_1.Api.messages.GetInlineBotResults;
7
+ // BotMethods
8
+ /** @hidden */
9
+ async function inlineQuery(client, bot, query, entity, offset, geoPoint) {
10
+ bot = await client.getInputEntity(bot);
11
+ let peer = new tl_1.Api.InputPeerSelf();
12
+ if (entity) {
13
+ peer = await client.getInputEntity(entity);
14
+ }
15
+ const result = await client.invoke(new GetInlineBotResults({
16
+ bot: bot,
17
+ peer: peer,
18
+ query: query,
19
+ offset: offset || "",
20
+ geoPoint: geoPoint,
21
+ }));
22
+ return new inlineResults_1.InlineResults(client, result, entity ? peer : undefined);
23
+ }
24
+ exports.inlineQuery = inlineQuery;
@@ -0,0 +1,4 @@
1
+ import { Api } from "../tl";
2
+ import type { ButtonLike } from "../define";
3
+ /** @hidden */
4
+ export declare function buildReplyMarkup(buttons: Api.TypeReplyMarkup | undefined | ButtonLike | ButtonLike[] | ButtonLike[][], inlineOnly?: boolean): Api.TypeReplyMarkup | undefined;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildReplyMarkup = void 0;
4
+ const tl_1 = require("../tl");
5
+ const button_1 = require("../tl/custom/button");
6
+ const messageButton_1 = require("../tl/custom/messageButton");
7
+ const Helpers_1 = require("../Helpers");
8
+ // ButtonMethods
9
+ /** @hidden */
10
+ function buildReplyMarkup(buttons, inlineOnly = false) {
11
+ if (buttons == undefined) {
12
+ return undefined;
13
+ }
14
+ if ("SUBCLASS_OF_ID" in buttons) {
15
+ if (buttons.SUBCLASS_OF_ID == 0xe2e10ef2) {
16
+ return buttons;
17
+ }
18
+ }
19
+ if (!(0, Helpers_1.isArrayLike)(buttons)) {
20
+ buttons = [[buttons]];
21
+ }
22
+ else if (!buttons || !(0, Helpers_1.isArrayLike)(buttons[0])) {
23
+ // @ts-ignore
24
+ buttons = [buttons];
25
+ }
26
+ let isInline = false;
27
+ let isNormal = false;
28
+ let resize = undefined;
29
+ const singleUse = false;
30
+ const selective = false;
31
+ const rows = [];
32
+ // @ts-ignore
33
+ for (const row of buttons) {
34
+ const current = [];
35
+ for (let button of row) {
36
+ if (button instanceof button_1.Button) {
37
+ if (button.resize != undefined) {
38
+ resize = button.resize;
39
+ }
40
+ if (button.singleUse != undefined) {
41
+ resize = button.singleUse;
42
+ }
43
+ if (button.selective != undefined) {
44
+ resize = button.selective;
45
+ }
46
+ button = button.button;
47
+ }
48
+ else if (button instanceof messageButton_1.MessageButton) {
49
+ button = button.button;
50
+ }
51
+ const inline = button_1.Button._isInline(button);
52
+ if (!isInline && inline) {
53
+ isInline = true;
54
+ }
55
+ if (!isNormal && inline) {
56
+ isNormal = false;
57
+ }
58
+ if (button.SUBCLASS_OF_ID == 0xbad74a3) {
59
+ // 0xbad74a3 == crc32(b'KeyboardButton')
60
+ current.push(button);
61
+ }
62
+ }
63
+ if (current) {
64
+ rows.push(new tl_1.Api.KeyboardButtonRow({
65
+ buttons: current,
66
+ }));
67
+ }
68
+ }
69
+ if (inlineOnly && isNormal) {
70
+ throw new Error("You cannot use non-inline buttons here");
71
+ }
72
+ else if (isInline === isNormal && isNormal) {
73
+ throw new Error("You cannot mix inline with normal buttons");
74
+ }
75
+ else if (isInline) {
76
+ return new tl_1.Api.ReplyInlineMarkup({
77
+ rows: rows,
78
+ });
79
+ }
80
+ return new tl_1.Api.ReplyKeyboardMarkup({
81
+ rows: rows,
82
+ resize: resize,
83
+ singleUse: singleUse,
84
+ selective: selective,
85
+ });
86
+ }
87
+ exports.buildReplyMarkup = buildReplyMarkup;
@@ -0,0 +1,46 @@
1
+ /// <reference types="node" />
2
+ import type { TelegramClient } from "./TelegramClient";
3
+ import type { EntityLike } from "../define";
4
+ import { TotalList } from "../Helpers";
5
+ import { RequestIter } from "../requestIter";
6
+ import { Api } from "../tl";
7
+ import { inspect } from "../inspect";
8
+ interface ParticipantsIterInterface {
9
+ entity: EntityLike;
10
+ filter: any;
11
+ offset?: number;
12
+ search?: string;
13
+ showTotal?: boolean;
14
+ }
15
+ export declare class _ParticipantsIter extends RequestIter {
16
+ private filterEntity;
17
+ private requests?;
18
+ [inspect.custom](): {
19
+ [key: string]: any;
20
+ };
21
+ _init({ entity, filter, offset, search, showTotal, }: ParticipantsIterInterface): Promise<boolean | void>;
22
+ _loadNextChunk(): Promise<boolean | undefined>;
23
+ [Symbol.asyncIterator](): AsyncIterator<Api.User, any, undefined>;
24
+ }
25
+ /**
26
+ * Used in iterParticipant and getParticipant. all params are optional.
27
+ */
28
+ export interface IterParticipantsParams {
29
+ /** how many members to retrieve. defaults to Number.MAX_SAFE_INTEGER (everyone) */
30
+ limit?: number;
31
+ /** how many members to skip. defaults to 0 */
32
+ offset?: number;
33
+ /** a query string to filter participants based on their display names and usernames. defaults to "" (everyone) */
34
+ search?: string;
35
+ /** optional filter to be used. E.g only admins filter or only banned members filter. PS : some filters need more permissions. */
36
+ filter?: Api.TypeChannelParticipantsFilter;
37
+ /** whether to call an extra request (GetFullChannel) to show the total of users in the group/channel. if set to false total will be 0 */
38
+ showTotal?: boolean;
39
+ }
40
+ /** @hidden */
41
+ export declare function iterParticipants(client: TelegramClient, entity: EntityLike, { limit, offset, search, filter, showTotal }: IterParticipantsParams): _ParticipantsIter;
42
+ /** @hidden */
43
+ export declare function getParticipants(client: TelegramClient, entity: EntityLike, params: IterParticipantsParams): Promise<TotalList<Api.User>>;
44
+ /** @hidden */
45
+ export declare function kickParticipant(client: TelegramClient, entity: EntityLike, participant: EntityLike): Promise<Api.TypeMessage | Map<number, Api.Message> | (Api.Message | undefined)[] | undefined>;
46
+ export {};