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