@wirecat/tg-cli 0.64.0 → 0.65.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 (99) hide show
  1. package/dist/commands/bot.d.ts.map +1 -1
  2. package/dist/commands/bot.js +14 -3
  3. package/dist/commands/bot.js.map +1 -1
  4. package/dist/commands/checks.d.ts +3 -0
  5. package/dist/commands/checks.d.ts.map +1 -0
  6. package/dist/commands/checks.js +21 -0
  7. package/dist/commands/checks.js.map +1 -0
  8. package/dist/commands/context.d.ts.map +1 -1
  9. package/dist/commands/context.js +7 -1
  10. package/dist/commands/context.js.map +1 -1
  11. package/dist/telegram/account.d.ts +29 -0
  12. package/dist/telegram/account.d.ts.map +1 -0
  13. package/dist/telegram/account.js +66 -0
  14. package/dist/telegram/account.js.map +1 -0
  15. package/dist/telegram/adapter.d.ts +66 -212
  16. package/dist/telegram/adapter.d.ts.map +1 -1
  17. package/dist/telegram/adapter.js +190 -1722
  18. package/dist/telegram/adapter.js.map +1 -1
  19. package/dist/telegram/bot-history.d.ts +2 -0
  20. package/dist/telegram/bot-history.d.ts.map +1 -1
  21. package/dist/telegram/bot-history.js +4 -4
  22. package/dist/telegram/bot-history.js.map +1 -1
  23. package/dist/telegram/chats.d.ts +30 -0
  24. package/dist/telegram/chats.d.ts.map +1 -0
  25. package/dist/telegram/chats.js +103 -0
  26. package/dist/telegram/chats.js.map +1 -0
  27. package/dist/telegram/contacts.d.ts +24 -0
  28. package/dist/telegram/contacts.d.ts.map +1 -0
  29. package/dist/telegram/contacts.js +82 -0
  30. package/dist/telegram/contacts.js.map +1 -0
  31. package/dist/telegram/errors.d.ts +4 -2
  32. package/dist/telegram/errors.d.ts.map +1 -1
  33. package/dist/telegram/errors.js +21 -14
  34. package/dist/telegram/errors.js.map +1 -1
  35. package/dist/telegram/feature.d.ts +52 -0
  36. package/dist/telegram/feature.d.ts.map +1 -0
  37. package/dist/telegram/feature.js +73 -0
  38. package/dist/telegram/feature.js.map +1 -0
  39. package/dist/telegram/folders.d.ts +11 -0
  40. package/dist/telegram/folders.d.ts.map +1 -0
  41. package/dist/telegram/folders.js +104 -0
  42. package/dist/telegram/folders.js.map +1 -0
  43. package/dist/telegram/groups.d.ts +101 -0
  44. package/dist/telegram/groups.d.ts.map +1 -0
  45. package/dist/telegram/groups.js +386 -0
  46. package/dist/telegram/groups.js.map +1 -0
  47. package/dist/telegram/join-requests.d.ts +2 -1
  48. package/dist/telegram/join-requests.d.ts.map +1 -1
  49. package/dist/telegram/join-requests.js +2 -2
  50. package/dist/telegram/join-requests.js.map +1 -1
  51. package/dist/telegram/login.d.ts +20 -0
  52. package/dist/telegram/login.d.ts.map +1 -0
  53. package/dist/telegram/login.js +113 -0
  54. package/dist/telegram/login.js.map +1 -0
  55. package/dist/telegram/messages.d.ts +134 -0
  56. package/dist/telegram/messages.d.ts.map +1 -0
  57. package/dist/telegram/messages.js +379 -0
  58. package/dist/telegram/messages.js.map +1 -0
  59. package/dist/telegram/polls.d.ts +23 -4
  60. package/dist/telegram/polls.d.ts.map +1 -1
  61. package/dist/telegram/polls.js +83 -3
  62. package/dist/telegram/polls.js.map +1 -1
  63. package/dist/telegram/proxy.d.ts +3 -1
  64. package/dist/telegram/proxy.d.ts.map +1 -1
  65. package/dist/telegram/proxy.js +2 -2
  66. package/dist/telegram/proxy.js.map +1 -1
  67. package/dist/telegram/registration.d.ts +5 -1
  68. package/dist/telegram/registration.d.ts.map +1 -1
  69. package/dist/telegram/registration.js +39 -8
  70. package/dist/telegram/registration.js.map +1 -1
  71. package/dist/telegram/send-as.d.ts +2 -1
  72. package/dist/telegram/send-as.d.ts.map +1 -1
  73. package/dist/telegram/send-as.js +2 -2
  74. package/dist/telegram/send-as.js.map +1 -1
  75. package/dist/telegram/sending.d.ts.map +1 -1
  76. package/dist/telegram/sending.js +2 -1
  77. package/dist/telegram/sending.js.map +1 -1
  78. package/dist/telegram/stats.d.ts +8 -2
  79. package/dist/telegram/stats.d.ts.map +1 -1
  80. package/dist/telegram/stats.js +54 -0
  81. package/dist/telegram/stats.js.map +1 -1
  82. package/dist/telegram/topics.d.ts +36 -0
  83. package/dist/telegram/topics.d.ts.map +1 -0
  84. package/dist/telegram/topics.js +276 -0
  85. package/dist/telegram/topics.js.map +1 -0
  86. package/dist/telegram/upload.d.ts.map +1 -1
  87. package/dist/telegram/upload.js +2 -1
  88. package/dist/telegram/upload.js.map +1 -1
  89. package/dist/telegram/watch.d.ts +13 -0
  90. package/dist/telegram/watch.d.ts.map +1 -0
  91. package/dist/telegram/watch.js +112 -0
  92. package/dist/telegram/watch.js.map +1 -0
  93. package/dist/update.d.ts +3 -23
  94. package/dist/update.d.ts.map +1 -1
  95. package/dist/update.js +10 -37
  96. package/dist/update.js.map +1 -1
  97. package/dist/version.d.ts +1 -1
  98. package/dist/version.js +1 -1
  99. package/package.json +2 -2
@@ -1,43 +1,31 @@
1
1
  import { chmodSync, existsSync, mkdirSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { format } from "node:util";
4
- import { ChatInviteLink, FileLocation, getMarkedPeerId, Long, MtcuteError, MtPeerNotFoundError, PeersIndex, TelegramClient, Message as TgMessage, tl, User, } from "@mtcute/node";
5
- import { CliError, isCliError } from "@wirecat/cli-base";
6
- import { observedCounters, pickChat, } from "@wirecat/cli-core";
7
- import { uploadBlob } from "@wirecat/cli-core/sends";
4
+ import { TelegramClient } from "@mtcute/node";
5
+ import * as account from "./account.js";
6
+ import * as chats from "./chats.js";
8
7
  import { commentsOf, discussionOf } from "./comments.js";
8
+ import * as contacts from "./contacts.js";
9
9
  import { backgroundError, toCliError } from "./errors.js";
10
- import { ruleFlags } from "./folder-rules.js";
10
+ import { bareCheck, messageNumber, unansweredText, unknownIfUnanswered, } from "./feature.js";
11
+ import * as folders from "./folders.js";
11
12
  import { formatHtml } from "./format-html.js";
12
13
  import { formatMarkdown } from "./format-markdown.js";
13
- import { answerJoinRequestOf, joinRequestsOf } from "./join-requests.js";
14
- import { ADMIN_RIGHT_FIELDS, answerId, attachmentsOf, checkSpoiler, eventOf, GROUP_SETTINGS, groupMembersCount, peerToChat, toAccount, toAccountSession, toChat, toDeletions, toFolder, toFormatted, toGroupCard, toGroupMember, toInputMedia, toInputPoll, toInviteLink, toInvitePreview, toLinkChat, toMember, toMessage, toMessageHit, toPoll, toReactionChange, toTopic, } from "./map.js";
15
- import { pollVotersOf } from "./poll-voters.js";
16
- import { refuseClose, refuseVote } from "./polls.js";
17
- import { toProfileFacts } from "./profile.js";
14
+ import * as groups from "./groups.js";
15
+ import * as login from "./login.js";
16
+ import { toMessage } from "./map.js";
17
+ import * as messages from "./messages.js";
18
+ import * as polls from "./polls.js";
18
19
  import { proxiedTransport } from "./proxy.js";
19
- import { savedSenderOf, sendAsIdentities, sendAsPeer } from "./send-as.js";
20
+ import { savedSenderOf, sendAsIdentities } from "./send-as.js";
20
21
  import { middlewaresOf, sending } from "./sending.js";
21
- import { toOfficialChannelStats, toOfficialGraph, toOfficialGroupStats } from "./stats.js";
22
+ import * as stats from "./stats.js";
22
23
  import { openSessionStorage } from "./storage.js";
23
- import { uploadAttachment } from "./upload.js";
24
- /** `https://t.me/name`, `t.me/name` or `@name`, as the name alone. */
25
- const publicName = (link) => link
26
- .replace(/^(https?:\/\/)?(t\.me|telegram\.me)\//, "")
27
- .replace(/^@/, "")
28
- .replace(/[/?].*$/, "");
29
- const SAVED = new Set(["me", "self", "saved"]);
30
- const PHONE_CODE_RETRIES = ["PHONE_CODE_EMPTY", "PHONE_CODE_EXPIRED", "PHONE_CODE_INVALID", "PHONE_CODE_HASH_EMPTY"];
31
- /** Pages of one listing come about a second apart; a page asked for later than this reads fresh dialogs. */
32
- const DIALOG_WALK_KEPT_MS = 60_000;
33
- /** Telegram's own cap on a group's member list. */
34
- const MEMBERS_MAX = 10_000;
35
- /** Up to 50 pages of a big group back to back is the kind of burst Telegram answers with FLOOD_WAIT. */
36
- const MEMBER_PAGE_PAUSE_MS = 1000;
37
- /** Pages of 100 that `chats events` reads at most; the rest is `more`. */
38
- const EVENT_PAGES = 10;
39
- /** The Bot API's deleteMessages cap; assumed for MTProto's getMessages and deleteMessages, not checked against Telegram. */
40
- const BY_ID_BATCH = 100;
24
+ import * as topics from "./topics.js";
25
+ import * as watching from "./watch.js";
26
+ export { ADMIN_RIGHTS, GROUP_SETTINGS } from "./groups.js";
27
+ export { TRANSCRIBE_POLL_MS } from "./messages.js";
28
+ export { HEARTBEAT_TICKS, LOOP_CHECK_MS, STATE_WAIT_MS } from "./watch.js";
41
29
  /**
42
30
  * One Telegram account over one connection, speaking only the domain model above this line. Every
43
31
  * command closes it in a `finally`: an open socket keeps Node alive, and a piped command that prints
@@ -52,10 +40,9 @@ export class TelegramAdapter {
52
40
  }
53
41
  #client;
54
42
  #sessionPath;
55
- #login;
43
+ #feature;
56
44
  #proxyFailed;
57
- /** Where the last page of `chats` stopped; any other offset, a failure or a minute's gap starts a new walk. */
58
- #walk;
45
+ #walking = {};
59
46
  /** Async because the runtime's SQLite module is imported on demand (cli-core `openCache`). */
60
47
  static async open(options) {
61
48
  mkdirSync(dirname(options.sessionPath), { recursive: true, mode: 0o700 });
@@ -72,9 +59,8 @@ export class TelegramAdapter {
72
59
  }
73
60
  return adapter;
74
61
  }
75
- constructor({ credentials, sessionPath, diagnostic, verbose = false, listen = false, catchUp = false, login, proxy, note, }, storage) {
62
+ constructor({ credentials, sessionPath, diagnostic, verbose = false, listen = false, catchUp = false, login, proxy, note, checks = bareCheck, }, storage) {
76
63
  this.#sessionPath = sessionPath;
77
- this.#login = login;
78
64
  const proxied = proxy ? proxiedTransport(proxy) : undefined;
79
65
  // watch and serve outlive a proxy that is down for a moment; mtcute's own retries suit them.
80
66
  this.#proxyFailed = listen ? undefined : proxied?.failed;
@@ -94,159 +80,52 @@ export class TelegramAdapter {
94
80
  network: { middlewares: middlewaresOf(listen ? FLOOD_SLEEP.listening : FLOOD_SLEEP.oneShot, say) },
95
81
  });
96
82
  this.#client.log.mgr.handler = (_color, _level, tag, fmt, args) => write(`[${tag}] ${format(fmt, ...args)}`);
97
- this.#client.onError.add(backgroundError(write, verbose));
98
- }
99
- async login(prompts) {
100
- return this.#call(async () => {
101
- if (prompts.method === "phone" && prompts.forceSms)
102
- return toAccount(await this.#loginAskingForSms(prompts));
103
- const user = await this.#client.start({
104
- ...(prompts.method === "qr" ? { qrCodeHandler: prompts.showQr } : { phone: prompts.phone }),
105
- code: prompts.code,
106
- password: prompts.password,
107
- codeSentCallback: (sent) => prompts.note(`Telegram sent a login code (${sent.type})`),
108
- invalidCodeCallback: (what) => prompts.note(`that ${what} was not accepted — try again`),
109
- });
110
- return toAccount(user);
111
- });
112
- }
113
- /**
114
- * mtcute's `start({ forceSms })` without its one failure: when Telegram has no SMS to resend
115
- * (`SEND_CODE_UNAVAILABLE`) it aborts the login, though the code it first sent to the app still works.
116
- */
117
- async #loginAskingForSms(prompts) {
118
- let needsPassword = false;
119
- try {
120
- return await this.#client.getMe();
121
- }
122
- catch (error) {
123
- if (tl.RpcError.is(error, "SESSION_PASSWORD_NEEDED"))
124
- needsPassword = true;
125
- else if (!tl.RpcError.is(error, "AUTH_KEY_UNREGISTERED"))
126
- throw error;
127
- }
128
- if (!needsPassword) {
129
- const phone = await prompts.phone();
130
- let sent;
131
- try {
132
- const answer = await this.#client.sendCode({ phone });
133
- if (answer instanceof User)
134
- return answer;
135
- sent = answer;
136
- }
137
- catch (error) {
138
- if (!tl.RpcError.is(error, "SESSION_PASSWORD_NEEDED"))
139
- throw error;
140
- needsPassword = true;
141
- }
142
- if (sent) {
143
- if (sent.type === "app" || sent.type === "email") {
144
- try {
145
- sent = await this.#client.resendCode({ phone, phoneCodeHash: sent.phoneCodeHash });
146
- }
147
- catch (error) {
148
- if (!tl.RpcError.is(error, "SEND_CODE_UNAVAILABLE"))
149
- throw error;
150
- prompts.note("Telegram offers no SMS for this account");
151
- }
83
+ this.#client.onError.add(backgroundError(write, verbose, checks));
84
+ const unanswered = (error, what, details) => unknownIfUnanswered(error, typeof what === "string" ? what : unansweredText(what, checks), details);
85
+ this.#feature = {
86
+ client: this.#client,
87
+ login,
88
+ checks,
89
+ self: () => this.self(),
90
+ inputOf: (reference) => chats.inputOf(this.#client, reference),
91
+ call: (work) => this.#call(work),
92
+ send: (work) => this.#call(() => sending(work)),
93
+ write: (what, work) => this.#call(async () => {
94
+ try {
95
+ return await work();
152
96
  }
153
- if (sent.type === "email_required")
154
- throw new MtcuteError("Email login setup is required to sign in");
155
- prompts.note(`Telegram sent a login code (${sent.type})`);
156
- for (;;) {
157
- try {
158
- return await this.#client.signIn({
159
- phone,
160
- phoneCodeHash: sent.phoneCodeHash,
161
- phoneCode: await prompts.code(),
162
- });
163
- }
164
- catch (error) {
165
- if (tl.RpcError.is(error, "SESSION_PASSWORD_NEEDED")) {
166
- needsPassword = true;
167
- break;
168
- }
169
- if (!PHONE_CODE_RETRIES.some((text) => tl.RpcError.is(error, text)))
170
- throw error;
171
- prompts.note("that code was not accepted — try again");
172
- }
97
+ catch (error) {
98
+ throw unanswered(error, what);
173
99
  }
174
- }
175
- }
176
- for (;;) {
177
- try {
178
- return await this.#client.checkPassword(await prompts.password());
179
- }
180
- catch (error) {
181
- if (!tl.RpcError.is(error, "PASSWORD_HASH_INVALID"))
182
- throw error;
183
- prompts.note("that password was not accepted — try again");
184
- }
185
- }
100
+ }),
101
+ unanswered,
102
+ };
103
+ }
104
+ login(prompts) {
105
+ return login.login(this.#feature, prompts);
186
106
  }
187
107
  /** The logged-in user's id from the session, without a request; `null` before a login. */
188
108
  self() {
189
109
  const cached = this.#client.storage.self.getCached(true);
190
110
  return cached ? String(cached.userId) : null;
191
111
  }
192
- /** Only here the phone: `account show` masks it, and a login's answer is printed as it is. */
193
112
  me() {
194
- return this.#call(async () => {
195
- const user = await this.#client.getMe();
196
- return { ...toAccount(user), phone: user.phoneNumber };
197
- });
113
+ return account.me(this.#feature);
198
114
  }
199
- /**
200
- * For `doctor --online`: Telegram's clock, from `help.getConfig`'s `date` in whole seconds, and
201
- * whether the account is frozen, from `help.getAppConfig`'s `freeze_*` fields
202
- * (core.telegram.org/api/config, /api/auth#frozen-accounts). A frozen account still reads, so a
203
- * working `me()` cannot tell. Both read only.
204
- */
205
115
  health() {
206
- return this.#call(async () => {
207
- const config = await this.#client.call({ _: "help.getConfig" });
208
- const serverTime = config.date * 1000;
209
- let appConfig;
210
- try {
211
- appConfig = await this.#client.appConfig.get();
212
- }
213
- catch {
214
- // The clock is still worth reporting; the standing is then unknown, never "active".
215
- return { serverTime, serverTimeResolutionMs: 1000, standingChecked: false };
216
- }
217
- const standing = frozenOf(appConfig);
218
- return { serverTime, serverTimeResolutionMs: 1000, standingChecked: true, ...(standing ? { standing } : {}) };
219
- });
116
+ return account.health(this.#feature);
220
117
  }
221
- /**
222
- * Telegram lists dialogs by position; `limit` unset is every one. The next page goes on with the walk the
223
- * last one left off, so paging through N chats asks Telegram for each dialog once, not once per page.
224
- */
225
- chats({ limit, offset }) {
226
- return this.#call(async () => {
227
- if (limit === undefined) {
228
- const items = await this.#dialogs(Number.POSITIVE_INFINITY);
229
- return { items: items.slice(offset), hasMore: false };
230
- }
231
- const resumed = this.#walk;
232
- this.#walk = undefined;
233
- const walk = resumed && offset > 0 && resumed.at === offset && Date.now() < resumed.until
234
- ? resumed
235
- : {
236
- dialogs: this.#client.iterDialogs({ archived: "keep" }),
237
- seen: new Set(),
238
- held: [],
239
- at: 0,
240
- until: 0,
241
- };
242
- const pulled = await this.#pull(walk, offset - walk.at + limit + 1);
243
- const items = pulled.slice(offset - walk.at, offset - walk.at + limit);
244
- walk.held = pulled.slice(offset - walk.at + limit);
245
- walk.at = offset + items.length;
246
- walk.until = Date.now() + DIALOG_WALK_KEPT_MS;
247
- this.#walk = walk;
248
- return { items, hasMore: walk.held.length > 0 };
249
- });
118
+ updateProfile(change) {
119
+ return account.updateProfile(this.#feature, change);
120
+ }
121
+ chats(window) {
122
+ return chats.chats(this.#feature, this.#walking, window);
123
+ }
124
+ chat(reference) {
125
+ return chats.chat(this.#feature, reference);
126
+ }
127
+ resolve(reference) {
128
+ return chats.resolve(this.#feature, reference);
250
129
  }
251
130
  discussionOf(channelId, postId) {
252
131
  const post = messageNumber(postId, "a post id is a number");
@@ -263,1619 +142,269 @@ export class TelegramAdapter {
263
142
  return { items: page.items.map(toMessage), hasMore: page.hasMore };
264
143
  });
265
144
  }
266
- /** Telegram reads a thread with messages.search and its top message id (core.telegram.org/api/threads). */
267
- topicHistory(reference, threadId, { limit, before }) {
268
- const thread = topicNumber(threadId);
269
- const offset = before === undefined ? undefined : messageNumber(before, "`id<` takes a message id");
270
- return this.#call(async () => {
271
- const page = await this.#client.searchMessages({
272
- chatId: await this.#inputOf(reference),
273
- threadId: thread,
274
- limit,
275
- ...(offset === undefined ? {} : { offset }),
276
- });
277
- return { items: page.map(remoteMessage).reverse(), hasMore: page.next !== undefined };
278
- });
279
- }
280
- history(reference, { limit, before }) {
281
- return this.#call(async () => {
282
- const peer = await this.#inputOf(reference);
283
- const offset = before === undefined ? undefined : { id: messageNumber(before), date: 0 };
284
- const page = await this.#client.getHistory(peer, { limit, ...(offset ? { offset } : {}) });
285
- // mtcute drops deleted entries and the inexact-count flag. Its iterator follows next, never total.
286
- return { items: page.map(remoteMessage).reverse(), hasMore: page.next !== undefined };
287
- });
288
- }
289
- /**
290
- * Forward from a message or a moment: `reverse` reads upwards from the offset, inclusive, so an id
291
- * starts one past it. The filter keeps a date offset honest — Telegram places it, it does not cut at it.
292
- */
293
- historyAfter(reference, { limit, after }) {
294
- const offset = "id" in after
295
- ? { id: messageNumber(after.id, "`id>` takes a message id") + 1, date: 0 }
296
- : { id: 0, date: Math.floor(after.time / 1000) };
297
- const newer = (message) => "id" in after ? Number(message.id) > Number(after.id) : Date.parse(message.timestamp) > after.time;
298
- return this.#call(async () => {
299
- const peer = await this.#inputOf(reference);
300
- const page = await this.#client.getHistory(peer, { limit, reverse: true, offset });
301
- // As history(): a short page is no end, deleted entries are dropped from it; only an empty one is.
302
- return { items: page.map(remoteMessage).filter(newer), hasMore: page.next !== undefined };
303
- });
304
- }
305
- /** One person's newest messages in a chat: Telegram's search by sender, newest first, answered oldest first. */
306
- historyFrom(reference, person, { limit }) {
307
- return this.#call(async () => {
308
- const [chatId, fromUser] = await Promise.all([this.#inputOf(reference), this.#inputOf(person)]);
309
- const page = await this.#client.searchMessages({ chatId, fromUser, limit });
310
- return { items: page.map(remoteMessage).reverse(), hasMore: page.total > page.length };
311
- });
145
+ history(reference, window) {
146
+ return messages.history(this.#feature, reference, window);
312
147
  }
313
- /**
314
- * Telegram's own text search, newest first: in one chat with `chat`, in every chat otherwise. Its
315
- * matching is undocumented, so the answer is candidates for the store's strict query.
316
- */
317
- searchMessages(query, { limit, signal }) {
318
- return this.#call(async () => {
319
- const seconds = (ms) => (ms === undefined ? 0 : Math.floor(ms / 1000));
320
- const common = {
321
- q: query.text,
322
- filter: { _: "inputMessagesFilterEmpty" },
323
- minDate: seconds(query.minDate),
324
- maxDate: seconds(query.maxDate),
325
- limit,
326
- };
327
- // The raw call, because only it takes these: a flood wait is answered at once instead of slept
328
- // through, and the search's time bound cancels the request rather than leaving it to hold the connection.
329
- const options = { floodSleepThreshold: 0, ...(signal ? { abortSignal: signal } : {}) };
330
- const found = query.chat === undefined
331
- ? await this.#client.call({
332
- _: "messages.searchGlobal",
333
- ...common,
334
- offsetRate: 0,
335
- offsetPeer: { _: "inputPeerEmpty" },
336
- offsetId: 0,
337
- }, options)
338
- : await this.#client.call({
339
- _: "messages.search",
340
- ...common,
341
- peer: await this.#client.resolvePeer(await this.#inputOf(query.chat)),
342
- ...(query.from === undefined
343
- ? {}
344
- : { fromId: await this.#client.resolvePeer(await this.#inputOf(query.from)) }),
345
- offsetId: 0,
346
- addOffset: 0,
347
- maxId: 0,
348
- minId: 0,
349
- hash: Long.ZERO,
350
- }, options);
351
- if (found._ === "messages.messagesNotModified")
352
- return { items: [], hasMore: false, chats: [] };
353
- const peers = PeersIndex.from(found);
354
- const page = found.messages.filter((one) => one._ !== "messageEmpty").map((one) => new TgMessage(one, peers));
355
- const chats = new Map(page.map((message) => [String(message.chat.id), peerToChat(message.chat)]));
356
- return {
357
- items: page.map((message) => remoteHit(message, "remote_fetch")),
358
- hasMore: page.length === limit,
359
- chats: [...chats.values()],
360
- };
361
- });
148
+ historyAfter(reference, window) {
149
+ return messages.historyAfter(this.#feature, reference, window);
362
150
  }
363
- /** Back from a moment, newest first as Telegram reads, answered oldest first. The filter cuts at the moment itself. */
364
- historyBefore(reference, { limit, time }) {
365
- return this.#call(async () => {
366
- const peer = await this.#inputOf(reference);
367
- const page = await this.#client.getHistory(peer, { limit, offset: { id: 0, date: Math.floor(time / 1000) } });
368
- const older = page.map(remoteMessage).filter((message) => Date.parse(message.timestamp) < time);
369
- return { items: older.reverse(), hasMore: page.next !== undefined };
370
- });
151
+ historyFrom(reference, person, window) {
152
+ return messages.historyFrom(this.#feature, reference, person, window);
371
153
  }
372
- /** The chat as its dialog describes it, and for a group, who is in it — at most 200, Telegram's cap. */
373
- chat(reference) {
374
- return this.#call(async () => {
375
- const peer = await this.#inputOf(reference);
376
- const [dialog] = await this.#client.getPeerDialogs(peer);
377
- const found = dialog ? dialog.peer : await this.#client.getPeer(peer);
378
- const chat = dialog ? toChat(dialog) : peerToChat(found);
379
- if (chat.kind !== "group")
380
- return { ...chat, members: null };
381
- const members = await this.#membersOf(peer);
382
- return {
383
- ...chat,
384
- participantsCount: await this.#groupCount(found, members?.total ?? null),
385
- members: members?.map((member) => toMember(member.user)) ?? null,
386
- };
387
- });
154
+ historyBefore(reference, window) {
155
+ return messages.historyBefore(this.#feature, reference, window);
388
156
  }
389
- /** How many profile photos they show and the oldest one's date: the newest first, so the last page holds it. */
390
- photos(person) {
391
- return this.#call(async () => {
392
- const peer = await this.#inputOf(person);
393
- const newest = await this.#client.getProfilePhotos(peer, { limit: 1 });
394
- if (newest.total <= 1)
395
- return { count: newest.total, oldestAt: newest[0]?.date.toISOString() ?? null };
396
- const [oldest] = await this.#client.getProfilePhotos(peer, { offset: newest.total - 1, limit: 1 });
397
- return { count: newest.total, oldestAt: oldest?.date.toISOString() ?? null };
398
- });
157
+ searchMessages(query, options) {
158
+ return messages.searchMessages(this.#feature, query, options);
399
159
  }
400
- /** A person, their bio, and the groups this account shares with them — newest conversation first. */
401
- contact(reference) {
402
- return this.#call(async () => {
403
- const { user, full, dialog, chats } = await this.#personOf(reference);
404
- return {
405
- ...toMember(user),
406
- description: full.bio || null,
407
- lastMessagedAt: dialog ? (toChat(dialog).lastMessageAt ?? null) : null,
408
- chats,
409
- };
410
- });
160
+ around(reference, messageId, window) {
161
+ return messages.around(this.#feature, reference, messageId, window);
411
162
  }
412
- /** The same three requests as `contact`, with everything Telegram said kept. */
413
- profile(reference) {
414
- return this.#call(async () => {
415
- const { full, chats } = await this.#personOf(reference);
416
- return toProfileFacts(full, chats);
417
- });
418
- }
419
- async #personOf(reference) {
420
- const peer = await this.#inputOf(reference);
421
- const user = await this.#client.getPeer(peer);
422
- if (user.type !== "user")
423
- throw new CliError("validation_error", `"${reference}" is a chat, not a person`);
424
- const [full, [dialog], common] = await Promise.all([
425
- this.#client.getFullUser(peer),
426
- this.#client.getPeerDialogs(peer),
427
- this.#client.getCommonChats(peer),
428
- ]);
429
- const dialogs = common.length > 0 ? await this.#client.getPeerDialogs(common.map((chat) => chat.id)) : [];
430
- // Telegram's common chats are groups only; the one-to-one chat is shared with them too.
431
- const chats = [dialog ?? null, ...dialogs]
432
- .filter((one) => one !== null)
433
- .map(toChat)
434
- .map(({ id, title, kind, lastMessageAt }) => ({ id, title, kind, lastMessageAt }))
435
- .sort((a, b) => (b.lastMessageAt ?? "").localeCompare(a.lastMessageAt ?? ""));
436
- return { user, full, dialog, chats };
437
- }
438
- /**
439
- * One request: history from just above the message, shifted `after` messages newer. Telegram's
440
- * offset id is exclusive, hence the `+ 1`; ids are not contiguous, so the window is cut by position.
441
- */
442
163
  fetchCounters(reference, messageId, fields, signal) {
443
- const id = messageNumber(messageId);
444
- return this.#call(async () => {
445
- signal?.throwIfAborted();
446
- const [found] = await this.#client.getMessages(await this.#inputOf(reference), [id]);
447
- signal?.throwIfAborted();
448
- return found
449
- ? (observedCounters(toMessage(found), new Date().toISOString(), fields).counterObservations ?? {})
450
- : {};
451
- });
164
+ return messages.fetchCounters(this.#feature, reference, messageId, fields, signal);
452
165
  }
453
- around(reference, messageId, { before, after }) {
454
- const id = messageNumber(messageId, "a message id is a number");
455
- return this.#call(async () => {
456
- const peer = await this.#inputOf(reference);
457
- const page = await this.#client.getHistory(peer, {
458
- offset: { id: id + 1, date: 0 },
459
- addOffset: -after,
460
- limit: before + 1 + after,
461
- });
462
- const items = page.map(remoteMessage).reverse();
463
- const index = items.findIndex((message) => message.id === String(id));
464
- if (index < 0)
465
- throw new CliError("not_found", `no message ${id} in that chat`);
466
- return items
467
- .slice(Math.max(0, index - before), index + after + 1)
468
- .map((message) => (message.id === String(id) ? { ...message, anchor: true } : message));
469
- });
166
+ permalink(chatId, messageId) {
167
+ return messages.permalink(this.#feature, chatId, messageId);
470
168
  }
471
- /** The chat a reference names — by title, id, `@username` or `me` — so a write can be checked before it goes. */
472
- resolve(reference) {
473
- return this.#call(async () => {
474
- const peer = await this.#peerOf(reference);
475
- return typeof peer === "object" && "kind" in peer ? peer : peerToChat(await this.#client.getPeer(peer));
476
- });
169
+ scheduled(reference) {
170
+ return messages.scheduled(this.#feature, reference);
477
171
  }
478
- sendAsIdentities(chatId) {
479
- return this.#call(() => sendAsIdentities(this.#client, chatId));
172
+ send(chatId, text, options) {
173
+ return messages.send(this.#feature, chatId, text, options);
480
174
  }
481
- savedSender(chatId) {
482
- return this.#call(() => savedSenderOf(this.#client, chatId, this.self()));
175
+ edit(chatId, messageId, text, spans) {
176
+ return messages.edit(this.#feature, chatId, messageId, text, spans);
483
177
  }
484
- permalink(chatId, messageId) {
485
- const id = messageNumber(messageId, "a message id is a positive Telegram integer");
486
- if (id <= 0 || id > 2147483647)
487
- throw new CliError("validation_error", "a message id is a positive Telegram integer");
488
- return this.#call(async () => {
489
- const input = await this.#inputOf(chatId);
490
- const [found] = await this.#client.getMessages(input, [id]);
491
- if (!found || found.id !== id)
492
- throw new CliError("not_found", "that message no longer exists in this chat");
493
- const peer = await this.#client.getPeer(input);
494
- if (peer.type !== "chat" || peer.raw._ !== "channel")
495
- return { url: null, access: "unavailable", reason: "unsupported_chat" };
496
- const { link } = await this.#client.call({
497
- _: "channels.exportMessageLink",
498
- channel: await this.#client.resolveChannel(input),
499
- id,
500
- thread: true,
501
- });
502
- const url = new URL(link);
503
- const known = ["t.me", "telegram.me", "telegram.dog"].includes(url.hostname);
504
- const access = !known
505
- ? "unknown"
506
- : url.pathname.startsWith("/c/")
507
- ? "restricted"
508
- : "public";
509
- return { url: link, access, reason: null };
510
- });
178
+ forward(fromChatId, messageId, toChatId, options) {
179
+ return messages.forward(this.#feature, fromChatId, messageId, toChatId, options);
511
180
  }
512
- /**
513
- * One logical send carries one `random_id`, made before the request and repeated by a retry:
514
- * Telegram delivers one message for both (measured 2026-09-27, across two connections).
515
- */
516
- send(chatId, text, { sendId, replyTo, threadId, silent, noPreview, markup, formatting, at, attachments = [], sendAs, spoiler, captionAbove, }) {
517
- const id = parseSendId(sendId);
518
- const thread = threadId === undefined ? undefined : topicNumber(threadId);
519
- const answering = replyTo === undefined ? undefined : messageNumber(replyTo, "a message id is a number");
520
- const author = sendAs === undefined ? undefined : sendAsPeer(chatId, sendAs, this.self());
521
- if (attachments.length > 1)
522
- throw new CliError("validation_error", "tg sends one file or photo per message");
523
- const spans = formatting ?? markup;
524
- const body = spans ? toFormatted(text, spans) : text;
525
- const common = {
526
- randomId: id,
527
- ...(thread === undefined || thread === 1 ? {} : { threadId: thread }),
528
- ...(answering === undefined ? {} : { replyTo: answering }),
529
- ...(silent ? { silent } : {}),
530
- ...(at === undefined ? {} : { schedule: new Date(at) }),
531
- ...(author === undefined ? {} : { sendAs: author }),
532
- };
533
- return this.#send(async () => {
534
- const [attachment] = attachments;
535
- if (spoiler && attachment)
536
- checkSpoiler(attachment);
537
- const media = attachment
538
- ? toInputMedia(attachment, body, await uploadAttachment(this.#client, attachment), { spoiler })
539
- : undefined;
540
- try {
541
- const message = media
542
- ? await this.#client.sendMedia(Number(chatId), media, {
543
- ...common,
544
- ...(captionAbove ? { invert: true } : {}),
545
- })
546
- : await this.#client.sendText(Number(chatId), body, {
547
- ...common,
548
- ...(noPreview ? { disableWebPreview: true } : {}),
549
- });
550
- return { message: toMessage(message), sendId };
551
- }
552
- catch (error) {
553
- throw unknownIfUnanswered(error, `the message may have been sent. Repeat with ${repeatWith(sendId, sendAs)}, never without it`, retryDetails(sendId, sendAs));
554
- }
555
- });
181
+ pin(chatId, messageId, options) {
182
+ return messages.pin(this.#feature, chatId, messageId, options);
556
183
  }
557
- /**
558
- * New messages, edits, deletions and reaction changes as they arrive, until `signal` aborts. Only
559
- * on an adapter opened with `listen`. `onReady` once the updates loop runs, not before.
560
- */
561
- async watch(onEvent, signal, onReady) {
562
- const client = this.#client;
563
- const message = (found) => onEvent({ event: "message", message: remoteHit(found, "remote_update") });
564
- const edit = (found) => onEvent({ event: "edit", message: remoteHit(found, "remote_update") });
565
- const deletion = (update) => {
566
- for (const change of toDeletions(update))
567
- onEvent(change);
568
- };
569
- const raw = (info) => {
570
- const change = toReactionChange(info);
571
- if (change?.event === "reaction")
572
- onEvent({
573
- ...change,
574
- counterObservation: {
575
- value: change.reactions.total,
576
- observedAt: new Date().toISOString(),
577
- source: "remote_update",
578
- reactions: change.reactions,
579
- },
580
- });
581
- else if (change)
582
- onEvent(change);
583
- };
584
- client.onNewMessage.add(message);
585
- client.onEditMessage.add(edit);
586
- client.onDeleteMessage.add(deletion);
587
- client.onRawUpdate.add(raw);
588
- try {
589
- await this.#call(async () => {
590
- await client.connect();
591
- // With catchUp, mtcute fetches the updates state in the background and, on a revoked login,
592
- // quietly stops its loop — serve would sit "connected" forever. Asking first makes it fail here.
593
- await client.call({ _: "updates.getState" });
594
- await client.startUpdatesLoop();
595
- });
596
- onReady?.();
597
- await this.#untilStopped(signal);
598
- }
599
- finally {
600
- client.onNewMessage.remove(message);
601
- client.onEditMessage.remove(edit);
602
- client.onDeleteMessage.remove(deletion);
603
- client.onRawUpdate.remove(raw);
604
- }
184
+ unpin(chatId, messageId) {
185
+ return messages.unpin(this.#feature, chatId, messageId);
605
186
  }
606
- /**
607
- * Until `signal` aborts, or the login or mtcute's updates loop is found gone. mtcute stops the loop
608
- * without a word on AUTH_KEY_UNREGISTERED (`highlevel/updates/manager.js`, `_fetchUpdatesState` and
609
- * `_fetchDifferenceLater`), usually met by its own 15-minute keep-alive; the heartbeat asks itself
610
- * at the same rate, in case that path never runs. A refused login ends the watch with exit 4; a
611
- * stopped loop otherwise with exit 12, which a service unit restarts — never a process that looks
612
- * connected and receives nothing. A heartbeat that fails for any other reason is let pass.
613
- */
614
- async #untilStopped(signal) {
615
- const updates = this.#client._client
616
- ?.updates;
617
- for (let tick = 1;; tick += 1) {
618
- await pause(LOOP_CHECK_MS, signal);
619
- if (signal.aborted)
620
- return;
621
- const down = updates?.updatesLoopActive === false;
622
- if (!down && tick % HEARTBEAT_TICKS !== 0)
623
- continue;
624
- const refusal = await this.#askState();
625
- if (signal.aborted)
626
- return;
627
- if (refusal?.code === "authentication_error")
628
- throw refusal;
629
- if (down)
630
- throw new CliError("provider_unavailable", LOOP_STOPPED, refusal ? { cause: refusal.code } : {});
631
- }
187
+ react(chatId, messageId, emoji) {
188
+ return messages.react(this.#feature, chatId, messageId, emoji);
632
189
  }
633
- /** `updates.getState` under a timer of its own: a request that never answers must not hold the watch. */
634
- async #askState() {
635
- let timer;
636
- const late = new Promise((resolve) => {
637
- timer = setTimeout(() => resolve(new CliError("timeout", "Telegram did not answer in time")), STATE_WAIT_MS);
638
- });
639
- const asked = this.#call(() => this.#client.call({ _: "updates.getState" })).then(() => undefined, (error) => (isCliError(error) ? error : new CliError("provider_error", "Telegram failed")));
640
- try {
641
- return await Promise.race([asked, late]);
642
- }
643
- finally {
644
- clearTimeout(timer);
645
- }
190
+ markRead(chatId, until) {
191
+ return messages.markRead(this.#feature, chatId, until);
646
192
  }
647
- scheduled(reference) {
648
- return this.#call(async () => {
649
- const queued = await this.#client.getAllScheduledMessages(await this.#inputOf(reference));
650
- return queued.map(toMessage).sort((a, b) => a.timestamp.localeCompare(b.timestamp));
651
- });
193
+ delete(chatId, messageIds, options) {
194
+ return messages.deleteMessages(this.#feature, chatId, messageIds, options);
652
195
  }
653
- /** The message is fetched again, never taken from the store: Telegram's file references expire. */
654
196
  download(reference, messageId) {
655
- const id = messageNumber(messageId, "a message id is a number");
656
- return this.#call(async () => {
657
- const [found] = await this.#client.getMessages(await this.#inputOf(reference), id);
658
- if (!found)
659
- throw new CliError("not_found", `no message ${id} in that chat`);
660
- const media = found.media;
661
- if (!media)
662
- return { files: [], skipped: [] };
663
- if (!(media instanceof FileLocation))
664
- return { files: [], skipped: [media.type] };
665
- const [{ kind, name, mime, size }] = attachmentsOf(media);
666
- const client = this.#client;
667
- const login = this.#login;
668
- async function* bytes() {
669
- try {
670
- yield* client.downloadAsIterable(media);
671
- }
672
- catch (error) {
673
- throw toCliError(error, login);
674
- }
675
- }
676
- return { files: [{ kind, name, mime, size, bytes }], skipped: [] };
677
- });
197
+ return messages.download(this.#feature, reference, messageId);
678
198
  }
679
- /**
680
- * Telegram's own speech recognition; mtcute has no high-level method for `messages.transcribeAudio`.
681
- * A first answer is usually still pending. The finished text arrives as an update, which a one-shot
682
- * connection does not receive, but asking again returns it — measured 2026-09-29 on a 19 s voice note.
683
- */
684
199
  transcribe(reference, messageId) {
685
- const id = messageNumber(messageId, "a message id is a number");
686
- return this.#call(async () => {
687
- const peer = await this.#client.resolvePeer(await this.#inputOf(reference));
688
- const deadline = Date.now() + TRANSCRIBE_WAIT_MS;
689
- for (;;) {
690
- const answer = await this.#client.call({ _: "messages.transcribeAudio", peer, msgId: id });
691
- if (answer.pending !== true || Date.now() >= deadline) {
692
- return { text: answer.text, pending: answer.pending === true };
693
- }
694
- await sleep(TRANSCRIBE_POLL_MS);
695
- }
696
- });
697
- }
698
- /** Forgets the session on Telegram's side too, so the device disappears from the account's list. */
699
- logout() {
700
- return this.#call(async () => {
701
- await this.#client.logOut();
702
- });
200
+ return messages.transcribe(this.#feature, reference, messageId);
703
201
  }
704
- async close() {
705
- await this.#client.destroy();
706
- for (const suffix of ["", "-wal", "-shm"]) {
707
- const path = `${this.#sessionPath}${suffix}`;
708
- if (existsSync(path))
709
- chmodSync(path, 0o600);
710
- }
202
+ poll(chatId, messageId) {
203
+ return polls.poll(this.#feature, chatId, messageId);
711
204
  }
712
- /**
713
- * An edit has no `random_id`, but setting the same text twice is harmless: Telegram answers the
714
- * repeat with MESSAGE_NOT_MODIFIED, taken here as done — so a retry after an unknown outcome is safe.
715
- */
716
- edit(chatId, messageId, text, { markup, formatting } = {}) {
717
- const id = messageNumber(messageId, "a message id is a number");
718
- const spans = formatting ?? markup;
719
- const body = spans ? toFormatted(text, spans) : text;
720
- return this.#call(async () => {
721
- try {
722
- return toMessage(await this.#client.editMessage({ chatId: Number(chatId), message: id, text: body }));
723
- }
724
- catch (error) {
725
- if (tl.RpcError.is(error, "MESSAGE_NOT_MODIFIED")) {
726
- const [current] = await this.#client.getMessages(Number(chatId), [id]);
727
- if (current)
728
- return toMessage(current);
729
- }
730
- throw unknownIfUnanswered(error, "the edit may have been made — repeating it is safe");
731
- }
732
- });
205
+ pollVoters(chatId, messageId, window) {
206
+ return polls.pollVoters(this.#feature, chatId, messageId, window);
733
207
  }
734
- /**
735
- * The raw call, because mtcute's `forwardMessagesById` draws the `random_id` itself: a retry has to
736
- * repeat the first one for Telegram to keep one copy, as a send does.
737
- */
738
- forward(fromChatId, messageId, toChatId, { sendId, silent, sendAs, threadId }) {
739
- const id = messageNumber(messageId, "a message id is a number");
740
- const randomId = parseSendId(sendId);
741
- const thread = threadId === undefined ? undefined : topicNumber(threadId);
742
- const author = sendAs === undefined ? undefined : sendAsPeer(toChatId, sendAs, this.self());
743
- return this.#send(async () => {
744
- try {
745
- const updates = await this.#client.call({
746
- _: "messages.forwardMessages",
747
- fromPeer: await this.#client.resolvePeer(Number(fromChatId)),
748
- toPeer: await this.#client.resolvePeer(Number(toChatId)),
749
- id: [id],
750
- randomId: [randomId],
751
- ...(silent ? { silent } : {}),
752
- ...(thread === undefined || thread === 1 ? {} : { topMsgId: thread }),
753
- ...(author === undefined ? {} : { sendAs: await this.#client.resolvePeer(author) }),
754
- });
755
- this.#client.handleClientUpdate(updates, true);
756
- const copy = forwardedCopy(updates);
757
- if (!copy)
758
- throw new CliError("provider_error", "Telegram answered the forward without the new message");
759
- return toMessage(copy);
760
- }
761
- catch (error) {
762
- throw unknownIfUnanswered(error, `the message may have been forwarded. Repeat with ${repeatWith(sendId, sendAs)}, never without it`, retryDetails(sendId, sendAs));
763
- }
764
- });
208
+ vote(chatId, messageId, answerIds) {
209
+ return polls.vote(this.#feature, chatId, messageId, answerIds);
765
210
  }
766
- /** In a one-to-one chat the pin is on the owner's side only; `notify` reaches groups alone, as Telegram has it. */
767
- pin(chatId, messageId, { notify }) {
768
- const id = messageNumber(messageId, "a message id is a number");
769
- return this.#write("the pin may have been made — repeating it is safe", async () => {
770
- await this.#client.pinMessage({ chatId: Number(chatId), message: id, notify });
771
- });
211
+ closePoll(chatId, messageId) {
212
+ return polls.closePoll(this.#feature, chatId, messageId);
772
213
  }
773
- unpin(chatId, messageId) {
774
- const id = messageNumber(messageId, "a message id is a number");
775
- return this.#write("the message may have been unpinned — repeating it is safe", async () => {
776
- await this.#client.unpinMessage({ chatId: Number(chatId), message: id });
777
- });
214
+ createPoll(chatId, poll, options) {
215
+ return polls.createPoll(this.#feature, chatId, poll, options);
778
216
  }
779
- /**
780
- * Telegram sets the owner's reactions as a whole, so one emoji replaces what was there. An emoji the
781
- * chat does not allow, or a second one without Premium, comes back as Telegram's refusal.
782
- */
783
- react(chatId, messageId, emoji) {
784
- const id = messageNumber(messageId, "a message id is a number");
785
- return this.#write("the reaction may have been set — repeating it is safe", async () => {
786
- await this.#client.sendReaction({ chatId: Number(chatId), message: id, emoji });
787
- });
217
+ officialChatStats(reference) {
218
+ return stats.officialChatStats(this.#feature, reference);
788
219
  }
789
- /** Up to `until`, or everything; mentions stay, as Telegram's own clients leave them until they are seen. */
790
- markRead(chatId, until) {
791
- const maxId = until === undefined ? undefined : messageNumber(until, "--until takes a message id");
792
- return this.#write("the chat may have been marked read — repeating it is safe", async () => {
793
- await this.#client.readHistory(Number(chatId), maxId === undefined ? {} : { maxId });
794
- });
220
+ topicHistory(reference, threadId, window) {
221
+ return topics.topicHistory(this.#feature, reference, threadId, window);
795
222
  }
796
- /** Telegram reads a topic as a discussion thread, up to a message id: without `until`, the topic's newest. */
797
- markTopicRead(chatId, topicId, until) {
798
- const id = topicNumber(topicId);
799
- const maxId = until === undefined ? undefined : messageNumber(until, "--until takes a message id");
800
- return this.#write("the topic may have been marked read — repeating it is safe", async () => {
801
- let readMaxId = maxId;
802
- if (readMaxId === undefined) {
803
- const [topic] = await this.#client.getForumTopicsById(Number(chatId), id);
804
- if (!topic)
805
- throw new CliError("not_found", `no topic ${topicId} in that chat`);
806
- readMaxId = topic.lastMessage.id;
807
- }
808
- await this.#client.call({
809
- _: "messages.readDiscussion",
810
- peer: await this.#client.resolvePeer(Number(chatId)),
811
- msgId: id,
812
- readMaxId,
813
- });
814
- });
223
+ photos(person) {
224
+ return contacts.photos(this.#feature, person);
815
225
  }
816
- /**
817
- * mtcute deletes for everyone unless told otherwise, so `revoke` is always passed. In a supergroup or
818
- * a channel Telegram has no "for me": a deletion there is for everyone, and without `forEveryone` it is refused.
819
- *
820
- * **Outside a channel the ids are checked against the chat first.** Telegram numbers private-chat and
821
- * basic-group messages per account and `messages.deleteMessages` takes no chat, so an id from another
822
- * chat — or the other side's number for the same message — deletes whatever this account has under it
823
- * (SEC-30). `getMessages` answers null for an id that is not in the chat it was given.
824
- */
825
- async delete(chatId, messageIds, { forEveryone }) {
826
- const ids = messageIds.map((id) => messageNumber(id, "a message id is a number"));
827
- const peer = await this.#call(async () => {
828
- const peer = await this.#client.resolvePeer(Number(chatId));
829
- if (peer._ === "inputPeerChannel") {
830
- if (!forEveryone) {
831
- throw new CliError("validation_error", "in a supergroup or a channel Telegram deletes for everyone — add --for-everyone if that is what you want");
832
- }
833
- return peer;
834
- }
835
- const found = [];
836
- for (let at = 0; at < ids.length; at += BY_ID_BATCH)
837
- for (const one of await this.#client.getMessages(peer, ids.slice(at, at + BY_ID_BATCH)))
838
- found.push(one);
839
- const missing = ids.filter((_, index) => found[index] == null);
840
- if (missing.length > 0) {
841
- throw new CliError("validation_error", `no message ${missing.join(", ")} in chat ${chatId} — not in this chat, or already deleted; nothing was deleted`);
842
- }
843
- return peer;
844
- });
845
- return this.#write("the messages may have been deleted — repeating it is safe", async () => {
846
- for (let at = 0; at < ids.length; at += BY_ID_BATCH)
847
- await this.#client.deleteMessagesById(peer, ids.slice(at, at + BY_ID_BATCH), { revoke: forEveryone });
848
- });
226
+ contact(reference) {
227
+ return contacts.contact(this.#feature, reference);
849
228
  }
850
- poll(chatId, messageId) {
851
- return this.#call(async () => toPoll(chatId, messageId, await this.#pollOf(chatId, messageId)));
229
+ profile(reference) {
230
+ return contacts.profile(this.#feature, reference);
852
231
  }
853
- pollVoters(chatId, messageId, window) {
854
- const id = messageNumber(messageId, "a message id is a number");
855
- return this.#call(() => pollVotersOf(this.#client, Number(chatId), id, window));
232
+ sendAsIdentities(chatId) {
233
+ return this.#call(() => sendAsIdentities(this.#client, chatId));
856
234
  }
857
- /** Votes by the answers' own bytes, never by index: mtcute would fetch the poll and pick by position. */
858
- vote(chatId, messageId, answerIds) {
859
- const id = messageNumber(messageId, "a message id is a number");
860
- return this.#call(async () => {
861
- const current = await this.#pollOf(chatId, messageId);
862
- const known = new Map(current.answers.map((answer) => [answerId(answer.data), answer.data]));
863
- const unknown = answerIds.filter((answer) => !known.has(answer));
864
- if (unknown.length > 0) {
865
- throw new CliError("validation_error", `${unknown.join(", ")} ${unknown.length === 1 ? "is" : "are"} not an answer of this poll — its answers are ${[...known.keys()].join(", ")}`);
866
- }
867
- refuseVote(current, answerIds);
868
- const options = answerIds.length === 0 ? null : answerIds.map((answer) => known.get(answer));
869
- try {
870
- return toPoll(chatId, messageId, await this.#client.sendVote({ chatId: Number(chatId), message: id, options }));
871
- }
872
- catch (error) {
873
- throw unknownIfUnanswered(error, "the vote may have been cast — repeating it is safe");
874
- }
875
- });
235
+ savedSender(chatId) {
236
+ return this.#call(() => savedSenderOf(this.#client, chatId, this.self()));
876
237
  }
877
- closePoll(chatId, messageId) {
878
- const id = messageNumber(messageId, "a message id is a number");
879
- return this.#call(async () => {
880
- refuseClose(await this.#pollOf(chatId, messageId));
881
- try {
882
- return toPoll(chatId, messageId, await this.#client.closePoll({ chatId: Number(chatId), message: id }));
883
- }
884
- catch (error) {
885
- throw unknownIfUnanswered(error, "the poll may have been closed; check `tg polls show` before repeating");
886
- }
887
- });
238
+ watch(onEvent, signal, onReady) {
239
+ return watching.watch(this.#feature, onEvent, signal, onReady);
888
240
  }
889
- /**
890
- * One `random_id` per logical create, as a send has: a retry repeats it and Telegram keeps one poll
891
- * (measured 2026-10-08: the second call answered the first poll's message id — unlike topic creation).
892
- */
893
- createPoll(chatId, poll, { sendId, silent, threadId, sendAs }) {
894
- const randomId = parseSendId(sendId);
895
- const thread = threadId === undefined ? undefined : topicNumber(threadId);
896
- const author = sendAs === undefined ? undefined : sendAsPeer(chatId, sendAs, this.self());
897
- return this.#send(async () => {
898
- try {
899
- const message = await this.#client.sendMedia(Number(chatId), toInputPoll(poll), {
900
- randomId,
901
- ...(thread === undefined || thread === 1 ? {} : { threadId: thread }),
902
- ...(silent ? { silent } : {}),
903
- ...(author === undefined ? {} : { sendAs: author }),
904
- });
905
- return { message: toMessage(message), sendId };
906
- }
907
- catch (error) {
908
- throw unknownIfUnanswered(error, `the poll may have been sent. Repeat with ${repeatWith(sendId, sendAs)}, never without it`, retryDetails(sendId, sendAs));
909
- }
910
- });
241
+ logout() {
242
+ return login.logout(this.#feature);
911
243
  }
912
- async #pollOf(chatId, messageId) {
913
- const id = messageNumber(messageId, "a message id is a number");
914
- const [found] = await this.#client.getMessages(Number(chatId), [id]);
915
- if (!found)
916
- throw new CliError("not_found", `no message ${id} in that chat`);
917
- if (found.media?.type !== "poll")
918
- throw new CliError("not_found", `message ${id} carries no poll`);
919
- return found.media;
920
- }
921
- /** A name is matched against the dialogs and answered as the chat it found; anything else goes to Telegram as it is. */
922
- async #peerOf(reference) {
923
- const trimmed = reference.trim();
924
- if (SAVED.has(trimmed.toLowerCase()))
925
- return "me";
926
- if (/^-?\d+$/.test(trimmed))
927
- return Number(trimmed);
928
- if (trimmed.startsWith("@"))
929
- return trimmed.slice(1);
930
- return pickChat(trimmed, await this.#dialogs(Number.POSITIVE_INFINITY));
931
- }
932
- /**
933
- * Each chat once, up to `wanted`. With archived chats kept, Telegram's dialog pages bring the
934
- * pinned chats again further down: 8 of 1361 were listed twice on 2026-10-01, and a pinned chat's
935
- * title then matched itself as two chats.
936
- */
937
- async #pull(walk, wanted) {
938
- const chats = walk.held;
939
- while (chats.length < wanted) {
940
- const next = await walk.dialogs.next();
941
- if (next.done)
942
- break;
943
- const chat = toChat(next.value);
944
- if (walk.seen.has(chat.id))
945
- continue;
946
- walk.seen.add(chat.id);
947
- chats.push(chat);
948
- }
949
- return chats;
950
- }
951
- async #dialogs(wanted) {
952
- const seen = new Set();
953
- const chats = [];
954
- for await (const dialog of this.#client.iterDialogs({ archived: "keep" })) {
955
- const chat = toChat(dialog);
956
- if (seen.has(chat.id))
957
- continue;
958
- seen.add(chat.id);
959
- chats.push(chat);
960
- if (chats.length >= wanted)
961
- break;
244
+ async close() {
245
+ await this.#client.destroy();
246
+ for (const suffix of ["", "-wal", "-shm"]) {
247
+ const path = `${this.#sessionPath}${suffix}`;
248
+ if (existsSync(path))
249
+ chmodSync(path, 0o600);
962
250
  }
963
- return chats;
964
251
  }
965
- async #inputOf(reference) {
966
- const peer = await this.#peerOf(reference);
967
- return typeof peer === "object" && "kind" in peer ? Number(peer.id) : peer;
252
+ markTopicRead(chatId, topicId, until) {
253
+ return topics.markTopicRead(this.#feature, chatId, topicId, until);
968
254
  }
969
- /** An invite is previewed; one the owner already joined, or a public link, is read as the chat. Nothing joins. */
970
255
  inspect(link) {
971
- const typed = link.trim();
972
- const invite = /(t\.me|telegram\.me)\/(\+|joinchat\/)|^tg:\/\/join/.test(typed);
973
- return this.#call(async () => {
974
- if (invite) {
975
- try {
976
- return toInvitePreview(await this.#client.getChatPreview(typed));
977
- }
978
- catch (error) {
979
- if (!(error instanceof MtPeerNotFoundError))
980
- throw error;
981
- }
982
- }
983
- return toLinkChat(await this.#client.getFullChat(invite ? typed : publicName(typed)));
984
- });
256
+ return groups.inspect(this.#feature, link);
985
257
  }
986
258
  forumState(chatId) {
987
- return this.#call(() => this.#forumState(chatId));
988
- }
989
- async #forumState(chatId) {
990
- let full = await this.#client.getFullChat(Number(chatId));
991
- if (full.migratedToId != null)
992
- full = await this.#client.getFullChat(full.migratedToId);
993
- if (full.chatType !== "group" && full.chatType !== "supergroup") {
994
- throw new CliError("validation_error", "forum topics require a group, not a channel or dialog");
995
- }
996
- return {
997
- chat: peerToChat(full),
998
- forum: full.isForum,
999
- needsUpgrade: full.chatType === "group",
1000
- owner: full.isCreator,
1001
- linkedDiscussion: full.linkedChat !== null,
1002
- canCreate: full.isCreator ||
1003
- full.adminRights?.manageTopics === true ||
1004
- full.permissions?.canManageTopics === true ||
1005
- full.defaultPermissions?.canManageTopics === true,
1006
- };
259
+ return topics.forumState(this.#feature, chatId);
1007
260
  }
1008
261
  upgradeForum(chatId) {
1009
- return this.#call(async () => {
1010
- const state = await this.#forumState(chatId);
1011
- if (!state.owner)
1012
- throw new CliError("permission_error", "only the owner can prepare this group for topics");
1013
- if (!state.needsUpgrade)
1014
- return state;
1015
- const peer = await this.#client.resolvePeer(Number(state.chat.id));
1016
- if (peer._ !== "inputPeerChat")
1017
- throw new CliError("validation_error", "only a basic group can be upgraded");
1018
- let accepted = false;
1019
- let migratedChatId;
1020
- try {
1021
- const updates = await this.#client.call({ _: "messages.migrateChat", chatId: peer.chatId }, { maxRetryCount: 0, floodSleepThreshold: 0 });
1022
- accepted = true;
1023
- this.#client.handleClientUpdate(updates, true);
1024
- const made = updates._ === "updates" || updates._ === "updatesCombined"
1025
- ? updates.chats.find((chat) => chat._ === "channel" && chat.megagroup)
1026
- : undefined;
1027
- if (made?._ !== "channel")
1028
- throw new CliError("outcome_unknown", "the group may have been upgraded; check its current chat id before repeating");
1029
- migratedChatId = String(getMarkedPeerId({ _: "peerChannel", channelId: made.id }));
1030
- return await this.#forumState(migratedChatId);
1031
- }
1032
- catch (error) {
1033
- if (accepted)
1034
- throw new CliError("outcome_unknown", "the upgrade was accepted but its state could not be read; check the current group before continuing", {
1035
- previous_chat_id: state.chat.id,
1036
- ...(migratedChatId === undefined ? {} : { chat_id: migratedChatId, upgraded: true }),
1037
- stage: "upgrade",
1038
- });
1039
- throw unknownIfUnanswered(error, "the group may have been upgraded; check its current chat id before repeating");
1040
- }
1041
- });
262
+ return topics.upgradeForum(this.#feature, chatId);
1042
263
  }
1043
264
  enableForum(chatId) {
1044
- return this.#call(async () => {
1045
- const state = await this.#forumState(chatId);
1046
- if (!state.owner)
1047
- throw new CliError("permission_error", "only the group owner can enable forum topics");
1048
- if (state.needsUpgrade)
1049
- throw new CliError("validation_error", "upgrade the basic group explicitly before enabling topics");
1050
- if (state.linkedDiscussion)
1051
- throw new CliError("validation_error", "a linked discussion group cannot enable forum topics");
1052
- if (state.forum)
1053
- return state;
1054
- try {
1055
- const full = await this.#client.getFullChat(Number(state.chat.id));
1056
- await this.#client.updateForumSettings(Number(state.chat.id), {
1057
- isForum: true,
1058
- threadsMode: full.raw._ === "channel" && full.raw.forumTabs ? "tabs" : "list",
1059
- });
1060
- return await this.#forumState(state.chat.id);
1061
- }
1062
- catch (error) {
1063
- if (tl.RpcError.is(error, "CHAT_NOT_MODIFIED"))
1064
- return this.#forumState(state.chat.id);
1065
- throw unknownIfUnanswered(error, "topics may have been enabled; check the forum state before repeating");
1066
- }
1067
- });
265
+ return topics.enableForum(this.#feature, chatId);
1068
266
  }
1069
- createTopic(chatId, title, { sendId }) {
1070
- const randomId = parseSendId(sendId);
1071
- return this.#call(async () => {
1072
- const state = await this.#forumState(chatId);
1073
- if (!state.forum || state.needsUpgrade)
1074
- throw new CliError("validation_error", "enable topics before creating a topic");
1075
- if (!state.canCreate)
1076
- throw new CliError("permission_error", "creating a topic requires manage-topics permission");
1077
- let accepted = false;
1078
- try {
1079
- const updates = await this.#client.call({
1080
- _: "messages.createForumTopic",
1081
- peer: await this.#client.resolvePeer(Number(state.chat.id)),
1082
- title,
1083
- randomId,
1084
- }, { maxRetryCount: 0, floodSleepThreshold: 0 });
1085
- accepted = true;
1086
- this.#client.handleClientUpdate(updates, true);
1087
- const message = forwardedCopy(updates);
1088
- const mapped = updates._ === "updates" || updates._ === "updatesCombined"
1089
- ? updates.updates.find((update) => update._ === "updateMessageID" && String(update.randomId) === String(randomId))
1090
- : undefined;
1091
- const topicId = mapped && mapped._ === "updateMessageID" ? mapped.id : message?.id;
1092
- if (topicId === undefined)
1093
- throw new CliError("outcome_unknown", "Telegram did not return the topic id; check topics list and do not repeat this creation", { operation_id: sendId, retryable: false });
1094
- const [topic] = await this.#client.getForumTopicsById(Number(state.chat.id), topicId);
1095
- if (!topic)
1096
- throw new CliError("outcome_unknown", "the topic may exist but could not be read; check topics list and do not repeat this creation", { operation_id: sendId, retryable: false });
1097
- return toTopic(topic);
1098
- }
1099
- catch (error) {
1100
- if (accepted)
1101
- throw new CliError("outcome_unknown", "topic creation was accepted but its result could not be read; check topics list and do not repeat", { operation_id: sendId, retryable: false });
1102
- throw unknownIfUnanswered(error, `the topic may have been created; check topics list and do not repeat this creation`, { operation_id: sendId, retryable: false });
1103
- }
1104
- });
267
+ createTopic(chatId, title, options) {
268
+ return topics.createTopic(this.#feature, chatId, title, options);
1105
269
  }
1106
- /**
1107
- * A repeat answers TOPIC_NOT_MODIFIED: the change is already there, so the topic is read back as for a first.
1108
- * Pinning is Telegram's own call, made after the edit.
1109
- */
1110
- editTopic(chatId, topicId, { title, closed, pinned, hidden }) {
1111
- const id = topicNumber(topicId);
1112
- if (hidden !== undefined && id !== 1)
1113
- throw new CliError("validation_error", "only the General topic (id 1) can be hidden");
1114
- return this.#call(async () => {
1115
- const unchanged = (error) => {
1116
- if (!tl.RpcError.is(error, "TOPIC_NOT_MODIFIED") && !tl.RpcError.is(error, "PINNED_TOPIC_NOT_MODIFIED"))
1117
- throw unknownIfUnanswered(error, "the topic may have changed — repeating it is safe");
1118
- };
1119
- if (title !== undefined || closed !== undefined) {
1120
- await this.#client
1121
- .editForumTopic({
1122
- chatId: Number(chatId),
1123
- topicId: id,
1124
- ...(title === undefined ? {} : { title }),
1125
- ...(closed === undefined ? {} : { closed }),
1126
- })
1127
- .catch(unchanged);
1128
- }
1129
- if (pinned !== undefined)
1130
- await this.#client.toggleForumTopicPinned({ chatId: Number(chatId), topicId: id, pinned }).catch(unchanged);
1131
- if (hidden !== undefined)
1132
- await this.#client.toggleGeneralTopicHidden({ chatId: Number(chatId), hidden }).catch(unchanged);
1133
- const [topic] = await this.#client.getForumTopicsById(Number(chatId), id);
1134
- if (!topic)
1135
- throw new CliError("not_found", `no topic ${topicId} in that chat`);
1136
- // Measured 2026-10-04: a read right after the edit can still show the title and state of edits ago.
1137
- return {
1138
- ...toTopic(topic),
1139
- ...(title === undefined ? {} : { title }),
1140
- ...(closed === undefined ? {} : { closed }),
1141
- ...(pinned === undefined ? {} : { pinned }),
1142
- ...(hidden === undefined ? {} : { hidden }),
1143
- };
1144
- });
270
+ editTopic(chatId, topicId, change) {
271
+ return topics.editTopic(this.#feature, chatId, topicId, change);
1145
272
  }
1146
- /** Without `force` Telegram only reorders: a topic that is not pinned stays as it is. */
1147
273
  orderPinnedTopics(chatId, topicIds) {
1148
- const order = topicIds.map(topicNumber);
1149
- return this.#call(async () => {
1150
- try {
1151
- await this.#client.reorderPinnedForumTopics({ chatId: Number(chatId), order });
1152
- }
1153
- catch (error) {
1154
- throw unknownIfUnanswered(error, "the pinned topics may have been reordered — repeating it is safe");
1155
- }
1156
- });
274
+ return topics.orderPinnedTopics(this.#feature, chatId, topicIds);
1157
275
  }
1158
- /** Telegram deletes the topic's history with it; a topic that is gone answers TOPIC_ID_INVALID, `not_found`. */
1159
276
  deleteTopic(chatId, topicId) {
1160
- const topic = topicNumber(topicId);
1161
- return this.#call(async () => {
1162
- try {
1163
- await this.#client.deleteForumTopicHistory(Number(chatId), topic);
1164
- }
1165
- catch (error) {
1166
- throw unknownIfUnanswered(error, "the topic may have been deleted; check `tg topics list` before repeating");
1167
- }
1168
- });
277
+ return topics.deleteTopic(this.#feature, chatId, topicId);
1169
278
  }
1170
- async validateThread(chatId, threadId, { replyTo }) {
1171
- const topicId = topicNumber(threadId);
1172
- const replyId = replyTo === undefined ? undefined : messageNumber(replyTo, "--reply-to needs a message id");
1173
- return this.#call(async () => {
1174
- const peer = await this.#client.getPeer(Number(chatId));
1175
- if (peer.type !== "chat" || !peer.isForum) {
1176
- throw new CliError("validation_error", "--topic requires a Telegram forum group");
1177
- }
1178
- const [topic] = await this.#client.getForumTopicsById(Number(chatId), topicId);
1179
- if (!topic)
1180
- throw new CliError("not_found", "that forum topic does not exist; check `topics list`");
1181
- if (topic.isClosed)
1182
- throw new CliError("permission_error", "that forum topic is closed; choose an open topic");
1183
- if (replyId !== undefined) {
1184
- const [reply] = await this.#client.getMessages(Number(chatId), [replyId]);
1185
- if (!reply)
1186
- throw new CliError("not_found", "the message to reply to no longer exists in this chat");
1187
- const replyThread = reply.isTopicMessage ? (reply.replyToMessage?.threadId ?? reply.id) : 1;
1188
- if (reply.id !== topicId && replyThread !== topicId) {
1189
- throw new CliError("validation_error", "--reply-to belongs to a different topic; choose a message in --topic");
1190
- }
1191
- }
1192
- });
279
+ validateThread(chatId, threadId, options) {
280
+ return topics.validateThread(this.#feature, chatId, threadId, options);
1193
281
  }
1194
282
  topic(reference, topicId) {
1195
- const id = topicNumber(topicId);
1196
- return this.#call(async () => {
1197
- const input = await this.#inputOf(reference);
1198
- const peer = await this.#client.getPeer(input);
1199
- if (peer.type !== "chat" || !peer.isForum)
1200
- throw new CliError("validation_error", "that chat has no topics");
1201
- const [topic] = await this.#client.getForumTopicsById(input, id);
1202
- if (!topic)
1203
- throw new CliError("not_found", "that forum topic does not exist; check `topics list`");
1204
- return toTopic(topic);
1205
- });
283
+ return topics.topic(this.#feature, reference, topicId);
1206
284
  }
1207
- /** A forum's topics, newest activity first; Telegram matches `search` against their titles. */
1208
- topics(reference, { search, limit, offset }) {
1209
- return this.#call(async () => {
1210
- const peer = await this.#inputOf(reference);
1211
- const items = [];
1212
- const wanted = limit === undefined ? {} : { limit: offset + limit + 1 };
1213
- for await (const topic of this.#client.iterForumTopics(peer, {
1214
- ...wanted,
1215
- ...(search ? { query: search } : {}),
1216
- })) {
1217
- items.push(toTopic(topic));
1218
- }
1219
- const end = limit === undefined ? items.length : offset + limit;
1220
- return { items: items.slice(offset, end), hasMore: items.length > end };
1221
- });
285
+ topics(reference, window) {
286
+ return topics.topics(this.#feature, reference, window);
1222
287
  }
1223
- /** Telegram answers only where the person's privacy lets the owner find them by number. */
1224
288
  lookup(phone) {
1225
- return this.#call(async () => toMember(await this.#client.getPeer(await this.#client.resolvePhoneNumber(phone))));
289
+ return contacts.lookup(this.#feature, phone);
1226
290
  }
1227
- /** The owner's Telegram contacts — the address book, not the chats. */
1228
291
  addressBook() {
1229
- return this.#call(async () => (await this.#client.getContacts()).map(toMember));
292
+ return contacts.addressBook(this.#feature);
1230
293
  }
1231
- /** Every device and app logged in; the IP address Telegram also sends is left out. */
1232
294
  sessions() {
1233
- return this.#call(async () => {
1234
- const { authorizations } = await this.#client.call({ _: "account.getAuthorizations" });
1235
- return authorizations.map(toAccountSession);
1236
- });
295
+ return login.sessions(this.#feature);
1237
296
  }
1238
- /**
1239
- * A page of a group's members, 200 a request, a second apart. Telegram gives at most `MEMBERS_MAX` of a big
1240
- * group, and a group that hides its list answers only its admins or refuses.
1241
- */
1242
- members(reference, { limit, offset }) {
1243
- return this.#call(async () => {
1244
- const peer = await this.#inputOf(reference);
1245
- const group = await this.#client.getPeer(peer);
1246
- const wanted = Math.min(limit ?? MEMBERS_MAX, MEMBERS_MAX - offset);
1247
- const found = [];
1248
- let total = null;
1249
- while (found.length < wanted) {
1250
- if (found.length > 0)
1251
- await new Promise((resolve) => setTimeout(resolve, MEMBER_PAGE_PAUSE_MS));
1252
- const size = Math.min(200, wanted - found.length);
1253
- const page = await this.#client.getChatMembers(peer, { offset: offset + found.length, limit: size });
1254
- total = page.total;
1255
- found.push(...page.map(toGroupMember));
1256
- if (page.length < size)
1257
- break;
1258
- }
1259
- return {
1260
- chatId: String(group.id),
1261
- items: found,
1262
- hasMore: offset + found.length < Math.min(total ?? 0, MEMBERS_MAX),
1263
- participantsCount: offset === 0 ? await this.#groupCount(group, total) : null,
1264
- };
1265
- });
297
+ members(reference, window) {
298
+ return groups.members(this.#feature, reference, window);
1266
299
  }
1267
- /**
1268
- * Service messages back to `since`, newest page first, at most `EVENT_PAGES` of them — a busy
1269
- * group's week can be thousands. The people a message names only by id are looked up in one call.
1270
- */
1271
- chatEvents(reference, { since }) {
1272
- return this.#call(async () => {
1273
- const peer = await this.#inputOf(reference);
1274
- const found = [];
1275
- let offset;
1276
- let more = false;
1277
- for (let read = 1;; read++) {
1278
- const page = await this.#client.getHistory(peer, { limit: 100, ...(offset ? { offset } : {}) });
1279
- for (const message of page) {
1280
- const change = message.date.getTime() > since ? eventOf(message) : null;
1281
- if (change)
1282
- found.push({ message, change });
1283
- }
1284
- const oldest = page.at(-1);
1285
- if (!page.next || !oldest || oldest.date.getTime() <= since)
1286
- break;
1287
- if (read >= EVENT_PAGES) {
1288
- more = true;
1289
- break;
1290
- }
1291
- offset = page.next;
1292
- }
1293
- const names = new Map(found.map(({ message }) => [message.sender.id, message.sender.displayName || null]));
1294
- const unknown = [...new Set(found.flatMap(({ change }) => [change.by, ...change.people]))].filter((id) => !names.has(id));
1295
- if (unknown.length > 0) {
1296
- for (const user of await this.#client.getUsers(unknown))
1297
- if (user)
1298
- names.set(user.id, user.displayName || null);
1299
- }
1300
- const person = (id) => ({ id: String(id), name: names.get(id) ?? null });
1301
- return {
1302
- chatId: String((await this.#client.getPeer(peer)).id),
1303
- since: new Date(since).toISOString(),
1304
- more,
1305
- events: found.reverse().map(({ message, change }) => ({
1306
- messageId: String(message.id),
1307
- timestamp: message.date.toISOString(),
1308
- event: change.event,
1309
- by: person(change.by),
1310
- people: change.people.map(person),
1311
- ...(change.title === undefined ? {} : { title: change.title }),
1312
- })),
1313
- };
1314
- });
300
+ chatEvents(reference, window) {
301
+ return groups.chatEvents(this.#feature, reference, window);
1315
302
  }
1316
- /**
1317
- * A group's admins and its creator, for `review --unanswered`; `null` when the group hides them.
1318
- * A basic group ignores the `admins` filter and answers everyone, hence the status check.
1319
- */
1320
303
  admins(reference) {
1321
- return this.#call(async () => {
1322
- const peer = await this.#inputOf(reference);
1323
- try {
1324
- const members = await this.#client.getChatMembers(peer, { type: "admins", limit: 200 });
1325
- return members
1326
- .filter((member) => member.status === "creator" || member.status === "admin")
1327
- .map((member) => String(member.user.id));
1328
- }
1329
- catch (error) {
1330
- const known = toCliError(error, this.#login);
1331
- if (known instanceof CliError && known.code === "permission_error")
1332
- return null;
1333
- throw known;
1334
- }
1335
- });
304
+ return groups.admins(this.#feature, reference);
1336
305
  }
1337
- /** `null` when the group hides its member list from us: that is an answer about the group, not a failure. */
1338
- /** Each reference as a user id, in order; a group or a channel is not a person and is refused. */
1339
306
  people(references) {
1340
- return this.#call(async () => {
1341
- const ids = [];
1342
- for (const reference of references) {
1343
- const peer = await this.#client.getPeer(await this.#inputOf(reference));
1344
- if (peer.type !== "user")
1345
- throw new CliError("validation_error", `${reference} is a chat, not a person`);
1346
- ids.push(String(peer.id));
1347
- }
1348
- return ids;
1349
- });
307
+ return groups.people(this.#feature, references);
1350
308
  }
1351
- /**
1352
- * Always a supergroup, never a legacy group: a legacy group turns into a supergroup on some changes
1353
- * and its id changes with it. The people are added after, so a group exists even if some cannot be.
1354
- */
1355
- createGroup(title, people, { channel }) {
1356
- return this.#call(async () => {
1357
- try {
1358
- const made = channel
1359
- ? await this.#client.createChannel({ title })
1360
- : await this.#client.createSupergroup({ title });
1361
- const missing = people.length > 0 ? await this.#client.addChatMembers(made.id, people.map(Number), {}) : [];
1362
- const card = toGroupCard(await this.#client.getFullChat(made.id));
1363
- if (missing.length === 0)
1364
- return card;
1365
- const notAdded = missing.map((one) => String(one.userId));
1366
- return { ...card, providerMetadata: { ...card.providerMetadata, notAdded } };
1367
- }
1368
- catch (error) {
1369
- throw unknownIfUnanswered(error, "the group may or may not have been made; check `tg chats list`");
1370
- }
1371
- });
309
+ createGroup(title, people, options) {
310
+ return groups.createGroup(this.#feature, title, people, options);
1372
311
  }
1373
- /** An invite link, or a public one; a group that asks its admins first answers `requested`. */
1374
312
  join(link) {
1375
- const typed = link.trim();
1376
- const invite = /(t\.me|telegram\.me)\/(\+|joinchat\/)|^tg:\/\/join/.test(typed);
1377
- return this.#call(async () => {
1378
- let joined;
1379
- try {
1380
- joined = await this.#client.joinChat(invite ? typed : publicName(typed));
1381
- }
1382
- catch (error) {
1383
- throw unknownIfUnanswered(error, "you may or may not have joined; check `tg chats list`");
1384
- }
1385
- if (joined.status === "request_sent")
1386
- return { requested: true };
1387
- if (joined.status !== "ok") {
1388
- throw new CliError("provider_error", "this group asks a bot to check who joins, which only the Telegram app can show");
1389
- }
1390
- return toGroupCard(await this.#client.getFullChat(joined.chat.id));
1391
- });
313
+ return groups.join(this.#feature, link);
1392
314
  }
1393
315
  leave(reference) {
1394
- return this.#call(async () => {
1395
- const peer = await this.#inputOf(reference);
1396
- const chatId = String((await this.#client.getPeer(peer)).id);
1397
- try {
1398
- await this.#client.leaveChat(peer);
1399
- }
1400
- catch (error) {
1401
- throw unknownIfUnanswered(error, "you may or may not have left; check `tg chats list`");
1402
- }
1403
- return { chatId };
1404
- });
316
+ return groups.leave(this.#feature, reference);
1405
317
  }
1406
318
  group(reference) {
1407
- return this.#call(async () => toGroupCard(await this.#client.getFullChat(await this.#inputOf(reference))));
319
+ return groups.group(this.#feature, reference);
1408
320
  }
1409
- /**
1410
- * Telegram computes these only on the chat's statistics server (`stats_dc`); mtcute opens that
1411
- * connection and carries the login over itself, and `close` ends it with the others.
1412
- */
1413
- officialChatStats(reference) {
1414
- return this.#call(async () => {
1415
- let full = await this.#client.getFullChat(await this.#inputOf(reference));
1416
- if (full.migratedToId != null)
1417
- full = await this.#client.getFullChat(full.migratedToId);
1418
- const broadcast = full.chatType === "channel";
1419
- if (!broadcast && full.chatType !== "supergroup" && full.chatType !== "gigagroup") {
1420
- throw new CliError("validation_error", full.chatType === "group"
1421
- ? "Telegram keeps statistics only for supergroups and channels, not for a basic group"
1422
- : "Telegram keeps statistics only for supergroups and channels");
1423
- }
1424
- if (!full.canViewStats) {
1425
- throw new CliError("permission_error", "Telegram shows statistics only to admins of large enough groups and channels, and not for this one");
1426
- }
1427
- const statsDc = full.full._ === "channelFull" ? full.full.statsDc : undefined;
1428
- const options = statsDc === undefined ? undefined : { dcId: statsDc };
1429
- const channel = await this.#client.resolveChannel(full.id);
1430
- const chat = { id: String(full.id), title: full.displayName };
1431
- const graphOf = async (graph) => {
1432
- if (graph._ === "statsGraph")
1433
- return toOfficialGraph(graph.json.data);
1434
- if (graph._ === "statsGraphError")
1435
- return { error: graph.error };
1436
- try {
1437
- const loaded = await this.#client.call({ _: "stats.loadAsyncGraph", token: graph.token }, options);
1438
- if (loaded._ === "statsGraph")
1439
- return toOfficialGraph(loaded.json.data);
1440
- return { error: loaded._ === "statsGraphError" ? loaded.error : "Telegram did not finish this graph" };
1441
- }
1442
- catch (error) {
1443
- if (tl.RpcError.is(error))
1444
- return { error: error.text };
1445
- throw error;
1446
- }
1447
- };
1448
- try {
1449
- return broadcast
1450
- ? await toOfficialChannelStats(chat, await this.#client.call({ _: "stats.getBroadcastStats", channel }, options), graphOf)
1451
- : await toOfficialGroupStats(chat, await this.#client.call({ _: "stats.getMegagroupStats", channel }, options), graphOf);
1452
- }
1453
- catch (error) {
1454
- // Reached the main server a moment ago, so the login stands; only the statistics server refused it.
1455
- if (tl.RpcError.is(error, "AUTH_KEY_UNREGISTERED"))
1456
- throw new CliError("provider_error", "Telegram's statistics server did not accept this login (AUTH_KEY_UNREGISTERED); the login itself works — try again later", { provider_error: error.text, status: error.code });
1457
- throw error;
1458
- }
1459
- });
321
+ updateGroup(chatId, change) {
322
+ return groups.updateGroup(this.#feature, chatId, change);
1460
323
  }
1461
- /**
1462
- * Telegram keeps what members may do as rights taken away, and sets them all at once: the current
1463
- * ones are read first, and only the switches asked for change.
1464
- */
1465
- updateGroup(chatId, { title, description, settings = {} }) {
1466
- const missing = Object.keys(settings).filter((key) => !GROUP_SETTINGS.includes(key));
1467
- if (missing.length > 0) {
1468
- throw new CliError("validation_error", `Telegram has no group setting ${missing.join(", ")}`);
1469
- }
1470
- const peer = Number(chatId);
1471
- return this.#call(async () => {
1472
- try {
1473
- if (title !== undefined)
1474
- await this.#client.setChatTitle(peer, title);
1475
- if (description !== undefined)
1476
- await this.#client.setChatDescription(peer, description);
1477
- const { allCanPin, onlyAdminsAdd, joinApproval } = settings;
1478
- if (typeof joinApproval === "boolean")
1479
- await this.#client.toggleJoinRequests(peer, joinApproval);
1480
- if (typeof allCanPin === "boolean" || typeof onlyAdminsAdd === "boolean") {
1481
- const current = (await this.#client.getFullChat(peer)).defaultPermissions?.raw;
1482
- const { _: _kind, untilDate: _until, ...taken } = current ?? { _: "chatBannedRights", untilDate: 0 };
1483
- await this.#client.setChatDefaultPermissions(peer, {
1484
- ...taken,
1485
- ...(typeof allCanPin === "boolean" ? { pinMessages: !allCanPin } : {}),
1486
- ...(typeof onlyAdminsAdd === "boolean" ? { inviteUsers: onlyAdminsAdd } : {}),
1487
- });
1488
- }
1489
- }
1490
- catch (error) {
1491
- throw unknownIfUnanswered(error, "the group may have changed in part; check `tg chats show`");
1492
- }
1493
- return toGroupCard(await this.#client.getFullChat(peer));
1494
- });
1495
- }
1496
- /** A new primary link for the owner; the old one stops working. */
1497
324
  resetInviteLink(chatId) {
1498
- const peer = Number(chatId);
1499
- return this.#call(async () => {
1500
- try {
1501
- await this.#client.exportInviteLink(peer);
1502
- }
1503
- catch (error) {
1504
- throw unknownIfUnanswered(error, "the link may or may not have been replaced; check `tg chats link show`");
1505
- }
1506
- return toGroupCard(await this.#client.getFullChat(peer));
1507
- });
325
+ return groups.resetInviteLink(this.#feature, chatId);
1508
326
  }
1509
- createInviteLink(chatId, { approval, expiresAt, maxUses }) {
1510
- return this.#call(async () => {
1511
- try {
1512
- return toInviteLink(await this.#client.createInviteLink(Number(chatId), {
1513
- withApproval: approval,
1514
- ...(expiresAt === undefined ? {} : { expires: new Date(expiresAt) }),
1515
- ...(maxUses === undefined ? {} : { usageLimit: maxUses }),
1516
- }));
1517
- }
1518
- catch (error) {
1519
- throw unknownIfUnanswered(error, "a link may or may not have been made; it works only once shared");
1520
- }
1521
- });
327
+ createInviteLink(chatId, options) {
328
+ return groups.createInviteLink(this.#feature, chatId, options);
1522
329
  }
1523
- joinRequests(chatId, { limit, link, search }) {
1524
- return this.#call(() => joinRequestsOf(this.#client, Number(chatId), limit, {
1525
- ...(link ? { link } : {}),
1526
- ...(search ? { search } : {}),
1527
- }));
330
+ joinRequests(chatId, options) {
331
+ return groups.joinRequests(this.#feature, chatId, options);
1528
332
  }
1529
333
  answerAllJoinRequests(chatId, accept, link) {
1530
- return this.#call(async () => {
1531
- try {
1532
- await this.#client.hideAllJoinRequests({
1533
- chatId: Number(chatId),
1534
- action: accept ? "approve" : "decline",
1535
- ...(link ? { link } : {}),
1536
- });
1537
- }
1538
- catch (error) {
1539
- throw unknownIfUnanswered(error, "the requests may or may not have been answered; check `tg chats requests list`");
1540
- }
1541
- });
334
+ return groups.answerAllJoinRequests(this.#feature, chatId, accept, link);
1542
335
  }
1543
- /** Telegram shows an admin only their own links; the creator could ask for others', which we do not. */
1544
- inviteLinks(chatId, { limit, revoked }) {
1545
- return this.#call(async () => {
1546
- const page = await this.#client.getInviteLinks(Number(chatId), { limit, revoked });
1547
- return { items: page.map(toInviteLink), hasMore: page.total > page.length };
1548
- });
336
+ inviteLinks(chatId, options) {
337
+ return groups.inviteLinks(this.#feature, chatId, options);
1549
338
  }
1550
339
  revokeInviteLink(chatId, link) {
1551
- return this.#call(async () => {
1552
- try {
1553
- return toInviteLink(await this.#client.revokeInviteLink(Number(chatId), link));
1554
- }
1555
- catch (error) {
1556
- throw unknownIfUnanswered(error, "the link may or may not have been revoked; check `tg chats link list`");
1557
- }
1558
- });
340
+ return groups.revokeInviteLink(this.#feature, chatId, link);
1559
341
  }
1560
- updateInviteLink(chatId, link, { approval, expiresAt, maxUses }) {
1561
- return this.#call(async () => {
1562
- const peer = await this.#client.resolvePeer(Number(chatId));
1563
- try {
1564
- // Raw, because mtcute's editInviteLink drops an expiry of 0 — Telegram's "never expires".
1565
- const answer = await this.#client.call({
1566
- _: "messages.editExportedChatInvite",
1567
- peer,
1568
- link,
1569
- ...(approval === undefined ? {} : { requestNeeded: approval }),
1570
- ...(expiresAt === undefined ? {} : { expireDate: expiresAt === null ? 0 : Date.parse(expiresAt) / 1000 }),
1571
- ...(maxUses === undefined ? {} : { usageLimit: maxUses }),
1572
- });
1573
- return toInviteLink(new ChatInviteLink(answer.invite, PeersIndex.from(answer)));
1574
- }
1575
- catch (error) {
1576
- throw unknownIfUnanswered(error, "the link may or may not have been changed; check `tg chats link list`");
1577
- }
1578
- });
342
+ updateInviteLink(chatId, link, change) {
343
+ return groups.updateInviteLink(this.#feature, chatId, link, change);
1579
344
  }
1580
345
  answerJoinRequest(chatId, personId, accept) {
1581
- return this.#call(async () => {
1582
- try {
1583
- return await answerJoinRequestOf(this.#client, Number(chatId), Number(personId), accept);
1584
- }
1585
- catch (error) {
1586
- throw unknownIfUnanswered(error, `the request of ${personId} may or may not have been answered; check \`tg chats requests list\``);
1587
- }
1588
- });
346
+ return groups.answerJoinRequest(this.#feature, chatId, personId, accept);
1589
347
  }
1590
- /** A supergroup shows new members its history by its own setting, never per person: `history` is refused. */
1591
- addMembers(chatId, people, { history }) {
1592
- if (history)
1593
- throw new CliError("validation_error", "Telegram shows new members the history by the group's setting, not per person");
1594
- return this.#call(async () => {
1595
- try {
1596
- const missing = await this.#client.addChatMembers(Number(chatId), people.map(Number), {});
1597
- return { notAdded: missing.map((one) => String(one.userId)) };
1598
- }
1599
- catch (error) {
1600
- throw unknownIfUnanswered(error, "the people may or may not have been added; check `tg chats members list`");
1601
- }
1602
- });
348
+ addMembers(chatId, people, options) {
349
+ return groups.addMembers(this.#feature, chatId, people, options);
1603
350
  }
1604
- /** One request per person, in turn: Telegram rate-limits these hard. */
1605
351
  removeMembers(chatId, people) {
1606
- return this.#call(async () => {
1607
- for (const person of people) {
1608
- try {
1609
- await this.#client.kickChatMember({ chatId: Number(chatId), userId: Number(person) });
1610
- }
1611
- catch (error) {
1612
- throw unknownIfUnanswered(error, `${person} may or may not have been removed; check \`tg chats members list\``);
1613
- }
1614
- }
1615
- });
352
+ return groups.removeMembers(this.#feature, chatId, people);
1616
353
  }
1617
354
  addAdmin(chatId, person, rights) {
1618
- const missing = rights.filter((right) => !(right in ADMIN_RIGHT_FIELDS));
1619
- if (missing.length > 0)
1620
- throw new CliError("validation_error", `Telegram has no admin right ${missing.join(", ")}`);
1621
- const fields = Object.fromEntries(rights.map((right) => [ADMIN_RIGHT_FIELDS[right], true]));
1622
- return this.#editAdmin(chatId, person, fields);
355
+ return groups.addAdmin(this.#feature, chatId, person, rights);
1623
356
  }
1624
357
  removeAdmin(chatId, person) {
1625
- return this.#editAdmin(chatId, person, {});
1626
- }
1627
- #editAdmin(chatId, person, rights) {
1628
- return this.#call(async () => {
1629
- try {
1630
- await this.#client.editAdminRights({ chatId: Number(chatId), userId: Number(person), rights });
1631
- }
1632
- catch (error) {
1633
- throw unknownIfUnanswered(error, "the rights may or may not have changed; check `tg chats members list`");
1634
- }
1635
- });
358
+ return groups.removeAdmin(this.#feature, chatId, person);
1636
359
  }
1637
360
  folders() {
1638
- return this.#call(async () => (await this.#filters()).map(toFolder).filter((one) => one !== null));
1639
- }
1640
- createFolder(title, chatIds, rules = {}) {
1641
- return this.#write("the folder may have been made; check `tg chats folders list` before repeating — a repeat makes a second one", async () => {
1642
- const peers = (ids = []) => Promise.all(ids.map((id) => this.#client.resolvePeer(Number(id))));
1643
- const pinned = new Set(rules.pin);
1644
- const made = await this.#client.createFolder({
1645
- title: { _: "textWithEntities", text: title, entities: [] },
1646
- includePeers: await peers(chatIds.filter((id) => !pinned.has(id))),
1647
- pinnedPeers: await peers(rules.pin),
1648
- excludePeers: await peers(rules.exclude),
1649
- ...(rules.emoji === undefined ? {} : { emoticon: rules.emoji }),
1650
- ...ruleFlags(rules),
1651
- });
1652
- return this.#storedFolder(made);
1653
- });
361
+ return folders.folders(this.#feature);
362
+ }
363
+ createFolder(title, chatIds, rules) {
364
+ return folders.createFolder(this.#feature, title, chatIds, rules);
1654
365
  }
1655
- /** Telegram replaces a folder's chats as a list, so the ones it has are read and only the asked ones change. */
1656
366
  updateFolder(folderId, change) {
1657
- const { title, add = [], remove = [], exclude = [], pin = [], emoji, include, skip } = change;
1658
- return this.#write("the folder may have changed — repeating it is safe", async () => {
1659
- const current = (await this.#filters()).find((one) => one._ !== "dialogFilterDefault" && String(one.id) === folderId);
1660
- if (!current || current._ === "dialogFilterDefault")
1661
- throw new CliError("not_found", `no folder ${folderId}`);
1662
- const rulesAsked = include !== undefined || skip !== undefined || exclude.length > 0;
1663
- if (rulesAsked && current._ === "dialogFilterChatlist")
1664
- throw new CliError("validation_error", "a folder shared by a link holds only its chats; it takes no rules");
1665
- // A chat sits on one list at a time: pinning or excluding it takes it off the others.
1666
- const idOf = (peer) => String(getMarkedPeerId(peer));
1667
- const off = (peers, ...ids) => {
1668
- const gone = new Set(ids.flat());
1669
- return peers.filter((peer) => !gone.has(idOf(peer)));
1670
- };
1671
- const resolved = (ids, have) => {
1672
- const held = new Set(have.map(idOf));
1673
- return Promise.all(ids.filter((id) => !held.has(id)).map((id) => this.#client.resolvePeer(Number(id))));
1674
- };
1675
- const include0 = off(current.includePeers, remove, pin, exclude);
1676
- const pinned0 = off(current.pinnedPeers, remove, exclude);
1677
- const listsChanged = add.length > 0 || remove.length > 0 || pin.length > 0 || exclude.length > 0;
1678
- const excluded0 = current._ === "dialogFilter" ? off(current.excludePeers, remove, add, pin) : [];
1679
- const changed = await this.#client.editFolder({
1680
- folder: current._ === "dialogFilter" ? current : current.id,
1681
- modification: {
1682
- ...(title === undefined ? {} : { title: { _: "textWithEntities", text: title, entities: [] } }),
1683
- ...(emoji === undefined ? {} : { emoticon: emoji }),
1684
- ...ruleFlags({ ...(include === undefined ? {} : { include }), ...(skip === undefined ? {} : { skip }) }),
1685
- ...(listsChanged
1686
- ? {
1687
- includePeers: [...include0, ...(await resolved(add, [...include0, ...pinned0]))],
1688
- pinnedPeers: [...pinned0, ...(await resolved(pin, pinned0))],
1689
- ...(current._ === "dialogFilter"
1690
- ? { excludePeers: [...excluded0, ...(await resolved(exclude, excluded0))] }
1691
- : {}),
1692
- }
1693
- : {}),
1694
- },
1695
- });
1696
- return this.#storedFolder(changed);
1697
- });
367
+ return folders.updateFolder(this.#feature, folderId, change);
1698
368
  }
1699
369
  deleteFolder(folderId) {
1700
- return this.#write("the folder may have been deleted — repeating it is safe", async () => {
1701
- await this.#client.deleteFolder(Number(folderId));
1702
- });
370
+ return folders.deleteFolder(this.#feature, folderId);
1703
371
  }
1704
- /** "All chats" (id 0) keeps its place: only Premium accounts may move it, and tg does not list it. */
1705
372
  orderFolders(folderIds) {
1706
- return this.#write("the folders may be in the new order already — repeating it is safe", async () => {
1707
- const current = (await this.#filters()).map((one) => (one._ === "dialogFilterDefault" ? 0 : one.id));
1708
- const order = folderIds.map(Number);
1709
- const all = current.indexOf(0);
1710
- if (all >= 0)
1711
- order.splice(all, 0, 0);
1712
- await this.#client.setFoldersOrder(order);
1713
- });
373
+ return folders.orderFolders(this.#feature, folderIds);
1714
374
  }
1715
375
  joinFolder(link) {
1716
- return this.#write("the folder may have been joined; check `tg chats folders list` before repeating — a repeat joins nothing new", async () => {
1717
- try {
1718
- return toFolder(await this.#client.joinChatlist(link));
1719
- }
1720
- catch (error) {
1721
- if (tl.RpcError.is(error, "INVITE_SLUG_EXPIRED") || tl.RpcError.is(error, "INVITE_SLUG_INVALID"))
1722
- throw new CliError("not_found", "this folder link is invalid or has expired");
1723
- throw error;
1724
- }
1725
- });
1726
- }
1727
- /**
1728
- * mtcute answers with the folder it sent, but Telegram drops what it does not take — an emoji that is not
1729
- * one of its folder icons, measured live 2026-10-08 — so the answer is read back.
1730
- */
1731
- async #storedFolder(sent) {
1732
- const stored = sent._ === "dialogFilterDefault"
1733
- ? undefined
1734
- : (await this.#filters()).find((one) => one._ !== "dialogFilterDefault" && one.id === sent.id);
1735
- return toFolder(stored ?? sent);
376
+ return folders.joinFolder(this.#feature, link);
1736
377
  }
1737
- async #filters() {
1738
- return (await this.#client.getFolders()).filters;
1739
- }
1740
- /** Under the name they show; `renameContact` gives one of the owner's own. */
1741
378
  addContact(personId) {
1742
- return this.#write("the contact may have been added — repeating it is safe", async () => {
1743
- const peer = await this.#client.getPeer(Number(personId));
1744
- if (peer.type !== "user")
1745
- throw new CliError("validation_error", `${personId} is a chat, not a person`);
1746
- return toMember(await this.#client.addContact({
1747
- userId: peer.id,
1748
- firstName: peer.firstName,
1749
- ...(peer.lastName ? { lastName: peer.lastName } : {}),
1750
- }));
1751
- });
379
+ return contacts.addContact(this.#feature, personId);
1752
380
  }
1753
381
  removeContact(personId) {
1754
- return this.#write("the contact may have been removed — repeating it is safe", async () => {
1755
- await this.#client.deleteContacts([Number(personId)]);
1756
- });
382
+ return contacts.removeContact(this.#feature, personId);
1757
383
  }
1758
384
  block(personId) {
1759
- return this.#write("the person may have been blocked — repeating it is safe", async () => {
1760
- await this.#client.blockUser(Number(personId));
1761
- });
385
+ return contacts.block(this.#feature, personId);
1762
386
  }
1763
387
  unblock(personId) {
1764
- return this.#write("the person may have been unblocked — repeating it is safe", async () => {
1765
- await this.#client.unblockUser(Number(personId));
1766
- });
388
+ return contacts.unblock(this.#feature, personId);
1767
389
  }
1768
390
  renameContact(personId, firstName, lastName) {
1769
- return this.#write("the contact may have been renamed — repeating it is safe", async () => toMember(await this.#client.addContact({ userId: Number(personId), firstName, ...(lastName ? { lastName } : {}) })));
391
+ return contacts.renameContact(this.#feature, personId, firstName, lastName);
1770
392
  }
1771
- /** The name is split at its first space into Telegram's first and last name. */
1772
393
  importContacts(entries) {
1773
- return this.#write("the contacts may have been imported — repeating it is safe", async () => {
1774
- const result = await this.#client.importContacts(entries.map(({ phone, name }) => {
1775
- const [firstName = name, ...rest] = name.split(" ");
1776
- return { phone: `+${phone}`, firstName, lastName: rest.join(" ") };
1777
- }));
1778
- const found = new Set(result.imported.map((one) => String(one.userId)));
1779
- const users = await this.#client.getUsers([...found].map(Number));
1780
- return users.filter((user) => user !== null).map(toMember);
1781
- });
394
+ return contacts.importContacts(this.#feature, entries);
1782
395
  }
1783
- /** Telegram calls the description the bio. A photo goes up as a new profile photo. */
1784
- updateProfile({ firstName, lastName, description, photo, }) {
1785
- return this.#call(async () => {
1786
- if (firstName !== undefined || lastName !== undefined || description !== undefined) {
1787
- await this.#client.updateProfile({
1788
- ...(firstName === undefined ? {} : { firstName }),
1789
- ...(lastName === undefined ? {} : { lastName }),
1790
- ...(description === undefined ? {} : { bio: description }),
1791
- });
1792
- }
1793
- if (photo)
1794
- await this.#client.setMyProfilePhoto({ type: "photo", media: await uploadBlob(photo.source) });
1795
- const user = await this.#client.getMe();
1796
- return { ...toAccount(user), phone: user.phoneNumber };
1797
- });
1798
- }
1799
- /** mtcute has no call of its own for it; this is Telegram's `auth.resetAuthorizations`. */
1800
396
  endOtherSessions() {
1801
- return this.#call(async () => {
1802
- try {
1803
- await this.#client.call({ _: "auth.resetAuthorizations" });
1804
- }
1805
- catch (error) {
1806
- throw unknownIfUnanswered(error, "the other devices may or may not have been logged out; check `tg account sessions list`");
1807
- }
1808
- const { authorizations } = await this.#client.call({ _: "account.getAuthorizations" });
1809
- return authorizations.map(toAccountSession);
1810
- });
1811
- }
1812
- /**
1813
- * A supergroup's own count is its member list's total: its chat object and its full info both said 1 for a
1814
- * group of 2, seen live. A list hidden from non-admins answers only part of the group, so then the full info's
1815
- * count stands, which the shorter list never reaches. A basic group's list total is only the page it read.
1816
- */
1817
- async #groupCount(group, listTotal) {
1818
- if (group.type !== "chat" || group.raw?._ !== "channel")
1819
- return groupMembersCount(group);
1820
- const full = await this.#client.getFullChat(group.id);
1821
- const hidden = full.full._ === "channelFull" && full.full.participantsHidden === true && !full.isAdmin;
1822
- return hidden || listTotal === null ? groupMembersCount(full) : listTotal || null;
1823
- }
1824
- async #membersOf(peer) {
1825
- try {
1826
- return await this.#client.getChatMembers(peer, { limit: 200 });
1827
- }
1828
- catch (error) {
1829
- const known = toCliError(error, this.#login);
1830
- if (known instanceof CliError && known.code === "permission_error")
1831
- return null;
1832
- throw known;
1833
- }
1834
- }
1835
- /** A write with no id to repeat it by: no answer means it may have happened, and `what` says what to do. */
1836
- #write(what, work) {
1837
- return this.#call(async () => {
1838
- try {
1839
- return await work();
1840
- }
1841
- catch (error) {
1842
- throw unknownIfUnanswered(error, what);
1843
- }
1844
- });
1845
- }
1846
- #send(work) {
1847
- return this.#call(() => sending(work));
397
+ return login.endOtherSessions(this.#feature);
1848
398
  }
1849
399
  async #call(work) {
1850
400
  try {
1851
401
  return await (this.#proxyFailed ? Promise.race([work(), this.#proxyFailed]) : work());
1852
402
  }
1853
403
  catch (error) {
1854
- throw toCliError(error, this.#login);
404
+ throw toCliError(error, this.#feature.checks, this.#feature.login);
1855
405
  }
1856
406
  }
1857
407
  }
1858
- export { GROUP_SETTINGS };
1859
- const unixTime = (value) => typeof value === "number" && value > 0 ? new Date(value * 1000).toISOString() : undefined;
1860
- /** Telegram sets `freeze_since_date` non-zero only on a frozen account; the dates are unix seconds. */
1861
- export const frozenOf = (config) => {
1862
- const since = unixTime(config.freeze_since_date);
1863
- if (!since)
1864
- return undefined;
1865
- const until = unixTime(config.freeze_until_date);
1866
- const appealUrl = typeof config.freeze_appeal_url === "string" && config.freeze_appeal_url ? config.freeze_appeal_url : undefined;
1867
- return {
1868
- state: "frozen",
1869
- since,
1870
- ...(until ? { until } : {}),
1871
- ...(appealUrl ? { appealUrl } : {}),
1872
- hint: "Telegram froze this account: it can read but not write" +
1873
- (until ? `, and deletes it on ${until.slice(0, 10)}` : "") +
1874
- (appealUrl ? ` unless an appeal is accepted — appeal at ${appealUrl}` : " unless an appeal is accepted"),
1875
- };
1876
- };
1877
- /** The rights `tg chats admins add --can` offers: max's, less `read`. */
1878
- export const ADMIN_RIGHTS = Object.keys(ADMIN_RIGHT_FIELDS);
1879
408
  /**
1880
409
  * How long mtcute sits out a FLOOD_WAIT before the wait becomes `rate_limited` with `retryAfterMs`, and
1881
410
  * how many times. One-shot: 10 s, mtcute's own default, which covers the routine short waits; past it a
@@ -1888,65 +417,4 @@ export const FLOOD_SLEEP = {
1888
417
  oneShot: { maxWait: 10_000, maxRetries: 2 },
1889
418
  listening: { maxWait: 120_000, maxRetries: 3 },
1890
419
  };
1891
- /** A look at a local flag, not a request. */
1892
- export const LOOP_CHECK_MS = 30_000;
1893
- /** Every 15 minutes, mtcute's own keep-alive rate: ~96 light requests a day. */
1894
- export const HEARTBEAT_TICKS = 30;
1895
- export const STATE_WAIT_MS = 30_000;
1896
- const LOOP_STOPPED = "Telegram's updates stopped arriving although the connection is open — ending, so a service unit starts it again";
1897
- export const TRANSCRIBE_POLL_MS = 2000;
1898
- const TRANSCRIBE_WAIT_MS = 60_000;
1899
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1900
- const pause = (ms, signal) => new Promise((resolve) => {
1901
- const done = () => {
1902
- clearTimeout(timer);
1903
- signal.removeEventListener("abort", done);
1904
- resolve();
1905
- };
1906
- const timer = setTimeout(done, ms);
1907
- if (signal.aborted)
1908
- done();
1909
- else
1910
- signal.addEventListener("abort", done, { once: true });
1911
- });
1912
- const messageNumber = (id, rule = "`id<` takes a message id") => {
1913
- if (!/^\d+$/.test(id))
1914
- throw new CliError("validation_error", `${rule}, got "${id}"`);
1915
- return Number(id);
1916
- };
1917
- const forwardedCopy = (updates) => {
1918
- if (updates._ !== "updates" && updates._ !== "updatesCombined")
1919
- return undefined;
1920
- const update = updates.updates.find((one) => one._ === "updateNewMessage" || one._ === "updateNewChannelMessage");
1921
- return update && "message" in update ? new TgMessage(update.message, PeersIndex.from(updates)) : undefined;
1922
- };
1923
- const parseSendId = (typed) => {
1924
- if (!/^-?\d{1,20}$/.test(typed))
1925
- throw new CliError("validation_error", "--operation-id is the number a failed send printed");
1926
- return Long.fromString(typed);
1927
- };
1928
- /** No answer is not a refusal: the write may have reached Telegram. Anything else is left for `#call` to map. */
1929
- const unknownIfUnanswered = (error, what, details = {}) => {
1930
- const known = toCliError(error);
1931
- if (known instanceof CliError && ["timeout", "network_error"].includes(known.code)) {
1932
- return new CliError("outcome_unknown", `no answer from Telegram — ${what}`, { ...details, cause: known.code });
1933
- }
1934
- return error;
1935
- };
1936
- const repeatWith = (sendId, sendAs) => sendAs === undefined ? `--operation-id ${sendId}` : `--operation-id ${sendId} --send-as ${sendAs}`;
1937
- const retryDetails = (sendId, sendAs) => ({
1938
- operation_id: sendId,
1939
- ...(sendAs === undefined ? {} : { sendAs }),
1940
- });
1941
- const topicNumber = (id) => {
1942
- if (!/^[1-9]\d*$/.test(id) || Number(id) > 2147483647) {
1943
- throw new CliError("validation_error", "--topic needs a positive Telegram topic id");
1944
- }
1945
- return Number(id);
1946
- };
1947
- const remoteMessage = (message) => observedCounters(toMessage(message), new Date().toISOString(), ["views", "reactions", "comments"]);
1948
- const remoteHit = (message, source) => ({
1949
- ...toMessageHit(message),
1950
- ...observedCounters(toMessage(message), new Date().toISOString(), ["views", "reactions", "comments"], source),
1951
- });
1952
420
  //# sourceMappingURL=adapter.js.map