@wirecat/tg-cli 0.99.0 → 0.101.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/README.md +6 -5
- package/dist/bin/tg.js +23 -28
- package/dist/bundle/adapter-A3VD4Y6Z.js +2790 -0
- package/dist/bundle/all-profiles-UPVNHXB2.js +264 -0
- package/dist/bundle/anthropic-IRKNWPIB.js +71 -0
- package/dist/bundle/bot-api-UNTQG2M5.js +39793 -0
- package/dist/bundle/bot-history-V4RTY5K7.js +167 -0
- package/dist/bundle/bun-2JZPG2NL.js +169 -0
- package/dist/bundle/bun-sqlite-TZHKM225.js +70 -0
- package/dist/bundle/chunk-22PQUX72.js +190 -0
- package/dist/bundle/chunk-2DGOFLDA.js +58 -0
- package/dist/bundle/chunk-2SJOUK6J.js +2 -0
- package/dist/bundle/chunk-2XBSVRT2.js +98 -0
- package/dist/bundle/chunk-3KHKYYCR.js +24782 -0
- package/dist/bundle/chunk-4ZS73HTJ.js +6848 -0
- package/dist/bundle/chunk-54R2GDQ3.js +119 -0
- package/dist/bundle/chunk-5GKXETRP.js +1345 -0
- package/dist/bundle/chunk-5KU4UQBM.js +570 -0
- package/dist/bundle/chunk-5TPT2S2Z.js +41 -0
- package/dist/bundle/chunk-64DK7S4F.js +76 -0
- package/dist/bundle/chunk-6IPY2QRG.js +82 -0
- package/dist/bundle/chunk-7BFO3DY6.js +21 -0
- package/dist/bundle/chunk-7CBUCTB6.js +1142 -0
- package/dist/bundle/chunk-A5JSTZZZ.js +122 -0
- package/dist/bundle/chunk-ACGTFLEB.js +1275 -0
- package/dist/bundle/chunk-AFV74GK3.js +50 -0
- package/dist/bundle/chunk-AVWK4NCW.js +24600 -0
- package/dist/bundle/chunk-BJG6JA5U.js +35 -0
- package/dist/bundle/chunk-BX6HH4F6.js +215 -0
- package/dist/bundle/chunk-BXQS5RCE.js +8170 -0
- package/dist/bundle/chunk-CJ6IYCYP.js +583 -0
- package/dist/bundle/chunk-DG62L57H.js +2795 -0
- package/dist/bundle/chunk-DYNSP6FW.js +33720 -0
- package/dist/bundle/chunk-F7TDFWXY.js +82 -0
- package/dist/bundle/chunk-G2US6LJB.js +35 -0
- package/dist/bundle/chunk-G3ZRY436.js +3077 -0
- package/dist/bundle/chunk-G77QOTXE.js +18 -0
- package/dist/bundle/chunk-H6OXALTJ.js +45 -0
- package/dist/bundle/chunk-LPB2MDUW.js +452 -0
- package/dist/bundle/chunk-MLLJ74LM.js +24 -0
- package/dist/bundle/chunk-N5UFBWDM.js +166 -0
- package/dist/bundle/chunk-NC5WS7OP.js +31 -0
- package/dist/bundle/chunk-NKJJJAIJ.js +237 -0
- package/dist/bundle/chunk-NMGO6LW6.js +1950 -0
- package/dist/bundle/chunk-ODSVNH3H.js +18588 -0
- package/dist/bundle/chunk-OEJ5DMCX.js +2374 -0
- package/dist/bundle/chunk-OILBDLWL.js +724 -0
- package/dist/bundle/chunk-OPBTNQ35.js +1007 -0
- package/dist/bundle/chunk-PUBS2F5J.js +35803 -0
- package/dist/bundle/chunk-PYTOIDSM.js +153 -0
- package/dist/bundle/chunk-QOWSVDPZ.js +3526 -0
- package/dist/bundle/chunk-QYVVRQTN.js +73 -0
- package/dist/bundle/chunk-RF54YDBB.js +46 -0
- package/dist/bundle/chunk-RVCS7Q3A.js +6672 -0
- package/dist/bundle/chunk-S2JSZWEC.js +277 -0
- package/dist/bundle/chunk-S7ZNLLY5.js +54 -0
- package/dist/bundle/chunk-TGREFJVA.js +2315 -0
- package/dist/bundle/chunk-U46UNBMT.js +524 -0
- package/dist/bundle/chunk-UN6CKIBN.js +285 -0
- package/dist/bundle/chunk-VA5YEJS3.js +161 -0
- package/dist/bundle/chunk-VCGL2ETF.js +78 -0
- package/dist/bundle/chunk-VRSN7VLO.js +63 -0
- package/dist/bundle/chunk-VYDTI254.js +3332 -0
- package/dist/bundle/chunk-W2336E7Y.js +886 -0
- package/dist/bundle/chunk-X4Y2ROJI.js +541 -0
- package/dist/bundle/chunk-XCKD54TN.js +100 -0
- package/dist/bundle/chunk-ZEOCU24Z.js +738 -0
- package/dist/bundle/chunk-ZJVZXJOG.js +71 -0
- package/dist/bundle/chunk-ZV24I2UJ.js +25 -0
- package/dist/bundle/chunk-ZZLKX62Z.js +928 -0
- package/dist/bundle/command-contract-TKDI7E56.js +31 -0
- package/dist/bundle/dist-RJMT44PL.js +7577 -0
- package/dist/bundle/echarts-QZ6PR3VC.js +42501 -0
- package/dist/bundle/embed-UBXCXSRD.js +35 -0
- package/dist/bundle/embedder-B4ZTKC23.js +108 -0
- package/dist/bundle/entry-BTUTHO5M.js +14 -0
- package/dist/bundle/first-run-UC4HRIFV.js +24 -0
- package/dist/bundle/first-screen-SMCX6YKY.js +29 -0
- package/dist/bundle/identity-QSDEGDH7.js +11 -0
- package/dist/bundle/instructions-BBGLZKO3.js +9 -0
- package/dist/bundle/mcp-4Y37G2UY.js +165 -0
- package/dist/bundle/node-IUL5HSYI.js +2340 -0
- package/dist/bundle/node-LZZX22VR.js +176 -0
- package/dist/bundle/node-UPPL626U.js +21 -0
- package/dist/bundle/node-sqlite-BPGT6T5U.js +46 -0
- package/dist/bundle/oauth-XNE2KPKJ.js +18 -0
- package/dist/bundle/open-SXGYZLB5.js +20 -0
- package/dist/bundle/process-GPUXC4PG.js +91 -0
- package/dist/bundle/program-NEXEAL7T.js +1060 -0
- package/dist/bundle/prompt-SORGLEYI.js +13 -0
- package/dist/bundle/proxy-transport-G4MA6BGU.js +17 -0
- package/dist/bundle/recognize-UJBXORVD.js +191 -0
- package/dist/bundle/remote-W72AR7KH.js +26 -0
- package/dist/bundle/rerank-3Y2VZM3J.js +49 -0
- package/dist/bundle/serve-VDZIVOPR.js +196 -0
- package/dist/bundle/server-BERXP4GW.js +785 -0
- package/dist/bundle/server-ZFHN4GUF.js +178 -0
- package/dist/bundle/state-DGR4EE3E.js +34 -0
- package/dist/bundle/store-MRCFSCZD.js +121 -0
- package/dist/bundle/store-maintenance-command-DCMZDMYS.js +46 -0
- package/dist/bundle/tg.js +40 -0
- package/dist/commands/context.d.ts.map +1 -1
- package/dist/commands/context.js +3 -1
- package/dist/commands/context.js.map +1 -1
- package/dist/install/postinstall.js +1 -1
- package/dist/install/postinstall.js.map +1 -1
- package/dist/program.js +1 -1
- package/dist/program.js.map +1 -1
- package/dist/telegram/errors.js +1 -1
- package/dist/telegram/errors.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/install/windows.ps1 +1 -1
- package/package.json +6 -4
- package/skills/{wirecat-tg → tg-cli}/SKILL.md +4 -4
|
@@ -0,0 +1,2790 @@
|
|
|
1
|
+
import { createRequire as __tgRequire } from "node:module";
|
|
2
|
+
const require = __tgRequire(import.meta.url);
|
|
3
|
+
import {
|
|
4
|
+
answerId,
|
|
5
|
+
attachmentsOf,
|
|
6
|
+
backgroundError,
|
|
7
|
+
checkSpoiler,
|
|
8
|
+
eventOf,
|
|
9
|
+
groupMembersCount,
|
|
10
|
+
openSessionStorage,
|
|
11
|
+
peerToChat,
|
|
12
|
+
pollClosed,
|
|
13
|
+
ruleFlags,
|
|
14
|
+
toAccount,
|
|
15
|
+
toAccountSession,
|
|
16
|
+
toButtons,
|
|
17
|
+
toChat,
|
|
18
|
+
toCliError,
|
|
19
|
+
toDeletions,
|
|
20
|
+
toFolder,
|
|
21
|
+
toFormatted,
|
|
22
|
+
toGroupCard,
|
|
23
|
+
toGroupMember,
|
|
24
|
+
toInputMedia,
|
|
25
|
+
toInputPoll,
|
|
26
|
+
toInviteLink,
|
|
27
|
+
toInvitePreview,
|
|
28
|
+
toLinkChat,
|
|
29
|
+
toMember,
|
|
30
|
+
toMessage,
|
|
31
|
+
toMessageHit,
|
|
32
|
+
toPoll,
|
|
33
|
+
toReactionChange,
|
|
34
|
+
toTopic,
|
|
35
|
+
toUploadParams,
|
|
36
|
+
videoMime,
|
|
37
|
+
withCause
|
|
38
|
+
} from "./chunk-ZEOCU24Z.js";
|
|
39
|
+
import {
|
|
40
|
+
proxiedTransport
|
|
41
|
+
} from "./chunk-ZJVZXJOG.js";
|
|
42
|
+
import {
|
|
43
|
+
ADMIN_RIGHTS,
|
|
44
|
+
ADMIN_RIGHT_FIELDS,
|
|
45
|
+
GROUP_SETTINGS,
|
|
46
|
+
bareCheck,
|
|
47
|
+
formatMarkdown
|
|
48
|
+
} from "./chunk-NMGO6LW6.js";
|
|
49
|
+
import "./chunk-2XBSVRT2.js";
|
|
50
|
+
import "./chunk-NKJJJAIJ.js";
|
|
51
|
+
import "./chunk-22PQUX72.js";
|
|
52
|
+
import "./chunk-CJ6IYCYP.js";
|
|
53
|
+
import {
|
|
54
|
+
pickChat,
|
|
55
|
+
uploadBlob,
|
|
56
|
+
validateFormattedText
|
|
57
|
+
} from "./chunk-OILBDLWL.js";
|
|
58
|
+
import "./chunk-RF54YDBB.js";
|
|
59
|
+
import "./chunk-ZZLKX62Z.js";
|
|
60
|
+
import "./chunk-OPBTNQ35.js";
|
|
61
|
+
import "./chunk-54R2GDQ3.js";
|
|
62
|
+
import "./chunk-ZV24I2UJ.js";
|
|
63
|
+
import {
|
|
64
|
+
observedCounters
|
|
65
|
+
} from "./chunk-PUBS2F5J.js";
|
|
66
|
+
import "./chunk-G3ZRY436.js";
|
|
67
|
+
import "./chunk-TGREFJVA.js";
|
|
68
|
+
import "./chunk-W2336E7Y.js";
|
|
69
|
+
import "./chunk-2SJOUK6J.js";
|
|
70
|
+
import "./chunk-G77QOTXE.js";
|
|
71
|
+
import "./chunk-XCKD54TN.js";
|
|
72
|
+
import "./chunk-4ZS73HTJ.js";
|
|
73
|
+
import "./chunk-F7TDFWXY.js";
|
|
74
|
+
import "./chunk-6IPY2QRG.js";
|
|
75
|
+
import "./chunk-DG62L57H.js";
|
|
76
|
+
import {
|
|
77
|
+
CliError,
|
|
78
|
+
isCliError
|
|
79
|
+
} from "./chunk-OEJ5DMCX.js";
|
|
80
|
+
import "./chunk-BJG6JA5U.js";
|
|
81
|
+
import {
|
|
82
|
+
__name
|
|
83
|
+
} from "./chunk-AFV74GK3.js";
|
|
84
|
+
|
|
85
|
+
// dist/telegram/adapter.js
|
|
86
|
+
import { chmodSync, existsSync, mkdirSync } from "node:fs";
|
|
87
|
+
import { dirname } from "node:path";
|
|
88
|
+
import { format } from "node:util";
|
|
89
|
+
import { TelegramClient } from "@mtcute/node";
|
|
90
|
+
|
|
91
|
+
// dist/telegram/account.js
|
|
92
|
+
var unixTime = /* @__PURE__ */ __name((value2) => typeof value2 === "number" && value2 > 0 ? new Date(value2 * 1e3).toISOString() : void 0, "unixTime");
|
|
93
|
+
var frozenOf = /* @__PURE__ */ __name((config) => {
|
|
94
|
+
const since = unixTime(config.freeze_since_date);
|
|
95
|
+
if (!since)
|
|
96
|
+
return void 0;
|
|
97
|
+
const until = unixTime(config.freeze_until_date);
|
|
98
|
+
const appealUrl = typeof config.freeze_appeal_url === "string" && config.freeze_appeal_url ? config.freeze_appeal_url : void 0;
|
|
99
|
+
return {
|
|
100
|
+
state: "frozen",
|
|
101
|
+
since,
|
|
102
|
+
...until ? { until } : {},
|
|
103
|
+
...appealUrl ? { appealUrl } : {},
|
|
104
|
+
hint: "Telegram froze this account: it can read but not write" + (until ? `, and deletes it on ${until.slice(0, 10)} (UTC)` : "") + (appealUrl ? ` unless an appeal is accepted \u2014 appeal at ${appealUrl}` : " unless an appeal is accepted")
|
|
105
|
+
};
|
|
106
|
+
}, "frozenOf");
|
|
107
|
+
var me = /* @__PURE__ */ __name((feature) => {
|
|
108
|
+
return feature.call(async () => {
|
|
109
|
+
const user = await feature.client.getMe();
|
|
110
|
+
return { ...toAccount(user), phone: user.phoneNumber };
|
|
111
|
+
});
|
|
112
|
+
}, "me");
|
|
113
|
+
var health = /* @__PURE__ */ __name((feature) => {
|
|
114
|
+
return feature.call(async () => {
|
|
115
|
+
const config = await feature.client.call({ _: "help.getConfig" });
|
|
116
|
+
const serverTime = config.date * 1e3;
|
|
117
|
+
let appConfig;
|
|
118
|
+
try {
|
|
119
|
+
appConfig = await feature.client.appConfig.get();
|
|
120
|
+
} catch {
|
|
121
|
+
return { serverTime, serverTimeResolutionMs: 1e3, standingChecked: false };
|
|
122
|
+
}
|
|
123
|
+
const standing = frozenOf(appConfig);
|
|
124
|
+
return { serverTime, serverTimeResolutionMs: 1e3, standingChecked: true, ...standing ? { standing } : {} };
|
|
125
|
+
});
|
|
126
|
+
}, "health");
|
|
127
|
+
var updateProfile = /* @__PURE__ */ __name((feature, { firstName, lastName, description, photo }) => {
|
|
128
|
+
return feature.call(async () => {
|
|
129
|
+
if (firstName !== void 0 || lastName !== void 0 || description !== void 0) {
|
|
130
|
+
await feature.client.updateProfile({
|
|
131
|
+
...firstName === void 0 ? {} : { firstName },
|
|
132
|
+
...lastName === void 0 ? {} : { lastName },
|
|
133
|
+
...description === void 0 ? {} : { bio: description }
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
if (photo)
|
|
137
|
+
await feature.client.setMyProfilePhoto({ type: "photo", media: await uploadBlob(photo.source) });
|
|
138
|
+
const user = await feature.client.getMe();
|
|
139
|
+
return { ...toAccount(user), phone: user.phoneNumber };
|
|
140
|
+
});
|
|
141
|
+
}, "updateProfile");
|
|
142
|
+
|
|
143
|
+
// dist/telegram/bots.js
|
|
144
|
+
import { getMarkedPeerId as getMarkedPeerId2, tl } from "@mtcute/node";
|
|
145
|
+
|
|
146
|
+
// dist/telegram/feature.js
|
|
147
|
+
import { getMarkedPeerId, Long, PeersIndex, Message as TgMessage } from "@mtcute/node";
|
|
148
|
+
var unansweredText = /* @__PURE__ */ __name(({ what, check, after }, words) => `${what}; check ${words(check)}${after === void 0 ? "" : ` ${after}`}`, "unansweredText");
|
|
149
|
+
var repeatWith = /* @__PURE__ */ __name((sendId, sendAs) => sendAs === void 0 ? `--operation-id ${sendId}` : `--operation-id ${sendId} --send-as ${sendAs}`, "repeatWith");
|
|
150
|
+
var retryDetails = /* @__PURE__ */ __name((sendId, sendAs) => ({
|
|
151
|
+
operation_id: sendId,
|
|
152
|
+
...sendAs === void 0 ? {} : { sendAs }
|
|
153
|
+
}), "retryDetails");
|
|
154
|
+
var unknownIfUnanswered = /* @__PURE__ */ __name((error, what, details = {}) => {
|
|
155
|
+
const known = toCliError(error, bareCheck);
|
|
156
|
+
if (known instanceof CliError && ["timeout", "network_error"].includes(known.code)) {
|
|
157
|
+
return withCause(new CliError("outcome_unknown", `no answer from Telegram \u2014 ${what}`, { ...details, reason: "write.unanswered" }), known);
|
|
158
|
+
}
|
|
159
|
+
return error;
|
|
160
|
+
}, "unknownIfUnanswered");
|
|
161
|
+
var publicName = /* @__PURE__ */ __name((link) => link.replace(/^(https?:\/\/)?(t\.me|telegram\.me)\//, "").replace(/^@/, "").replace(/[/?].*$/, ""), "publicName");
|
|
162
|
+
var messageNumber = /* @__PURE__ */ __name((id, rule = "`id<` takes a message id") => {
|
|
163
|
+
if (!/^\d+$/.test(id))
|
|
164
|
+
throw new CliError("validation_error", `${rule}, got "${id}"`);
|
|
165
|
+
return Number(id);
|
|
166
|
+
}, "messageNumber");
|
|
167
|
+
var topicNumber = /* @__PURE__ */ __name((id) => {
|
|
168
|
+
if (!/^[1-9]\d*$/.test(id) || Number(id) > 2147483647) {
|
|
169
|
+
throw new CliError("validation_error", "--topic needs a positive Telegram topic id");
|
|
170
|
+
}
|
|
171
|
+
return Number(id);
|
|
172
|
+
}, "topicNumber");
|
|
173
|
+
var parseSendId = /* @__PURE__ */ __name((typed) => {
|
|
174
|
+
if (!/^-?\d{1,20}$/.test(typed))
|
|
175
|
+
throw new CliError("validation_error", "--operation-id is the number a failed send printed");
|
|
176
|
+
return Long.fromString(typed);
|
|
177
|
+
}, "parseSendId");
|
|
178
|
+
var forwardedCopy = /* @__PURE__ */ __name((updates, randomId, chatId) => {
|
|
179
|
+
if (updates._ !== "updates" && updates._ !== "updatesCombined")
|
|
180
|
+
return void 0;
|
|
181
|
+
const mapped = updates.updates.find((one) => one._ === "updateMessageID" && one.randomId.eq(randomId));
|
|
182
|
+
const id = mapped?._ === "updateMessageID" ? mapped.id : void 0;
|
|
183
|
+
for (const one of updates.updates) {
|
|
184
|
+
if (one._ !== "updateNewMessage" && one._ !== "updateNewChannelMessage")
|
|
185
|
+
continue;
|
|
186
|
+
if (one.message._ === "messageEmpty" || id !== void 0 && one.message.id !== id)
|
|
187
|
+
continue;
|
|
188
|
+
if (getMarkedPeerId(one.message.peerId) === Number(chatId))
|
|
189
|
+
return new TgMessage(one.message, PeersIndex.from(updates));
|
|
190
|
+
}
|
|
191
|
+
return void 0;
|
|
192
|
+
}, "forwardedCopy");
|
|
193
|
+
var remoteMessage = /* @__PURE__ */ __name((message) => observedCounters(toMessage(message), (/* @__PURE__ */ new Date()).toISOString(), ["views", "reactions", "comments"]), "remoteMessage");
|
|
194
|
+
var remoteHit = /* @__PURE__ */ __name((message, source) => ({
|
|
195
|
+
...toMessageHit(message),
|
|
196
|
+
...observedCounters(toMessage(message), (/* @__PURE__ */ new Date()).toISOString(), ["views", "reactions", "comments"], source)
|
|
197
|
+
}), "remoteHit");
|
|
198
|
+
|
|
199
|
+
// dist/telegram/bots.js
|
|
200
|
+
var LINK = /^(?:https?:\/\/)?(?:t|telegram)\.me\/([A-Za-z][\w]{3,})\/?(?:\?(.*))?$/;
|
|
201
|
+
var messageOf = /* @__PURE__ */ __name(async (feature, chatId, messageId) => {
|
|
202
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
203
|
+
const [message] = await feature.client.getMessages(Number(chatId), [id]);
|
|
204
|
+
if (!message)
|
|
205
|
+
throw new CliError("not_found", `message ${messageId} is not in this chat`);
|
|
206
|
+
return message;
|
|
207
|
+
}, "messageOf");
|
|
208
|
+
var buttons = /* @__PURE__ */ __name((feature, chatId, messageId) => feature.call(async () => toButtons((await messageOf(feature, chatId, messageId)).markup) ?? []), "buttons");
|
|
209
|
+
var pressButton = /* @__PURE__ */ __name((feature, chatId, messageId, row, column) => feature.write("the button may have reached the bot \u2014 pressing again tells it twice", async () => {
|
|
210
|
+
const message = await messageOf(feature, chatId, messageId);
|
|
211
|
+
const pressed = message.markup?.type === "inline" ? message.markup.buttons[row]?.[column] : void 0;
|
|
212
|
+
if (!pressed)
|
|
213
|
+
throw new CliError("not_found", "the message's buttons changed \u2014 read them again");
|
|
214
|
+
const { type } = pressed;
|
|
215
|
+
if (type._ !== "inlineButtonTypeCallback" || type.requiresPassword)
|
|
216
|
+
throw new CliError("validation_error", `not pressed: "${pressed.text}" is not a button this CLI presses`);
|
|
217
|
+
try {
|
|
218
|
+
await feature.client.getCallbackAnswer({
|
|
219
|
+
chatId: Number(chatId),
|
|
220
|
+
message: message.id,
|
|
221
|
+
data: type.data
|
|
222
|
+
});
|
|
223
|
+
} catch (error) {
|
|
224
|
+
if (!tl.RpcError.is(error, "BOT_RESPONSE_TIMEOUT"))
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
}), "pressButton");
|
|
228
|
+
var botByLink = /* @__PURE__ */ __name((feature, reference) => {
|
|
229
|
+
const typed = reference.trim();
|
|
230
|
+
const web = LINK.exec(typed);
|
|
231
|
+
const app = /^tg:\/\/resolve\?(.*)$/.exec(typed);
|
|
232
|
+
const query = new URLSearchParams(web?.[2] ?? app?.[1] ?? "");
|
|
233
|
+
const name = web ? publicName(typed) : query.get("domain");
|
|
234
|
+
if (!name || !/bot$/i.test(name))
|
|
235
|
+
return Promise.resolve(void 0);
|
|
236
|
+
const payload = query.get("start") ?? void 0;
|
|
237
|
+
return feature.call(async () => ({
|
|
238
|
+
chatId: String(getMarkedPeerId2(await feature.client.resolvePeer(name))),
|
|
239
|
+
...payload === void 0 ? {} : { payload }
|
|
240
|
+
}));
|
|
241
|
+
}, "botByLink");
|
|
242
|
+
var startBot = /* @__PURE__ */ __name((feature, chatId, { sendId, payload }) => {
|
|
243
|
+
const randomId = parseSendId(sendId);
|
|
244
|
+
return feature.send(async () => {
|
|
245
|
+
const bot = await feature.client.getPeer(Number(chatId));
|
|
246
|
+
if (bot.type !== "user" || !bot.isBot)
|
|
247
|
+
throw new CliError("validation_error", "this chat is not a bot");
|
|
248
|
+
const peer = await feature.client.resolvePeer(Number(chatId));
|
|
249
|
+
const user = await feature.client.resolveUser(Number(chatId));
|
|
250
|
+
try {
|
|
251
|
+
await feature.client.call({
|
|
252
|
+
_: "messages.startBot",
|
|
253
|
+
bot: user,
|
|
254
|
+
peer,
|
|
255
|
+
randomId,
|
|
256
|
+
startParam: payload ?? ""
|
|
257
|
+
});
|
|
258
|
+
} catch (error) {
|
|
259
|
+
throw unknownIfUnanswered(error, `the bot may have been started. Repeat with ${repeatWith(sendId, void 0)}, never without it`, retryDetails(sendId, void 0));
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
}, "startBot");
|
|
263
|
+
var botApp = /* @__PURE__ */ __name((feature, chatId, { startParam }) => feature.call(async () => {
|
|
264
|
+
const bot = await feature.client.getPeer(Number(chatId));
|
|
265
|
+
if (bot.type !== "user" || !bot.isBot)
|
|
266
|
+
throw new CliError("validation_error", "this chat is not a bot");
|
|
267
|
+
const view = await feature.client.openWebview({
|
|
268
|
+
webview: { type: "main", ...startParam === void 0 ? {} : { startParam } },
|
|
269
|
+
bot: Number(chatId),
|
|
270
|
+
platform: "tdesktop"
|
|
271
|
+
});
|
|
272
|
+
return { url: view.url };
|
|
273
|
+
}), "botApp");
|
|
274
|
+
|
|
275
|
+
// dist/telegram/chat-list.js
|
|
276
|
+
var FOREVER = 2147483647;
|
|
277
|
+
var REPEAT_SAFE = "repeating it is safe";
|
|
278
|
+
var mute = /* @__PURE__ */ __name((feature, chatId, until) => feature.write(`the notification setting may have changed \u2014 ${REPEAT_SAFE}`, async () => {
|
|
279
|
+
const { client } = feature;
|
|
280
|
+
const muteUntil = until === null ? 0 : until === "forever" ? FOREVER : Math.floor(Date.parse(until) / 1e3);
|
|
281
|
+
await client.call({
|
|
282
|
+
_: "account.updateNotifySettings",
|
|
283
|
+
peer: { _: "inputNotifyPeer", peer: await client.resolvePeer(await feature.inputOf(chatId)) },
|
|
284
|
+
settings: { _: "inputPeerNotifySettings", muteUntil }
|
|
285
|
+
});
|
|
286
|
+
}), "mute");
|
|
287
|
+
var archiveChat = /* @__PURE__ */ __name((feature, chatId, archived) => feature.write(`the chat may have moved \u2014 ${REPEAT_SAFE}`, async () => {
|
|
288
|
+
const peer = await feature.inputOf(chatId);
|
|
289
|
+
await (archived ? feature.client.archiveChats(peer) : feature.client.unarchiveChats(peer));
|
|
290
|
+
}), "archiveChat");
|
|
291
|
+
var pinChat = /* @__PURE__ */ __name((feature, chatId, pinned) => feature.write(`the chat may have been ${pinned ? "pinned" : "unpinned"} \u2014 ${REPEAT_SAFE}`, async () => {
|
|
292
|
+
const { client } = feature;
|
|
293
|
+
await client.call({
|
|
294
|
+
_: "messages.toggleDialogPin",
|
|
295
|
+
pinned,
|
|
296
|
+
peer: { _: "inputDialogPeer", peer: await client.resolvePeer(await feature.inputOf(chatId)) }
|
|
297
|
+
});
|
|
298
|
+
}), "pinChat");
|
|
299
|
+
var markChatUnread = /* @__PURE__ */ __name((feature, chatId) => feature.write(`the chat may have been marked \u2014 ${REPEAT_SAFE}`, async () => {
|
|
300
|
+
await feature.client.markChatUnread(await feature.inputOf(chatId));
|
|
301
|
+
}), "markChatUnread");
|
|
302
|
+
|
|
303
|
+
// dist/telegram/groups.js
|
|
304
|
+
import { ChatInviteLink, MtPeerNotFoundError, PeersIndex as PeersIndex2 } from "@mtcute/node";
|
|
305
|
+
|
|
306
|
+
// dist/telegram/join-requests.js
|
|
307
|
+
import { tl as tl2 } from "@mtcute/node";
|
|
308
|
+
var joinRequestsOf = /* @__PURE__ */ __name(async (client, chatId, limit, { link, search } = {}) => {
|
|
309
|
+
const page = await client.getInviteLinkMembers(chatId, {
|
|
310
|
+
requested: true,
|
|
311
|
+
limit,
|
|
312
|
+
...link ? { link } : {},
|
|
313
|
+
...search ? { requestedSearch: search } : {}
|
|
314
|
+
});
|
|
315
|
+
return {
|
|
316
|
+
items: page.map((one) => ({
|
|
317
|
+
person: toMember(one.user),
|
|
318
|
+
requestedAt: one.date.toISOString(),
|
|
319
|
+
...one.bio ? { about: one.bio } : {}
|
|
320
|
+
})),
|
|
321
|
+
hasMore: page.total > page.length,
|
|
322
|
+
total: page.total
|
|
323
|
+
};
|
|
324
|
+
}, "joinRequestsOf");
|
|
325
|
+
var answerJoinRequestOf = /* @__PURE__ */ __name(async (client, chatId, personId, accept, words) => {
|
|
326
|
+
try {
|
|
327
|
+
await client.hideJoinRequest({ chatId, user: personId, action: accept ? "approve" : "decline" });
|
|
328
|
+
return { already: false };
|
|
329
|
+
} catch (error) {
|
|
330
|
+
if (tl2.RpcError.is(error, "USER_ALREADY_PARTICIPANT"))
|
|
331
|
+
return { already: true };
|
|
332
|
+
if (tl2.RpcError.is(error, "HIDE_REQUESTER_MISSING"))
|
|
333
|
+
throw new CliError("not_found", `they have no request to answer \u2014 it was answered already, or withdrawn; see ${words("chats.requests.list")}`);
|
|
334
|
+
throw error;
|
|
335
|
+
}
|
|
336
|
+
}, "answerJoinRequestOf");
|
|
337
|
+
|
|
338
|
+
// dist/telegram/groups.js
|
|
339
|
+
var MEMBERS_MAX = 1e4;
|
|
340
|
+
var MEMBER_PAGE_PAUSE_MS = 1e3;
|
|
341
|
+
var EVENT_PAGES = 10;
|
|
342
|
+
var isInvite = /* @__PURE__ */ __name((link) => /(t\.me|telegram\.me)\/(\+|joinchat\/)|^tg:\/\/join/.test(link), "isInvite");
|
|
343
|
+
var groupCount = /* @__PURE__ */ __name(async ({ client }, group2, listTotal) => {
|
|
344
|
+
if (group2.type !== "chat" || group2.raw?._ !== "channel")
|
|
345
|
+
return groupMembersCount(group2);
|
|
346
|
+
const full = await client.getFullChat(group2.id);
|
|
347
|
+
const hidden = full.full._ === "channelFull" && full.full.participantsHidden === true && !full.isAdmin;
|
|
348
|
+
return hidden || listTotal === null ? groupMembersCount(full) : listTotal || null;
|
|
349
|
+
}, "groupCount");
|
|
350
|
+
var membersOf = /* @__PURE__ */ __name(async ({ client, login: login2, checks }, peer) => {
|
|
351
|
+
try {
|
|
352
|
+
return await client.getChatMembers(peer, { limit: 200 });
|
|
353
|
+
} catch (error) {
|
|
354
|
+
const known = toCliError(error, checks, login2);
|
|
355
|
+
if (known instanceof CliError && known.code === "permission_error")
|
|
356
|
+
return null;
|
|
357
|
+
throw known;
|
|
358
|
+
}
|
|
359
|
+
}, "membersOf");
|
|
360
|
+
var inspect = /* @__PURE__ */ __name((feature, link) => {
|
|
361
|
+
const typed = link.trim();
|
|
362
|
+
const invite = isInvite(typed);
|
|
363
|
+
return feature.call(async () => {
|
|
364
|
+
if (invite) {
|
|
365
|
+
try {
|
|
366
|
+
return toInvitePreview(await feature.client.getChatPreview(typed));
|
|
367
|
+
} catch (error) {
|
|
368
|
+
if (!(error instanceof MtPeerNotFoundError))
|
|
369
|
+
throw error;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return toLinkChat(await feature.client.getFullChat(invite ? typed : publicName(typed)));
|
|
373
|
+
});
|
|
374
|
+
}, "inspect");
|
|
375
|
+
var members = /* @__PURE__ */ __name((feature, reference, { limit, offset }) => feature.call(async () => {
|
|
376
|
+
const peer = await feature.inputOf(reference);
|
|
377
|
+
const group2 = await feature.client.getPeer(peer);
|
|
378
|
+
const wanted = Math.min(limit ?? MEMBERS_MAX, MEMBERS_MAX - offset);
|
|
379
|
+
const found = [];
|
|
380
|
+
let total = null;
|
|
381
|
+
while (found.length < wanted) {
|
|
382
|
+
if (found.length > 0)
|
|
383
|
+
await new Promise((resolve2) => setTimeout(resolve2, MEMBER_PAGE_PAUSE_MS));
|
|
384
|
+
const size = Math.min(200, wanted - found.length);
|
|
385
|
+
const page = await feature.client.getChatMembers(peer, { offset: offset + found.length, limit: size });
|
|
386
|
+
total = page.total;
|
|
387
|
+
found.push(...page.map(toGroupMember));
|
|
388
|
+
if (page.length < size)
|
|
389
|
+
break;
|
|
390
|
+
}
|
|
391
|
+
return {
|
|
392
|
+
chatId: String(group2.id),
|
|
393
|
+
items: found,
|
|
394
|
+
hasMore: offset + found.length < Math.min(total ?? 0, MEMBERS_MAX),
|
|
395
|
+
participantsCount: offset === 0 ? await groupCount(feature, group2, total) : null
|
|
396
|
+
};
|
|
397
|
+
}), "members");
|
|
398
|
+
var chatEvents = /* @__PURE__ */ __name((feature, reference, { since }) => feature.call(async () => {
|
|
399
|
+
const { client } = feature;
|
|
400
|
+
const peer = await feature.inputOf(reference);
|
|
401
|
+
const found = [];
|
|
402
|
+
let offset;
|
|
403
|
+
let more = false;
|
|
404
|
+
for (let read = 1; ; read++) {
|
|
405
|
+
const page = await client.getHistory(peer, { limit: 100, ...offset ? { offset } : {} });
|
|
406
|
+
for (const message of page) {
|
|
407
|
+
const change = message.date.getTime() > since ? eventOf(message) : null;
|
|
408
|
+
if (change)
|
|
409
|
+
found.push({ message, change });
|
|
410
|
+
}
|
|
411
|
+
const oldest = page.at(-1);
|
|
412
|
+
if (!page.next || !oldest || oldest.date.getTime() <= since)
|
|
413
|
+
break;
|
|
414
|
+
if (read >= EVENT_PAGES) {
|
|
415
|
+
more = true;
|
|
416
|
+
break;
|
|
417
|
+
}
|
|
418
|
+
offset = page.next;
|
|
419
|
+
}
|
|
420
|
+
const names = new Map(found.map(({ message }) => [message.sender.id, message.sender.displayName || null]));
|
|
421
|
+
const unknown = [...new Set(found.flatMap(({ change }) => [change.by, ...change.people]))].filter((id) => !names.has(id));
|
|
422
|
+
if (unknown.length > 0) {
|
|
423
|
+
for (const user of await client.getUsers(unknown))
|
|
424
|
+
if (user)
|
|
425
|
+
names.set(user.id, user.displayName || null);
|
|
426
|
+
}
|
|
427
|
+
const person = /* @__PURE__ */ __name((id) => ({ id: String(id), name: names.get(id) ?? null }), "person");
|
|
428
|
+
return {
|
|
429
|
+
chatId: String((await client.getPeer(peer)).id),
|
|
430
|
+
since: new Date(since).toISOString(),
|
|
431
|
+
more,
|
|
432
|
+
events: found.reverse().map(({ message, change }) => ({
|
|
433
|
+
messageId: String(message.id),
|
|
434
|
+
timestamp: message.date.toISOString(),
|
|
435
|
+
event: change.event,
|
|
436
|
+
by: person(change.by),
|
|
437
|
+
people: change.people.map(person),
|
|
438
|
+
...change.title === void 0 ? {} : { title: change.title }
|
|
439
|
+
}))
|
|
440
|
+
};
|
|
441
|
+
}), "chatEvents");
|
|
442
|
+
var admins = /* @__PURE__ */ __name((feature, reference) => feature.call(async () => {
|
|
443
|
+
const peer = await feature.inputOf(reference);
|
|
444
|
+
try {
|
|
445
|
+
const found = await feature.client.getChatMembers(peer, { type: "admins", limit: 200 });
|
|
446
|
+
return found.filter((member) => member.status === "creator" || member.status === "admin").map((member) => String(member.user.id));
|
|
447
|
+
} catch (error) {
|
|
448
|
+
const known = toCliError(error, feature.checks, feature.login);
|
|
449
|
+
if (known instanceof CliError && known.code === "permission_error")
|
|
450
|
+
return null;
|
|
451
|
+
throw known;
|
|
452
|
+
}
|
|
453
|
+
}), "admins");
|
|
454
|
+
var people = /* @__PURE__ */ __name((feature, references) => feature.call(async () => {
|
|
455
|
+
const ids = [];
|
|
456
|
+
for (const reference of references) {
|
|
457
|
+
const peer = await feature.client.getPeer(await feature.inputOf(reference));
|
|
458
|
+
if (peer.type !== "user")
|
|
459
|
+
throw new CliError("validation_error", `${reference} is a chat, not a person`);
|
|
460
|
+
ids.push(String(peer.id));
|
|
461
|
+
}
|
|
462
|
+
return ids;
|
|
463
|
+
}), "people");
|
|
464
|
+
var createGroup = /* @__PURE__ */ __name((feature, title, invited, { channel }) => feature.call(async () => {
|
|
465
|
+
const { client } = feature;
|
|
466
|
+
try {
|
|
467
|
+
const made = channel ? await client.createChannel({ title }) : await client.createSupergroup({ title });
|
|
468
|
+
const missing = invited.length > 0 ? await client.addChatMembers(made.id, invited.map(Number), {}) : [];
|
|
469
|
+
const card = toGroupCard(await client.getFullChat(made.id));
|
|
470
|
+
if (missing.length === 0)
|
|
471
|
+
return card;
|
|
472
|
+
const notAdded = missing.map((one) => String(one.userId));
|
|
473
|
+
return { ...card, providerMetadata: { ...card.providerMetadata, notAdded } };
|
|
474
|
+
} catch (error) {
|
|
475
|
+
throw feature.unanswered(error, { what: "the group may or may not have been made", check: "chats.list" });
|
|
476
|
+
}
|
|
477
|
+
}), "createGroup");
|
|
478
|
+
var join = /* @__PURE__ */ __name((feature, link) => {
|
|
479
|
+
const typed = link.trim();
|
|
480
|
+
const invite = isInvite(typed);
|
|
481
|
+
return feature.call(async () => {
|
|
482
|
+
let joined;
|
|
483
|
+
try {
|
|
484
|
+
joined = await feature.client.joinChat(invite ? typed : publicName(typed));
|
|
485
|
+
} catch (error) {
|
|
486
|
+
throw feature.unanswered(error, { what: "you may or may not have joined", check: "chats.list" });
|
|
487
|
+
}
|
|
488
|
+
if (joined.status === "request_sent")
|
|
489
|
+
return { requested: true };
|
|
490
|
+
if (joined.status !== "ok") {
|
|
491
|
+
throw new CliError("provider_error", "this group asks a bot to check who joins, which only the Telegram app can show");
|
|
492
|
+
}
|
|
493
|
+
return toGroupCard(await feature.client.getFullChat(joined.chat.id));
|
|
494
|
+
});
|
|
495
|
+
}, "join");
|
|
496
|
+
var leave = /* @__PURE__ */ __name((feature, reference) => feature.call(async () => {
|
|
497
|
+
const peer = await feature.inputOf(reference);
|
|
498
|
+
const chatId = String((await feature.client.getPeer(peer)).id);
|
|
499
|
+
try {
|
|
500
|
+
await feature.client.leaveChat(peer);
|
|
501
|
+
} catch (error) {
|
|
502
|
+
throw feature.unanswered(error, { what: "you may or may not have left", check: "chats.list" });
|
|
503
|
+
}
|
|
504
|
+
return { chatId };
|
|
505
|
+
}), "leave");
|
|
506
|
+
var group = /* @__PURE__ */ __name((feature, reference) => feature.call(async () => toGroupCard(await feature.client.getFullChat(await feature.inputOf(reference)))), "group");
|
|
507
|
+
var updateGroup = /* @__PURE__ */ __name((feature, chatId, { title, description, settings = {} }) => {
|
|
508
|
+
const missing = Object.keys(settings).filter((key) => !GROUP_SETTINGS.includes(key));
|
|
509
|
+
if (missing.length > 0) {
|
|
510
|
+
throw new CliError("validation_error", `Telegram has no group setting ${missing.join(", ")}`);
|
|
511
|
+
}
|
|
512
|
+
const peer = Number(chatId);
|
|
513
|
+
return feature.call(async () => {
|
|
514
|
+
const { client } = feature;
|
|
515
|
+
try {
|
|
516
|
+
if (title !== void 0)
|
|
517
|
+
await client.setChatTitle(peer, title);
|
|
518
|
+
if (description !== void 0)
|
|
519
|
+
await client.setChatDescription(peer, description);
|
|
520
|
+
const { allCanPin, onlyAdminsAdd, joinApproval } = settings;
|
|
521
|
+
if (typeof joinApproval === "boolean")
|
|
522
|
+
await client.toggleJoinRequests(peer, joinApproval);
|
|
523
|
+
if (typeof allCanPin === "boolean" || typeof onlyAdminsAdd === "boolean") {
|
|
524
|
+
const current = (await client.getFullChat(peer)).defaultPermissions?.raw;
|
|
525
|
+
const { _: _kind, untilDate: _until, ...taken } = current ?? { _: "chatBannedRights", untilDate: 0 };
|
|
526
|
+
await client.setChatDefaultPermissions(peer, {
|
|
527
|
+
...taken,
|
|
528
|
+
...typeof allCanPin === "boolean" ? { pinMessages: !allCanPin } : {},
|
|
529
|
+
...typeof onlyAdminsAdd === "boolean" ? { inviteUsers: onlyAdminsAdd } : {}
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
} catch (error) {
|
|
533
|
+
throw feature.unanswered(error, { what: "the group may have changed in part", check: "chats.show" });
|
|
534
|
+
}
|
|
535
|
+
return toGroupCard(await client.getFullChat(peer));
|
|
536
|
+
});
|
|
537
|
+
}, "updateGroup");
|
|
538
|
+
var resetInviteLink = /* @__PURE__ */ __name((feature, chatId) => {
|
|
539
|
+
const peer = Number(chatId);
|
|
540
|
+
return feature.call(async () => {
|
|
541
|
+
try {
|
|
542
|
+
await feature.client.exportInviteLink(peer);
|
|
543
|
+
} catch (error) {
|
|
544
|
+
throw feature.unanswered(error, { what: "the link may or may not have been replaced", check: "chats.links.show" });
|
|
545
|
+
}
|
|
546
|
+
return toGroupCard(await feature.client.getFullChat(peer));
|
|
547
|
+
});
|
|
548
|
+
}, "resetInviteLink");
|
|
549
|
+
var createInviteLink = /* @__PURE__ */ __name((feature, chatId, { approval, expiresAt, maxUses }) => feature.call(async () => {
|
|
550
|
+
try {
|
|
551
|
+
return toInviteLink(await feature.client.createInviteLink(Number(chatId), {
|
|
552
|
+
withApproval: approval,
|
|
553
|
+
...expiresAt === void 0 ? {} : { expires: new Date(expiresAt) },
|
|
554
|
+
...maxUses === void 0 ? {} : { usageLimit: maxUses }
|
|
555
|
+
}));
|
|
556
|
+
} catch (error) {
|
|
557
|
+
throw feature.unanswered(error, "a link may or may not have been made; it works only once shared");
|
|
558
|
+
}
|
|
559
|
+
}), "createInviteLink");
|
|
560
|
+
var joinRequests = /* @__PURE__ */ __name((feature, chatId, { limit, link, search }) => feature.call(() => joinRequestsOf(feature.client, Number(chatId), limit, {
|
|
561
|
+
...link ? { link } : {},
|
|
562
|
+
...search ? { search } : {}
|
|
563
|
+
})), "joinRequests");
|
|
564
|
+
var answerAllJoinRequests = /* @__PURE__ */ __name((feature, chatId, accept, link) => feature.call(async () => {
|
|
565
|
+
try {
|
|
566
|
+
await feature.client.hideAllJoinRequests({
|
|
567
|
+
chatId: Number(chatId),
|
|
568
|
+
action: accept ? "approve" : "decline",
|
|
569
|
+
...link ? { link } : {}
|
|
570
|
+
});
|
|
571
|
+
} catch (error) {
|
|
572
|
+
throw feature.unanswered(error, {
|
|
573
|
+
what: "the requests may or may not have been answered",
|
|
574
|
+
check: "chats.requests.list"
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
}), "answerAllJoinRequests");
|
|
578
|
+
var inviteLinks = /* @__PURE__ */ __name((feature, chatId, { limit, revoked }) => feature.call(async () => {
|
|
579
|
+
const page = await feature.client.getInviteLinks(Number(chatId), { limit, revoked });
|
|
580
|
+
return { items: page.map(toInviteLink), hasMore: page.total > page.length };
|
|
581
|
+
}), "inviteLinks");
|
|
582
|
+
var revokeInviteLink = /* @__PURE__ */ __name((feature, chatId, link) => feature.call(async () => {
|
|
583
|
+
try {
|
|
584
|
+
return toInviteLink(await feature.client.revokeInviteLink(Number(chatId), link));
|
|
585
|
+
} catch (error) {
|
|
586
|
+
throw feature.unanswered(error, { what: "the link may or may not have been revoked", check: "chats.links.list" });
|
|
587
|
+
}
|
|
588
|
+
}), "revokeInviteLink");
|
|
589
|
+
var updateInviteLink = /* @__PURE__ */ __name((feature, chatId, link, { approval, expiresAt, maxUses }) => feature.call(async () => {
|
|
590
|
+
const peer = await feature.client.resolvePeer(Number(chatId));
|
|
591
|
+
try {
|
|
592
|
+
const answer = await feature.client.call({
|
|
593
|
+
_: "messages.editExportedChatInvite",
|
|
594
|
+
peer,
|
|
595
|
+
link,
|
|
596
|
+
...approval === void 0 ? {} : { requestNeeded: approval },
|
|
597
|
+
...expiresAt === void 0 ? {} : { expireDate: expiresAt === null ? 0 : Date.parse(expiresAt) / 1e3 },
|
|
598
|
+
...maxUses === void 0 ? {} : { usageLimit: maxUses }
|
|
599
|
+
});
|
|
600
|
+
return toInviteLink(new ChatInviteLink(answer.invite, PeersIndex2.from(answer)));
|
|
601
|
+
} catch (error) {
|
|
602
|
+
throw feature.unanswered(error, { what: "the link may or may not have been changed", check: "chats.links.list" });
|
|
603
|
+
}
|
|
604
|
+
}), "updateInviteLink");
|
|
605
|
+
var answerJoinRequest = /* @__PURE__ */ __name((feature, chatId, personId, accept) => feature.call(async () => {
|
|
606
|
+
try {
|
|
607
|
+
return await answerJoinRequestOf(feature.client, Number(chatId), Number(personId), accept, feature.checks);
|
|
608
|
+
} catch (error) {
|
|
609
|
+
throw feature.unanswered(error, {
|
|
610
|
+
what: `the request of ${personId} may or may not have been answered`,
|
|
611
|
+
check: "chats.requests.list"
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
}), "answerJoinRequest");
|
|
615
|
+
var addMembers = /* @__PURE__ */ __name((feature, chatId, added, { history: history2 }) => {
|
|
616
|
+
if (history2)
|
|
617
|
+
throw new CliError("validation_error", "Telegram shows new members the history by the group's setting, not per person");
|
|
618
|
+
return feature.call(async () => {
|
|
619
|
+
try {
|
|
620
|
+
const missing = await feature.client.addChatMembers(Number(chatId), added.map(Number), {});
|
|
621
|
+
return { notAdded: missing.map((one) => String(one.userId)) };
|
|
622
|
+
} catch (error) {
|
|
623
|
+
throw feature.unanswered(error, {
|
|
624
|
+
what: "the people may or may not have been added",
|
|
625
|
+
check: "chats.members.list"
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
});
|
|
629
|
+
}, "addMembers");
|
|
630
|
+
var removeMembers = /* @__PURE__ */ __name((feature, chatId, removed) => feature.call(async () => {
|
|
631
|
+
for (const person of removed) {
|
|
632
|
+
try {
|
|
633
|
+
await feature.client.kickChatMember({ chatId: Number(chatId), userId: Number(person) });
|
|
634
|
+
} catch (error) {
|
|
635
|
+
throw feature.unanswered(error, {
|
|
636
|
+
what: `${person} may or may not have been removed`,
|
|
637
|
+
check: "chats.members.list"
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}), "removeMembers");
|
|
642
|
+
var editAdmin = /* @__PURE__ */ __name((feature, chatId, person, rights) => feature.call(async () => {
|
|
643
|
+
try {
|
|
644
|
+
await feature.client.editAdminRights({ chatId: Number(chatId), userId: Number(person), rights });
|
|
645
|
+
} catch (error) {
|
|
646
|
+
throw feature.unanswered(error, {
|
|
647
|
+
what: "the rights may or may not have changed",
|
|
648
|
+
check: "chats.members.list"
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
}), "editAdmin");
|
|
652
|
+
var addAdmin = /* @__PURE__ */ __name((feature, chatId, person, rights) => {
|
|
653
|
+
const missing = rights.filter((right) => !(right in ADMIN_RIGHT_FIELDS));
|
|
654
|
+
if (missing.length > 0)
|
|
655
|
+
throw new CliError("validation_error", `Telegram has no admin right ${missing.join(", ")}`);
|
|
656
|
+
const fields = Object.fromEntries(rights.map((right) => [ADMIN_RIGHT_FIELDS[right], true]));
|
|
657
|
+
return editAdmin(feature, chatId, person, fields);
|
|
658
|
+
}, "addAdmin");
|
|
659
|
+
var removeAdmin = /* @__PURE__ */ __name((feature, chatId, person) => editAdmin(feature, chatId, person, {}), "removeAdmin");
|
|
660
|
+
|
|
661
|
+
// dist/telegram/chats.js
|
|
662
|
+
var SAVED = /* @__PURE__ */ new Set(["me", "self", "saved"]);
|
|
663
|
+
var DIALOG_WALK_KEPT_MS = 6e4;
|
|
664
|
+
var pull = /* @__PURE__ */ __name(async (walk, wanted) => {
|
|
665
|
+
const chats2 = walk.held;
|
|
666
|
+
while (chats2.length < wanted) {
|
|
667
|
+
const next = await walk.dialogs.next();
|
|
668
|
+
if (next.done)
|
|
669
|
+
break;
|
|
670
|
+
const chat2 = toChat(next.value);
|
|
671
|
+
if (walk.seen.has(chat2.id))
|
|
672
|
+
continue;
|
|
673
|
+
walk.seen.add(chat2.id);
|
|
674
|
+
chats2.push(chat2);
|
|
675
|
+
}
|
|
676
|
+
return chats2;
|
|
677
|
+
}, "pull");
|
|
678
|
+
var dialogs = /* @__PURE__ */ __name(async (client, wanted) => {
|
|
679
|
+
const seen = /* @__PURE__ */ new Set();
|
|
680
|
+
const chats2 = [];
|
|
681
|
+
for await (const dialog of client.iterDialogs({ archived: "keep" })) {
|
|
682
|
+
const chat2 = toChat(dialog);
|
|
683
|
+
if (seen.has(chat2.id))
|
|
684
|
+
continue;
|
|
685
|
+
seen.add(chat2.id);
|
|
686
|
+
chats2.push(chat2);
|
|
687
|
+
if (chats2.length >= wanted)
|
|
688
|
+
break;
|
|
689
|
+
}
|
|
690
|
+
return chats2;
|
|
691
|
+
}, "dialogs");
|
|
692
|
+
var peerOf = /* @__PURE__ */ __name(async (client, reference) => {
|
|
693
|
+
const trimmed = reference.trim();
|
|
694
|
+
if (SAVED.has(trimmed.toLowerCase()))
|
|
695
|
+
return "me";
|
|
696
|
+
if (/^-?\d+$/.test(trimmed))
|
|
697
|
+
return Number(trimmed);
|
|
698
|
+
if (trimmed.startsWith("@"))
|
|
699
|
+
return trimmed.slice(1);
|
|
700
|
+
return pickChat(trimmed, await dialogs(client, Number.POSITIVE_INFINITY));
|
|
701
|
+
}, "peerOf");
|
|
702
|
+
var inputOf = /* @__PURE__ */ __name(async (client, reference) => {
|
|
703
|
+
const peer = await peerOf(client, reference);
|
|
704
|
+
return typeof peer === "object" && "kind" in peer ? Number(peer.id) : peer;
|
|
705
|
+
}, "inputOf");
|
|
706
|
+
var chats = /* @__PURE__ */ __name(({ call, client }, walking, { limit, offset }) => call(async () => {
|
|
707
|
+
if (limit === void 0) {
|
|
708
|
+
const items2 = await dialogs(client, Number.POSITIVE_INFINITY);
|
|
709
|
+
return { items: items2.slice(offset), hasMore: false };
|
|
710
|
+
}
|
|
711
|
+
const resumed = walking.walk;
|
|
712
|
+
walking.walk = void 0;
|
|
713
|
+
const walk = resumed && offset > 0 && resumed.at === offset && Date.now() < resumed.until ? resumed : {
|
|
714
|
+
dialogs: client.iterDialogs({ archived: "keep" }),
|
|
715
|
+
seen: /* @__PURE__ */ new Set(),
|
|
716
|
+
held: [],
|
|
717
|
+
at: 0,
|
|
718
|
+
until: 0
|
|
719
|
+
};
|
|
720
|
+
const pulled = await pull(walk, offset - walk.at + limit + 1);
|
|
721
|
+
const items = pulled.slice(offset - walk.at, offset - walk.at + limit);
|
|
722
|
+
walk.held = pulled.slice(offset - walk.at + limit);
|
|
723
|
+
walk.at = offset + items.length;
|
|
724
|
+
walk.until = Date.now() + DIALOG_WALK_KEPT_MS;
|
|
725
|
+
walking.walk = walk;
|
|
726
|
+
return { items, hasMore: walk.held.length > 0 };
|
|
727
|
+
}), "chats");
|
|
728
|
+
var chat = /* @__PURE__ */ __name((feature, reference) => feature.call(async () => {
|
|
729
|
+
const peer = await feature.inputOf(reference);
|
|
730
|
+
const [dialog] = await feature.client.getPeerDialogs(peer);
|
|
731
|
+
const found = dialog ? dialog.peer : await feature.client.getPeer(peer);
|
|
732
|
+
const chat2 = dialog ? toChat(dialog) : peerToChat(found);
|
|
733
|
+
if (chat2.kind !== "group")
|
|
734
|
+
return { ...chat2, members: null };
|
|
735
|
+
const members2 = await membersOf(feature, peer);
|
|
736
|
+
return {
|
|
737
|
+
...chat2,
|
|
738
|
+
participantsCount: await groupCount(feature, found, members2?.total ?? null),
|
|
739
|
+
members: members2?.map((member) => toMember(member.user)) ?? null
|
|
740
|
+
};
|
|
741
|
+
}), "chat");
|
|
742
|
+
var resolve = /* @__PURE__ */ __name(({ call, client }, reference) => call(async () => {
|
|
743
|
+
const peer = await peerOf(client, reference);
|
|
744
|
+
return typeof peer === "object" && "kind" in peer ? peer : peerToChat(await client.getPeer(peer));
|
|
745
|
+
}), "resolve");
|
|
746
|
+
|
|
747
|
+
// dist/telegram/comments.js
|
|
748
|
+
import { getMarkedPeerId as getMarkedPeerId3, Long as Long2, PeersIndex as PeersIndex3, Message as TgMessage2, tl as tl3 } from "@mtcute/node";
|
|
749
|
+
var PAGE = 100;
|
|
750
|
+
var noComments = /* @__PURE__ */ __name(() => new CliError("not_found", "this post takes no comments \u2014 the channel has no discussion, or the post is closed to them"), "noComments");
|
|
751
|
+
var discussionOf = /* @__PURE__ */ __name(async (client, channelId, postId) => {
|
|
752
|
+
try {
|
|
753
|
+
const answer = await client.call({
|
|
754
|
+
_: "messages.getDiscussionMessage",
|
|
755
|
+
peer: await client.resolvePeer(channelId),
|
|
756
|
+
msgId: postId
|
|
757
|
+
});
|
|
758
|
+
const [root] = answer.messages;
|
|
759
|
+
if (!root || root._ === "messageEmpty")
|
|
760
|
+
throw noComments();
|
|
761
|
+
return { chatId: String(getMarkedPeerId3(root.peerId)), messageId: String(root.id) };
|
|
762
|
+
} catch (error) {
|
|
763
|
+
if (tl3.RpcError.is(error, "MSG_ID_INVALID"))
|
|
764
|
+
throw noComments();
|
|
765
|
+
throw error;
|
|
766
|
+
}
|
|
767
|
+
}, "discussionOf");
|
|
768
|
+
var commentsOf = /* @__PURE__ */ __name(async (client, channelId, postId, { limit, before }) => {
|
|
769
|
+
const answer = await client.call({
|
|
770
|
+
_: "messages.getReplies",
|
|
771
|
+
peer: await client.resolvePeer(channelId),
|
|
772
|
+
msgId: postId,
|
|
773
|
+
offsetId: before ?? 0,
|
|
774
|
+
offsetDate: 0,
|
|
775
|
+
addOffset: 0,
|
|
776
|
+
limit: Math.min(limit + 1, PAGE),
|
|
777
|
+
maxId: 0,
|
|
778
|
+
minId: 0,
|
|
779
|
+
hash: Long2.ZERO
|
|
780
|
+
});
|
|
781
|
+
if (answer._ === "messages.messagesNotModified")
|
|
782
|
+
return { items: [], hasMore: false };
|
|
783
|
+
const peers = PeersIndex3.from(answer);
|
|
784
|
+
const found = answer.messages.filter((one) => one._ === "message").map((one) => new TgMessage2(one, peers));
|
|
785
|
+
return { items: found.slice(0, limit).reverse(), hasMore: found.length > limit || found.length === PAGE };
|
|
786
|
+
}, "commentsOf");
|
|
787
|
+
|
|
788
|
+
// dist/telegram/profile.js
|
|
789
|
+
var ID_MONTHS = [
|
|
790
|
+
[1, "2013-08"],
|
|
791
|
+
[2e6, "2013-11"],
|
|
792
|
+
[5e6, "2013-12"],
|
|
793
|
+
[1e7, "2014-02"],
|
|
794
|
+
[3e7, "2014-03"],
|
|
795
|
+
[4e7, "2014-05"],
|
|
796
|
+
[5e7, "2014-09"],
|
|
797
|
+
[6e7, "2014-10"],
|
|
798
|
+
[1e8, "2015-03"],
|
|
799
|
+
[102e6, "2015-05"],
|
|
800
|
+
[112e6, "2015-07"],
|
|
801
|
+
[124e6, "2015-08"],
|
|
802
|
+
[125e6, "2015-09"],
|
|
803
|
+
[132e6, "2015-10"],
|
|
804
|
+
[14e7, "2015-12"],
|
|
805
|
+
[145e6, "2016-01"],
|
|
806
|
+
[16e7, "2016-03"],
|
|
807
|
+
[18e7, "2016-04"],
|
|
808
|
+
[2e8, "2016-06"],
|
|
809
|
+
[25e7, "2016-09"],
|
|
810
|
+
[28e7, "2016-10"],
|
|
811
|
+
[29e7, "2016-11"],
|
|
812
|
+
[295e6, "2016-12"],
|
|
813
|
+
[3e8, "2017-01"],
|
|
814
|
+
[33e7, "2017-02"],
|
|
815
|
+
[36e7, "2017-03"],
|
|
816
|
+
[4e8, "2017-07"],
|
|
817
|
+
[5e8, "2018-01"],
|
|
818
|
+
[55e7, "2018-04"],
|
|
819
|
+
[6e8, "2018-06"],
|
|
820
|
+
[65e7, "2018-08"],
|
|
821
|
+
[7e8, "2018-09"],
|
|
822
|
+
[75e7, "2018-11"],
|
|
823
|
+
[8e8, "2019-01"],
|
|
824
|
+
[805e6, "2019-03"],
|
|
825
|
+
[9e8, "2019-05"],
|
|
826
|
+
[95e7, "2019-07"],
|
|
827
|
+
[1e9, "2019-09"],
|
|
828
|
+
[11e8, "2020-02"],
|
|
829
|
+
[12e8, "2020-06"],
|
|
830
|
+
[13e8, "2020-10"],
|
|
831
|
+
[14e8, "2021-01"],
|
|
832
|
+
[15e8, "2021-04"],
|
|
833
|
+
[16e8, "2021-06"],
|
|
834
|
+
[17e8, "2021-08"],
|
|
835
|
+
[18e8, "2021-10"],
|
|
836
|
+
[5e9, "2021-12"],
|
|
837
|
+
[504e7, "2022-01"],
|
|
838
|
+
[51e8, "2022-02"],
|
|
839
|
+
[515e7, "2022-03"],
|
|
840
|
+
[53e8, "2022-04"],
|
|
841
|
+
[535e7, "2022-05"],
|
|
842
|
+
[5434e6, "2022-06"],
|
|
843
|
+
[544e7, "2022-07"],
|
|
844
|
+
[555e7, "2022-10"],
|
|
845
|
+
[578e7, "2022-11"],
|
|
846
|
+
[58e8, "2022-12"],
|
|
847
|
+
[5865e6, "2023-01"],
|
|
848
|
+
[599e7, "2023-05"],
|
|
849
|
+
[63e8, "2023-07"],
|
|
850
|
+
[64e8, "2023-11"],
|
|
851
|
+
[653e7, "2023-12"],
|
|
852
|
+
[655e7, "2024-01"],
|
|
853
|
+
[7e9, "2024-04"],
|
|
854
|
+
[705e7, "2024-05"],
|
|
855
|
+
[7243e6, "2024-06"],
|
|
856
|
+
[726e7, "2024-07"],
|
|
857
|
+
[745e7, "2024-08"],
|
|
858
|
+
[75e8, "2024-12"],
|
|
859
|
+
[78e8, "2025-01"],
|
|
860
|
+
[7834e6, "2025-06"],
|
|
861
|
+
[79e8, "2025-07"],
|
|
862
|
+
[809e7, "2025-08"],
|
|
863
|
+
[82e8, "2025-10"],
|
|
864
|
+
[842e7, "2025-12"],
|
|
865
|
+
[858e7, "2026-01"],
|
|
866
|
+
[868e7, "2026-03"],
|
|
867
|
+
[876e7, "2026-04"],
|
|
868
|
+
[895e7, "2026-08"],
|
|
869
|
+
[896e7, "2026-08"]
|
|
870
|
+
];
|
|
871
|
+
var TABLE_END = ID_MONTHS.at(-1)?.[0] ?? 0;
|
|
872
|
+
var estimatedRegistration = /* @__PURE__ */ __name((id) => {
|
|
873
|
+
if (id < 1 || id >= TABLE_END)
|
|
874
|
+
return null;
|
|
875
|
+
const month = ID_MONTHS.findLast(([from]) => id >= from)?.[1];
|
|
876
|
+
return month ? { at: `${month}-01T00:00:00.000Z`, source: "estimate", precision: "month" } : null;
|
|
877
|
+
}, "estimatedRegistration");
|
|
878
|
+
var registrationOf = /* @__PURE__ */ __name((id, registrationMonth) => {
|
|
879
|
+
const told = registrationMonth?.match(/^(\d{1,2})\.(\d{4})$/);
|
|
880
|
+
if (told) {
|
|
881
|
+
const [, month = "", year = ""] = told;
|
|
882
|
+
return { at: `${year}-${month.padStart(2, "0")}-01T00:00:00.000Z`, source: "telegram", precision: "month" };
|
|
883
|
+
}
|
|
884
|
+
return estimatedRegistration(id);
|
|
885
|
+
}, "registrationOf");
|
|
886
|
+
var seenOf = /* @__PURE__ */ __name((user) => {
|
|
887
|
+
switch (user.status) {
|
|
888
|
+
case "online":
|
|
889
|
+
return "online";
|
|
890
|
+
case "offline":
|
|
891
|
+
return user.lastOnline?.toISOString() ?? "hidden";
|
|
892
|
+
case "recently":
|
|
893
|
+
return "recently";
|
|
894
|
+
case "within_week":
|
|
895
|
+
return "week";
|
|
896
|
+
case "within_month":
|
|
897
|
+
return "month";
|
|
898
|
+
case "bot":
|
|
899
|
+
return void 0;
|
|
900
|
+
default:
|
|
901
|
+
return "hidden";
|
|
902
|
+
}
|
|
903
|
+
}, "seenOf");
|
|
904
|
+
var hasOwnPhoto = /* @__PURE__ */ __name(({ full }) => full._ === "userFull" && (full.profilePhoto?._ === "photo" || full.fallbackPhoto?._ === "photo"), "hasOwnPhoto");
|
|
905
|
+
var toProfileFacts = /* @__PURE__ */ __name((full, chats2) => {
|
|
906
|
+
const settings = full.peerSettings;
|
|
907
|
+
const birthday = full.birthday;
|
|
908
|
+
const usernames = (full.usernames ?? []).filter(({ active }) => active).map(({ username }) => username);
|
|
909
|
+
const seen = seenOf(full);
|
|
910
|
+
return {
|
|
911
|
+
id: String(full.id),
|
|
912
|
+
name: full.displayName || null,
|
|
913
|
+
usernames: usernames.length > 0 ? usernames : full.username ? [full.username] : [],
|
|
914
|
+
bio: full.bio || null,
|
|
915
|
+
birthday: birthday ? [birthday.day, birthday.month, birthday.year].filter((part) => part !== void 0).map((part, index) => index < 2 ? String(part).padStart(2, "0") : String(part)).join(".") : null,
|
|
916
|
+
phone: full.phoneNumber,
|
|
917
|
+
flags: {
|
|
918
|
+
bot: full.isBot,
|
|
919
|
+
verified: full.isVerified,
|
|
920
|
+
premium: full.isPremium,
|
|
921
|
+
scam: full.isScam,
|
|
922
|
+
fake: full.isFake,
|
|
923
|
+
restricted: full.isRestricted,
|
|
924
|
+
deleted: full.isDeleted,
|
|
925
|
+
support: full.isSupport
|
|
926
|
+
},
|
|
927
|
+
...seen === void 0 ? {} : { seen },
|
|
928
|
+
contact: full.isContact,
|
|
929
|
+
mutualContact: full.isMutualContact,
|
|
930
|
+
commonChatsCount: full.commonChatsCount,
|
|
931
|
+
registered: registrationOf(full.id, settings?._ === "peerSettings" ? settings.registrationMonth : void 0),
|
|
932
|
+
hasPhoto: hasOwnPhoto(full),
|
|
933
|
+
chats: chats2
|
|
934
|
+
};
|
|
935
|
+
}, "toProfileFacts");
|
|
936
|
+
|
|
937
|
+
// dist/telegram/contacts.js
|
|
938
|
+
var personOf = /* @__PURE__ */ __name(async ({ client, inputOf: inputOf2 }, reference) => {
|
|
939
|
+
const peer = await inputOf2(reference);
|
|
940
|
+
const user = await client.getPeer(peer);
|
|
941
|
+
if (user.type !== "user")
|
|
942
|
+
throw new CliError("validation_error", `"${reference}" is a chat, not a person`);
|
|
943
|
+
const [full, [dialog], common] = await Promise.all([
|
|
944
|
+
client.getFullUser(peer),
|
|
945
|
+
client.getPeerDialogs(peer),
|
|
946
|
+
client.getCommonChats(peer)
|
|
947
|
+
]);
|
|
948
|
+
const dialogs2 = common.length > 0 ? await client.getPeerDialogs(common.map((chat2) => chat2.id)) : [];
|
|
949
|
+
const chats2 = [dialog ?? null, ...dialogs2].filter((one) => one !== null).map(toChat).map(({ id, title, kind, lastMessageAt }) => ({ id, title, kind, lastMessageAt })).sort((a, b) => (b.lastMessageAt ?? "").localeCompare(a.lastMessageAt ?? ""));
|
|
950
|
+
return { user, full, dialog, chats: chats2 };
|
|
951
|
+
}, "personOf");
|
|
952
|
+
var photos = /* @__PURE__ */ __name((feature, person) => feature.call(async () => {
|
|
953
|
+
const peer = await feature.inputOf(person);
|
|
954
|
+
const newest = await feature.client.getProfilePhotos(peer, { limit: 1 });
|
|
955
|
+
if (newest.total <= 1)
|
|
956
|
+
return { count: newest.total, oldestAt: newest[0]?.date.toISOString() ?? null };
|
|
957
|
+
const [oldest] = await feature.client.getProfilePhotos(peer, { offset: newest.total - 1, limit: 1 });
|
|
958
|
+
return { count: newest.total, oldestAt: oldest?.date.toISOString() ?? null };
|
|
959
|
+
}), "photos");
|
|
960
|
+
var contact = /* @__PURE__ */ __name((feature, reference) => feature.call(async () => {
|
|
961
|
+
const { user, full, dialog, chats: chats2 } = await personOf(feature, reference);
|
|
962
|
+
return {
|
|
963
|
+
...toMember(user),
|
|
964
|
+
description: full.bio || null,
|
|
965
|
+
lastMessagedAt: dialog ? toChat(dialog).lastMessageAt ?? null : null,
|
|
966
|
+
chats: chats2
|
|
967
|
+
};
|
|
968
|
+
}), "contact");
|
|
969
|
+
var profile = /* @__PURE__ */ __name((feature, reference) => feature.call(async () => {
|
|
970
|
+
const { full, chats: chats2 } = await personOf(feature, reference);
|
|
971
|
+
return toProfileFacts(full, chats2);
|
|
972
|
+
}), "profile");
|
|
973
|
+
var lookup = /* @__PURE__ */ __name(({ call, client }, phone) => call(async () => toMember(await client.getPeer(await client.resolvePhoneNumber(phone)))), "lookup");
|
|
974
|
+
var addressBook = /* @__PURE__ */ __name(({ call, client }) => call(async () => (await client.getContacts()).map(toMember)), "addressBook");
|
|
975
|
+
var addContact = /* @__PURE__ */ __name(({ write, client }, personId) => write("the contact may have been added \u2014 repeating it is safe", async () => {
|
|
976
|
+
const peer = await client.getPeer(Number(personId));
|
|
977
|
+
if (peer.type !== "user")
|
|
978
|
+
throw new CliError("validation_error", `${personId} is a chat, not a person`);
|
|
979
|
+
return toMember(await client.addContact({
|
|
980
|
+
userId: peer.id,
|
|
981
|
+
firstName: peer.firstName,
|
|
982
|
+
...peer.lastName ? { lastName: peer.lastName } : {}
|
|
983
|
+
}));
|
|
984
|
+
}), "addContact");
|
|
985
|
+
var removeContact = /* @__PURE__ */ __name(({ write, client }, personId) => write("the contact may have been removed \u2014 repeating it is safe", async () => {
|
|
986
|
+
await client.deleteContacts([Number(personId)]);
|
|
987
|
+
}), "removeContact");
|
|
988
|
+
var block = /* @__PURE__ */ __name(({ write, client }, personId) => write("the person may have been blocked \u2014 repeating it is safe", async () => {
|
|
989
|
+
await client.blockUser(Number(personId));
|
|
990
|
+
}), "block");
|
|
991
|
+
var unblock = /* @__PURE__ */ __name(({ write, client }, personId) => write("the person may have been unblocked \u2014 repeating it is safe", async () => {
|
|
992
|
+
await client.unblockUser(Number(personId));
|
|
993
|
+
}), "unblock");
|
|
994
|
+
var renameContact = /* @__PURE__ */ __name(({ write, client }, personId, firstName, lastName) => write("the contact may have been renamed \u2014 repeating it is safe", async () => toMember(await client.addContact({ userId: Number(personId), firstName, ...lastName ? { lastName } : {} }))), "renameContact");
|
|
995
|
+
var importContacts = /* @__PURE__ */ __name(({ write, client }, entries) => write("the contacts may have been imported \u2014 repeating it is safe", async () => {
|
|
996
|
+
const result = await client.importContacts(entries.map(({ phone, name }) => {
|
|
997
|
+
const [firstName = name, ...rest] = name.split(" ");
|
|
998
|
+
return { phone: `+${phone}`, firstName, lastName: rest.join(" ") };
|
|
999
|
+
}));
|
|
1000
|
+
const found = new Set(result.imported.map((one) => String(one.userId)));
|
|
1001
|
+
const users = await client.getUsers([...found].map(Number));
|
|
1002
|
+
return users.filter((user) => user !== null).map(toMember);
|
|
1003
|
+
}), "importContacts");
|
|
1004
|
+
|
|
1005
|
+
// dist/telegram/folders.js
|
|
1006
|
+
import { getMarkedPeerId as getMarkedPeerId4, tl as tl4 } from "@mtcute/node";
|
|
1007
|
+
var filtersOf = /* @__PURE__ */ __name(async ({ client }) => (await client.getFolders()).filters, "filtersOf");
|
|
1008
|
+
var storedFolder = /* @__PURE__ */ __name(async (feature, sent) => {
|
|
1009
|
+
const stored = sent._ === "dialogFilterDefault" ? void 0 : (await filtersOf(feature)).find((one) => one._ !== "dialogFilterDefault" && one.id === sent.id);
|
|
1010
|
+
return toFolder(stored ?? sent);
|
|
1011
|
+
}, "storedFolder");
|
|
1012
|
+
var folders = /* @__PURE__ */ __name((feature) => feature.call(async () => (await filtersOf(feature)).map(toFolder).filter((one) => one !== null)), "folders");
|
|
1013
|
+
var createFolder = /* @__PURE__ */ __name((feature, title, chatIds, rules = {}) => feature.write({
|
|
1014
|
+
what: "the folder may have been made",
|
|
1015
|
+
check: "chats.folders.list",
|
|
1016
|
+
after: "before repeating \u2014 a repeat makes a second one"
|
|
1017
|
+
}, async () => {
|
|
1018
|
+
const peers = /* @__PURE__ */ __name((ids = []) => Promise.all(ids.map((id) => feature.client.resolvePeer(Number(id)))), "peers");
|
|
1019
|
+
const pinned = new Set(rules.pin);
|
|
1020
|
+
const made = await feature.client.createFolder({
|
|
1021
|
+
title: { _: "textWithEntities", text: title, entities: [] },
|
|
1022
|
+
includePeers: await peers(chatIds.filter((id) => !pinned.has(id))),
|
|
1023
|
+
pinnedPeers: await peers(rules.pin),
|
|
1024
|
+
excludePeers: await peers(rules.exclude),
|
|
1025
|
+
...rules.emoji === void 0 ? {} : { emoticon: rules.emoji },
|
|
1026
|
+
...ruleFlags(rules)
|
|
1027
|
+
});
|
|
1028
|
+
return storedFolder(feature, made);
|
|
1029
|
+
}), "createFolder");
|
|
1030
|
+
var updateFolder = /* @__PURE__ */ __name((feature, folderId, change) => {
|
|
1031
|
+
const { title, add = [], remove = [], exclude = [], pin: pin2 = [], emoji, include, skip } = change;
|
|
1032
|
+
return feature.write("the folder may have changed \u2014 repeating it is safe", async () => {
|
|
1033
|
+
const current = (await filtersOf(feature)).find((one) => one._ !== "dialogFilterDefault" && String(one.id) === folderId);
|
|
1034
|
+
if (!current || current._ === "dialogFilterDefault")
|
|
1035
|
+
throw new CliError("not_found", `no folder ${folderId}`);
|
|
1036
|
+
const rulesAsked = include !== void 0 || skip !== void 0 || exclude.length > 0;
|
|
1037
|
+
if (rulesAsked && current._ === "dialogFilterChatlist")
|
|
1038
|
+
throw new CliError("validation_error", "a folder shared by a link holds only its chats; it takes no rules");
|
|
1039
|
+
const idOf = /* @__PURE__ */ __name((peer) => String(getMarkedPeerId4(peer)), "idOf");
|
|
1040
|
+
const off = /* @__PURE__ */ __name((peers, ...ids) => {
|
|
1041
|
+
const gone = new Set(ids.flat());
|
|
1042
|
+
return peers.filter((peer) => !gone.has(idOf(peer)));
|
|
1043
|
+
}, "off");
|
|
1044
|
+
const resolved = /* @__PURE__ */ __name((ids, have) => {
|
|
1045
|
+
const held = new Set(have.map(idOf));
|
|
1046
|
+
return Promise.all(ids.filter((id) => !held.has(id)).map((id) => feature.client.resolvePeer(Number(id))));
|
|
1047
|
+
}, "resolved");
|
|
1048
|
+
const include0 = off(current.includePeers, remove, pin2, exclude);
|
|
1049
|
+
const pinned0 = off(current.pinnedPeers, remove, exclude);
|
|
1050
|
+
const listsChanged = add.length > 0 || remove.length > 0 || pin2.length > 0 || exclude.length > 0;
|
|
1051
|
+
const excluded0 = current._ === "dialogFilter" ? off(current.excludePeers, remove, add, pin2) : [];
|
|
1052
|
+
const changed = await feature.client.editFolder({
|
|
1053
|
+
folder: current._ === "dialogFilter" ? current : current.id,
|
|
1054
|
+
modification: {
|
|
1055
|
+
...title === void 0 ? {} : { title: { _: "textWithEntities", text: title, entities: [] } },
|
|
1056
|
+
...emoji === void 0 ? {} : { emoticon: emoji },
|
|
1057
|
+
...ruleFlags({ ...include === void 0 ? {} : { include }, ...skip === void 0 ? {} : { skip } }),
|
|
1058
|
+
...listsChanged ? {
|
|
1059
|
+
includePeers: [...include0, ...await resolved(add, [...include0, ...pinned0])],
|
|
1060
|
+
pinnedPeers: [...pinned0, ...await resolved(pin2, pinned0)],
|
|
1061
|
+
...current._ === "dialogFilter" ? { excludePeers: [...excluded0, ...await resolved(exclude, excluded0)] } : {}
|
|
1062
|
+
} : {}
|
|
1063
|
+
}
|
|
1064
|
+
});
|
|
1065
|
+
return storedFolder(feature, changed);
|
|
1066
|
+
});
|
|
1067
|
+
}, "updateFolder");
|
|
1068
|
+
var deleteFolder = /* @__PURE__ */ __name((feature, folderId) => feature.write("the folder may have been deleted \u2014 repeating it is safe", async () => {
|
|
1069
|
+
await feature.client.deleteFolder(Number(folderId));
|
|
1070
|
+
}), "deleteFolder");
|
|
1071
|
+
var orderFolders = /* @__PURE__ */ __name((feature, folderIds) => feature.write("the folders may be in the new order already \u2014 repeating it is safe", async () => {
|
|
1072
|
+
const current = (await filtersOf(feature)).map((one) => one._ === "dialogFilterDefault" ? 0 : one.id);
|
|
1073
|
+
const order = folderIds.map(Number);
|
|
1074
|
+
const all = current.indexOf(0);
|
|
1075
|
+
if (all >= 0)
|
|
1076
|
+
order.splice(all, 0, 0);
|
|
1077
|
+
await feature.client.setFoldersOrder(order);
|
|
1078
|
+
}), "orderFolders");
|
|
1079
|
+
var joinFolder = /* @__PURE__ */ __name((feature, link) => feature.write({
|
|
1080
|
+
what: "the folder may have been joined",
|
|
1081
|
+
check: "chats.folders.list",
|
|
1082
|
+
after: "before repeating \u2014 a repeat joins nothing new"
|
|
1083
|
+
}, async () => {
|
|
1084
|
+
try {
|
|
1085
|
+
return toFolder(await feature.client.joinChatlist(link));
|
|
1086
|
+
} catch (error) {
|
|
1087
|
+
if (tl4.RpcError.is(error, "INVITE_SLUG_EXPIRED") || tl4.RpcError.is(error, "INVITE_SLUG_INVALID"))
|
|
1088
|
+
throw new CliError("not_found", "this folder link is invalid or has expired");
|
|
1089
|
+
throw error;
|
|
1090
|
+
}
|
|
1091
|
+
}), "joinFolder");
|
|
1092
|
+
|
|
1093
|
+
// dist/telegram/format-html.js
|
|
1094
|
+
import { thtml } from "@mtcute/node";
|
|
1095
|
+
var PLAIN = {
|
|
1096
|
+
messageEntityBold: "bold",
|
|
1097
|
+
messageEntityItalic: "italic",
|
|
1098
|
+
messageEntityUnderline: "underline",
|
|
1099
|
+
messageEntityStrike: "strike",
|
|
1100
|
+
messageEntityCode: "code",
|
|
1101
|
+
messageEntitySpoiler: "spoiler",
|
|
1102
|
+
messageEntityBlockquote: "blockquote"
|
|
1103
|
+
};
|
|
1104
|
+
var spanOf = /* @__PURE__ */ __name((entity) => {
|
|
1105
|
+
const base = { from: entity.offset, length: entity.length };
|
|
1106
|
+
if (entity._ === "messageEntityTextUrl")
|
|
1107
|
+
return { type: "link", ...base, url: entity.url };
|
|
1108
|
+
if (entity._ === "messageEntityPre")
|
|
1109
|
+
return { type: "pre", ...base, ...entity.language ? { language: entity.language } : {} };
|
|
1110
|
+
const type = PLAIN[entity._];
|
|
1111
|
+
if (type)
|
|
1112
|
+
return { type, ...base };
|
|
1113
|
+
throw new CliError("validation_error", "this HTML has a mention or a custom emoji; tg sends <b>, <i>, <u>, <s>, <a href>, <code>, <pre>, <blockquote> and <tg-spoiler>");
|
|
1114
|
+
}, "spanOf");
|
|
1115
|
+
var formatHtml = /* @__PURE__ */ __name((input) => {
|
|
1116
|
+
const { text, entities = [] } = thtml(input);
|
|
1117
|
+
return validateFormattedText({ text, spans: entities.map(spanOf) });
|
|
1118
|
+
}, "formatHtml");
|
|
1119
|
+
|
|
1120
|
+
// dist/telegram/login.js
|
|
1121
|
+
import { MtcuteError, tl as tl5, User } from "@mtcute/node";
|
|
1122
|
+
var PHONE_CODE_RETRIES = ["PHONE_CODE_EMPTY", "PHONE_CODE_EXPIRED", "PHONE_CODE_INVALID", "PHONE_CODE_HASH_EMPTY"];
|
|
1123
|
+
var loginAskingForSms = /* @__PURE__ */ __name(async ({ client }, prompts) => {
|
|
1124
|
+
let needsPassword = false;
|
|
1125
|
+
try {
|
|
1126
|
+
return await client.getMe();
|
|
1127
|
+
} catch (error) {
|
|
1128
|
+
if (tl5.RpcError.is(error, "SESSION_PASSWORD_NEEDED"))
|
|
1129
|
+
needsPassword = true;
|
|
1130
|
+
else if (!tl5.RpcError.is(error, "AUTH_KEY_UNREGISTERED"))
|
|
1131
|
+
throw error;
|
|
1132
|
+
}
|
|
1133
|
+
if (!needsPassword) {
|
|
1134
|
+
const phone = await prompts.phone();
|
|
1135
|
+
let sent;
|
|
1136
|
+
try {
|
|
1137
|
+
const answer = await client.sendCode({ phone });
|
|
1138
|
+
if (answer instanceof User)
|
|
1139
|
+
return answer;
|
|
1140
|
+
sent = answer;
|
|
1141
|
+
} catch (error) {
|
|
1142
|
+
if (!tl5.RpcError.is(error, "SESSION_PASSWORD_NEEDED"))
|
|
1143
|
+
throw error;
|
|
1144
|
+
needsPassword = true;
|
|
1145
|
+
}
|
|
1146
|
+
if (sent) {
|
|
1147
|
+
if (sent.type === "app" || sent.type === "email") {
|
|
1148
|
+
try {
|
|
1149
|
+
sent = await client.resendCode({ phone, phoneCodeHash: sent.phoneCodeHash });
|
|
1150
|
+
} catch (error) {
|
|
1151
|
+
if (!tl5.RpcError.is(error, "SEND_CODE_UNAVAILABLE"))
|
|
1152
|
+
throw error;
|
|
1153
|
+
prompts.note("Telegram offers no SMS for this account");
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
if (sent.type === "email_required")
|
|
1157
|
+
throw new MtcuteError("Email login setup is required to sign in");
|
|
1158
|
+
prompts.note(`Telegram sent a login code (${sent.type})`);
|
|
1159
|
+
for (; ; ) {
|
|
1160
|
+
try {
|
|
1161
|
+
return await client.signIn({
|
|
1162
|
+
phone,
|
|
1163
|
+
phoneCodeHash: sent.phoneCodeHash,
|
|
1164
|
+
phoneCode: await prompts.code()
|
|
1165
|
+
});
|
|
1166
|
+
} catch (error) {
|
|
1167
|
+
if (tl5.RpcError.is(error, "SESSION_PASSWORD_NEEDED")) {
|
|
1168
|
+
needsPassword = true;
|
|
1169
|
+
break;
|
|
1170
|
+
}
|
|
1171
|
+
if (!PHONE_CODE_RETRIES.some((text) => tl5.RpcError.is(error, text)))
|
|
1172
|
+
throw error;
|
|
1173
|
+
prompts.note("that code was not accepted \u2014 try again");
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
for (; ; ) {
|
|
1179
|
+
try {
|
|
1180
|
+
return await client.checkPassword(await prompts.password());
|
|
1181
|
+
} catch (error) {
|
|
1182
|
+
if (!tl5.RpcError.is(error, "PASSWORD_HASH_INVALID"))
|
|
1183
|
+
throw error;
|
|
1184
|
+
prompts.note("that password was not accepted \u2014 try again");
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
}, "loginAskingForSms");
|
|
1188
|
+
var login = /* @__PURE__ */ __name((feature, prompts) => feature.call(async () => {
|
|
1189
|
+
if (prompts.method === "phone" && prompts.forceSms)
|
|
1190
|
+
return toAccount(await loginAskingForSms(feature, prompts));
|
|
1191
|
+
const user = await feature.client.start({
|
|
1192
|
+
...prompts.method === "qr" ? { qrCodeHandler: prompts.showQr } : { phone: prompts.phone },
|
|
1193
|
+
code: prompts.code,
|
|
1194
|
+
password: prompts.password,
|
|
1195
|
+
codeSentCallback: /* @__PURE__ */ __name((sent) => prompts.note(`Telegram sent a login code (${sent.type})`), "codeSentCallback"),
|
|
1196
|
+
invalidCodeCallback: /* @__PURE__ */ __name((what) => prompts.note(`that ${what} was not accepted \u2014 try again`), "invalidCodeCallback")
|
|
1197
|
+
});
|
|
1198
|
+
return toAccount(user);
|
|
1199
|
+
}), "login");
|
|
1200
|
+
var logout = /* @__PURE__ */ __name(({ call, client }) => call(async () => {
|
|
1201
|
+
await client.logOut();
|
|
1202
|
+
}), "logout");
|
|
1203
|
+
var sessions = /* @__PURE__ */ __name(({ call, client }) => call(async () => {
|
|
1204
|
+
const { authorizations } = await client.call({ _: "account.getAuthorizations" });
|
|
1205
|
+
return authorizations.map(toAccountSession);
|
|
1206
|
+
}), "sessions");
|
|
1207
|
+
var endOtherSessions = /* @__PURE__ */ __name((feature) => feature.call(async () => {
|
|
1208
|
+
try {
|
|
1209
|
+
await feature.client.call({ _: "auth.resetAuthorizations" });
|
|
1210
|
+
} catch (error) {
|
|
1211
|
+
throw feature.unanswered(error, {
|
|
1212
|
+
what: "the other devices may or may not have been logged out",
|
|
1213
|
+
check: "account.sessions.list"
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
const { authorizations } = await feature.client.call({ _: "account.getAuthorizations" });
|
|
1217
|
+
return authorizations.map(toAccountSession);
|
|
1218
|
+
}), "endOtherSessions");
|
|
1219
|
+
|
|
1220
|
+
// dist/telegram/messages.js
|
|
1221
|
+
import { FileLocation, Long as Long4, PeersIndex as PeersIndex6, Message as TgMessage4, tl as tl7 } from "@mtcute/node";
|
|
1222
|
+
|
|
1223
|
+
// dist/telegram/albums.js
|
|
1224
|
+
import { createHash } from "node:crypto";
|
|
1225
|
+
import { getMarkedPeerId as getMarkedPeerId6, Long as Long3, PeersIndex as PeersIndex5, Message as TgMessage3 } from "@mtcute/node";
|
|
1226
|
+
|
|
1227
|
+
// dist/telegram/send-as.js
|
|
1228
|
+
import { getBasicPeerType, getMarkedPeerId as getMarkedPeerId5, PeersIndex as PeersIndex4, tl as tl6 } from "@mtcute/node";
|
|
1229
|
+
var sendAsIdentities = /* @__PURE__ */ __name(async (client, chatId) => {
|
|
1230
|
+
const me2 = await client.getMe();
|
|
1231
|
+
const self = { id: String(me2.id), title: me2.displayName, kind: "self", premiumRequired: false };
|
|
1232
|
+
const alone = [{ ...self, default: true }];
|
|
1233
|
+
if (getBasicPeerType(Number(chatId)) !== "channel")
|
|
1234
|
+
return alone;
|
|
1235
|
+
const { full } = await client.getFullChat(Number(chatId));
|
|
1236
|
+
if (full._ !== "channelFull")
|
|
1237
|
+
return alone;
|
|
1238
|
+
const chosen = full.defaultSendAs ? String(getMarkedPeerId5(full.defaultSendAs)) : self.id;
|
|
1239
|
+
let answer;
|
|
1240
|
+
try {
|
|
1241
|
+
answer = await client.call({ _: "channels.getSendAs", peer: await client.resolvePeer(Number(chatId)) });
|
|
1242
|
+
} catch (error) {
|
|
1243
|
+
if (tl6.RpcError.is(error, "PEER_ID_INVALID"))
|
|
1244
|
+
return alone;
|
|
1245
|
+
throw error;
|
|
1246
|
+
}
|
|
1247
|
+
const index = PeersIndex4.from(answer);
|
|
1248
|
+
const others = answer.peers.flatMap(({ peer, premiumRequired }) => {
|
|
1249
|
+
const found = index.has(peer) ? index.get(peer) : void 0;
|
|
1250
|
+
if (found?._ !== "channel")
|
|
1251
|
+
return [];
|
|
1252
|
+
return [
|
|
1253
|
+
{
|
|
1254
|
+
id: String(getMarkedPeerId5(peer)),
|
|
1255
|
+
title: found.title,
|
|
1256
|
+
kind: found.broadcast ? "channel" : "group",
|
|
1257
|
+
premiumRequired: premiumRequired === true
|
|
1258
|
+
}
|
|
1259
|
+
];
|
|
1260
|
+
});
|
|
1261
|
+
return [self, ...others].map((one) => ({ ...one, default: one.id === chosen }));
|
|
1262
|
+
}, "sendAsIdentities");
|
|
1263
|
+
var savedSenderOf = /* @__PURE__ */ __name(async (client, chatId, self) => {
|
|
1264
|
+
if (getBasicPeerType(Number(chatId)) !== "channel")
|
|
1265
|
+
return null;
|
|
1266
|
+
const { full } = await client.getFullChat(Number(chatId));
|
|
1267
|
+
if (full._ !== "channelFull" || !full.defaultSendAs)
|
|
1268
|
+
return null;
|
|
1269
|
+
const saved = String(getMarkedPeerId5(full.defaultSendAs));
|
|
1270
|
+
return saved === self ? null : saved;
|
|
1271
|
+
}, "savedSenderOf");
|
|
1272
|
+
var sendAsPeer = /* @__PURE__ */ __name((chatId, sendAs, self, words) => {
|
|
1273
|
+
if (!/^-?\d{1,16}$/.test(sendAs) || !Number.isSafeInteger(Number(sendAs))) {
|
|
1274
|
+
throw new CliError("validation_error", `--send-as takes an id from ${words("chats.send-as")}`);
|
|
1275
|
+
}
|
|
1276
|
+
if (getBasicPeerType(Number(chatId)) === "channel")
|
|
1277
|
+
return Number(sendAs);
|
|
1278
|
+
if (sendAs === self)
|
|
1279
|
+
return void 0;
|
|
1280
|
+
throw new CliError("validation_error", "only a supergroup offers identities other than the account");
|
|
1281
|
+
}, "sendAsPeer");
|
|
1282
|
+
|
|
1283
|
+
// dist/telegram/upload.js
|
|
1284
|
+
var UPLOAD_ATTEMPTS = 3;
|
|
1285
|
+
var sleep = /* @__PURE__ */ __name((ms) => new Promise((resolve2) => setTimeout(resolve2, ms)), "sleep");
|
|
1286
|
+
var uploadAttachment = /* @__PURE__ */ __name(async (client, upload, wait = sleep) => {
|
|
1287
|
+
for (let attempt = 1; ; attempt++) {
|
|
1288
|
+
try {
|
|
1289
|
+
return await client.uploadFile({ file: await uploadBlob(upload.source), ...toUploadParams(upload) });
|
|
1290
|
+
} catch (error) {
|
|
1291
|
+
const known = toCliError(error, bareCheck);
|
|
1292
|
+
const dropped = known instanceof CliError && ["timeout", "network_error"].includes(known.code);
|
|
1293
|
+
if (!dropped)
|
|
1294
|
+
throw error;
|
|
1295
|
+
if (attempt >= UPLOAD_ATTEMPTS) {
|
|
1296
|
+
throw new CliError(known.code, `the file did not upload after ${attempt} tries; nothing was sent`, {
|
|
1297
|
+
attempts: attempt
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
await wait(attempt * 1e3);
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
}, "uploadAttachment");
|
|
1304
|
+
|
|
1305
|
+
// dist/telegram/albums.js
|
|
1306
|
+
var checkAlbum = /* @__PURE__ */ __name((attachments, spoiler = false) => {
|
|
1307
|
+
if (attachments.length > 10)
|
|
1308
|
+
throw new CliError("validation_error", "an album holds at most 10 photos or files");
|
|
1309
|
+
if (attachments.some((item) => item.kind === "voice"))
|
|
1310
|
+
throw new CliError("validation_error", "send voice messages separately from an album");
|
|
1311
|
+
const visual = /* @__PURE__ */ __name((item) => item.kind === "photo" || Boolean(videoMime(item)), "visual");
|
|
1312
|
+
if (attachments.some(visual) && !attachments.every(visual))
|
|
1313
|
+
throw new CliError("validation_error", "an album can mix photos and videos, or contain only documents");
|
|
1314
|
+
if (spoiler)
|
|
1315
|
+
for (const item of attachments)
|
|
1316
|
+
checkSpoiler(item);
|
|
1317
|
+
}, "checkAlbum");
|
|
1318
|
+
var albumRandomId = /* @__PURE__ */ __name((id, index) => {
|
|
1319
|
+
const bytes = createHash("sha256").update(`tg-album:${id.toString()}:${index}`).digest();
|
|
1320
|
+
return Long3.fromString(bytes.readBigInt64BE().toString());
|
|
1321
|
+
}, "albumRandomId");
|
|
1322
|
+
var sendAlbum = /* @__PURE__ */ __name((feature, chatId, text, options) => {
|
|
1323
|
+
const { sendId, attachments = [], replyTo, threadId, sendAs, silent, at, spoiler, captionAbove } = options;
|
|
1324
|
+
const id = parseSendId(sendId);
|
|
1325
|
+
const thread = threadId === void 0 ? void 0 : topicNumber(threadId);
|
|
1326
|
+
const answering = replyTo === void 0 ? void 0 : messageNumber(replyTo);
|
|
1327
|
+
const author = sendAs === void 0 ? void 0 : sendAsPeer(chatId, sendAs, feature.self(), feature.checks);
|
|
1328
|
+
const caption = toFormatted(text, options.formatting ?? options.markup ?? []);
|
|
1329
|
+
return feature.send(async () => {
|
|
1330
|
+
const peer = await feature.client.resolvePeer(Number(chatId));
|
|
1331
|
+
const multiMedia = [];
|
|
1332
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
1333
|
+
const input = toInputMedia(attachment, "", await uploadAttachment(feature.client, attachment), { spoiler });
|
|
1334
|
+
const uploaded = await feature.client.uploadMedia(input, { peer });
|
|
1335
|
+
const media = uploaded.inputMedia;
|
|
1336
|
+
if (spoiler && (media._ === "inputMediaPhoto" || media._ === "inputMediaDocument"))
|
|
1337
|
+
media.spoiler = true;
|
|
1338
|
+
multiMedia.push({
|
|
1339
|
+
_: "inputSingleMedia",
|
|
1340
|
+
media,
|
|
1341
|
+
randomId: albumRandomId(id, index),
|
|
1342
|
+
message: index === 0 ? caption.text : "",
|
|
1343
|
+
...index === 0 && caption.entities?.length ? { entities: caption.entities } : {}
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
const sendAsInput = author === void 0 ? void 0 : await feature.client.resolvePeer(author);
|
|
1347
|
+
try {
|
|
1348
|
+
const updates = await feature.client.call({
|
|
1349
|
+
_: "messages.sendMultiMedia",
|
|
1350
|
+
peer,
|
|
1351
|
+
multiMedia,
|
|
1352
|
+
...silent ? { silent } : {},
|
|
1353
|
+
...captionAbove ? { invertMedia: true } : {},
|
|
1354
|
+
...at === void 0 ? {} : { scheduleDate: Math.floor(Date.parse(at) / 1e3) },
|
|
1355
|
+
...sendAsInput === void 0 ? {} : { sendAs: sendAsInput },
|
|
1356
|
+
...answering === void 0 && (thread === void 0 || thread === 1) ? {} : {
|
|
1357
|
+
replyTo: {
|
|
1358
|
+
_: "inputReplyToMessage",
|
|
1359
|
+
replyToMsgId: answering ?? thread ?? 1,
|
|
1360
|
+
...thread === void 0 || thread === 1 ? {} : { topMsgId: thread }
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
});
|
|
1364
|
+
feature.client.handleClientUpdate(updates, true);
|
|
1365
|
+
if (updates._ !== "updates" && updates._ !== "updatesCombined")
|
|
1366
|
+
throw new CliError("outcome_unknown", "Telegram answered the album without its messages", retryDetails(sendId, sendAs));
|
|
1367
|
+
const peers = PeersIndex5.from(updates);
|
|
1368
|
+
const messages = multiMedia.map(({ randomId }) => {
|
|
1369
|
+
const mapped = updates.updates.find((one) => one._ === "updateMessageID" && one.randomId.eq(randomId));
|
|
1370
|
+
const candidates = updates.updates.flatMap((one) => (one._ === "updateNewMessage" || one._ === "updateNewChannelMessage" || one._ === "updateNewScheduledMessage") && one.message._ !== "messageEmpty" ? [one.message] : []);
|
|
1371
|
+
const copy = mapped?._ === "updateMessageID" ? candidates.find((message) => message.id === mapped.id && getMarkedPeerId6(message.peerId) === Number(chatId)) : void 0;
|
|
1372
|
+
if (!copy)
|
|
1373
|
+
throw new CliError("outcome_unknown", `the album may have been sent. Repeat with ${repeatWith(sendId, sendAs)}`, retryDetails(sendId, sendAs));
|
|
1374
|
+
return toMessage(new TgMessage3(copy, peers));
|
|
1375
|
+
});
|
|
1376
|
+
const first = messages[0];
|
|
1377
|
+
if (!first)
|
|
1378
|
+
throw new CliError("provider_error", "Telegram answered the album without a first message");
|
|
1379
|
+
return { message: first, messages, sendId };
|
|
1380
|
+
} catch (error) {
|
|
1381
|
+
throw unknownIfUnanswered(error, `the album may have been sent. Repeat with ${repeatWith(sendId, sendAs)}, never without it`, retryDetails(sendId, sendAs));
|
|
1382
|
+
}
|
|
1383
|
+
});
|
|
1384
|
+
}, "sendAlbum");
|
|
1385
|
+
|
|
1386
|
+
// dist/telegram/messages.js
|
|
1387
|
+
var BY_ID_BATCH = 100;
|
|
1388
|
+
var TRANSCRIBE_POLL_MS = 2e3;
|
|
1389
|
+
var TRANSCRIBE_WAIT_MS = 6e4;
|
|
1390
|
+
var sleep2 = /* @__PURE__ */ __name((ms) => new Promise((resolve2) => setTimeout(resolve2, ms)), "sleep");
|
|
1391
|
+
var history = /* @__PURE__ */ __name((feature, reference, { limit, before }) => {
|
|
1392
|
+
return feature.call(async () => {
|
|
1393
|
+
const peer = await feature.inputOf(reference);
|
|
1394
|
+
const offset = before === void 0 ? void 0 : { id: messageNumber(before), date: 0 };
|
|
1395
|
+
const page = await feature.client.getHistory(peer, { limit, ...offset ? { offset } : {} });
|
|
1396
|
+
return { items: page.map(remoteMessage).reverse(), hasMore: page.next !== void 0 };
|
|
1397
|
+
});
|
|
1398
|
+
}, "history");
|
|
1399
|
+
var historyAfter = /* @__PURE__ */ __name((feature, reference, { limit, after }) => {
|
|
1400
|
+
const offset = "id" in after ? { id: messageNumber(after.id, "`id>` takes a message id") + 1, date: 0 } : { id: 0, date: Math.floor(after.time / 1e3) };
|
|
1401
|
+
const newer = /* @__PURE__ */ __name((message) => "id" in after ? Number(message.id) > Number(after.id) : Date.parse(message.timestamp) > after.time, "newer");
|
|
1402
|
+
return feature.call(async () => {
|
|
1403
|
+
const peer = await feature.inputOf(reference);
|
|
1404
|
+
const page = await feature.client.getHistory(peer, { limit, reverse: true, offset });
|
|
1405
|
+
return { items: page.map(remoteMessage).filter(newer), hasMore: page.next !== void 0 };
|
|
1406
|
+
});
|
|
1407
|
+
}, "historyAfter");
|
|
1408
|
+
var historyFrom = /* @__PURE__ */ __name((feature, reference, person, { limit }) => {
|
|
1409
|
+
return feature.call(async () => {
|
|
1410
|
+
const [chatId, fromUser] = await Promise.all([feature.inputOf(reference), feature.inputOf(person)]);
|
|
1411
|
+
const page = await feature.client.searchMessages({ chatId, fromUser, limit });
|
|
1412
|
+
return { items: page.map(remoteMessage).reverse(), hasMore: page.total > page.length };
|
|
1413
|
+
});
|
|
1414
|
+
}, "historyFrom");
|
|
1415
|
+
var historyBefore = /* @__PURE__ */ __name((feature, reference, { limit, time }) => {
|
|
1416
|
+
return feature.call(async () => {
|
|
1417
|
+
const peer = await feature.inputOf(reference);
|
|
1418
|
+
const page = await feature.client.getHistory(peer, { limit, offset: { id: 0, date: Math.floor(time / 1e3) } });
|
|
1419
|
+
const older = page.map(remoteMessage).filter((message) => Date.parse(message.timestamp) < time);
|
|
1420
|
+
return { items: older.reverse(), hasMore: page.next !== void 0 };
|
|
1421
|
+
});
|
|
1422
|
+
}, "historyBefore");
|
|
1423
|
+
var searchMessages = /* @__PURE__ */ __name((feature, query, { limit, signal }) => {
|
|
1424
|
+
return feature.call(async () => {
|
|
1425
|
+
const seconds = /* @__PURE__ */ __name((ms) => ms === void 0 ? 0 : Math.floor(ms / 1e3), "seconds");
|
|
1426
|
+
const common = {
|
|
1427
|
+
q: query.text,
|
|
1428
|
+
filter: { _: "inputMessagesFilterEmpty" },
|
|
1429
|
+
minDate: seconds(query.minDate),
|
|
1430
|
+
maxDate: seconds(query.maxDate),
|
|
1431
|
+
limit
|
|
1432
|
+
};
|
|
1433
|
+
const options = { floodSleepThreshold: 0, ...signal ? { abortSignal: signal } : {} };
|
|
1434
|
+
const found = query.chat === void 0 ? await feature.client.call({
|
|
1435
|
+
_: "messages.searchGlobal",
|
|
1436
|
+
...common,
|
|
1437
|
+
offsetRate: 0,
|
|
1438
|
+
offsetPeer: { _: "inputPeerEmpty" },
|
|
1439
|
+
offsetId: 0
|
|
1440
|
+
}, options) : await feature.client.call({
|
|
1441
|
+
_: "messages.search",
|
|
1442
|
+
...common,
|
|
1443
|
+
peer: await feature.client.resolvePeer(await feature.inputOf(query.chat)),
|
|
1444
|
+
...query.from === void 0 ? {} : { fromId: await feature.client.resolvePeer(await feature.inputOf(query.from)) },
|
|
1445
|
+
offsetId: 0,
|
|
1446
|
+
addOffset: 0,
|
|
1447
|
+
maxId: 0,
|
|
1448
|
+
minId: 0,
|
|
1449
|
+
hash: Long4.ZERO
|
|
1450
|
+
}, options);
|
|
1451
|
+
if (found._ === "messages.messagesNotModified")
|
|
1452
|
+
return { items: [], hasMore: false, chats: [] };
|
|
1453
|
+
const peers = PeersIndex6.from(found);
|
|
1454
|
+
const page = found.messages.filter((one) => one._ !== "messageEmpty").map((one) => new TgMessage4(one, peers));
|
|
1455
|
+
const chats2 = new Map(page.map((message) => [String(message.chat.id), peerToChat(message.chat)]));
|
|
1456
|
+
return {
|
|
1457
|
+
items: page.map((message) => remoteHit(message, "remote_fetch")),
|
|
1458
|
+
hasMore: page.length === limit,
|
|
1459
|
+
chats: [...chats2.values()]
|
|
1460
|
+
};
|
|
1461
|
+
});
|
|
1462
|
+
}, "searchMessages");
|
|
1463
|
+
var around = /* @__PURE__ */ __name((feature, reference, messageId, { before, after }) => {
|
|
1464
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1465
|
+
return feature.call(async () => {
|
|
1466
|
+
const peer = await feature.inputOf(reference);
|
|
1467
|
+
const page = await feature.client.getHistory(peer, {
|
|
1468
|
+
offset: { id: id + 1, date: 0 },
|
|
1469
|
+
addOffset: -after,
|
|
1470
|
+
limit: before + 1 + after
|
|
1471
|
+
});
|
|
1472
|
+
const items = page.map(remoteMessage).reverse();
|
|
1473
|
+
const index = items.findIndex((message) => message.id === String(id));
|
|
1474
|
+
if (index < 0)
|
|
1475
|
+
throw new CliError("not_found", `no message ${id} in that chat`);
|
|
1476
|
+
return items.slice(Math.max(0, index - before), index + after + 1).map((message) => message.id === String(id) ? { ...message, anchor: true } : message);
|
|
1477
|
+
});
|
|
1478
|
+
}, "around");
|
|
1479
|
+
var fetchCounters = /* @__PURE__ */ __name((feature, reference, messageId, fields, signal) => {
|
|
1480
|
+
const id = messageNumber(messageId);
|
|
1481
|
+
return feature.call(async () => {
|
|
1482
|
+
signal?.throwIfAborted();
|
|
1483
|
+
const [found] = await feature.client.getMessages(await feature.inputOf(reference), [id]);
|
|
1484
|
+
signal?.throwIfAborted();
|
|
1485
|
+
return found ? observedCounters(toMessage(found), (/* @__PURE__ */ new Date()).toISOString(), fields).counterObservations ?? {} : {};
|
|
1486
|
+
});
|
|
1487
|
+
}, "fetchCounters");
|
|
1488
|
+
var permalink = /* @__PURE__ */ __name((feature, chatId, messageId) => {
|
|
1489
|
+
const id = messageNumber(messageId, "a message id is a positive Telegram integer");
|
|
1490
|
+
if (id <= 0 || id > 2147483647)
|
|
1491
|
+
throw new CliError("validation_error", "a message id is a positive Telegram integer");
|
|
1492
|
+
return feature.call(async () => {
|
|
1493
|
+
const input = await feature.inputOf(chatId);
|
|
1494
|
+
const [found] = await feature.client.getMessages(input, [id]);
|
|
1495
|
+
if (!found || found.id !== id)
|
|
1496
|
+
throw new CliError("not_found", "that message no longer exists in this chat");
|
|
1497
|
+
const peer = await feature.client.getPeer(input);
|
|
1498
|
+
if (peer.type !== "chat" || peer.raw._ !== "channel")
|
|
1499
|
+
return { url: null, access: "unavailable", reason: "unsupported_chat" };
|
|
1500
|
+
const { link } = await feature.client.call({
|
|
1501
|
+
_: "channels.exportMessageLink",
|
|
1502
|
+
channel: await feature.client.resolveChannel(input),
|
|
1503
|
+
id,
|
|
1504
|
+
thread: true
|
|
1505
|
+
});
|
|
1506
|
+
const url = new URL(link);
|
|
1507
|
+
const known = ["t.me", "telegram.me", "telegram.dog"].includes(url.hostname);
|
|
1508
|
+
const access = !known ? "unknown" : url.pathname.startsWith("/c/") ? "restricted" : "public";
|
|
1509
|
+
return { url: link, access, reason: null };
|
|
1510
|
+
});
|
|
1511
|
+
}, "permalink");
|
|
1512
|
+
var scheduled = /* @__PURE__ */ __name((feature, reference) => {
|
|
1513
|
+
return feature.call(async () => {
|
|
1514
|
+
const queued = await feature.client.getAllScheduledMessages(await feature.inputOf(reference));
|
|
1515
|
+
return queued.map(toMessage).sort((a, b) => a.timestamp.localeCompare(b.timestamp));
|
|
1516
|
+
});
|
|
1517
|
+
}, "scheduled");
|
|
1518
|
+
var saveDraft = /* @__PURE__ */ __name((feature, chatId, text, { replyTo, threadId, formatting, noPreview }) => {
|
|
1519
|
+
if (text.trim() === "")
|
|
1520
|
+
throw new CliError("validation_error", "a draft needs nonempty text; clearing is not supported");
|
|
1521
|
+
const thread = threadId === void 0 || threadId === "1" ? void 0 : topicNumber(threadId);
|
|
1522
|
+
const answering = replyTo === void 0 ? thread : messageNumber(replyTo, "a message id is a number");
|
|
1523
|
+
const body = toFormatted(text, formatting ?? []);
|
|
1524
|
+
return feature.write("the draft may have been saved \u2014 repeating it is safe", () => feature.client.saveDraft(Number(chatId), {
|
|
1525
|
+
message: body.text,
|
|
1526
|
+
entities: body.entities,
|
|
1527
|
+
...noPreview ? { noWebpage: true } : {},
|
|
1528
|
+
...answering === void 0 ? {} : { replyTo: { _: "inputReplyToMessage", replyToMsgId: answering, ...thread ? { topMsgId: thread } : {} } }
|
|
1529
|
+
}));
|
|
1530
|
+
}, "saveDraft");
|
|
1531
|
+
var send = /* @__PURE__ */ __name((feature, chatId, text, { sendId, replyTo, threadId, silent, noPreview, markup, formatting, at, attachments = [], sendAs, spoiler, captionAbove }) => {
|
|
1532
|
+
const id = parseSendId(sendId);
|
|
1533
|
+
const thread = threadId === void 0 ? void 0 : topicNumber(threadId);
|
|
1534
|
+
const answering = replyTo === void 0 ? void 0 : messageNumber(replyTo, "a message id is a number");
|
|
1535
|
+
const author = sendAs === void 0 ? void 0 : sendAsPeer(chatId, sendAs, feature.self(), feature.checks);
|
|
1536
|
+
if (attachments.length > 1)
|
|
1537
|
+
checkAlbum(attachments, spoiler);
|
|
1538
|
+
const spans = formatting ?? markup;
|
|
1539
|
+
const body = spans ? toFormatted(text, spans) : text;
|
|
1540
|
+
const common = {
|
|
1541
|
+
randomId: id,
|
|
1542
|
+
...thread === void 0 || thread === 1 ? {} : { threadId: thread },
|
|
1543
|
+
...answering === void 0 ? {} : { replyTo: answering },
|
|
1544
|
+
...silent ? { silent } : {},
|
|
1545
|
+
...at === void 0 ? {} : { schedule: new Date(at) },
|
|
1546
|
+
...author === void 0 ? {} : { sendAs: author }
|
|
1547
|
+
};
|
|
1548
|
+
if (attachments.length > 1)
|
|
1549
|
+
return sendAlbum(feature, chatId, text, {
|
|
1550
|
+
sendId,
|
|
1551
|
+
replyTo,
|
|
1552
|
+
threadId,
|
|
1553
|
+
silent,
|
|
1554
|
+
formatting: spans,
|
|
1555
|
+
at,
|
|
1556
|
+
attachments,
|
|
1557
|
+
sendAs,
|
|
1558
|
+
spoiler,
|
|
1559
|
+
captionAbove
|
|
1560
|
+
});
|
|
1561
|
+
return feature.send(async () => {
|
|
1562
|
+
const [attachment] = attachments;
|
|
1563
|
+
if (spoiler && attachment)
|
|
1564
|
+
checkSpoiler(attachment);
|
|
1565
|
+
const media = attachment ? toInputMedia(attachment, body, await uploadAttachment(feature.client, attachment), { spoiler }) : void 0;
|
|
1566
|
+
try {
|
|
1567
|
+
const message = media ? await feature.client.sendMedia(Number(chatId), media, {
|
|
1568
|
+
...common,
|
|
1569
|
+
...captionAbove ? { invert: true } : {}
|
|
1570
|
+
}) : await feature.client.sendText(Number(chatId), body, {
|
|
1571
|
+
...common,
|
|
1572
|
+
...noPreview ? { disableWebPreview: true } : {}
|
|
1573
|
+
});
|
|
1574
|
+
return { message: toMessage(message), sendId };
|
|
1575
|
+
} catch (error) {
|
|
1576
|
+
throw unknownIfUnanswered(error, `the message may have been sent. Repeat with ${repeatWith(sendId, sendAs)}, never without it`, retryDetails(sendId, sendAs));
|
|
1577
|
+
}
|
|
1578
|
+
});
|
|
1579
|
+
}, "send");
|
|
1580
|
+
var edit = /* @__PURE__ */ __name((feature, chatId, messageId, text, { markup, formatting } = {}) => {
|
|
1581
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1582
|
+
const spans = formatting ?? markup;
|
|
1583
|
+
const body = spans ? toFormatted(text, spans) : text;
|
|
1584
|
+
return feature.call(async () => {
|
|
1585
|
+
try {
|
|
1586
|
+
return toMessage(await feature.client.editMessage({ chatId: Number(chatId), message: id, text: body }));
|
|
1587
|
+
} catch (error) {
|
|
1588
|
+
if (tl7.RpcError.is(error, "MESSAGE_NOT_MODIFIED")) {
|
|
1589
|
+
const [current] = await feature.client.getMessages(Number(chatId), [id]);
|
|
1590
|
+
if (current)
|
|
1591
|
+
return toMessage(current);
|
|
1592
|
+
}
|
|
1593
|
+
throw unknownIfUnanswered(error, "the edit may have been made \u2014 repeating it is safe");
|
|
1594
|
+
}
|
|
1595
|
+
});
|
|
1596
|
+
}, "edit");
|
|
1597
|
+
var forward = /* @__PURE__ */ __name((feature, fromChatId, messageId, toChatId, { sendId, silent, sendAs, threadId }) => {
|
|
1598
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1599
|
+
const randomId = parseSendId(sendId);
|
|
1600
|
+
const thread = threadId === void 0 ? void 0 : topicNumber(threadId);
|
|
1601
|
+
const author = sendAs === void 0 ? void 0 : sendAsPeer(toChatId, sendAs, feature.self(), feature.checks);
|
|
1602
|
+
return feature.send(async () => {
|
|
1603
|
+
try {
|
|
1604
|
+
const updates = await feature.client.call({
|
|
1605
|
+
_: "messages.forwardMessages",
|
|
1606
|
+
fromPeer: await feature.client.resolvePeer(Number(fromChatId)),
|
|
1607
|
+
toPeer: await feature.client.resolvePeer(Number(toChatId)),
|
|
1608
|
+
id: [id],
|
|
1609
|
+
randomId: [randomId],
|
|
1610
|
+
...silent ? { silent } : {},
|
|
1611
|
+
...thread === void 0 || thread === 1 ? {} : { topMsgId: thread },
|
|
1612
|
+
...author === void 0 ? {} : { sendAs: await feature.client.resolvePeer(author) }
|
|
1613
|
+
});
|
|
1614
|
+
feature.client.handleClientUpdate(updates, true);
|
|
1615
|
+
const copy = forwardedCopy(updates, randomId, toChatId);
|
|
1616
|
+
if (!copy)
|
|
1617
|
+
throw new CliError("provider_error", "Telegram answered the forward without the new message");
|
|
1618
|
+
return toMessage(copy);
|
|
1619
|
+
} catch (error) {
|
|
1620
|
+
throw unknownIfUnanswered(error, `the message may have been forwarded. Repeat with ${repeatWith(sendId, sendAs)}, never without it`, retryDetails(sendId, sendAs));
|
|
1621
|
+
}
|
|
1622
|
+
});
|
|
1623
|
+
}, "forward");
|
|
1624
|
+
var pin = /* @__PURE__ */ __name((feature, chatId, messageId, { notify }) => {
|
|
1625
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1626
|
+
return feature.write("the pin may have been made \u2014 repeating it is safe", async () => {
|
|
1627
|
+
await feature.client.pinMessage({ chatId: Number(chatId), message: id, notify });
|
|
1628
|
+
});
|
|
1629
|
+
}, "pin");
|
|
1630
|
+
var unpin = /* @__PURE__ */ __name((feature, chatId, messageId) => {
|
|
1631
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1632
|
+
return feature.write("the message may have been unpinned \u2014 repeating it is safe", async () => {
|
|
1633
|
+
await feature.client.unpinMessage({ chatId: Number(chatId), message: id });
|
|
1634
|
+
});
|
|
1635
|
+
}, "unpin");
|
|
1636
|
+
var react = /* @__PURE__ */ __name((feature, chatId, messageId, emoji) => {
|
|
1637
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1638
|
+
return feature.write("the reaction may have been set \u2014 repeating it is safe", async () => {
|
|
1639
|
+
await feature.client.sendReaction({ chatId: Number(chatId), message: id, emoji });
|
|
1640
|
+
});
|
|
1641
|
+
}, "react");
|
|
1642
|
+
var markRead = /* @__PURE__ */ __name((feature, chatId, until) => {
|
|
1643
|
+
const maxId = until === void 0 ? void 0 : messageNumber(until, "--until takes a message id");
|
|
1644
|
+
return feature.write("the chat may have been marked read \u2014 repeating it is safe", async () => {
|
|
1645
|
+
await feature.client.readHistory(Number(chatId), maxId === void 0 ? {} : { maxId });
|
|
1646
|
+
});
|
|
1647
|
+
}, "markRead");
|
|
1648
|
+
var deleteMessages = /* @__PURE__ */ __name(async (feature, chatId, messageIds, { forEveryone }) => {
|
|
1649
|
+
const ids = messageIds.map((id) => messageNumber(id, "a message id is a number"));
|
|
1650
|
+
const peer = await feature.call(async () => {
|
|
1651
|
+
const peer2 = await feature.client.resolvePeer(Number(chatId));
|
|
1652
|
+
if (peer2._ === "inputPeerChannel") {
|
|
1653
|
+
if (!forEveryone) {
|
|
1654
|
+
throw new CliError("validation_error", "in a supergroup or a channel Telegram deletes for everyone \u2014 add --for-everyone if that is what you want");
|
|
1655
|
+
}
|
|
1656
|
+
return peer2;
|
|
1657
|
+
}
|
|
1658
|
+
const found = [];
|
|
1659
|
+
for (let at = 0; at < ids.length; at += BY_ID_BATCH)
|
|
1660
|
+
for (const one of await feature.client.getMessages(peer2, ids.slice(at, at + BY_ID_BATCH)))
|
|
1661
|
+
found.push(one);
|
|
1662
|
+
const missing = ids.filter((_, index) => found[index] == null);
|
|
1663
|
+
if (missing.length > 0) {
|
|
1664
|
+
throw new CliError("validation_error", `no message ${missing.join(", ")} in chat ${chatId} \u2014 not in this chat, or already deleted; nothing was deleted`);
|
|
1665
|
+
}
|
|
1666
|
+
return peer2;
|
|
1667
|
+
});
|
|
1668
|
+
return feature.write("the messages may have been deleted \u2014 repeating it is safe", async () => {
|
|
1669
|
+
for (let at = 0; at < ids.length; at += BY_ID_BATCH)
|
|
1670
|
+
await feature.client.deleteMessagesById(peer, ids.slice(at, at + BY_ID_BATCH), { revoke: forEveryone });
|
|
1671
|
+
});
|
|
1672
|
+
}, "deleteMessages");
|
|
1673
|
+
var download = /* @__PURE__ */ __name((feature, reference, messageId) => {
|
|
1674
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1675
|
+
return feature.call(async () => {
|
|
1676
|
+
const [found] = await feature.client.getMessages(await feature.inputOf(reference), id);
|
|
1677
|
+
if (!found)
|
|
1678
|
+
throw new CliError("not_found", `no message ${id} in that chat`);
|
|
1679
|
+
const media = found.media;
|
|
1680
|
+
if (!media)
|
|
1681
|
+
return { files: [], skipped: [] };
|
|
1682
|
+
if (!(media instanceof FileLocation))
|
|
1683
|
+
return { files: [], skipped: [media.type] };
|
|
1684
|
+
const [{ kind, name, mime, size }] = attachmentsOf(media);
|
|
1685
|
+
const client = feature.client;
|
|
1686
|
+
const { login: login2, checks } = feature;
|
|
1687
|
+
async function* bytes() {
|
|
1688
|
+
try {
|
|
1689
|
+
yield* client.downloadAsIterable(media);
|
|
1690
|
+
} catch (error) {
|
|
1691
|
+
throw toCliError(error, checks, login2);
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
__name(bytes, "bytes");
|
|
1695
|
+
return { files: [{ kind, name, mime, size, bytes }], skipped: [] };
|
|
1696
|
+
});
|
|
1697
|
+
}, "download");
|
|
1698
|
+
var transcribe = /* @__PURE__ */ __name((feature, reference, messageId) => {
|
|
1699
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1700
|
+
return feature.call(async () => {
|
|
1701
|
+
const peer = await feature.client.resolvePeer(await feature.inputOf(reference));
|
|
1702
|
+
const deadline = Date.now() + TRANSCRIBE_WAIT_MS;
|
|
1703
|
+
for (; ; ) {
|
|
1704
|
+
const answer = await feature.client.call({ _: "messages.transcribeAudio", peer, msgId: id }).catch((error) => {
|
|
1705
|
+
if (!tl7.RpcError.is(error, "PREMIUM_ACCOUNT_REQUIRED"))
|
|
1706
|
+
throw error;
|
|
1707
|
+
throw new CliError("permission_error", "Telegram transcribes only for Premium accounts, or a few messages a week on the free trial, used up now", { provider_error: error.text, status: error.code });
|
|
1708
|
+
});
|
|
1709
|
+
if (answer.pending !== true || Date.now() >= deadline) {
|
|
1710
|
+
return { text: answer.text, pending: answer.pending === true };
|
|
1711
|
+
}
|
|
1712
|
+
await sleep2(TRANSCRIBE_POLL_MS);
|
|
1713
|
+
}
|
|
1714
|
+
});
|
|
1715
|
+
}, "transcribe");
|
|
1716
|
+
|
|
1717
|
+
// dist/telegram/poll-voters.js
|
|
1718
|
+
import { PeersIndex as PeersIndex7, parsePeer } from "@mtcute/node";
|
|
1719
|
+
var pollVotersOf = /* @__PURE__ */ __name(async (client, chatId, messageId, { limit, answerId: answer }) => {
|
|
1720
|
+
const list = await client.call({
|
|
1721
|
+
_: "messages.getPollVotes",
|
|
1722
|
+
peer: await client.resolvePeer(chatId),
|
|
1723
|
+
id: messageId,
|
|
1724
|
+
limit,
|
|
1725
|
+
...answer === void 0 ? {} : { option: Buffer.from(answer, "base64url") }
|
|
1726
|
+
});
|
|
1727
|
+
const peers = PeersIndex7.from(list);
|
|
1728
|
+
const answersOf = /* @__PURE__ */ __name((vote2) => {
|
|
1729
|
+
if (vote2._ === "messagePeerVote")
|
|
1730
|
+
return [answerId(vote2.option)];
|
|
1731
|
+
if (vote2._ === "messagePeerVoteMultiple")
|
|
1732
|
+
return vote2.options.map(answerId);
|
|
1733
|
+
return answer === void 0 ? [] : [answer];
|
|
1734
|
+
}, "answersOf");
|
|
1735
|
+
const items = list.votes.map((vote2) => ({
|
|
1736
|
+
person: toMember(parsePeer(vote2.peer, peers)),
|
|
1737
|
+
answers: answersOf(vote2),
|
|
1738
|
+
votedAt: new Date(vote2.date * 1e3).toISOString()
|
|
1739
|
+
}));
|
|
1740
|
+
return { items, hasMore: Boolean(list.nextOffset) && items.length < list.count, total: list.count };
|
|
1741
|
+
}, "pollVotersOf");
|
|
1742
|
+
|
|
1743
|
+
// dist/telegram/polls.js
|
|
1744
|
+
var refuseVote = /* @__PURE__ */ __name((poll2, answerIds, words) => {
|
|
1745
|
+
if (poll2.isClosed)
|
|
1746
|
+
throw new CliError("validation_error", pollClosed(words));
|
|
1747
|
+
const voted = poll2.answers.some((answer) => answer.chosen);
|
|
1748
|
+
if (answerIds.length === 0 && !voted)
|
|
1749
|
+
throw new CliError("validation_error", "you have not voted in this poll");
|
|
1750
|
+
if (voted && poll2.isRevotingDisabled)
|
|
1751
|
+
throw new CliError("validation_error", "this poll takes one vote, and yours is final \u2014 it cannot be changed");
|
|
1752
|
+
if (answerIds.length > 1 && !poll2.isMultiple)
|
|
1753
|
+
throw new CliError("validation_error", "this poll takes one answer; give one id");
|
|
1754
|
+
}, "refuseVote");
|
|
1755
|
+
var refuseClose = /* @__PURE__ */ __name((poll2) => {
|
|
1756
|
+
if (poll2.isClosed)
|
|
1757
|
+
throw new CliError("validation_error", "this poll is closed already");
|
|
1758
|
+
if (!poll2.isCreator)
|
|
1759
|
+
throw new CliError("permission_error", "only whoever made a poll can close it");
|
|
1760
|
+
}, "refuseClose");
|
|
1761
|
+
var poll = /* @__PURE__ */ __name((feature, chatId, messageId) => {
|
|
1762
|
+
return feature.call(async () => toPoll(chatId, messageId, await pollOf(feature, chatId, messageId)));
|
|
1763
|
+
}, "poll");
|
|
1764
|
+
var pollVoters = /* @__PURE__ */ __name((feature, chatId, messageId, window) => {
|
|
1765
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1766
|
+
return feature.call(() => pollVotersOf(feature.client, Number(chatId), id, window));
|
|
1767
|
+
}, "pollVoters");
|
|
1768
|
+
var vote = /* @__PURE__ */ __name((feature, chatId, messageId, answerIds) => {
|
|
1769
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1770
|
+
return feature.call(async () => {
|
|
1771
|
+
const current = await pollOf(feature, chatId, messageId);
|
|
1772
|
+
const known = new Map(current.answers.map((answer) => [answerId(answer.data), answer.data]));
|
|
1773
|
+
const unknown = answerIds.filter((answer) => !known.has(answer));
|
|
1774
|
+
if (unknown.length > 0) {
|
|
1775
|
+
throw new CliError("validation_error", `${unknown.join(", ")} ${unknown.length === 1 ? "is" : "are"} not an answer of this poll \u2014 its answers are ${[...known.keys()].join(", ")}`);
|
|
1776
|
+
}
|
|
1777
|
+
refuseVote(current, answerIds, feature.checks);
|
|
1778
|
+
const options = answerIds.length === 0 ? null : answerIds.map((answer) => known.get(answer));
|
|
1779
|
+
try {
|
|
1780
|
+
return toPoll(chatId, messageId, await feature.client.sendVote({ chatId: Number(chatId), message: id, options }));
|
|
1781
|
+
} catch (error) {
|
|
1782
|
+
throw unknownIfUnanswered(error, "the vote may have been cast \u2014 repeating it is safe");
|
|
1783
|
+
}
|
|
1784
|
+
});
|
|
1785
|
+
}, "vote");
|
|
1786
|
+
var closePoll = /* @__PURE__ */ __name((feature, chatId, messageId) => {
|
|
1787
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1788
|
+
return feature.call(async () => {
|
|
1789
|
+
refuseClose(await pollOf(feature, chatId, messageId));
|
|
1790
|
+
try {
|
|
1791
|
+
return toPoll(chatId, messageId, await feature.client.closePoll({ chatId: Number(chatId), message: id }));
|
|
1792
|
+
} catch (error) {
|
|
1793
|
+
throw feature.unanswered(error, {
|
|
1794
|
+
what: "the poll may have been closed",
|
|
1795
|
+
check: "polls.show",
|
|
1796
|
+
after: "before repeating"
|
|
1797
|
+
});
|
|
1798
|
+
}
|
|
1799
|
+
});
|
|
1800
|
+
}, "closePoll");
|
|
1801
|
+
var createPoll = /* @__PURE__ */ __name((feature, chatId, poll2, { sendId, silent, threadId, sendAs }) => {
|
|
1802
|
+
const randomId = parseSendId(sendId);
|
|
1803
|
+
const thread = threadId === void 0 ? void 0 : topicNumber(threadId);
|
|
1804
|
+
const author = sendAs === void 0 ? void 0 : sendAsPeer(chatId, sendAs, feature.self(), feature.checks);
|
|
1805
|
+
return feature.send(async () => {
|
|
1806
|
+
try {
|
|
1807
|
+
const message = await feature.client.sendMedia(Number(chatId), toInputPoll(poll2), {
|
|
1808
|
+
randomId,
|
|
1809
|
+
...thread === void 0 || thread === 1 ? {} : { threadId: thread },
|
|
1810
|
+
...silent ? { silent } : {},
|
|
1811
|
+
...author === void 0 ? {} : { sendAs: author }
|
|
1812
|
+
});
|
|
1813
|
+
return { message: toMessage(message), sendId };
|
|
1814
|
+
} catch (error) {
|
|
1815
|
+
throw unknownIfUnanswered(error, `the poll may have been sent. Repeat with ${repeatWith(sendId, sendAs)}, never without it`, retryDetails(sendId, sendAs));
|
|
1816
|
+
}
|
|
1817
|
+
});
|
|
1818
|
+
}, "createPoll");
|
|
1819
|
+
var pollOf = /* @__PURE__ */ __name(async (feature, chatId, messageId) => {
|
|
1820
|
+
const id = messageNumber(messageId, "a message id is a number");
|
|
1821
|
+
const [found] = await feature.client.getMessages(Number(chatId), [id]);
|
|
1822
|
+
if (!found)
|
|
1823
|
+
throw new CliError("not_found", `no message ${id} in that chat`);
|
|
1824
|
+
if (found.media?.type !== "poll")
|
|
1825
|
+
throw new CliError("not_found", `message ${id} carries no poll`);
|
|
1826
|
+
return found.media;
|
|
1827
|
+
}, "pollOf");
|
|
1828
|
+
|
|
1829
|
+
// dist/telegram/sending.js
|
|
1830
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1831
|
+
import { networkMiddlewares } from "@mtcute/node";
|
|
1832
|
+
var SENDS = /* @__PURE__ */ new Set([
|
|
1833
|
+
"messages.sendMessage",
|
|
1834
|
+
"messages.sendMedia",
|
|
1835
|
+
"messages.sendMultiMedia",
|
|
1836
|
+
"messages.forwardMessages",
|
|
1837
|
+
"messages.startBot"
|
|
1838
|
+
]);
|
|
1839
|
+
var send2 = new AsyncLocalStorage();
|
|
1840
|
+
var noteAcceptedSend = /* @__PURE__ */ __name(async (context, next) => {
|
|
1841
|
+
const answer = await next(context);
|
|
1842
|
+
const current = send2.getStore();
|
|
1843
|
+
if (current && SENDS.has(context.request._) && answer?._ !== "mt_rpc_error")
|
|
1844
|
+
current.accepted = true;
|
|
1845
|
+
return answer;
|
|
1846
|
+
}, "noteAcceptedSend");
|
|
1847
|
+
var middlewaresOf = /* @__PURE__ */ __name(({ maxWait, maxRetries }, say) => [
|
|
1848
|
+
...networkMiddlewares.basic({
|
|
1849
|
+
floodWaiter: {
|
|
1850
|
+
maxWait,
|
|
1851
|
+
maxRetries,
|
|
1852
|
+
onBeforeWait: /* @__PURE__ */ __name((context, seconds) => say(`Telegram asks to wait ${seconds} s before ${context.request._} \u2014 waiting, then going on`), "onBeforeWait")
|
|
1853
|
+
}
|
|
1854
|
+
}),
|
|
1855
|
+
noteAcceptedSend
|
|
1856
|
+
], "middlewaresOf");
|
|
1857
|
+
var sending = /* @__PURE__ */ __name(async (work) => {
|
|
1858
|
+
const current = { accepted: false };
|
|
1859
|
+
try {
|
|
1860
|
+
return await send2.run(current, work);
|
|
1861
|
+
} catch (error) {
|
|
1862
|
+
const known = toCliError(error, bareCheck);
|
|
1863
|
+
if (current.accepted || !(known instanceof CliError) || known.code !== "rate_limited")
|
|
1864
|
+
throw error;
|
|
1865
|
+
throw new CliError(known.code, known.message, { ...known.details, sent: false });
|
|
1866
|
+
}
|
|
1867
|
+
}, "sending");
|
|
1868
|
+
|
|
1869
|
+
// dist/telegram/stats.js
|
|
1870
|
+
import { tl as tl8 } from "@mtcute/node";
|
|
1871
|
+
var DAY_MS = 864e5;
|
|
1872
|
+
var MS_FROM = 1e11;
|
|
1873
|
+
var axisOf = /* @__PURE__ */ __name((values) => {
|
|
1874
|
+
if (values.length === 0 || values.some((value2) => value2 < MS_FROM))
|
|
1875
|
+
return { type: "number", values };
|
|
1876
|
+
const days = values.every((value2) => value2 % DAY_MS === 0);
|
|
1877
|
+
return days ? { type: "date", values: values.map((value2) => new Date(value2).toISOString().slice(0, 10)) } : { type: "time", values: values.map((value2) => new Date(value2).toISOString()) };
|
|
1878
|
+
}, "axisOf");
|
|
1879
|
+
var toOfficialGraph = /* @__PURE__ */ __name((data) => {
|
|
1880
|
+
let chart;
|
|
1881
|
+
try {
|
|
1882
|
+
chart = JSON.parse(data);
|
|
1883
|
+
} catch {
|
|
1884
|
+
return { error: "Telegram sent a graph tg cannot read" };
|
|
1885
|
+
}
|
|
1886
|
+
if (!Array.isArray(chart?.columns) || typeof chart.types !== "object")
|
|
1887
|
+
return { error: "Telegram sent a graph tg cannot read" };
|
|
1888
|
+
const x = chart.columns.find(([key]) => chart.types[key] === "x");
|
|
1889
|
+
const series = chart.columns.filter(([key]) => chart.types[key] !== "x").map(([key, ...values]) => ({
|
|
1890
|
+
key,
|
|
1891
|
+
name: chart.names?.[key] ?? key,
|
|
1892
|
+
kind: chart.types[key] ?? "line",
|
|
1893
|
+
values
|
|
1894
|
+
}));
|
|
1895
|
+
return {
|
|
1896
|
+
kind: series[0]?.kind ?? "line",
|
|
1897
|
+
x: axisOf(x ? x.slice(1).map(Number) : []),
|
|
1898
|
+
series,
|
|
1899
|
+
...chart.stacked ? { stacked: true } : {},
|
|
1900
|
+
...chart.percentage ? { percentage: true } : {}
|
|
1901
|
+
};
|
|
1902
|
+
}, "toOfficialGraph");
|
|
1903
|
+
var value = /* @__PURE__ */ __name(({ current, previous }) => ({ current, previous }), "value");
|
|
1904
|
+
var period = /* @__PURE__ */ __name(({ minDate, maxDate }) => ({
|
|
1905
|
+
since: new Date(minDate * 1e3).toISOString(),
|
|
1906
|
+
until: new Date(maxDate * 1e3).toISOString()
|
|
1907
|
+
}), "period");
|
|
1908
|
+
var graphs = /* @__PURE__ */ __name(async (keys, graphOf) => {
|
|
1909
|
+
const answered = {};
|
|
1910
|
+
for (const [key, graph] of Object.entries(keys))
|
|
1911
|
+
answered[key] = await graphOf(graph);
|
|
1912
|
+
return answered;
|
|
1913
|
+
}, "graphs");
|
|
1914
|
+
var nameOf = /* @__PURE__ */ __name((user) => {
|
|
1915
|
+
if (user?._ !== "user")
|
|
1916
|
+
return null;
|
|
1917
|
+
const full = [user.firstName, user.lastName].filter(Boolean).join(" ");
|
|
1918
|
+
return full || user.username || null;
|
|
1919
|
+
}, "nameOf");
|
|
1920
|
+
var toOfficialGroupStats = /* @__PURE__ */ __name(async (chat2, stats, graphOf) => {
|
|
1921
|
+
const users = new Map(stats.users.map((user) => [user.id, user]));
|
|
1922
|
+
const person = /* @__PURE__ */ __name((userId) => ({ person: String(userId), name: nameOf(users.get(userId)) }), "person");
|
|
1923
|
+
return {
|
|
1924
|
+
version: 1,
|
|
1925
|
+
kind: "group",
|
|
1926
|
+
chat: chat2,
|
|
1927
|
+
period: period(stats.period),
|
|
1928
|
+
totals: {
|
|
1929
|
+
members: value(stats.members),
|
|
1930
|
+
messages: value(stats.messages),
|
|
1931
|
+
viewers: value(stats.viewers),
|
|
1932
|
+
posters: value(stats.posters)
|
|
1933
|
+
},
|
|
1934
|
+
top: {
|
|
1935
|
+
posters: stats.topPosters.map((one) => ({
|
|
1936
|
+
...person(one.userId),
|
|
1937
|
+
messages: one.messages,
|
|
1938
|
+
averageChars: one.avgChars
|
|
1939
|
+
})),
|
|
1940
|
+
admins: stats.topAdmins.map((one) => ({
|
|
1941
|
+
...person(one.userId),
|
|
1942
|
+
deleted: one.deleted,
|
|
1943
|
+
removed: one.kicked,
|
|
1944
|
+
banned: one.banned
|
|
1945
|
+
})),
|
|
1946
|
+
inviters: stats.topInviters.map((one) => ({ ...person(one.userId), invited: one.invitations }))
|
|
1947
|
+
},
|
|
1948
|
+
graphs: await graphs({
|
|
1949
|
+
growth: stats.growthGraph,
|
|
1950
|
+
members: stats.membersGraph,
|
|
1951
|
+
newMembersBySource: stats.newMembersBySourceGraph,
|
|
1952
|
+
languages: stats.languagesGraph,
|
|
1953
|
+
messages: stats.messagesGraph,
|
|
1954
|
+
actions: stats.actionsGraph,
|
|
1955
|
+
hours: stats.topHoursGraph,
|
|
1956
|
+
weekdays: stats.weekdaysGraph
|
|
1957
|
+
}, graphOf)
|
|
1958
|
+
};
|
|
1959
|
+
}, "toOfficialGroupStats");
|
|
1960
|
+
var toOfficialChannelStats = /* @__PURE__ */ __name(async (chat2, stats, graphOf) => ({
|
|
1961
|
+
version: 1,
|
|
1962
|
+
kind: "channel",
|
|
1963
|
+
chat: chat2,
|
|
1964
|
+
period: period(stats.period),
|
|
1965
|
+
totals: {
|
|
1966
|
+
followers: value(stats.followers),
|
|
1967
|
+
viewsPerPost: value(stats.viewsPerPost),
|
|
1968
|
+
sharesPerPost: value(stats.sharesPerPost),
|
|
1969
|
+
reactionsPerPost: value(stats.reactionsPerPost),
|
|
1970
|
+
viewsPerStory: value(stats.viewsPerStory),
|
|
1971
|
+
sharesPerStory: value(stats.sharesPerStory),
|
|
1972
|
+
reactionsPerStory: value(stats.reactionsPerStory)
|
|
1973
|
+
},
|
|
1974
|
+
notifications: { enabled: stats.enabledNotifications.part, total: stats.enabledNotifications.total },
|
|
1975
|
+
recentPosts: stats.recentPostsInteractions.map((post) => ({
|
|
1976
|
+
kind: post._ === "postInteractionCountersMessage" ? "message" : "story",
|
|
1977
|
+
id: String(post._ === "postInteractionCountersMessage" ? post.msgId : post.storyId),
|
|
1978
|
+
views: post.views,
|
|
1979
|
+
forwards: post.forwards,
|
|
1980
|
+
reactions: post.reactions
|
|
1981
|
+
})),
|
|
1982
|
+
graphs: await graphs({
|
|
1983
|
+
growth: stats.growthGraph,
|
|
1984
|
+
followers: stats.followersGraph,
|
|
1985
|
+
muted: stats.muteGraph,
|
|
1986
|
+
hours: stats.topHoursGraph,
|
|
1987
|
+
interactions: stats.interactionsGraph,
|
|
1988
|
+
instantView: stats.ivInteractionsGraph,
|
|
1989
|
+
viewsBySource: stats.viewsBySourceGraph,
|
|
1990
|
+
newFollowersBySource: stats.newFollowersBySourceGraph,
|
|
1991
|
+
languages: stats.languagesGraph,
|
|
1992
|
+
reactionsByEmotion: stats.reactionsByEmotionGraph,
|
|
1993
|
+
storyInteractions: stats.storyInteractionsGraph,
|
|
1994
|
+
storyReactionsByEmotion: stats.storyReactionsByEmotionGraph
|
|
1995
|
+
}, graphOf)
|
|
1996
|
+
}), "toOfficialChannelStats");
|
|
1997
|
+
var officialChatStats = /* @__PURE__ */ __name((feature, reference) => {
|
|
1998
|
+
return feature.call(async () => {
|
|
1999
|
+
let full = await feature.client.getFullChat(await feature.inputOf(reference));
|
|
2000
|
+
if (full.migratedToId != null)
|
|
2001
|
+
full = await feature.client.getFullChat(full.migratedToId);
|
|
2002
|
+
const broadcast = full.chatType === "channel";
|
|
2003
|
+
if (!broadcast && full.chatType !== "supergroup" && full.chatType !== "gigagroup") {
|
|
2004
|
+
throw new CliError("validation_error", full.chatType === "group" ? "Telegram keeps statistics only for supergroups and channels, not for a basic group" : "Telegram keeps statistics only for supergroups and channels");
|
|
2005
|
+
}
|
|
2006
|
+
if (!full.canViewStats) {
|
|
2007
|
+
throw new CliError("permission_error", "Telegram shows statistics only to admins of large enough groups and channels, and not for this one");
|
|
2008
|
+
}
|
|
2009
|
+
const statsDc = full.full._ === "channelFull" ? full.full.statsDc : void 0;
|
|
2010
|
+
const options = statsDc === void 0 ? void 0 : { dcId: statsDc };
|
|
2011
|
+
const channel = await feature.client.resolveChannel(full.id);
|
|
2012
|
+
const chat2 = { id: String(full.id), title: full.displayName };
|
|
2013
|
+
const graphOf = /* @__PURE__ */ __name(async (graph) => {
|
|
2014
|
+
if (graph._ === "statsGraph")
|
|
2015
|
+
return toOfficialGraph(graph.json.data);
|
|
2016
|
+
if (graph._ === "statsGraphError")
|
|
2017
|
+
return { error: graph.error };
|
|
2018
|
+
try {
|
|
2019
|
+
const loaded = await feature.client.call({ _: "stats.loadAsyncGraph", token: graph.token }, options);
|
|
2020
|
+
if (loaded._ === "statsGraph")
|
|
2021
|
+
return toOfficialGraph(loaded.json.data);
|
|
2022
|
+
return { error: loaded._ === "statsGraphError" ? loaded.error : "Telegram did not finish this graph" };
|
|
2023
|
+
} catch (error) {
|
|
2024
|
+
if (tl8.RpcError.is(error))
|
|
2025
|
+
return { error: error.text };
|
|
2026
|
+
throw error;
|
|
2027
|
+
}
|
|
2028
|
+
}, "graphOf");
|
|
2029
|
+
try {
|
|
2030
|
+
return broadcast ? await toOfficialChannelStats(chat2, await feature.client.call({ _: "stats.getBroadcastStats", channel }, options), graphOf) : await toOfficialGroupStats(chat2, await feature.client.call({ _: "stats.getMegagroupStats", channel }, options), graphOf);
|
|
2031
|
+
} catch (error) {
|
|
2032
|
+
if (tl8.RpcError.is(error, "AUTH_KEY_UNREGISTERED"))
|
|
2033
|
+
throw new CliError("provider_error", "Telegram's statistics server did not accept this login (AUTH_KEY_UNREGISTERED); the login itself works \u2014 try again later", { provider_error: error.text, status: error.code });
|
|
2034
|
+
throw error;
|
|
2035
|
+
}
|
|
2036
|
+
});
|
|
2037
|
+
}, "officialChatStats");
|
|
2038
|
+
|
|
2039
|
+
// dist/telegram/topics.js
|
|
2040
|
+
import { getMarkedPeerId as getMarkedPeerId7, tl as tl9 } from "@mtcute/node";
|
|
2041
|
+
var stateOf = /* @__PURE__ */ __name(async ({ client }, chatId) => {
|
|
2042
|
+
let full = await client.getFullChat(Number(chatId));
|
|
2043
|
+
if (full.migratedToId != null)
|
|
2044
|
+
full = await client.getFullChat(full.migratedToId);
|
|
2045
|
+
if (full.chatType !== "group" && full.chatType !== "supergroup") {
|
|
2046
|
+
throw new CliError("validation_error", "forum topics require a group, not a channel or dialog");
|
|
2047
|
+
}
|
|
2048
|
+
return {
|
|
2049
|
+
chat: peerToChat(full),
|
|
2050
|
+
forum: full.isForum,
|
|
2051
|
+
needsUpgrade: full.chatType === "group",
|
|
2052
|
+
owner: full.isCreator,
|
|
2053
|
+
linkedDiscussion: full.linkedChat !== null,
|
|
2054
|
+
canCreate: full.isCreator || full.adminRights?.manageTopics === true || full.permissions?.canManageTopics === true || full.defaultPermissions?.canManageTopics === true
|
|
2055
|
+
};
|
|
2056
|
+
}, "stateOf");
|
|
2057
|
+
var forumState = /* @__PURE__ */ __name((feature, chatId) => feature.call(() => stateOf(feature, chatId)), "forumState");
|
|
2058
|
+
var upgradeForum = /* @__PURE__ */ __name((feature, chatId) => feature.call(async () => {
|
|
2059
|
+
const { client } = feature;
|
|
2060
|
+
const state = await stateOf(feature, chatId);
|
|
2061
|
+
if (!state.owner)
|
|
2062
|
+
throw new CliError("permission_error", "only the owner can prepare this group for topics");
|
|
2063
|
+
if (!state.needsUpgrade)
|
|
2064
|
+
return state;
|
|
2065
|
+
const peer = await client.resolvePeer(Number(state.chat.id));
|
|
2066
|
+
if (peer._ !== "inputPeerChat")
|
|
2067
|
+
throw new CliError("validation_error", "only a basic group can be upgraded");
|
|
2068
|
+
let accepted = false;
|
|
2069
|
+
let migratedChatId;
|
|
2070
|
+
try {
|
|
2071
|
+
const updates = await client.call({ _: "messages.migrateChat", chatId: peer.chatId }, { maxRetryCount: 0, floodSleepThreshold: 0 });
|
|
2072
|
+
accepted = true;
|
|
2073
|
+
client.handleClientUpdate(updates, true);
|
|
2074
|
+
const made = updates._ === "updates" || updates._ === "updatesCombined" ? updates.chats.find((chat2) => chat2._ === "channel" && chat2.megagroup) : void 0;
|
|
2075
|
+
if (made?._ !== "channel")
|
|
2076
|
+
throw new CliError("outcome_unknown", "the group may have been upgraded; check its current chat id before repeating");
|
|
2077
|
+
migratedChatId = String(getMarkedPeerId7({ _: "peerChannel", channelId: made.id }));
|
|
2078
|
+
return await stateOf(feature, migratedChatId);
|
|
2079
|
+
} catch (error) {
|
|
2080
|
+
if (accepted)
|
|
2081
|
+
throw new CliError("outcome_unknown", "the upgrade was accepted but its state could not be read; check the current group before continuing", {
|
|
2082
|
+
previous_chat_id: state.chat.id,
|
|
2083
|
+
...migratedChatId === void 0 ? {} : { chat_id: migratedChatId, upgraded: true },
|
|
2084
|
+
stage: "upgrade"
|
|
2085
|
+
});
|
|
2086
|
+
throw unknownIfUnanswered(error, "the group may have been upgraded; check its current chat id before repeating");
|
|
2087
|
+
}
|
|
2088
|
+
}), "upgradeForum");
|
|
2089
|
+
var enableForum = /* @__PURE__ */ __name((feature, chatId) => feature.call(async () => {
|
|
2090
|
+
const state = await stateOf(feature, chatId);
|
|
2091
|
+
if (!state.owner)
|
|
2092
|
+
throw new CliError("permission_error", "only the group owner can enable forum topics");
|
|
2093
|
+
if (state.needsUpgrade)
|
|
2094
|
+
throw new CliError("validation_error", "upgrade the basic group explicitly before enabling topics");
|
|
2095
|
+
if (state.linkedDiscussion)
|
|
2096
|
+
throw new CliError("validation_error", "a linked discussion group cannot enable forum topics");
|
|
2097
|
+
if (state.forum)
|
|
2098
|
+
return state;
|
|
2099
|
+
try {
|
|
2100
|
+
const full = await feature.client.getFullChat(Number(state.chat.id));
|
|
2101
|
+
await feature.client.updateForumSettings(Number(state.chat.id), {
|
|
2102
|
+
isForum: true,
|
|
2103
|
+
threadsMode: full.raw._ === "channel" && full.raw.forumTabs ? "tabs" : "list"
|
|
2104
|
+
});
|
|
2105
|
+
return await stateOf(feature, state.chat.id);
|
|
2106
|
+
} catch (error) {
|
|
2107
|
+
if (tl9.RpcError.is(error, "CHAT_NOT_MODIFIED"))
|
|
2108
|
+
return stateOf(feature, state.chat.id);
|
|
2109
|
+
throw unknownIfUnanswered(error, "topics may have been enabled; check the forum state before repeating");
|
|
2110
|
+
}
|
|
2111
|
+
}), "enableForum");
|
|
2112
|
+
var createTopic = /* @__PURE__ */ __name((feature, chatId, title, { sendId }) => {
|
|
2113
|
+
const randomId = parseSendId(sendId);
|
|
2114
|
+
return feature.call(async () => {
|
|
2115
|
+
const { client } = feature;
|
|
2116
|
+
const state = await stateOf(feature, chatId);
|
|
2117
|
+
if (!state.forum || state.needsUpgrade)
|
|
2118
|
+
throw new CliError("validation_error", "enable topics before creating a topic");
|
|
2119
|
+
if (!state.canCreate)
|
|
2120
|
+
throw new CliError("permission_error", "creating a topic requires manage-topics permission");
|
|
2121
|
+
let accepted = false;
|
|
2122
|
+
try {
|
|
2123
|
+
const updates = await client.call({
|
|
2124
|
+
_: "messages.createForumTopic",
|
|
2125
|
+
peer: await client.resolvePeer(Number(state.chat.id)),
|
|
2126
|
+
title,
|
|
2127
|
+
randomId
|
|
2128
|
+
}, { maxRetryCount: 0, floodSleepThreshold: 0 });
|
|
2129
|
+
accepted = true;
|
|
2130
|
+
client.handleClientUpdate(updates, true);
|
|
2131
|
+
const message = forwardedCopy(updates, randomId, state.chat.id);
|
|
2132
|
+
const mapped = updates._ === "updates" || updates._ === "updatesCombined" ? updates.updates.find((update) => update._ === "updateMessageID" && String(update.randomId) === String(randomId)) : void 0;
|
|
2133
|
+
const topicId = mapped && mapped._ === "updateMessageID" ? mapped.id : message?.id;
|
|
2134
|
+
if (topicId === void 0)
|
|
2135
|
+
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 });
|
|
2136
|
+
const [topic2] = await client.getForumTopicsById(Number(state.chat.id), topicId);
|
|
2137
|
+
if (!topic2)
|
|
2138
|
+
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 });
|
|
2139
|
+
return toTopic(topic2);
|
|
2140
|
+
} catch (error) {
|
|
2141
|
+
if (accepted)
|
|
2142
|
+
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 });
|
|
2143
|
+
throw unknownIfUnanswered(error, `the topic may have been created; check topics list and do not repeat this creation`, { operation_id: sendId, retryable: false });
|
|
2144
|
+
}
|
|
2145
|
+
});
|
|
2146
|
+
}, "createTopic");
|
|
2147
|
+
var editTopic = /* @__PURE__ */ __name((feature, chatId, topicId, { title, closed, pinned, hidden }) => {
|
|
2148
|
+
const id = topicNumber(topicId);
|
|
2149
|
+
if (hidden !== void 0 && id !== 1)
|
|
2150
|
+
throw new CliError("validation_error", "only the General topic (id 1) can be hidden");
|
|
2151
|
+
return feature.call(async () => {
|
|
2152
|
+
const { client } = feature;
|
|
2153
|
+
const unchanged = /* @__PURE__ */ __name((error) => {
|
|
2154
|
+
if (!tl9.RpcError.is(error, "TOPIC_NOT_MODIFIED") && !tl9.RpcError.is(error, "PINNED_TOPIC_NOT_MODIFIED"))
|
|
2155
|
+
throw unknownIfUnanswered(error, "the topic may have changed \u2014 repeating it is safe");
|
|
2156
|
+
}, "unchanged");
|
|
2157
|
+
if (title !== void 0 || closed !== void 0) {
|
|
2158
|
+
await client.editForumTopic({
|
|
2159
|
+
chatId: Number(chatId),
|
|
2160
|
+
topicId: id,
|
|
2161
|
+
...title === void 0 ? {} : { title },
|
|
2162
|
+
...closed === void 0 ? {} : { closed }
|
|
2163
|
+
}).catch(unchanged);
|
|
2164
|
+
}
|
|
2165
|
+
if (pinned !== void 0)
|
|
2166
|
+
await client.toggleForumTopicPinned({ chatId: Number(chatId), topicId: id, pinned }).catch(unchanged);
|
|
2167
|
+
if (hidden !== void 0)
|
|
2168
|
+
await client.toggleGeneralTopicHidden({ chatId: Number(chatId), hidden }).catch(unchanged);
|
|
2169
|
+
const [topic2] = await client.getForumTopicsById(Number(chatId), id);
|
|
2170
|
+
if (!topic2)
|
|
2171
|
+
throw new CliError("not_found", `no topic ${topicId} in that chat`);
|
|
2172
|
+
return {
|
|
2173
|
+
...toTopic(topic2),
|
|
2174
|
+
...title === void 0 ? {} : { title },
|
|
2175
|
+
...closed === void 0 ? {} : { closed },
|
|
2176
|
+
...pinned === void 0 ? {} : { pinned },
|
|
2177
|
+
...hidden === void 0 ? {} : { hidden }
|
|
2178
|
+
};
|
|
2179
|
+
});
|
|
2180
|
+
}, "editTopic");
|
|
2181
|
+
var orderPinnedTopics = /* @__PURE__ */ __name((feature, chatId, topicIds) => {
|
|
2182
|
+
const order = topicIds.map(topicNumber);
|
|
2183
|
+
return feature.call(async () => {
|
|
2184
|
+
try {
|
|
2185
|
+
await feature.client.reorderPinnedForumTopics({ chatId: Number(chatId), order });
|
|
2186
|
+
} catch (error) {
|
|
2187
|
+
throw unknownIfUnanswered(error, "the pinned topics may have been reordered \u2014 repeating it is safe");
|
|
2188
|
+
}
|
|
2189
|
+
});
|
|
2190
|
+
}, "orderPinnedTopics");
|
|
2191
|
+
var deleteTopic = /* @__PURE__ */ __name((feature, chatId, topicId) => {
|
|
2192
|
+
const id = topicNumber(topicId);
|
|
2193
|
+
return feature.call(async () => {
|
|
2194
|
+
try {
|
|
2195
|
+
await feature.client.deleteForumTopicHistory(Number(chatId), id);
|
|
2196
|
+
} catch (error) {
|
|
2197
|
+
throw feature.unanswered(error, {
|
|
2198
|
+
what: "the topic may have been deleted",
|
|
2199
|
+
check: "topics.list",
|
|
2200
|
+
after: "before repeating"
|
|
2201
|
+
});
|
|
2202
|
+
}
|
|
2203
|
+
});
|
|
2204
|
+
}, "deleteTopic");
|
|
2205
|
+
var validateThread = /* @__PURE__ */ __name(async (feature, chatId, threadId, { replyTo }) => {
|
|
2206
|
+
const topicId = topicNumber(threadId);
|
|
2207
|
+
const replyId = replyTo === void 0 ? void 0 : messageNumber(replyTo, "--reply-to needs a message id");
|
|
2208
|
+
return feature.call(async () => {
|
|
2209
|
+
const { client } = feature;
|
|
2210
|
+
const peer = await client.getPeer(Number(chatId));
|
|
2211
|
+
if (peer.type !== "chat" || !peer.isForum) {
|
|
2212
|
+
throw new CliError("validation_error", "--topic requires a Telegram forum group");
|
|
2213
|
+
}
|
|
2214
|
+
const [topic2] = await client.getForumTopicsById(Number(chatId), topicId);
|
|
2215
|
+
if (!topic2)
|
|
2216
|
+
throw new CliError("not_found", "that forum topic does not exist; check `topics list`");
|
|
2217
|
+
if (topic2.isClosed)
|
|
2218
|
+
throw new CliError("permission_error", "that forum topic is closed; choose an open topic");
|
|
2219
|
+
if (replyId !== void 0) {
|
|
2220
|
+
const [reply] = await client.getMessages(Number(chatId), [replyId]);
|
|
2221
|
+
if (!reply)
|
|
2222
|
+
throw new CliError("not_found", "the message to reply to no longer exists in this chat");
|
|
2223
|
+
const replyThread = reply.isTopicMessage ? reply.replyToMessage?.threadId ?? reply.id : 1;
|
|
2224
|
+
if (reply.id !== topicId && replyThread !== topicId) {
|
|
2225
|
+
throw new CliError("validation_error", "--reply-to belongs to a different topic; choose a message in --topic");
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
});
|
|
2229
|
+
}, "validateThread");
|
|
2230
|
+
var topic = /* @__PURE__ */ __name((feature, reference, topicId) => {
|
|
2231
|
+
const id = topicNumber(topicId);
|
|
2232
|
+
return feature.call(async () => {
|
|
2233
|
+
const input = await feature.inputOf(reference);
|
|
2234
|
+
const peer = await feature.client.getPeer(input);
|
|
2235
|
+
if (peer.type !== "chat" || !peer.isForum)
|
|
2236
|
+
throw new CliError("validation_error", "that chat has no topics");
|
|
2237
|
+
const [found] = await feature.client.getForumTopicsById(input, id);
|
|
2238
|
+
if (!found)
|
|
2239
|
+
throw new CliError("not_found", "that forum topic does not exist; check `topics list`");
|
|
2240
|
+
return toTopic(found);
|
|
2241
|
+
});
|
|
2242
|
+
}, "topic");
|
|
2243
|
+
var topics = /* @__PURE__ */ __name((feature, reference, { search, limit, offset }) => feature.call(async () => {
|
|
2244
|
+
const peer = await feature.inputOf(reference);
|
|
2245
|
+
const items = [];
|
|
2246
|
+
const wanted = limit === void 0 ? {} : { limit: offset + limit + 1 };
|
|
2247
|
+
for await (const one of feature.client.iterForumTopics(peer, {
|
|
2248
|
+
...wanted,
|
|
2249
|
+
...search ? { query: search } : {}
|
|
2250
|
+
})) {
|
|
2251
|
+
items.push(toTopic(one));
|
|
2252
|
+
}
|
|
2253
|
+
const end = limit === void 0 ? items.length : offset + limit;
|
|
2254
|
+
return { items: items.slice(offset, end), hasMore: items.length > end };
|
|
2255
|
+
}), "topics");
|
|
2256
|
+
var topicHistory = /* @__PURE__ */ __name((feature, reference, threadId, { limit, before }) => {
|
|
2257
|
+
const thread = topicNumber(threadId);
|
|
2258
|
+
const offset = before === void 0 ? void 0 : messageNumber(before, "`id<` takes a message id");
|
|
2259
|
+
return feature.call(async () => {
|
|
2260
|
+
const page = await feature.client.searchMessages({
|
|
2261
|
+
chatId: await feature.inputOf(reference),
|
|
2262
|
+
threadId: thread,
|
|
2263
|
+
limit,
|
|
2264
|
+
...offset === void 0 ? {} : { offset }
|
|
2265
|
+
});
|
|
2266
|
+
return { items: page.map(remoteMessage).reverse(), hasMore: page.next !== void 0 };
|
|
2267
|
+
});
|
|
2268
|
+
}, "topicHistory");
|
|
2269
|
+
var markTopicRead = /* @__PURE__ */ __name((feature, chatId, topicId, until) => {
|
|
2270
|
+
const id = topicNumber(topicId);
|
|
2271
|
+
const maxId = until === void 0 ? void 0 : messageNumber(until, "--until takes a message id");
|
|
2272
|
+
return feature.write("the topic may have been marked read \u2014 repeating it is safe", async () => {
|
|
2273
|
+
let readMaxId = maxId;
|
|
2274
|
+
if (readMaxId === void 0) {
|
|
2275
|
+
const [found] = await feature.client.getForumTopicsById(Number(chatId), id);
|
|
2276
|
+
if (!found)
|
|
2277
|
+
throw new CliError("not_found", `no topic ${topicId} in that chat`);
|
|
2278
|
+
readMaxId = found.lastMessage.id;
|
|
2279
|
+
}
|
|
2280
|
+
await feature.client.call({
|
|
2281
|
+
_: "messages.readDiscussion",
|
|
2282
|
+
peer: await feature.client.resolvePeer(Number(chatId)),
|
|
2283
|
+
msgId: id,
|
|
2284
|
+
readMaxId
|
|
2285
|
+
});
|
|
2286
|
+
});
|
|
2287
|
+
}, "markTopicRead");
|
|
2288
|
+
|
|
2289
|
+
// dist/telegram/watch.js
|
|
2290
|
+
var LOOP_CHECK_MS = 3e4;
|
|
2291
|
+
var HEARTBEAT_TICKS = 30;
|
|
2292
|
+
var STATE_WAIT_MS = 3e4;
|
|
2293
|
+
var LOOP_STOPPED = "Telegram's updates stopped arriving although the connection is open \u2014 ending, so a service unit starts it again";
|
|
2294
|
+
var pause = /* @__PURE__ */ __name((ms, signal) => new Promise((resolve2) => {
|
|
2295
|
+
const done = /* @__PURE__ */ __name(() => {
|
|
2296
|
+
clearTimeout(timer);
|
|
2297
|
+
signal.removeEventListener("abort", done);
|
|
2298
|
+
resolve2();
|
|
2299
|
+
}, "done");
|
|
2300
|
+
const timer = setTimeout(done, ms);
|
|
2301
|
+
if (signal.aborted)
|
|
2302
|
+
done();
|
|
2303
|
+
else
|
|
2304
|
+
signal.addEventListener("abort", done, { once: true });
|
|
2305
|
+
}), "pause");
|
|
2306
|
+
var askState = /* @__PURE__ */ __name(async ({ call, client }) => {
|
|
2307
|
+
let timer;
|
|
2308
|
+
const late = new Promise((resolve2) => {
|
|
2309
|
+
timer = setTimeout(() => resolve2(new CliError("timeout", "Telegram did not answer in time")), STATE_WAIT_MS);
|
|
2310
|
+
});
|
|
2311
|
+
const asked = call(() => client.call({ _: "updates.getState" })).then(() => void 0, (error) => isCliError(error) ? error : new CliError("provider_error", "Telegram failed"));
|
|
2312
|
+
try {
|
|
2313
|
+
return await Promise.race([asked, late]);
|
|
2314
|
+
} finally {
|
|
2315
|
+
clearTimeout(timer);
|
|
2316
|
+
}
|
|
2317
|
+
}, "askState");
|
|
2318
|
+
var untilStopped = /* @__PURE__ */ __name(async (feature, signal) => {
|
|
2319
|
+
const updates = feature.client._client?.updates;
|
|
2320
|
+
for (let tick = 1; ; tick += 1) {
|
|
2321
|
+
await pause(LOOP_CHECK_MS, signal);
|
|
2322
|
+
if (signal.aborted)
|
|
2323
|
+
return;
|
|
2324
|
+
const down = updates?.updatesLoopActive === false;
|
|
2325
|
+
if (!down && tick % HEARTBEAT_TICKS !== 0)
|
|
2326
|
+
continue;
|
|
2327
|
+
const refusal = await askState(feature);
|
|
2328
|
+
if (signal.aborted)
|
|
2329
|
+
return;
|
|
2330
|
+
if (refusal?.code === "authentication_error")
|
|
2331
|
+
throw refusal;
|
|
2332
|
+
if (down) {
|
|
2333
|
+
const stopped = new CliError("provider_unavailable", LOOP_STOPPED, { reason: "updates.stopped" });
|
|
2334
|
+
throw refusal ? withCause(stopped, refusal) : stopped;
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2337
|
+
}, "untilStopped");
|
|
2338
|
+
var watch = /* @__PURE__ */ __name(async (feature, onEvent, signal, onReady) => {
|
|
2339
|
+
const { client } = feature;
|
|
2340
|
+
const message = /* @__PURE__ */ __name((found) => onEvent({ event: "message", message: remoteHit(found, "remote_update") }), "message");
|
|
2341
|
+
const reaction = /* @__PURE__ */ __name((change) => onEvent({
|
|
2342
|
+
...change,
|
|
2343
|
+
counterObservation: {
|
|
2344
|
+
value: change.reactions.total,
|
|
2345
|
+
observedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2346
|
+
source: "remote_update",
|
|
2347
|
+
reactions: change.reactions
|
|
2348
|
+
}
|
|
2349
|
+
}), "reaction");
|
|
2350
|
+
const edit2 = /* @__PURE__ */ __name((found) => {
|
|
2351
|
+
const message2 = remoteHit(found, "remote_update");
|
|
2352
|
+
onEvent({ event: "edit", message: message2 });
|
|
2353
|
+
if (message2.reactions)
|
|
2354
|
+
reaction({
|
|
2355
|
+
event: "reaction",
|
|
2356
|
+
chatId: message2.chatId,
|
|
2357
|
+
chatTitle: message2.chatTitle ?? null,
|
|
2358
|
+
messageId: message2.id,
|
|
2359
|
+
reactions: message2.reactions
|
|
2360
|
+
});
|
|
2361
|
+
}, "edit");
|
|
2362
|
+
const deletion = /* @__PURE__ */ __name((update) => {
|
|
2363
|
+
for (const change of toDeletions(update))
|
|
2364
|
+
onEvent(change);
|
|
2365
|
+
}, "deletion");
|
|
2366
|
+
const raw = /* @__PURE__ */ __name((info) => {
|
|
2367
|
+
const change = toReactionChange(info);
|
|
2368
|
+
if (change?.event === "reaction")
|
|
2369
|
+
reaction(change);
|
|
2370
|
+
else if (change)
|
|
2371
|
+
onEvent(change);
|
|
2372
|
+
}, "raw");
|
|
2373
|
+
client.onNewMessage.add(message);
|
|
2374
|
+
client.onEditMessage.add(edit2);
|
|
2375
|
+
client.onDeleteMessage.add(deletion);
|
|
2376
|
+
client.onRawUpdate.add(raw);
|
|
2377
|
+
try {
|
|
2378
|
+
await feature.call(async () => {
|
|
2379
|
+
await client.connect();
|
|
2380
|
+
await client.call({ _: "updates.getState" });
|
|
2381
|
+
await client.startUpdatesLoop();
|
|
2382
|
+
});
|
|
2383
|
+
onReady?.();
|
|
2384
|
+
await untilStopped(feature, signal);
|
|
2385
|
+
} finally {
|
|
2386
|
+
client.onNewMessage.remove(message);
|
|
2387
|
+
client.onEditMessage.remove(edit2);
|
|
2388
|
+
client.onDeleteMessage.remove(deletion);
|
|
2389
|
+
client.onRawUpdate.remove(raw);
|
|
2390
|
+
}
|
|
2391
|
+
}, "watch");
|
|
2392
|
+
|
|
2393
|
+
// dist/telegram/adapter.js
|
|
2394
|
+
var TelegramAdapter = class _TelegramAdapter {
|
|
2395
|
+
static {
|
|
2396
|
+
__name(this, "TelegramAdapter");
|
|
2397
|
+
}
|
|
2398
|
+
async formatMarkdown(text) {
|
|
2399
|
+
return formatMarkdown(text);
|
|
2400
|
+
}
|
|
2401
|
+
async formatHtml(text) {
|
|
2402
|
+
return formatHtml(text);
|
|
2403
|
+
}
|
|
2404
|
+
#client;
|
|
2405
|
+
#sessionPath;
|
|
2406
|
+
#feature;
|
|
2407
|
+
#proxyFailed;
|
|
2408
|
+
#walking = {};
|
|
2409
|
+
/** Async because the runtime's SQLite module is imported on demand (cli-core `openCache`). */
|
|
2410
|
+
static async open(options) {
|
|
2411
|
+
mkdirSync(dirname(options.sessionPath), { recursive: true, mode: 448 });
|
|
2412
|
+
const adapter = new _TelegramAdapter(options, await openSessionStorage(options.sessionPath));
|
|
2413
|
+
try {
|
|
2414
|
+
await adapter.#client.prepare();
|
|
2415
|
+
} catch (error) {
|
|
2416
|
+
await adapter.close().catch(() => {
|
|
2417
|
+
});
|
|
2418
|
+
throw error;
|
|
2419
|
+
}
|
|
2420
|
+
return adapter;
|
|
2421
|
+
}
|
|
2422
|
+
constructor({ credentials, sessionPath, diagnostic, verbose = false, listen = false, catchUp = false, login: login2, proxy, note, checks = bareCheck }, storage) {
|
|
2423
|
+
this.#sessionPath = sessionPath;
|
|
2424
|
+
const proxied = proxy ? proxiedTransport(proxy) : void 0;
|
|
2425
|
+
this.#proxyFailed = listen ? void 0 : proxied?.failed;
|
|
2426
|
+
const write = diagnostic ?? ((line) => process.stderr.write(`${line}
|
|
2427
|
+
`));
|
|
2428
|
+
const say = note ?? write;
|
|
2429
|
+
this.#client = new TelegramClient({
|
|
2430
|
+
...proxied ? { transport: proxied.transport } : {},
|
|
2431
|
+
apiId: credentials.id,
|
|
2432
|
+
apiHash: credentials.hash,
|
|
2433
|
+
storage,
|
|
2434
|
+
// The storage manager has an exit hook of its own; the close is the command's (storage.ts `setup`).
|
|
2435
|
+
storageOptions: { cleanup: false },
|
|
2436
|
+
disableUpdates: !listen,
|
|
2437
|
+
...listen ? { updates: { catchUp } } : {},
|
|
2438
|
+
logLevel: verbose ? 3 : 1,
|
|
2439
|
+
network: { middlewares: middlewaresOf(listen ? FLOOD_SLEEP.listening : FLOOD_SLEEP.oneShot, say) }
|
|
2440
|
+
});
|
|
2441
|
+
this.#client.log.mgr.handler = (_color, _level, tag, fmt, args) => write(`[${tag}] ${format(fmt, ...args)}`);
|
|
2442
|
+
this.#client.onError.add(backgroundError(write, verbose, checks));
|
|
2443
|
+
const unanswered = /* @__PURE__ */ __name((error, what, details) => unknownIfUnanswered(error, typeof what === "string" ? what : unansweredText(what, checks), details), "unanswered");
|
|
2444
|
+
this.#feature = {
|
|
2445
|
+
client: this.#client,
|
|
2446
|
+
login: login2,
|
|
2447
|
+
checks,
|
|
2448
|
+
self: /* @__PURE__ */ __name(() => this.self(), "self"),
|
|
2449
|
+
inputOf: /* @__PURE__ */ __name((reference) => inputOf(this.#client, reference), "inputOf"),
|
|
2450
|
+
call: /* @__PURE__ */ __name((work) => this.#call(work), "call"),
|
|
2451
|
+
send: /* @__PURE__ */ __name((work) => this.#call(() => sending(work)), "send"),
|
|
2452
|
+
write: /* @__PURE__ */ __name((what, work) => this.#call(async () => {
|
|
2453
|
+
try {
|
|
2454
|
+
return await work();
|
|
2455
|
+
} catch (error) {
|
|
2456
|
+
throw unanswered(error, what);
|
|
2457
|
+
}
|
|
2458
|
+
}), "write"),
|
|
2459
|
+
unanswered
|
|
2460
|
+
};
|
|
2461
|
+
}
|
|
2462
|
+
login(prompts) {
|
|
2463
|
+
return login(this.#feature, prompts);
|
|
2464
|
+
}
|
|
2465
|
+
/** The logged-in user's id from the session, without a request; `null` before a login. */
|
|
2466
|
+
self() {
|
|
2467
|
+
const cached = this.#client.storage.self.getCached(true);
|
|
2468
|
+
return cached ? String(cached.userId) : null;
|
|
2469
|
+
}
|
|
2470
|
+
me() {
|
|
2471
|
+
return me(this.#feature);
|
|
2472
|
+
}
|
|
2473
|
+
health() {
|
|
2474
|
+
return health(this.#feature);
|
|
2475
|
+
}
|
|
2476
|
+
updateProfile(change) {
|
|
2477
|
+
return updateProfile(this.#feature, change);
|
|
2478
|
+
}
|
|
2479
|
+
chats(window) {
|
|
2480
|
+
return chats(this.#feature, this.#walking, window);
|
|
2481
|
+
}
|
|
2482
|
+
chat(reference) {
|
|
2483
|
+
return chat(this.#feature, reference);
|
|
2484
|
+
}
|
|
2485
|
+
resolve(reference) {
|
|
2486
|
+
return resolve(this.#feature, reference);
|
|
2487
|
+
}
|
|
2488
|
+
discussionOf(channelId, postId) {
|
|
2489
|
+
const post = messageNumber(postId, "a post id is a number");
|
|
2490
|
+
return this.#call(() => discussionOf(this.#client, Number(channelId), post));
|
|
2491
|
+
}
|
|
2492
|
+
comments(channelId, postId, { limit, before }) {
|
|
2493
|
+
const post = messageNumber(postId, "a post id is a number");
|
|
2494
|
+
const offset = before === void 0 ? void 0 : messageNumber(before, "`id<` takes a comment id");
|
|
2495
|
+
return this.#call(async () => {
|
|
2496
|
+
const page = await commentsOf(this.#client, Number(channelId), post, {
|
|
2497
|
+
limit,
|
|
2498
|
+
...offset === void 0 ? {} : { before: offset }
|
|
2499
|
+
});
|
|
2500
|
+
return { items: page.items.map(toMessage), hasMore: page.hasMore };
|
|
2501
|
+
});
|
|
2502
|
+
}
|
|
2503
|
+
history(reference, window) {
|
|
2504
|
+
return history(this.#feature, reference, window);
|
|
2505
|
+
}
|
|
2506
|
+
historyAfter(reference, window) {
|
|
2507
|
+
return historyAfter(this.#feature, reference, window);
|
|
2508
|
+
}
|
|
2509
|
+
historyFrom(reference, person, window) {
|
|
2510
|
+
return historyFrom(this.#feature, reference, person, window);
|
|
2511
|
+
}
|
|
2512
|
+
historyBefore(reference, window) {
|
|
2513
|
+
return historyBefore(this.#feature, reference, window);
|
|
2514
|
+
}
|
|
2515
|
+
searchMessages(query, options) {
|
|
2516
|
+
return searchMessages(this.#feature, query, options);
|
|
2517
|
+
}
|
|
2518
|
+
around(reference, messageId, window) {
|
|
2519
|
+
return around(this.#feature, reference, messageId, window);
|
|
2520
|
+
}
|
|
2521
|
+
fetchCounters(reference, messageId, fields, signal) {
|
|
2522
|
+
return fetchCounters(this.#feature, reference, messageId, fields, signal);
|
|
2523
|
+
}
|
|
2524
|
+
permalink(chatId, messageId) {
|
|
2525
|
+
return permalink(this.#feature, chatId, messageId);
|
|
2526
|
+
}
|
|
2527
|
+
scheduled(reference) {
|
|
2528
|
+
return scheduled(this.#feature, reference);
|
|
2529
|
+
}
|
|
2530
|
+
send(chatId, text, options) {
|
|
2531
|
+
return send(this.#feature, chatId, text, options);
|
|
2532
|
+
}
|
|
2533
|
+
saveDraft(chatId, text, options) {
|
|
2534
|
+
return saveDraft(this.#feature, chatId, text, options);
|
|
2535
|
+
}
|
|
2536
|
+
edit(chatId, messageId, text, spans) {
|
|
2537
|
+
return edit(this.#feature, chatId, messageId, text, spans);
|
|
2538
|
+
}
|
|
2539
|
+
forward(fromChatId, messageId, toChatId, options) {
|
|
2540
|
+
return forward(this.#feature, fromChatId, messageId, toChatId, options);
|
|
2541
|
+
}
|
|
2542
|
+
pin(chatId, messageId, options) {
|
|
2543
|
+
return pin(this.#feature, chatId, messageId, options);
|
|
2544
|
+
}
|
|
2545
|
+
unpin(chatId, messageId) {
|
|
2546
|
+
return unpin(this.#feature, chatId, messageId);
|
|
2547
|
+
}
|
|
2548
|
+
react(chatId, messageId, emoji) {
|
|
2549
|
+
return react(this.#feature, chatId, messageId, emoji);
|
|
2550
|
+
}
|
|
2551
|
+
markRead(chatId, until) {
|
|
2552
|
+
return markRead(this.#feature, chatId, until);
|
|
2553
|
+
}
|
|
2554
|
+
delete(chatId, messageIds, options) {
|
|
2555
|
+
return deleteMessages(this.#feature, chatId, messageIds, options);
|
|
2556
|
+
}
|
|
2557
|
+
download(reference, messageId) {
|
|
2558
|
+
return download(this.#feature, reference, messageId);
|
|
2559
|
+
}
|
|
2560
|
+
transcribe(reference, messageId) {
|
|
2561
|
+
return transcribe(this.#feature, reference, messageId);
|
|
2562
|
+
}
|
|
2563
|
+
poll(chatId, messageId) {
|
|
2564
|
+
return poll(this.#feature, chatId, messageId);
|
|
2565
|
+
}
|
|
2566
|
+
pollVoters(chatId, messageId, window) {
|
|
2567
|
+
return pollVoters(this.#feature, chatId, messageId, window);
|
|
2568
|
+
}
|
|
2569
|
+
vote(chatId, messageId, answerIds) {
|
|
2570
|
+
return vote(this.#feature, chatId, messageId, answerIds);
|
|
2571
|
+
}
|
|
2572
|
+
closePoll(chatId, messageId) {
|
|
2573
|
+
return closePoll(this.#feature, chatId, messageId);
|
|
2574
|
+
}
|
|
2575
|
+
createPoll(chatId, poll2, options) {
|
|
2576
|
+
return createPoll(this.#feature, chatId, poll2, options);
|
|
2577
|
+
}
|
|
2578
|
+
buttons = /* @__PURE__ */ __name((chatId, messageId) => buttons(this.#feature, chatId, messageId), "buttons");
|
|
2579
|
+
pressButton = /* @__PURE__ */ __name((chatId, messageId, row, column) => pressButton(this.#feature, chatId, messageId, row, column), "pressButton");
|
|
2580
|
+
botByLink = /* @__PURE__ */ __name((reference) => botByLink(this.#feature, reference), "botByLink");
|
|
2581
|
+
startBot = /* @__PURE__ */ __name((chatId, options) => startBot(this.#feature, chatId, options), "startBot");
|
|
2582
|
+
botApp = /* @__PURE__ */ __name((chatId, options) => botApp(this.#feature, chatId, options), "botApp");
|
|
2583
|
+
officialChatStats(reference) {
|
|
2584
|
+
return officialChatStats(this.#feature, reference);
|
|
2585
|
+
}
|
|
2586
|
+
topicHistory(reference, threadId, window) {
|
|
2587
|
+
return topicHistory(this.#feature, reference, threadId, window);
|
|
2588
|
+
}
|
|
2589
|
+
photos(person) {
|
|
2590
|
+
return photos(this.#feature, person);
|
|
2591
|
+
}
|
|
2592
|
+
contact(reference) {
|
|
2593
|
+
return contact(this.#feature, reference);
|
|
2594
|
+
}
|
|
2595
|
+
profile(reference) {
|
|
2596
|
+
return profile(this.#feature, reference);
|
|
2597
|
+
}
|
|
2598
|
+
sendAsIdentities(chatId) {
|
|
2599
|
+
return this.#call(() => sendAsIdentities(this.#client, chatId));
|
|
2600
|
+
}
|
|
2601
|
+
savedSender(chatId) {
|
|
2602
|
+
return this.#call(() => savedSenderOf(this.#client, chatId, this.self()));
|
|
2603
|
+
}
|
|
2604
|
+
watch(onEvent, signal, onReady) {
|
|
2605
|
+
return watch(this.#feature, onEvent, signal, onReady);
|
|
2606
|
+
}
|
|
2607
|
+
logout() {
|
|
2608
|
+
return logout(this.#feature);
|
|
2609
|
+
}
|
|
2610
|
+
async close() {
|
|
2611
|
+
await this.#client.destroy();
|
|
2612
|
+
for (const suffix of ["", "-wal", "-shm"]) {
|
|
2613
|
+
const path = `${this.#sessionPath}${suffix}`;
|
|
2614
|
+
if (existsSync(path))
|
|
2615
|
+
chmodSync(path, 384);
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2618
|
+
markTopicRead(chatId, topicId, until) {
|
|
2619
|
+
return markTopicRead(this.#feature, chatId, topicId, until);
|
|
2620
|
+
}
|
|
2621
|
+
inspect(link) {
|
|
2622
|
+
return inspect(this.#feature, link);
|
|
2623
|
+
}
|
|
2624
|
+
forumState(chatId) {
|
|
2625
|
+
return forumState(this.#feature, chatId);
|
|
2626
|
+
}
|
|
2627
|
+
upgradeForum(chatId) {
|
|
2628
|
+
return upgradeForum(this.#feature, chatId);
|
|
2629
|
+
}
|
|
2630
|
+
enableForum(chatId) {
|
|
2631
|
+
return enableForum(this.#feature, chatId);
|
|
2632
|
+
}
|
|
2633
|
+
createTopic(chatId, title, options) {
|
|
2634
|
+
return createTopic(this.#feature, chatId, title, options);
|
|
2635
|
+
}
|
|
2636
|
+
editTopic(chatId, topicId, change) {
|
|
2637
|
+
return editTopic(this.#feature, chatId, topicId, change);
|
|
2638
|
+
}
|
|
2639
|
+
orderPinnedTopics(chatId, topicIds) {
|
|
2640
|
+
return orderPinnedTopics(this.#feature, chatId, topicIds);
|
|
2641
|
+
}
|
|
2642
|
+
deleteTopic(chatId, topicId) {
|
|
2643
|
+
return deleteTopic(this.#feature, chatId, topicId);
|
|
2644
|
+
}
|
|
2645
|
+
validateThread(chatId, threadId, options) {
|
|
2646
|
+
return validateThread(this.#feature, chatId, threadId, options);
|
|
2647
|
+
}
|
|
2648
|
+
topic(reference, topicId) {
|
|
2649
|
+
return topic(this.#feature, reference, topicId);
|
|
2650
|
+
}
|
|
2651
|
+
topics(reference, window) {
|
|
2652
|
+
return topics(this.#feature, reference, window);
|
|
2653
|
+
}
|
|
2654
|
+
lookup(phone) {
|
|
2655
|
+
return lookup(this.#feature, phone);
|
|
2656
|
+
}
|
|
2657
|
+
addressBook() {
|
|
2658
|
+
return addressBook(this.#feature);
|
|
2659
|
+
}
|
|
2660
|
+
sessions() {
|
|
2661
|
+
return sessions(this.#feature);
|
|
2662
|
+
}
|
|
2663
|
+
members(reference, window) {
|
|
2664
|
+
return members(this.#feature, reference, window);
|
|
2665
|
+
}
|
|
2666
|
+
chatEvents(reference, window) {
|
|
2667
|
+
return chatEvents(this.#feature, reference, window);
|
|
2668
|
+
}
|
|
2669
|
+
admins(reference) {
|
|
2670
|
+
return admins(this.#feature, reference);
|
|
2671
|
+
}
|
|
2672
|
+
people(references) {
|
|
2673
|
+
return people(this.#feature, references);
|
|
2674
|
+
}
|
|
2675
|
+
createGroup(title, people2, options) {
|
|
2676
|
+
return createGroup(this.#feature, title, people2, options);
|
|
2677
|
+
}
|
|
2678
|
+
join(link) {
|
|
2679
|
+
return join(this.#feature, link);
|
|
2680
|
+
}
|
|
2681
|
+
leave(reference) {
|
|
2682
|
+
return leave(this.#feature, reference);
|
|
2683
|
+
}
|
|
2684
|
+
group(reference) {
|
|
2685
|
+
return group(this.#feature, reference);
|
|
2686
|
+
}
|
|
2687
|
+
updateGroup(chatId, change) {
|
|
2688
|
+
return updateGroup(this.#feature, chatId, change);
|
|
2689
|
+
}
|
|
2690
|
+
resetInviteLink(chatId) {
|
|
2691
|
+
return resetInviteLink(this.#feature, chatId);
|
|
2692
|
+
}
|
|
2693
|
+
createInviteLink(chatId, options) {
|
|
2694
|
+
return createInviteLink(this.#feature, chatId, options);
|
|
2695
|
+
}
|
|
2696
|
+
joinRequests(chatId, options) {
|
|
2697
|
+
return joinRequests(this.#feature, chatId, options);
|
|
2698
|
+
}
|
|
2699
|
+
answerAllJoinRequests(chatId, accept, link) {
|
|
2700
|
+
return answerAllJoinRequests(this.#feature, chatId, accept, link);
|
|
2701
|
+
}
|
|
2702
|
+
inviteLinks(chatId, options) {
|
|
2703
|
+
return inviteLinks(this.#feature, chatId, options);
|
|
2704
|
+
}
|
|
2705
|
+
revokeInviteLink(chatId, link) {
|
|
2706
|
+
return revokeInviteLink(this.#feature, chatId, link);
|
|
2707
|
+
}
|
|
2708
|
+
updateInviteLink(chatId, link, change) {
|
|
2709
|
+
return updateInviteLink(this.#feature, chatId, link, change);
|
|
2710
|
+
}
|
|
2711
|
+
answerJoinRequest(chatId, personId, accept) {
|
|
2712
|
+
return answerJoinRequest(this.#feature, chatId, personId, accept);
|
|
2713
|
+
}
|
|
2714
|
+
addMembers(chatId, people2, options) {
|
|
2715
|
+
return addMembers(this.#feature, chatId, people2, options);
|
|
2716
|
+
}
|
|
2717
|
+
removeMembers(chatId, people2) {
|
|
2718
|
+
return removeMembers(this.#feature, chatId, people2);
|
|
2719
|
+
}
|
|
2720
|
+
addAdmin(chatId, person, rights) {
|
|
2721
|
+
return addAdmin(this.#feature, chatId, person, rights);
|
|
2722
|
+
}
|
|
2723
|
+
removeAdmin(chatId, person) {
|
|
2724
|
+
return removeAdmin(this.#feature, chatId, person);
|
|
2725
|
+
}
|
|
2726
|
+
folders() {
|
|
2727
|
+
return folders(this.#feature);
|
|
2728
|
+
}
|
|
2729
|
+
createFolder(title, chatIds, rules) {
|
|
2730
|
+
return createFolder(this.#feature, title, chatIds, rules);
|
|
2731
|
+
}
|
|
2732
|
+
updateFolder(folderId, change) {
|
|
2733
|
+
return updateFolder(this.#feature, folderId, change);
|
|
2734
|
+
}
|
|
2735
|
+
deleteFolder(folderId) {
|
|
2736
|
+
return deleteFolder(this.#feature, folderId);
|
|
2737
|
+
}
|
|
2738
|
+
orderFolders(folderIds) {
|
|
2739
|
+
return orderFolders(this.#feature, folderIds);
|
|
2740
|
+
}
|
|
2741
|
+
joinFolder(link) {
|
|
2742
|
+
return joinFolder(this.#feature, link);
|
|
2743
|
+
}
|
|
2744
|
+
addContact(personId) {
|
|
2745
|
+
return addContact(this.#feature, personId);
|
|
2746
|
+
}
|
|
2747
|
+
removeContact(personId) {
|
|
2748
|
+
return removeContact(this.#feature, personId);
|
|
2749
|
+
}
|
|
2750
|
+
block(personId) {
|
|
2751
|
+
return block(this.#feature, personId);
|
|
2752
|
+
}
|
|
2753
|
+
unblock(personId) {
|
|
2754
|
+
return unblock(this.#feature, personId);
|
|
2755
|
+
}
|
|
2756
|
+
renameContact(personId, firstName, lastName) {
|
|
2757
|
+
return renameContact(this.#feature, personId, firstName, lastName);
|
|
2758
|
+
}
|
|
2759
|
+
importContacts(entries) {
|
|
2760
|
+
return importContacts(this.#feature, entries);
|
|
2761
|
+
}
|
|
2762
|
+
mute = /* @__PURE__ */ __name((chatId, until) => mute(this.#feature, chatId, until), "mute");
|
|
2763
|
+
archiveChat = /* @__PURE__ */ __name((chatId, archived) => archiveChat(this.#feature, chatId, archived), "archiveChat");
|
|
2764
|
+
pinChat = /* @__PURE__ */ __name((chatId, pinned) => pinChat(this.#feature, chatId, pinned), "pinChat");
|
|
2765
|
+
markChatUnread = /* @__PURE__ */ __name((chatId) => markChatUnread(this.#feature, chatId), "markChatUnread");
|
|
2766
|
+
endOtherSessions() {
|
|
2767
|
+
return endOtherSessions(this.#feature);
|
|
2768
|
+
}
|
|
2769
|
+
async #call(work) {
|
|
2770
|
+
try {
|
|
2771
|
+
return await (this.#proxyFailed ? Promise.race([work(), this.#proxyFailed]) : work());
|
|
2772
|
+
} catch (error) {
|
|
2773
|
+
throw toCliError(error, this.#feature.checks, this.#feature.login);
|
|
2774
|
+
}
|
|
2775
|
+
}
|
|
2776
|
+
};
|
|
2777
|
+
var FLOOD_SLEEP = {
|
|
2778
|
+
oneShot: { maxWait: 1e4, maxRetries: 2 },
|
|
2779
|
+
listening: { maxWait: 12e4, maxRetries: 3 }
|
|
2780
|
+
};
|
|
2781
|
+
export {
|
|
2782
|
+
ADMIN_RIGHTS,
|
|
2783
|
+
FLOOD_SLEEP,
|
|
2784
|
+
GROUP_SETTINGS,
|
|
2785
|
+
HEARTBEAT_TICKS,
|
|
2786
|
+
LOOP_CHECK_MS,
|
|
2787
|
+
STATE_WAIT_MS,
|
|
2788
|
+
TRANSCRIBE_POLL_MS,
|
|
2789
|
+
TelegramAdapter
|
|
2790
|
+
};
|