teleproto 1.214.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 (222) hide show
  1. package/CryptoFile.d.ts +2 -0
  2. package/CryptoFile.js +37 -0
  3. package/Helpers.d.ts +150 -0
  4. package/Helpers.js +477 -0
  5. package/LICENSE +23 -0
  6. package/Password.d.ts +14 -0
  7. package/Password.js +270 -0
  8. package/README.md +98 -0
  9. package/Utils.d.ts +227 -0
  10. package/Utils.js +1247 -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 +108 -0
  15. package/client/TelegramClient.d.ts +1043 -0
  16. package/client/TelegramClient.js +1181 -0
  17. package/client/account.d.ts +0 -0
  18. package/client/account.js +1 -0
  19. package/client/auth.d.ts +92 -0
  20. package/client/auth.js +388 -0
  21. package/client/bots.d.ts +6 -0
  22. package/client/bots.js +23 -0
  23. package/client/buttons.d.ts +4 -0
  24. package/client/buttons.js +86 -0
  25. package/client/chats.d.ts +45 -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 +156 -0
  30. package/client/downloads.js +614 -0
  31. package/client/fs.d.ts +1 -0
  32. package/client/fs.js +17 -0
  33. package/client/index.d.ts +15 -0
  34. package/client/index.js +64 -0
  35. package/client/messageParse.d.ts +17 -0
  36. package/client/messageParse.js +191 -0
  37. package/client/messages.d.ts +263 -0
  38. package/client/messages.js +813 -0
  39. package/client/os.d.ts +2 -0
  40. package/client/os.js +37 -0
  41. package/client/path.d.ts +2 -0
  42. package/client/path.js +7 -0
  43. package/client/telegramBaseClient.d.ts +237 -0
  44. package/client/telegramBaseClient.js +368 -0
  45. package/client/updates.d.ts +33 -0
  46. package/client/updates.js +260 -0
  47. package/client/uploads.d.ts +136 -0
  48. package/client/uploads.js +514 -0
  49. package/client/users.d.ts +29 -0
  50. package/client/users.js +490 -0
  51. package/crypto/AuthKey.d.ts +19 -0
  52. package/crypto/AuthKey.js +76 -0
  53. package/crypto/CTR.d.ts +5 -0
  54. package/crypto/CTR.js +16 -0
  55. package/crypto/Factorizator.d.ts +19 -0
  56. package/crypto/Factorizator.js +74 -0
  57. package/crypto/IGE.d.ts +11 -0
  58. package/crypto/IGE.js +115 -0
  59. package/crypto/RSA.d.ts +14 -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 +19 -0
  64. package/crypto/crypto.js +58 -0
  65. package/crypto/words.d.ts +6 -0
  66. package/crypto/words.js +47 -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 +71 -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 +32 -0
  78. package/events/Album.d.ts +36 -0
  79. package/events/Album.js +104 -0
  80. package/events/CallbackQuery.d.ts +73 -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 +99 -0
  97. package/extensions/BinaryReader.js +242 -0
  98. package/extensions/BinaryWriter.d.ts +6 -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 +54 -0
  103. package/extensions/Logger.js +128 -0
  104. package/extensions/MessagePacker.d.ts +21 -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 +24 -0
  109. package/extensions/PromisedNetSockets.js +192 -0
  110. package/extensions/PromisedWebSockets.d.ts +18 -0
  111. package/extensions/PromisedWebSockets.js +124 -0
  112. package/extensions/html.d.ts +5 -0
  113. package/extensions/html.js +228 -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 +17 -0
  122. package/extensions/socks.d.ts +1 -0
  123. package/extensions/socks.js +17 -0
  124. package/index.d.ts +14 -0
  125. package/index.js +62 -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 +192 -0
  130. package/network/MTProtoPlainSender.d.ts +19 -0
  131. package/network/MTProtoPlainSender.js +74 -0
  132. package/network/MTProtoSender.d.ts +290 -0
  133. package/network/MTProtoSender.js +873 -0
  134. package/network/MTProtoState.d.ts +102 -0
  135. package/network/MTProtoState.js +267 -0
  136. package/network/RequestState.d.ts +18 -0
  137. package/network/RequestState.js +35 -0
  138. package/network/connection/Connection.d.ts +69 -0
  139. package/network/connection/Connection.js +162 -0
  140. package/network/connection/TCPAbridged.d.ts +19 -0
  141. package/network/connection/TCPAbridged.js +58 -0
  142. package/network/connection/TCPFull.d.ts +16 -0
  143. package/network/connection/TCPFull.js +61 -0
  144. package/network/connection/TCPMTProxy.d.ts +49 -0
  145. package/network/connection/TCPMTProxy.js +121 -0
  146. package/network/connection/TCPObfuscated.d.ts +18 -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 +50 -0
  153. package/requestIter.d.ts +24 -0
  154. package/requestIter.js +109 -0
  155. package/sessions/Abstract.d.ts +103 -0
  156. package/sessions/Abstract.js +6 -0
  157. package/sessions/Memory.d.ts +38 -0
  158. package/sessions/Memory.js +272 -0
  159. package/sessions/StoreSession.d.ts +14 -0
  160. package/sessions/StoreSession.js +77 -0
  161. package/sessions/StringSession.d.ts +32 -0
  162. package/sessions/StringSession.js +116 -0
  163. package/sessions/index.d.ts +4 -0
  164. package/sessions/index.js +11 -0
  165. package/sessions/localStorage.d.ts +1 -0
  166. package/sessions/localStorage.js +4 -0
  167. package/tl/AllTLObjects.d.ts +3 -0
  168. package/tl/AllTLObjects.js +17 -0
  169. package/tl/MTProtoRequest.d.ts +18 -0
  170. package/tl/MTProtoRequest.js +38 -0
  171. package/tl/api.d.ts +32488 -0
  172. package/tl/api.js +507 -0
  173. package/tl/apiTl.d.ts +2 -0
  174. package/tl/apiTl.js +2209 -0
  175. package/tl/core/GZIPPacked.d.ts +15 -0
  176. package/tl/core/GZIPPacked.js +51 -0
  177. package/tl/core/MessageContainer.d.ts +12 -0
  178. package/tl/core/MessageContainer.js +42 -0
  179. package/tl/core/RPCResult.d.ts +14 -0
  180. package/tl/core/RPCResult.js +32 -0
  181. package/tl/core/TLMessage.d.ts +10 -0
  182. package/tl/core/TLMessage.js +14 -0
  183. package/tl/core/index.d.ts +6 -0
  184. package/tl/core/index.js +16 -0
  185. package/tl/custom/button.d.ts +24 -0
  186. package/tl/custom/button.js +78 -0
  187. package/tl/custom/chatGetter.d.ts +29 -0
  188. package/tl/custom/chatGetter.js +116 -0
  189. package/tl/custom/dialog.d.ts +30 -0
  190. package/tl/custom/dialog.js +40 -0
  191. package/tl/custom/draft.d.ts +21 -0
  192. package/tl/custom/draft.js +48 -0
  193. package/tl/custom/file.d.ts +21 -0
  194. package/tl/custom/file.js +68 -0
  195. package/tl/custom/forward.d.ts +15 -0
  196. package/tl/custom/forward.js +47 -0
  197. package/tl/custom/index.d.ts +1 -0
  198. package/tl/custom/index.js +5 -0
  199. package/tl/custom/inlineResult.d.ts +32 -0
  200. package/tl/custom/inlineResult.js +87 -0
  201. package/tl/custom/inlineResults.d.ts +20 -0
  202. package/tl/custom/inlineResults.js +26 -0
  203. package/tl/custom/message.d.ts +427 -0
  204. package/tl/custom/message.js +716 -0
  205. package/tl/custom/messageButton.d.ts +54 -0
  206. package/tl/custom/messageButton.js +152 -0
  207. package/tl/custom/senderGetter.d.ts +28 -0
  208. package/tl/custom/senderGetter.js +55 -0
  209. package/tl/generateModule.d.ts +1 -0
  210. package/tl/generateModule.js +17 -0
  211. package/tl/generationHelpers.d.ts +11 -0
  212. package/tl/generationHelpers.js +289 -0
  213. package/tl/index.d.ts +3 -0
  214. package/tl/index.js +10 -0
  215. package/tl/patched/index.d.ts +2 -0
  216. package/tl/patched/index.js +76 -0
  217. package/tl/schemaTl.d.ts +2 -0
  218. package/tl/schemaTl.js +64 -0
  219. package/tl/types-generator/generate.d.ts +1 -0
  220. package/tl/types-generator/generate.js +84 -0
  221. package/tl/types-generator/template.d.ts +6 -0
  222. package/tl/types-generator/template.js +257 -0
@@ -0,0 +1,1181 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.TelegramClient = void 0;
37
+ const telegramBaseClient_1 = require("./telegramBaseClient");
38
+ const authMethods = __importStar(require("./auth"));
39
+ const botMethods = __importStar(require("./bots"));
40
+ const buttonsMethods = __importStar(require("./buttons"));
41
+ const downloadMethods = __importStar(require("./downloads"));
42
+ const parseMethods = __importStar(require("./messageParse"));
43
+ const messageMethods = __importStar(require("./messages"));
44
+ const updateMethods = __importStar(require("./updates"));
45
+ const uploadMethods = __importStar(require("./uploads"));
46
+ const userMethods = __importStar(require("./users"));
47
+ const chatMethods = __importStar(require("./chats"));
48
+ const dialogMethods = __importStar(require("./dialogs"));
49
+ const twoFA = __importStar(require("./2fa"));
50
+ const tl_1 = require("../tl");
51
+ const Utils_1 = require("../Utils");
52
+ const network_1 = require("../network");
53
+ const AllTLObjects_1 = require("../tl/AllTLObjects");
54
+ const Helpers_1 = require("../Helpers");
55
+ const updates_1 = require("./updates");
56
+ const Logger_1 = require("../extensions/Logger");
57
+ const inspect_1 = require("../inspect");
58
+ /**
59
+ * The TelegramClient uses several methods in different files to provide all the common functionality in a nice interface.</br>
60
+ * **In short, to create a client you must do:**
61
+ *
62
+ * ```ts
63
+ * import {TelegramClient} from "teleproto";
64
+ *
65
+ * const client = new TelegramClient(new StringSession(''),apiId,apiHash,{});
66
+ * ```
67
+ *
68
+ * You don't need to import any methods that are inside the TelegramClient class as they binding in it.
69
+ */
70
+ class TelegramClient extends telegramBaseClient_1.TelegramBaseClient {
71
+ /**
72
+ * @param session - a session to be used to save the connection and auth key to. This can be a custom session that inherits MemorySession.
73
+ * @param apiId - The API ID you obtained from https://my.telegram.org.
74
+ * @param apiHash - The API hash you obtained from https://my.telegram.org.
75
+ * @param clientParams - see {@link TelegramClientParams}
76
+ */
77
+ constructor(session, apiId, apiHash, clientParams) {
78
+ super(session, apiId, apiHash, clientParams);
79
+ }
80
+ // region auth
81
+ /**
82
+ * Used to handle all aspects of connecting to telegram.<br/>
83
+ * This method will connect to the telegram servers and check if the user is already logged in.<br/>
84
+ * in the case of a new connection this will sign in if the phone already exists or sign up otherwise<br/>
85
+ * By using this method you are **agreeing to Telegram's Terms of Service** https://core.telegram.org/api/terms.<br/>
86
+ * this method also calls {@link getMe} to tell telegram that we want to receive updates.<br/>
87
+ * @param authParams - see UserAuthParams and BotAuthParams
88
+ * @return nothing
89
+ * @example
90
+ * ```ts
91
+ * // this example assumes you've installed and imported the input package. npm i input.
92
+ * // This package uses CLI to receive input from the user. you can use your own callback function.
93
+ * import { TelegramClient } from "teleproto";
94
+ * import { StringSession } from "teleproto/sessions";
95
+ *
96
+ * const client = new TelegramClient(new StringSession(''), apiId, apiHash, {});
97
+ * // logging in as a bot account
98
+ * await client.start(botToken="123456:abcdfgh123456789);
99
+ * // logging in as a user account
100
+ * await client.start({
101
+ * phoneNumber: async () => await input.text("number ?"),
102
+ * password: async () => await input.text("password?"),
103
+ * phoneCode: async () => await input.text("Code ?"),
104
+ * onError: (err) => console.log(err),
105
+ * });
106
+ * >Number ? +1234567897
107
+ * >Code ? 12345
108
+ * >password ? 111111
109
+ * Logged in as user...
110
+ *
111
+ * You can now use the client instance to call other api requests.
112
+ */
113
+ start(authParams) {
114
+ return authMethods.start(this, authParams);
115
+ }
116
+ /**
117
+ * Checks whether the current client is authorized or not. (logged in as a user)
118
+ * @example
119
+ * ```ts
120
+ * await client.connect();
121
+ * if (await client.checkAuthorization()){
122
+ * console.log("I am logged in!");
123
+ * }else{
124
+ * console.log("I am connected to telegram servers but not logged in with any account/bot");
125
+ * }
126
+ * ```
127
+ * @return boolean (true of authorized else false)
128
+ */
129
+ checkAuthorization() {
130
+ return authMethods.checkAuthorization(this);
131
+ }
132
+ /**
133
+ * Logs in as a user. Should only be used when not already logged in.<br/>
134
+ * This method will send a code when needed.<br/>
135
+ * This will also sign up if needed.
136
+ * @example
137
+ * ```ts
138
+ * await client.connect();
139
+ * // we should only use this when we are not already authorized.
140
+ * // This function is very similar to `client.start`
141
+ * // The minor difference that start checks if already authorized and supports bots as well.
142
+ * if (!await client.checkAuthorization()){
143
+ * const phoneNumber = "+123456789";
144
+ * await client.signIn({
145
+ * apiId:132456,
146
+ * apiHash:"132456",
147
+ * },{
148
+ * phoneNumber: async () => await input.text("number ?"),
149
+ * password: async () => await input.text("password?"),
150
+ * phoneCode: async () => await input.text("Code ?"),
151
+ * onError: (err) => console.log(err),
152
+ * })
153
+ * }
154
+ * ```
155
+ * @param apiCredentials - credentials to be used.
156
+ * @param authParams - user auth params.
157
+ */
158
+ signInUser(apiCredentials, authParams) {
159
+ return authMethods.signInUser(this, apiCredentials, authParams);
160
+ }
161
+ /**
162
+ * logs the user using a QR code to be scanned.<br/>
163
+ * this function generates the QR code that needs to be scanned by mobile.
164
+ * @example
165
+ * '''ts
166
+ * await client.connect();
167
+ * const user = await client.signInUserWithQrCode({ apiId, apiHash },
168
+ * {
169
+ * onError: async function(p1: Error) {
170
+ * console.log("error", p1);
171
+ * // true = stop the authentication processes
172
+ * return true;
173
+ * },
174
+ * qrCode: async (code) => {
175
+ * console.log("Convert the next string to a QR code and scan it");
176
+ * console.log(
177
+ * `tg://login?token=${code.token.toString("base64url")}`
178
+ * );
179
+ * },
180
+ * password: async (hint) => {
181
+ * // password if needed
182
+ * return "1111";
183
+ * }
184
+ * }
185
+ * );
186
+ * console.log("user is", user);
187
+ *
188
+ * '''
189
+ * @param apiCredentials - credentials to be used.
190
+ * @param authParams - user auth params.
191
+ */
192
+ signInUserWithQrCode(apiCredentials, authParams) {
193
+ return authMethods.signInUserWithQrCode(this, apiCredentials, authParams);
194
+ }
195
+ /**
196
+ * Sends a telegram authentication code to the phone number.
197
+ * @example
198
+ * ```ts
199
+ * await client.connect();
200
+ * const {phoneCodeHash,isCodeViaApp} = await client.sendCode({
201
+ * apiId:1234,
202
+ * apiHash:"123456789abcfghj",
203
+ * },"+123456798"});
204
+ * ```
205
+ * @param apiCredentials - credentials to be used.
206
+ * @param phoneNumber - the phone number to send the code to
207
+ * @param forceSMS - whether to send it as an SMS or a normal in app message
208
+ * @return the phone code hash and whether it was sent via app
209
+ */
210
+ sendCode(apiCredentials, phoneNumber, forceSMS = false) {
211
+ return authMethods.sendCode(this, apiCredentials, phoneNumber, forceSMS);
212
+ }
213
+ /**
214
+ * Uses the 2FA password to sign in the account.<br/>
215
+ * This function should be used after the user has signed in with the code they received.
216
+ * @param apiCredentials - credentials to be used.
217
+ * @param authParams - user auth params.
218
+ * @returns the logged in user.
219
+ */
220
+ signInWithPassword(apiCredentials, authParams) {
221
+ return authMethods.signInWithPassword(this, apiCredentials, authParams);
222
+ }
223
+ /**
224
+ * Used to sign in as a bot.
225
+ * @example
226
+ * ```ts
227
+ * await client.connect();
228
+ * const bot = await client.signInBot({
229
+ * apiId:1234,
230
+ * apiHash:"12345",
231
+ * },{
232
+ * botToken:"123456:abcdfghae4fg654",
233
+ * });
234
+ * // we are now logged in as a bot
235
+ * console.log("Logged in",bot);
236
+ * ```
237
+ * @param apiCredentials - credentials to be used.
238
+ * @param authParams - user auth params.
239
+ * @return instance User of the logged in bot.
240
+ */
241
+ signInBot(apiCredentials, authParams) {
242
+ return authMethods.signInBot(this, apiCredentials, authParams);
243
+ }
244
+ /**
245
+ * Changes the 2FA settings of the logged in user.
246
+ Note that this method may be *incredibly* slow depending on the
247
+ prime numbers that must be used during the process to make sure
248
+ that everything is safe.
249
+
250
+ Has no effect if both current and new password are omitted.
251
+
252
+ * @param client: The telegram client instance
253
+ * @param isCheckPassword: Must be ``true`` if you want to check the current password
254
+ * @param currentPassword: The current password, to authorize changing to ``new_password``.
255
+ Must be set if changing existing 2FA settings.
256
+ Must **not** be set if 2FA is currently disabled.
257
+ Passing this by itself will remove 2FA (if correct).
258
+ * @param newPassword: The password to set as 2FA.
259
+ If 2FA was already enabled, ``currentPassword`` **must** be set.
260
+ Leaving this blank or `undefined` will remove the password.
261
+ * @param hint: Hint to be displayed by Telegram when it asks for 2FA.
262
+ Must be set when changing or creating a new password.
263
+ Has no effect if ``newPassword`` is not set.
264
+ * @param email: Recovery and verification email. If present, you must also
265
+ set `emailCodeCallback`, else it raises an Error.
266
+ * @param emailCodeCallback: If an email is provided, a callback that returns the code sent
267
+ to it must also be set. This callback may be asynchronous.
268
+ It should return a string with the code. The length of the
269
+ code will be passed to the callback as an input parameter.
270
+ * @param onEmailCodeError: Called when an error happens while sending an email.
271
+
272
+ If the callback returns an invalid code, it will raise an rpc error with the message
273
+ ``CODE_INVALID``
274
+
275
+ * @returns Promise<void>
276
+ * @throws this method can throw:
277
+ "PASSWORD_HASH_INVALID" if you entered a wrong password (or set it to undefined).
278
+ "EMAIL_INVALID" if the entered email is wrong
279
+ "EMAIL_HASH_EXPIRED" if the user took too long to verify their email
280
+ */
281
+ async updateTwoFaSettings({ isCheckPassword, currentPassword, newPassword, hint = "", email, emailCodeCallback, onEmailCodeError, }) {
282
+ return twoFA.updateTwoFaSettings(this, {
283
+ isCheckPassword,
284
+ currentPassword,
285
+ newPassword,
286
+ hint,
287
+ email,
288
+ emailCodeCallback,
289
+ onEmailCodeError,
290
+ });
291
+ }
292
+ //endregion auth
293
+ //region bot
294
+ /**
295
+ * Makes an inline query to the specified bot and gets the result list.<br/>
296
+ * This is equivalent to writing `@pic something` in clients
297
+ * @param bot - the bot entity to which the inline query should be made
298
+ * @param query - the query string that should be made for that bot (up to 512 characters). can be empty
299
+ * @param entity - The entity where the inline query is being made from.<br/>
300
+ * Certain bots use this to display different results depending on where it's used, such as private chats, groups or channels.<br/>
301
+ * If specified, it will also be the default entity where the message will be sent after clicked.<br/>
302
+ * Otherwise, the “empty peer” will be used, which some bots may not handle correctly.
303
+ * @param offset - String offset of the results to be returned. can be empty
304
+ * @param geoPoint - The geo point location information to send to the bot for localised results. Available under some bots.
305
+ * @return a list of InlineResults
306
+ * @example
307
+ * ```ts
308
+ * // Makes the query to @pic
309
+ * const results = await client.inlineQuery("pic", "something");
310
+ * // clicks on the first result
311
+ * await results[0].click();
312
+ * ```
313
+ */
314
+ inlineQuery(bot, query, entity, offset, geoPoint) {
315
+ return botMethods.inlineQuery(this, bot, query, entity, offset, geoPoint);
316
+ }
317
+ //endregion
318
+ //region buttons
319
+ /**
320
+ * Builds a ReplyInlineMarkup or ReplyKeyboardMarkup for the given buttons.<br/><br/>
321
+ * Does nothing if either no buttons are provided or the provided argument is already a reply markup.<br/><br/>
322
+ * this function is called internally when passing an array of buttons.
323
+
324
+ * @param buttons - The button, array of buttons, array of array of buttons or markup to convert into a markup.
325
+ * @param inlineOnly - Whether the buttons **must** be inline buttons only or not.
326
+ * @example
327
+ * ```ts
328
+ * import {Button} from "teleproto/tl/custom/button";
329
+ * // PS this function is not async
330
+ * const markup = client.buildReplyMarkup(Button.inline("Hello!"));
331
+ *
332
+ * await client.sendMessage(chat, {
333
+ * message: "click me!",
334
+ * buttons: markup,
335
+ * }
336
+ *
337
+ * // The following example can also be used in a simpler way like so
338
+ *
339
+ * await client.sendMessage(chat, {
340
+ * message: "click me!",
341
+ * buttons: [Button.inline("Hello!")],
342
+ * }
343
+ * ```
344
+ */
345
+ buildReplyMarkup(buttons, inlineOnly = false) {
346
+ return buttonsMethods.buildReplyMarkup(buttons, inlineOnly);
347
+ }
348
+ //endregion
349
+ //region download
350
+ /**
351
+ * Low-level method to download files from their input location.
352
+ * downloadMedia should generally be used over this.
353
+ * @param inputLocation - The file location from which the file will be downloaded. See getInputLocation source for a complete list of supported types.
354
+ * @param fileParams - {@link DownloadFileParams}
355
+ * @return a Buffer downloaded from the inputFile.
356
+ * @example
357
+ * ```ts
358
+ * const photo = message.photo;
359
+ * const buffer = await client.downloadFile(
360
+ * new Api.InputPhotoFileLocation({
361
+ * id: photo.id,
362
+ * accessHash: photo.accessHash,
363
+ * fileReference: photo.fileReference,
364
+ * thumbSize: size.type
365
+ * }),
366
+ * {
367
+ * dcId: photo.dcId,
368
+ * fileSize: "m",
369
+ * }
370
+ * );
371
+ * ```
372
+ */
373
+ downloadFile(inputLocation, fileParams = {}) {
374
+ return downloadMethods.downloadFileV2(this, inputLocation, fileParams);
375
+ }
376
+ /**
377
+ * Iterates over a file download, yielding chunks of the file.
378
+ * This method can be used to stream files in a more convenient way, since it offers more control (pausing, resuming, etc.)
379
+ * @param iterFileParams - {@link IterDownloadFunction}
380
+ * @return a Buffer downloaded from the inputFile.
381
+ * @example
382
+ * ```ts
383
+ * const photo = message.photo;
384
+ * for await (const chunk of client.iterDownload({
385
+ * file: new Api.InputPhotoFileLocation({
386
+ * id: photo.id,
387
+ * accessHash: photo.accessHash,
388
+ * fileReference: photo.fileReference,
389
+ * thumbSize: size.type
390
+ * }),
391
+ * offset: start,
392
+ * limit: end,
393
+ * requestSize:2048*1024
394
+ * )){
395
+ * console.log("Downloaded chunk of size",chunk.length);
396
+ * };
397
+ * ```
398
+ */
399
+ iterDownload(iterFileParams) {
400
+ return downloadMethods.iterDownload(this, iterFileParams);
401
+ }
402
+ //region download
403
+ /**
404
+ * Downloads the profile photo from the given user,chat or channel.<br/>
405
+ * This method will return an empty buffer in case of no profile photo.
406
+ * @param entity - where to download the photo from.
407
+ * @param downloadProfilePhotoParams - {@link DownloadProfilePhotoParams}
408
+ * @return buffer containing the profile photo. can be empty in case of no profile photo.
409
+ * @example
410
+ * ```ts
411
+ * // Download your own profile photo
412
+ * const buffer = await client.downloadProfilePhoto('me')
413
+ * console.log("Downloaded image is",buffer);
414
+ * // if you want to save it as a file you can use the fs module on node for that.
415
+ * import { promises as fs } from 'fs';
416
+ * await fs.writeFile("picture.jpg",buffer);
417
+ * ```
418
+ */
419
+ downloadProfilePhoto(entity, downloadProfilePhotoParams = {
420
+ isBig: false,
421
+ }) {
422
+ return downloadMethods.downloadProfilePhoto(this, entity, downloadProfilePhotoParams);
423
+ }
424
+ /**
425
+ * Downloads the given media from a message or a media object.<br/>
426
+ * this will return an empty Buffer in case of wrong or empty media.
427
+ * @param messageOrMedia - instance of a message or a media.
428
+ * @param downloadParams {@link DownloadMediaInterface}
429
+ * @return a buffer containing the downloaded data if outputFile is undefined else nothing.
430
+ * @example ```ts
431
+ * const buffer = await client.downloadMedia(message, {})
432
+ * // to save it to a file later on using fs.
433
+ * import { promises as fs } from 'fs';
434
+ * await fs.writeFile("file",buffer);
435
+ * // to use a progress callback you can pass it like so.
436
+ * const buffer = await client.downloadMedia(message, {
437
+ * progressCallback : console.log
438
+ * })
439
+ * ```
440
+ */
441
+ downloadMedia(messageOrMedia, downloadParams) {
442
+ return downloadMethods.downloadMedia(this, messageOrMedia, downloadParams === null || downloadParams === void 0 ? void 0 : downloadParams.outputFile, downloadParams === null || downloadParams === void 0 ? void 0 : downloadParams.thumb, downloadParams === null || downloadParams === void 0 ? void 0 : downloadParams.progressCallback);
443
+ }
444
+ //endregion
445
+ //region message parse
446
+ /**
447
+ * This property is the default parse mode used when sending messages. Defaults to {@link MarkdownParser}.<br/>
448
+ * It will always be either undefined or an object with parse and unparse methods.<br/>
449
+ * When setting a different value it should be one of:<br/>
450
+ *<br/>
451
+ * - Object with parse and unparse methods.<br/>
452
+ * - A str indicating the parse_mode. For Markdown 'md' or 'markdown' may be used. For HTML, 'html' may be used.<br/>
453
+ * The parse method should be a function accepting a single parameter, the text to parse, and returning a tuple consisting of (parsed message str, [MessageEntity instances]).<br/>
454
+ * <br/>
455
+ * The unparse method should be the inverse of parse such that text == unparse(parse(text)).<br/>
456
+ * <br/>
457
+ * See {@link Api.TypeMessageEntity} for allowed message entities.
458
+ * @example
459
+ * ```ts
460
+ * // gets the current parse mode.
461
+ * console.log("parse mode is :", client.parseMode)
462
+ * ```
463
+ */
464
+ get parseMode() {
465
+ return this._parseMode;
466
+ }
467
+ /** Setter for parseMode.
468
+ * {@link parseMode}
469
+ * @param mode can be md,markdown for Markdown or html for html. can also pass a custom mode.
470
+ * pass undefined for no parsing.
471
+ * @example
472
+ * // sets the mode to HTML
473
+ * client.setParseMode("html");
474
+ * await client.sendMessage("me",{message:"<u>This is an underline text</u>"});
475
+ * // disable formatting
476
+ * client.setParseMode(undefined);
477
+ * await client.sendMessage("me",{message:"<u> this will be sent as it is</u> ** with no formatting **});
478
+ */
479
+ setParseMode(mode) {
480
+ if (mode) {
481
+ this._parseMode = (0, Utils_1.sanitizeParseMode)(mode);
482
+ }
483
+ else {
484
+ this._parseMode = undefined;
485
+ }
486
+ }
487
+ //endregion
488
+ // region messages
489
+ /**
490
+ * Iterates over the messages for a given chat.
491
+ * <br/>
492
+ * The default order is from newest to oldest but can be changed with the reverse param.<br/>
493
+ * If either `search`, `filter` or `fromUser` are provided this will use {@link Api.messages.Search} instead of {@link Api.messages.GetHistory}.
494
+ * @remarks
495
+ * Telegram limits GetHistory requests every 10 requests (1 000 messages) therefore a sleep of 1 seconds will be the default for this limit.
496
+ * @param entity - The entity from whom to retrieve the message history.<br/>
497
+ * It may be undefined to perform a global search, or to get messages by their ID from no particular chat<br/>
498
+ * **Note** that some of the offsets will not work if this is the case.<br/>
499
+ * **Note** that if you want to perform a global search, you must set a non-empty search string, a filter. or fromUser.
500
+ * @param iterParams - {@link IterMessagesParams}
501
+ * @yield Instances of custom {@link Message}
502
+ * @example
503
+ * ```ts
504
+ * // From most-recent to oldest
505
+ * for await (const message of client.iterMessages(chat,{}){
506
+ * console.log(message.id, message.text)
507
+ * }
508
+ *
509
+ * // From oldest to most-recent
510
+ * for await (const message of client.iterMessages(chat,{reverse:true}){
511
+ * console.log(message.id, message.text)
512
+ * }
513
+ *
514
+ * // Filter by sender
515
+ * for await (const message of client.iterMessages(chat,{fromUser:"me"}){
516
+ * console.log(message.id, message.text)
517
+ * }
518
+ *
519
+ * // Server-side search with fuzzy text
520
+ * for await (const message of client.iterMessages(chat,{search:"hello"}){
521
+ * console.log(message.id, message.text)
522
+ * }
523
+ *
524
+ * // Filter by message type:
525
+ * import { Api } from "teleproto";
526
+ * for await (const message of client.iterMessages(chat,{filter: Api.InputMessagesFilterPhotos}){
527
+ * console.log(message.id, message.photo)
528
+ * }
529
+ *
530
+ * // Getting comments from a post in a channel:
531
+ * * for await (const message of client.iterMessages(chat,{replyTo: 123}){
532
+ * console.log(message.chat.title,, message.text)
533
+ * }
534
+ * ```
535
+ */
536
+ iterMessages(entity, iterParams = {}) {
537
+ return messageMethods.iterMessages(this, entity, iterParams);
538
+ }
539
+ /**
540
+ * Same as iterMessages() but returns a TotalList instead.<br/>
541
+ * if the `limit` is not set, it will be 1 by default unless both `minId` **and** `maxId` are set. in which case the entire range will be returned.<br/>
542
+ * @param entity - The entity from whom to retrieve the message history. see {@link iterMessages}.<br/>
543
+ * @param getMessagesParams - see {@link IterMessagesParams}.
544
+ * @return {@link TotalList} of messages.
545
+ * @example
546
+ * ```ts
547
+ * // The totalList has a .total attribute which will show the complete number of messages even if none are fetched.
548
+ * // Get 0 photos and print the total to show how many photos there are
549
+ * import { Api } from "teleproto";
550
+ * const photos = await client.getMessages(chat, {limit: 0, filter:Api.InputMessagesFilterPhotos})
551
+ * console.log(photos.total)
552
+ *
553
+ * // Get all the photos
554
+ * const photos = await client.getMessages(chat, {limit: undefined, filter:Api.InputMessagesFilterPhotos})
555
+ *
556
+ // Get messages by ID:
557
+ * const messages = await client.getMessages(chat, {ids:1337})
558
+ * const message_1337 = messages[0];
559
+ * ```
560
+ */
561
+ getMessages(entity, getMessagesParams = {}) {
562
+ return messageMethods.getMessages(this, entity, getMessagesParams);
563
+ }
564
+ /**
565
+ * Sends a message to the specified user, chat or channel.<br/>
566
+ * The default parse mode is the same as the official applications (a custom flavour of markdown). **bold**, `code` or __italic__ are available.<br/>
567
+ * In addition you can send [links](https://example.com) and [mentions](@username) (or using IDs like in the Bot API: [mention](tg://user?id=123456789)) and pre blocks with three backticks.<br/>
568
+ * <br/>
569
+ * Sending a /start command with a parameter (like ?start=data) is also done through this method. Simply send '/start data' to the bot.<br/>
570
+ * <br/>
571
+ * See also Message.respond() and Message.reply().
572
+ *
573
+ * @param entity - Who to sent the message to.
574
+ * @param sendMessageParams - see {@link SendMessageParams}
575
+ * @return
576
+ * The sent custom Message.
577
+ * @example
578
+ * ```ts
579
+ * // Markdown is the default.
580
+ * await client.sendMessage("me",{message:"Hello **world!**});
581
+ *
582
+ * // Defaults to another parse mode.
583
+ * client.setParseMode("HTML");
584
+ *
585
+ * await client.sendMessage('me', {message:'Some <b>bold</b> and <i>italic</i> text'})
586
+ * await client.sendMessage('me', {message:'An <a href="https://example.com">URL</a>'})
587
+ * await client.sendMessage('me', {message:'<a href="tg://user?id=me">Mentions</a>'})
588
+ *
589
+ * // Explicit parse mode.
590
+ * // No parse mode by default
591
+ * client.setParseMode(undefined);
592
+ * //...but here I want markdown
593
+ * await client.sendMessage('me', {message:'Hello, **world**!', {parseMode:"md"}})
594
+ *
595
+ * // ...and here I need HTML
596
+ * await client.sendMessage('me', {message:'Hello, <i>world</i>!', {parseMode='html'}})
597
+ *
598
+ *
599
+ * // Scheduling a message to be sent after 5 minutes
600
+ *
601
+ * await client.sendMessage(chat, {message:'Hi, future!', schedule:(60 * 5) + (Date.now() / 1000)})
602
+ *
603
+ * ```
604
+ */
605
+ sendMessage(entity, sendMessageParams = {}) {
606
+ return messageMethods.sendMessage(this, entity, sendMessageParams);
607
+ }
608
+ /**
609
+ * Forwards the given messages to the specified entity.<br/>
610
+ *<br/>
611
+ * If you want to "forward" a message without the forward header
612
+ * (the "forwarded from" text), you should use `sendMessage` with
613
+ * the original message instead. This will send a copy of it.
614
+ *<br/>
615
+ * See also {@link Message.forwardTo}`.
616
+ * @param entity - To which entity the message(s) will be forwarded.
617
+ * @param forwardMessagesParams - see {@link ForwardMessagesParams}
618
+ * @return The list of forwarded Message, Note.<br/>
619
+ * if some messages failed to be forwarded the returned list will have them as undefined.
620
+ * @example ```ts
621
+ * // a single one
622
+ * await client.forwardMessages(chat, {messages: message});
623
+ * // or
624
+ * await client.forwardMessages(chat, {messages:messageId,fromPeer:fromChat});
625
+ * // or
626
+ * await message.forwardTo(chat)
627
+ *
628
+ * // multiple
629
+ * await client.forwardMessages(chat, {messages:messages});
630
+ * // or
631
+ * await client.forwardMessages(chat, {messages:messageIds,fromPeer:fromChat});
632
+ *
633
+ * // Forwarding as a copy
634
+ * await client.sendMessage(chat, {message:message});
635
+ * ```
636
+ */
637
+ forwardMessages(entity, forwardMessagesParams) {
638
+ return messageMethods.forwardMessages(this, entity, forwardMessagesParams);
639
+ }
640
+ /**
641
+ * Used to edit a message by changing it's text or media
642
+ * message refers to the message to be edited not what to edit
643
+ * text refers to the new text
644
+ * See also Message.edit()<br/>
645
+ * Notes: It is not possible to edit the media of a message that doesn't contain media.
646
+ * @param entity - From which chat to edit the message.<br/>
647
+ * This can also be the message to be edited, and the entity will be inferred from it, so the next parameter will be assumed to be the message text.<br/>
648
+ * You may also pass a InputBotInlineMessageID, which is the only way to edit messages that were sent after the user selects an inline query result. Not supported yet!
649
+ * @param editMessageParams - see {@link EditMessageParams}.
650
+ * @return The edited Message.
651
+ * @throws
652
+ * `MESSAGE_AUTHOR_REQUIRED` if you're not the author of the message but tried editing it anyway.
653
+ * `MESSAGE_NOT_MODIFIED` if the contents of the message were not modified at all.
654
+ * `MESSAGE_ID_INVALID` if the ID of the message is invalid (the ID itself may be correct, but the message with that ID cannot be edited).<br/>
655
+ * For example, when trying to edit messages with a reply markup (or clear markup) this error will be raised.
656
+ * @example
657
+ * ```ts
658
+ * const message = await client.sendMessage(chat,{message:"Hi!"});
659
+ *
660
+ * await client.editMessage(chat,{message:message,text:"Hello!"}
661
+ * // or
662
+ * await client.editMessage(chat,{message:message.id,text:"Hello!"}
663
+ * ```
664
+ */
665
+ editMessage(entity, editMessageParams) {
666
+ return messageMethods.editMessage(this, entity, editMessageParams);
667
+ }
668
+ /**
669
+ * Deletes the given messages, optionally "for everyone".
670
+ *
671
+ * See also {@link Message.delete}`.
672
+ *
673
+ * @remarks This method does **not** validate that the message IDs belong to the chat that you passed! It's possible for the method to delete messages from different private chats and small group chats at once, so make sure to pass the right IDs.
674
+ * @param entity - From who the message will be deleted. This can actually be `undefined` for normal chats, but **must** be present for channels and megagroups.
675
+ * @param messageIds - The IDs (or ID) or messages to be deleted.
676
+ * @param revoke - Whether the message should be deleted for everyone or not.
677
+ * By default it has the opposite behaviour of official clients,
678
+ * and it will delete the message for everyone.
679
+ * Disabling this has no effect on channels or megagroups,
680
+ * since it will unconditionally delete the message for everyone.
681
+ * @return
682
+ * A list of {@link AffectedMessages}, each item being the result for the delete calls of the messages in chunks of 100 each.
683
+ * @example
684
+ * ```ts
685
+ * await client.deleteMessages(chat, messages);
686
+ *
687
+ * await client.deleteMessages(chat, messages, {revoke:false});
688
+ * ```
689
+ */
690
+ deleteMessages(entity, messageIds, { revoke = true }) {
691
+ return messageMethods.deleteMessages(this, entity, messageIds, {
692
+ revoke: revoke,
693
+ });
694
+ }
695
+ pinMessage(entity, message, pinMessageParams) {
696
+ return messageMethods.pinMessage(this, entity, message, pinMessageParams);
697
+ }
698
+ unpinMessage(entity, message, unpinMessageParams) {
699
+ return messageMethods.unpinMessage(this, entity, message, unpinMessageParams);
700
+ }
701
+ /**
702
+ * Marks messages as read and optionally clears mentions. <br/>
703
+ * This effectively marks a message as read (or more than one) in the given conversation. <br />
704
+ * If a message or maximum ID is provided, all the messages up to and
705
+ * including such ID will be marked as read (for all messages whose ID ≤ max_id).
706
+ *
707
+ * See also {@link Message.markRead}`.
708
+ *
709
+ * @remarks If neither message nor maximum ID are provided, all messages will be marked as read by assuming that `max_id = 0`.
710
+ * @param entity - The chat where the message should be pinned.
711
+ * @param message - The message or the message ID to pin. If it's `undefined`, all messages will be unpinned instead.
712
+ * @param markAsReadParams - see {@link MarkAsReadParams}.
713
+ * @return boolean
714
+ * @example
715
+ * ```ts
716
+ * // using a Message object
717
+ * const message = await client.sendMessage(chat, 'teleproto is awesome!');
718
+ * await client.markAsRead(chat, message)
719
+ * // ...or using the int ID of a Message
720
+ * await client.markAsRead(chat, message.id);
721
+ *
722
+ * // ...or passing a list of messages to mark as read
723
+ * await client.markAsRead(chat, messages)
724
+ * ```
725
+ */
726
+ markAsRead(entity, message, markAsReadParams) {
727
+ return messageMethods.markAsRead(this, entity, message, markAsReadParams);
728
+ }
729
+ //endregion
730
+ //region dialogs
731
+ /**
732
+ * Iterator over the dialogs (open conversations/subscribed channels) sequentially.<br/>
733
+ * The order is the same as the one seen in official applications. (dialogs that had recent messages come first)
734
+ * @param iterDialogsParams - see {@link IterDialogsParams}
735
+ * @yield instances of custom {@link Dialog}.
736
+ * @example
737
+ * ```ts
738
+ * // logs all dialog IDs and their title.
739
+ * for await (const dialog of client.iterDialogs({})){
740
+ * console.log(`${dialog.id}: ${dialog.title}`);
741
+ * }
742
+ * ```
743
+ */
744
+ iterDialogs(iterDialogsParams = {}) {
745
+ return dialogMethods.iterDialogs(this, iterDialogsParams);
746
+ }
747
+ /**
748
+ * Same as iterDialogs but returns a TotalList instead of an iterator.
749
+ * @param params - {@link IterDialogsParams}
750
+ * @example
751
+ * ```ts
752
+ * // Get all open conversation, print the title of the first
753
+ * const dialogs = await client.getDialogs({});
754
+ * const first = dialogs[0];
755
+ * console.log(first.title);
756
+ * <br/>
757
+ * // Use the dialog somewhere else
758
+ * await client.sendMessage(first, {message: "hi"});
759
+ * <br/>
760
+ * // Getting only non-archived dialogs (both equivalent)
761
+ * non_archived = await client.get_dialogs({folder:0})
762
+ * non_archived = await client.get_dialogs({archived:false})
763
+ * <br/>
764
+ * // Getting only archived dialogs (both equivalent)
765
+ * archived = await client.get_dialogs({folder:1})
766
+ * archived = await client.get_dialogs({archived:true})
767
+ * ```
768
+ */
769
+ getDialogs(params = {}) {
770
+ return dialogMethods.getDialogs(this, params);
771
+ }
772
+ //endregion
773
+ //region chats
774
+ /**
775
+ * Iterates over the participants belonging to a specified chat , channel or supergroup.<br/>
776
+ * <br/>
777
+ * Channels can return a maximum of 200 users while supergroups can return up to 10 000.<br/>
778
+ * You must be an admin to retrieve users from a channel.<br/>
779
+ * @param entity - The entity from which to retrieve the participants list.
780
+ * @param params - {@link IterParticipantsParams}
781
+ * @remarks
782
+ * The filter ChannelParticipantsBanned will return restricted users. If you want banned users you should use ChannelParticipantsKicked instead.
783
+ * @yield The User objects returned by GetParticipants with an additional .participant attribute<br/>
784
+ * which is the matched ChannelParticipant type for channels/supergroup or ChatParticipants for normal chats.
785
+ * @example
786
+ * ```ts
787
+ * // logs all user IDs in a chat.
788
+ * for await (const user of client.iterParticipants(chat)){
789
+ * console.log("User id",user.id);
790
+ * }
791
+ *
792
+ * // Searches by name.
793
+ * for await (const user of client.iterParticipants(chat, {search: "name"})){
794
+ * console.log("Username is ",user.username); // Some users don't have a username so this can be undefined.
795
+ * }
796
+ *
797
+ * // Filter by admins.
798
+ * import { Api } from "teleproto";
799
+ *
800
+ * for await (const user of client.iterParticipants(chat, {filter: Api.ChannelParticipantsAdmins})){
801
+ * console.log("admin first name is ",user.firstName);
802
+ * }
803
+ * ```
804
+ */
805
+ iterParticipants(entity, params = {}) {
806
+ return chatMethods.iterParticipants(this, entity, params);
807
+ }
808
+ /**
809
+ * Exact same as iterParticipants but returns a TotalList instead.<br/>
810
+ * This can be used if you want to retrieve a list instead of iterating over the users.
811
+ * @param entity - entity to get users from.
812
+ * @param params - {@link IterParticipantsParams}.
813
+ * @return
814
+ */
815
+ getParticipants(entity, params = {}) {
816
+ return chatMethods.getParticipants(this, entity, params);
817
+ }
818
+ /**
819
+ * Kicks a user from a chat.
820
+ *
821
+ * Kicking yourself (`'me'`) will result in leaving the chat.
822
+ *
823
+ * @note
824
+ * Attempting to kick someone who was banned will remove their
825
+ * restrictions (and thus unbanning them), since kicking is just
826
+ * ban + unban.
827
+ *
828
+ * @example
829
+ * // Kick some user from some chat, and deleting the service message
830
+ * const msg = await client.kickParticipant(chat, user);
831
+ * await msg.delete();
832
+ *
833
+ * // Leaving chat
834
+ * await client.kickParticipant(chat, 'me');
835
+ */
836
+ kickParticipant(entity, participant) {
837
+ return chatMethods.kickParticipant(this, entity, participant);
838
+ }
839
+ //endregion
840
+ //region updates
841
+ /** TODO */
842
+ on(event) {
843
+ return updateMethods.on(this, event);
844
+ }
845
+ addEventHandler(callback, event) {
846
+ return updateMethods.addEventHandler(this, callback, event);
847
+ }
848
+ /**
849
+ * Inverse operation of addEventHandler().<br>
850
+ *
851
+ * @param callback - the callback function to be removed.
852
+ * @param event - the type of the event.
853
+ */
854
+ removeEventHandler(callback, event) {
855
+ return updateMethods.removeEventHandler(this, callback, event);
856
+ }
857
+ /**
858
+ * Lists all registered event handlers.
859
+ * @return pair of [eventBuilder,CallableFunction]
860
+ */
861
+ listEventHandlers() {
862
+ return updateMethods.listEventHandlers(this);
863
+ }
864
+ // region uploads
865
+ /**
866
+ * Uploads a file to Telegram's servers, without sending it.
867
+ * @remarks generally it's better to use {@link sendFile} instead.
868
+ * This method returns a handle (an instance of InputFile or InputFileBig, as required) which can be later used before it expires (they are usable during less than a day).<br/>
869
+ * Uploading a file will simply return a "handle" to the file stored remotely in the Telegram servers,
870
+ * which can be later used on. This will not upload the file to your own chat or any chat at all.
871
+ * This also can be used to update profile pictures
872
+ * @param fileParams see {@link UploadFileParams}
873
+ * @return {@link Api.InputFileBig} if the file size is larger than 10mb otherwise {@link Api.InputFile}
874
+ * @example
875
+ * ```ts
876
+ * import { CustomFile } from "teleproto/client/uploads";
877
+ * const toUpload = new CustomFile("photo.jpg", fs.statSync("../photo.jpg").size, "../photo.jpg");
878
+ * const file = await client.uploadFile({
879
+ * file: toUpload,
880
+ * workers: 1,
881
+ * });
882
+ * await client.invoke(new Api.photos.UploadProfilePhoto({
883
+ * file: file,
884
+ * }));
885
+ * ```
886
+ */
887
+ uploadFile(fileParams) {
888
+ return uploadMethods.uploadFile(this, fileParams);
889
+ }
890
+ /**
891
+ * Sends message with the given file to the specified entity.
892
+ * This uses {@link uploadFile} internally so if you want more control over uploads you can use that.
893
+ * @param entity - who will receive the file.
894
+ * @param sendFileParams - see {@link SendFileInterface}
895
+ * @example
896
+ * ```
897
+ * // Normal files like photos
898
+ * await client.sendFile(chat, {file:'/my/photos/me.jpg', caption:"It's me!"})
899
+ * // or
900
+ * await client.sendMessage(chat, {message:"It's me!", file:'/my/photos/me.jpg'})
901
+ *
902
+ * Voice notes or round videos
903
+ * await client.sendFile(chat, {file: '/my/songs/song.mp3', voiceNote:True})
904
+ * await client.sendFile(chat, {file: '/my/videos/video.mp4', videoNote:True})
905
+ *
906
+ * // Custom thumbnails
907
+ * await client.sendFile(chat, {file:'/my/documents/doc.txt', thumb:'photo.jpg'})
908
+ *
909
+ * // Only documents
910
+ * await client.sendFile(chat, {file:'/my/photos/photo.png', forceDocument:True})
911
+ *
912
+ * //logging progress
913
+ * await client.sendFile(chat, {file: file, progressCallback=console.log})
914
+ *
915
+ * // Dices, including dart and other future emoji
916
+ * await client.sendFile(chat, {file:new Api.InputMediaDice("")})
917
+ * await client.sendFile(chat, {file:new Api.InputMediaDice("🎯")})
918
+ *
919
+ * // Contacts
920
+ * await client.sendFile(chat, {file: new Api.InputMediaContact({
921
+ * phoneNumber:'+1 123 456 789',
922
+ * firstName:'Example',
923
+ * lastName:'',
924
+ * vcard:''
925
+ * }))
926
+ * ```
927
+ */
928
+ sendFile(entity, sendFileParams) {
929
+ return uploadMethods.sendFile(this, entity, sendFileParams);
930
+ }
931
+ // endregion
932
+ //region user methods
933
+ /**
934
+ * invokes raw Telegram requests.<br/>
935
+ * This is a low level method that can be used to call manually any Telegram API method.<br/>
936
+ * Generally this should only be used when there isn't a friendly method that does what you need.<br/>
937
+ * All available requests and types are found under the `Api.` namespace.
938
+ * @param request - The request to send. this should be of type request.
939
+ * @param dcId - Optional dc id to use when sending.
940
+ * @return The response from Telegram.
941
+ * @example
942
+ * ```ts
943
+ * //
944
+ * const result = await client.invoke(new Api.account.CheckUsername({
945
+ * username: 'some string here'
946
+ * }));
947
+ * console.log("does this username exist?",result);
948
+ *
949
+ * ```
950
+ */
951
+ invoke(request, dcId) {
952
+ return userMethods.invoke(this, request, dcId);
953
+ }
954
+ invokeWithSender(request, sender) {
955
+ return userMethods.invoke(this, request, undefined, sender);
956
+ }
957
+ getMe(inputPeer = false) {
958
+ return userMethods.getMe(this, inputPeer);
959
+ }
960
+ /**
961
+ * Return true if the signed-in user is a bot, false otherwise.
962
+ * @example
963
+ * ```ts
964
+ * if (await client.isBot()){
965
+ * console.log("I am a bot. PI is 3.14159265359);
966
+ * } else {
967
+ * console.log("I am a human. Pies are delicious);
968
+ * }
969
+ * ```
970
+ */
971
+ isBot() {
972
+ return userMethods.isBot(this);
973
+ }
974
+ /**
975
+ * Returns true if the user is authorized (logged in).
976
+ * @example
977
+ * if (await client.isUserAuthorized()){
978
+ * console.log("I am authorized. I can call functions and use requests");
979
+ * }else{
980
+ * console.log("I am not logged in. I need to sign in first before being able to call methods");
981
+ * }
982
+ */
983
+ isUserAuthorized() {
984
+ return userMethods.isUserAuthorized(this);
985
+ }
986
+ getEntity(entity) {
987
+ return userMethods.getEntity(this, entity);
988
+ }
989
+ /**
990
+ * Turns the given entity into its input entity version.<br/>
991
+ * Almost all requests use this kind of InputPeer, so this is the most suitable call to make for those cases.<br/>
992
+ * **Generally you should let the library do its job** and don't worry about getting the input entity first, but if you're going to use an entity often, consider making the call.
993
+ * @param entity - If a username or invite link is given, the library will use the cache.<br/>
994
+ * This means that it's possible to be using a username that changed or an old invite link (this only happens if an invite link for a small group chat is used after it was upgraded to a mega-group).
995
+ *<br/>
996
+ * - If the username or ID from the invite link is not found in the cache, it will be fetched. The same rules apply to phone numbers ('+34 123456789') from people in your contact list.
997
+ *<br/>
998
+ * - If an exact name is given, it must be in the cache too. This is not reliable as different people can share the same name and which entity is returned is arbitrary,<br/>
999
+ * and should be used only for quick tests.
1000
+ *<br/>
1001
+ * - If a positive integer ID is given, the entity will be searched in cached users, chats or channels, without making any call.
1002
+ *<br/>
1003
+ * - If a negative integer ID is given, the entity will be searched exactly as either a chat (prefixed with -) or as a channel (prefixed with -100).
1004
+ *<br/>
1005
+ * - If a Peer is given, it will be searched exactly in the cache as either a user, chat or channel.
1006
+ *<br/>
1007
+ * - If the given object can be turned into an input entity directly, said operation will be done.
1008
+ *<br/>
1009
+ * -If the entity can't be found, this will throw an error.
1010
+ * @return
1011
+ * {@link Api.InputPeerUser} , {@link Api.InputPeerChat} , {@link Api.InputPeerChannel} or {@link Api.InputPeerSelf} if the parameter is "me" or "self"
1012
+ * @example
1013
+ * ```ts
1014
+ * // If you're going to use "username" often in your code
1015
+ * // (make a lot of calls), consider getting its input entity
1016
+ * // once, and then using the "user" everywhere instead.
1017
+ * user = await client.getInputEntity('username')
1018
+ *
1019
+ * // The same applies to IDs, chats or channels.
1020
+ * chat = await client.getInputEntity(-123456789)
1021
+ * ```
1022
+ */
1023
+ getInputEntity(entity) {
1024
+ return userMethods.getInputEntity(this, entity);
1025
+ }
1026
+ /**
1027
+ * Gets the ID for the given entity.<br/>
1028
+ * This method needs to be async because peer supports usernames, invite-links, phone numbers (from people in your contact list), etc.<br/>
1029
+ * <br/>
1030
+ * If addMark is false, then a positive ID will be returned instead. By default, bot-API style IDs (signed) are returned.
1031
+ * @param peer
1032
+ * @param addMark - whether to return a bot api style id.
1033
+ * @return the ID of the entity.
1034
+ * @example
1035
+ * ```ts
1036
+ * console.log(await client.getPeerId("me"));
1037
+ * ```
1038
+ */
1039
+ getPeerId(peer, addMark = true) {
1040
+ return userMethods.getPeerId(this, peer, addMark);
1041
+ }
1042
+ /** @hidden */
1043
+ _getInputDialog(peer) {
1044
+ return userMethods._getInputDialog(this, peer);
1045
+ }
1046
+ /** @hidden */
1047
+ _getInputNotify(notify) {
1048
+ return userMethods._getInputNotify(this, notify);
1049
+ }
1050
+ //endregion
1051
+ /** @hidden */
1052
+ async _handleReconnect() {
1053
+ this._log.info("Handling reconnect!");
1054
+ try {
1055
+ const res = await this.getMe();
1056
+ }
1057
+ catch (e) {
1058
+ this._log.error(`Error while trying to reconnect`);
1059
+ if (this._errorHandler) {
1060
+ await this._errorHandler(e);
1061
+ }
1062
+ if (this._log.canSend(Logger_1.LogLevel.ERROR)) {
1063
+ console.error(e);
1064
+ }
1065
+ }
1066
+ }
1067
+ //region base methods
1068
+ async connect() {
1069
+ await this._initSession();
1070
+ if (this._sender === undefined) {
1071
+ this._sender = new network_1.MTProtoSender(this.session.getAuthKey(), {
1072
+ logger: this._log,
1073
+ dcId: this.session.dcId || 4,
1074
+ retries: this._connectionRetries,
1075
+ delay: this._retryDelay,
1076
+ autoReconnect: this._autoReconnect,
1077
+ connectTimeout: this._timeout,
1078
+ authKeyCallback: this._authKeyCallback.bind(this),
1079
+ updateCallback: updates_1._handleUpdate.bind(this),
1080
+ isMainSender: true,
1081
+ client: this,
1082
+ securityChecks: this._securityChecks,
1083
+ autoReconnectCallback: this._handleReconnect.bind(this),
1084
+ _exportedSenderPromises: this._exportedSenderPromises,
1085
+ reconnectRetries: this._reconnectRetries,
1086
+ });
1087
+ }
1088
+ const connection = new this._connection({
1089
+ ip: this.session.serverAddress,
1090
+ port: this.useWSS ? 443 : 80,
1091
+ dcId: this.session.dcId,
1092
+ loggers: this._log,
1093
+ proxy: this._proxy,
1094
+ socket: this.networkSocket,
1095
+ testServers: this.testServers,
1096
+ });
1097
+ if (!(await this._sender.connect(connection, false))) {
1098
+ if (!this._loopStarted) {
1099
+ (0, updates_1._updateLoop)(this);
1100
+ this._loopStarted = true;
1101
+ }
1102
+ return false;
1103
+ }
1104
+ this.session.setAuthKey(this._sender.authKey);
1105
+ this.session.save();
1106
+ this._initRequest.query = new tl_1.Api.help.GetConfig();
1107
+ this._log.info(`Using LAYER ${AllTLObjects_1.LAYER} for initial connect`);
1108
+ await this._sender.send(new tl_1.Api.InvokeWithLayer({
1109
+ layer: AllTLObjects_1.LAYER,
1110
+ query: this._initRequest,
1111
+ }));
1112
+ if (!this._loopStarted) {
1113
+ (0, updates_1._updateLoop)(this);
1114
+ this._loopStarted = true;
1115
+ }
1116
+ this._connectedDeferred.resolve();
1117
+ this._isSwitchingDc = false;
1118
+ return true;
1119
+ }
1120
+ //endregion
1121
+ // region Working with different connections/Data Centers
1122
+ /** @hidden */
1123
+ async _switchDC(newDc) {
1124
+ this._log.info(`Reconnecting to new data center ${newDc}`);
1125
+ const DC = await this.getDC(newDc);
1126
+ this.session.setDC(newDc, DC.ipAddress, DC.port);
1127
+ // authKey's are associated with a server, which has now changed
1128
+ // so it's not valid anymore. Set to undefined to force recreating it.
1129
+ await this._sender.authKey.setKey(undefined);
1130
+ this.session.setAuthKey(undefined);
1131
+ this.session.save();
1132
+ this._isSwitchingDc = true;
1133
+ await this._disconnect();
1134
+ this._sender = undefined;
1135
+ return await this.connect();
1136
+ }
1137
+ /**
1138
+ * Returns the DC ip in case of node or the DC web address in case of browser.<br/>
1139
+ * This will do an API request to fill the cache if it's the first time it's called.
1140
+ * @param dcId The DC ID.
1141
+ * @param downloadDC whether to use -1 DCs or not
1142
+ * @param web if true this will get the web DCs.
1143
+ * TODO, hardcode IPs.
1144
+ * (These only support downloading/uploading and not creating a new AUTH key)
1145
+ */
1146
+ async getDC(dcId, downloadDC = false, web = false) {
1147
+ this._log.debug(`Getting DC ${dcId}`);
1148
+ if (!this._config) {
1149
+ this._config = await this.invoke(new tl_1.Api.help.GetConfig());
1150
+ }
1151
+ for (const DC of this._config.dcOptions) {
1152
+ if (DC.id === dcId && !!DC.ipv6 === this._useIPV6) {
1153
+ return {
1154
+ id: DC.id,
1155
+ ipAddress: DC.ipAddress,
1156
+ port: 443,
1157
+ };
1158
+ }
1159
+ }
1160
+ throw new Error(`Cannot find the DC with the ID of ${dcId}`);
1161
+ }
1162
+ /** @hidden */
1163
+ _removeSender(dcId) {
1164
+ delete this._borrowedSenderPromises[dcId];
1165
+ }
1166
+ /** @hidden */
1167
+ _getResponseMessage(req, result, inputChat) {
1168
+ return parseMethods._getResponseMessage(this, req, result, inputChat);
1169
+ }
1170
+ /** @hidden */
1171
+ [inspect_1.inspect.custom]() {
1172
+ return (0, Helpers_1.betterConsoleLog)(this);
1173
+ }
1174
+ /**
1175
+ * Small hack for using it in browsers
1176
+ */
1177
+ static get events() {
1178
+ return require("../events");
1179
+ }
1180
+ }
1181
+ exports.TelegramClient = TelegramClient;