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