@wirecat/tg-cli 0.100.0 → 0.102.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 +3 -3
- package/dist/bin/tg.js +1 -1
- package/dist/bot/transport.d.ts.map +1 -1
- package/dist/bot/transport.js +14 -17
- package/dist/bot/transport.js.map +1 -1
- package/dist/bundle/{adapter-2LVPMFKF.js → adapter-M2HRSFFL.js} +95 -33
- package/dist/bundle/{all-profiles-BLTK2AAB.js → all-profiles-GOD2QNTK.js} +42 -12
- package/dist/bundle/{anthropic-RJE4XEOO.js → anthropic-LKU7RWMA.js} +5 -5
- package/dist/bundle/{bot-api-4XM3NVWG.js → bot-api-X3MPFVPL.js} +49 -53
- package/dist/bundle/{bot-history-WVM5GEQN.js → bot-history-OUMVVG22.js} +15 -15
- package/dist/bundle/{bun-UZXO2LRQ.js → bun-LIZ6MKFS.js} +2 -2
- package/dist/bundle/{bun-sqlite-GJLGSQIT.js → bun-sqlite-2IFQYQ44.js} +4 -4
- package/dist/bundle/chunk-264DAFJV.js +161 -0
- package/dist/bundle/{chunk-ASDZHG5I.js → chunk-2SUTCDGO.js} +2 -2
- package/dist/bundle/{chunk-2IM4M7Q2.js → chunk-2XBSVRT2.js} +1 -1
- package/dist/bundle/{chunk-Q26JMPBP.js → chunk-334UBWOB.js} +11 -11
- package/dist/bundle/{chunk-MQNFEVAH.js → chunk-4PDEQL6T.js} +2 -2
- package/dist/bundle/chunk-4QB4WDLT.js +922 -0
- package/dist/bundle/{chunk-66E5QDLH.js → chunk-5D6OJREA.js} +1 -1
- package/dist/bundle/{chunk-RDQMV6EU.js → chunk-5DFGJPT6.js} +4 -4
- package/dist/bundle/{chunk-GTURDJJD.js → chunk-5KU4UQBM.js} +1 -1
- package/dist/bundle/{chunk-JSKT5UZX.js → chunk-5VSR5ENL.js} +8 -8
- package/dist/bundle/{chunk-DN4QUTWU.js → chunk-AUOXTGTU.js} +1 -1
- package/dist/bundle/{chunk-X4Y2ROJI.js → chunk-BBC546ZA.js} +91 -2
- package/dist/bundle/{chunk-RER6DAHP.js → chunk-BQYTIYGB.js} +171 -148
- package/dist/bundle/{chunk-3S5CL55R.js → chunk-CLWYQNSC.js} +6 -6
- package/dist/bundle/{chunk-I6WZJVRT.js → chunk-CRZPQQHE.js} +59 -46
- package/dist/bundle/chunk-DE7LFMY2.js +440 -0
- package/dist/bundle/{chunk-GYEOQS2D.js → chunk-DG62L57H.js} +17 -17
- package/dist/bundle/{chunk-QU2FJMFB.js → chunk-ENE5CSVY.js} +2903 -1490
- package/dist/bundle/{chunk-P26LWFNZ.js → chunk-ERQDBK5I.js} +1 -1
- package/dist/bundle/{chunk-UD4DOZCN.js → chunk-F2TG3BA2.js} +6 -6
- package/dist/bundle/{chunk-4U7QOFDA.js → chunk-FBWOQMPE.js} +1698 -816
- package/dist/bundle/{chunk-JFJVS5JC.js → chunk-FOUE7XLK.js} +2 -2
- package/dist/bundle/{chunk-3QDPV34J.js → chunk-GSKFAE3I.js} +1297 -518
- package/dist/bundle/{chunk-BAIZAZ6Q.js → chunk-HLAZ65AW.js} +2 -2
- package/dist/bundle/{chunk-LI7TXFLS.js → chunk-JFSVXMN6.js} +3 -3
- package/dist/bundle/{chunk-6VEOR6GD.js → chunk-M5UH5CF3.js} +6 -8
- package/dist/bundle/{chunk-HXTTDIL7.js → chunk-MGG7JSNO.js} +3 -3
- package/dist/bundle/{chunk-6YLT4YVJ.js → chunk-OCWARAFE.js} +2 -2
- package/dist/bundle/{chunk-WE3LBRMB.js → chunk-OEJ5DMCX.js} +7 -7
- package/dist/bundle/{chunk-SGJYU3SB.js → chunk-OHBHHBYL.js} +3 -3
- package/dist/bundle/{chunk-2MXQ2EUN.js → chunk-PSH7K6TL.js} +617 -57
- package/dist/bundle/{chunk-H3X5LS6U.js → chunk-PYTOIDSM.js} +4 -4
- package/dist/bundle/{chunk-ATZ44Z77.js → chunk-Q2NYEX4A.js} +150 -52
- package/dist/bundle/{chunk-KE6L2UEG.js → chunk-QEPZUFPL.js} +70 -61
- package/dist/bundle/{chunk-CV5ASHTW.js → chunk-QL7CQ6VZ.js} +255 -80
- package/dist/bundle/{chunk-THVNP6S6.js → chunk-SRU3OF4R.js} +2 -2
- package/dist/bundle/{chunk-OOOV3JBZ.js → chunk-TV5DGHBT.js} +953 -677
- package/dist/bundle/{chunk-A7OBVRJV.js → chunk-TXBUDJ3P.js} +3 -3
- package/dist/bundle/{chunk-OW3COBN5.js → chunk-U4RRZUNP.js} +9 -9
- package/dist/bundle/{chunk-WKOY3POD.js → chunk-UK3GAN7Q.js} +7 -7
- package/dist/bundle/{chunk-BL36RR34.js → chunk-UR6ASUSG.js} +10 -7
- package/dist/bundle/{chunk-4VBDVZNE.js → chunk-V52SBQYF.js} +242 -19
- package/dist/bundle/{chunk-4YCLWWZ3.js → chunk-VUJ34PEQ.js} +11 -11
- package/dist/bundle/{chunk-2XUGPE5W.js → chunk-W5EB4JLV.js} +3 -3
- package/dist/bundle/{chunk-3KHKYYCR.js → chunk-WMOEOVWZ.js} +1 -0
- package/dist/bundle/{chunk-UMLPXNJI.js → chunk-WVEHUKCZ.js} +1 -1
- package/dist/bundle/{chunk-SYPL4PHV.js → chunk-XXTJUZMB.js} +1 -1
- package/dist/bundle/{chunk-SMJTL5U7.js → chunk-Y4XSWI22.js} +6 -4
- package/dist/bundle/{chunk-HKT5EOT5.js → chunk-YHB57PFN.js} +1 -1
- package/dist/bundle/{chunk-BZANDKWT.js → chunk-ZJVZXJOG.js} +2 -2
- package/dist/bundle/{chunk-QY3YOOTP.js → chunk-ZRNRQFTF.js} +2 -2
- package/dist/bundle/command-contract-A6VZN3ZR.js +31 -0
- package/dist/bundle/{echarts-YHSYUWLY.js → echarts-27W2CIBD.js} +2 -2
- package/dist/bundle/{embed-3HGI2XIW.js → embed-FGJ273X2.js} +4 -4
- package/dist/bundle/{embedder-2CJMZETJ.js → embedder-7ELL3CQ3.js} +7 -7
- package/dist/bundle/{entry-UVE53OV3.js → entry-SEE5YWIX.js} +5 -5
- package/dist/bundle/{first-run-6GYC2QS3.js → first-run-BD7FEC3W.js} +9 -9
- package/dist/bundle/first-screen-ASZV6LSA.js +29 -0
- package/dist/bundle/{identity-HEV5E57G.js → identity-QR4F42T6.js} +3 -3
- package/dist/bundle/{instructions-5UVAXSQV.js → instructions-L74K64PV.js} +1 -1
- package/dist/bundle/{mcp-NWXBVNUA.js → mcp-4Y37G2UY.js} +2 -2
- package/dist/bundle/{node-YHYEGYVE.js → node-RSL3HANO.js} +2 -2
- package/dist/bundle/{node-sqlite-CQ33A3R2.js → node-sqlite-7R3PYQGJ.js} +4 -4
- package/dist/bundle/{oauth-OB3JFAD7.js → oauth-4ESGXF6U.js} +7 -7
- package/dist/bundle/{open-JHGZIXU2.js → open-DFYEUGTA.js} +3 -3
- package/dist/bundle/{process-PSKS3N5B.js → process-RMV3AKLB.js} +1 -1
- package/dist/bundle/{program-RPYVPNRX.js → program-PIUYQHBF.js} +62 -67
- package/dist/bundle/{prompt-7BXUMJGG.js → prompt-H7GYQQLL.js} +4 -4
- package/dist/bundle/{proxy-transport-3EEMW2HW.js → proxy-transport-G4MA6BGU.js} +4 -4
- package/dist/bundle/{recognize-YMZPL47R.js → recognize-3GMOLZF4.js} +5 -5
- package/dist/bundle/{remote-LQ3Q22NG.js → remote-IRWTCI2B.js} +5 -5
- package/dist/bundle/{rerank-SM7IYVXJ.js → rerank-W3OSXXBN.js} +5 -5
- package/dist/bundle/{serve-GHUEP5H5.js → serve-ZCPO44NO.js} +24 -9
- package/dist/bundle/{server-A45HVXQY.js → server-FXU4QFRB.js} +42 -39
- package/dist/bundle/{server-K2BQPPHN.js → server-YWL4HDOP.js} +77 -68
- package/dist/bundle/{state-WIOL52GZ.js → state-MJPTDIB5.js} +9 -5
- package/dist/bundle/{store-XE5AKUJZ.js → store-6VNQG56O.js} +10 -10
- package/dist/bundle/store-maintenance-command-62TQTMER.js +43 -0
- package/dist/bundle/tg.js +4 -4
- package/dist/commands/context.d.ts.map +1 -1
- package/dist/commands/context.js +2 -0
- package/dist/commands/context.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/telegram/sending.d.ts.map +1 -1
- package/dist/telegram/sending.js +52 -3
- package/dist/telegram/sending.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/install/windows.ps1 +1 -1
- package/package.json +3 -3
- package/skills/tg-cli/SKILL.md +4 -4
- package/dist/bundle/chunk-3N6LXAPE.js +0 -724
- package/dist/bundle/chunk-DVOUKGFK.js +0 -1950
- package/dist/bundle/chunk-MUEXF4ME.js +0 -582
- package/dist/bundle/chunk-U7LXA4SO.js +0 -1007
- package/dist/bundle/chunk-V4JSVH4M.js +0 -190
- package/dist/bundle/chunk-YG7PNCSW.js +0 -230
- package/dist/bundle/chunk-Z2FHEIXN.js +0 -63
- package/dist/bundle/command-contract-AIVKJYIR.js +0 -31
- package/dist/bundle/first-screen-HRRLVLOG.js +0 -29
- package/dist/bundle/store-maintenance-command-YS5E7VUN.js +0 -46
- /package/dist/bundle/{chunk-3MVHRZWR.js → chunk-2SJOUK6J.js} +0 -0
|
@@ -0,0 +1,922 @@
|
|
|
1
|
+
import { createRequire as __tgRequire } from "node:module";
|
|
2
|
+
const require = __tgRequire(import.meta.url);
|
|
3
|
+
import {
|
|
4
|
+
ADMIN_RIGHTS,
|
|
5
|
+
BotTokenStore,
|
|
6
|
+
GROUP_SETTINGS,
|
|
7
|
+
apiJson,
|
|
8
|
+
apiPlainJson,
|
|
9
|
+
botCopy,
|
|
10
|
+
checkWords,
|
|
11
|
+
formatMarkdown,
|
|
12
|
+
parseApiJson,
|
|
13
|
+
privateFiles,
|
|
14
|
+
providerRequest,
|
|
15
|
+
withSqliteSidecars
|
|
16
|
+
} from "./chunk-ENE5CSVY.js";
|
|
17
|
+
import {
|
|
18
|
+
parseProxy,
|
|
19
|
+
proxyAddress,
|
|
20
|
+
proxyError,
|
|
21
|
+
proxyLabel,
|
|
22
|
+
proxySetting
|
|
23
|
+
} from "./chunk-2XBSVRT2.js";
|
|
24
|
+
import {
|
|
25
|
+
messengerContext
|
|
26
|
+
} from "./chunk-PSH7K6TL.js";
|
|
27
|
+
import {
|
|
28
|
+
uploadBlob
|
|
29
|
+
} from "./chunk-FBWOQMPE.js";
|
|
30
|
+
import {
|
|
31
|
+
asFirstWord,
|
|
32
|
+
currentAttempt,
|
|
33
|
+
environmentOf,
|
|
34
|
+
fromFile,
|
|
35
|
+
settingsFor
|
|
36
|
+
} from "./chunk-GSKFAE3I.js";
|
|
37
|
+
import {
|
|
38
|
+
TG
|
|
39
|
+
} from "./chunk-FOUE7XLK.js";
|
|
40
|
+
import {
|
|
41
|
+
Credentials,
|
|
42
|
+
pathsAreOverridden,
|
|
43
|
+
resolvePaths
|
|
44
|
+
} from "./chunk-DG62L57H.js";
|
|
45
|
+
import {
|
|
46
|
+
CliError,
|
|
47
|
+
isCliError,
|
|
48
|
+
optional
|
|
49
|
+
} from "./chunk-OEJ5DMCX.js";
|
|
50
|
+
import {
|
|
51
|
+
importFrom
|
|
52
|
+
} from "./chunk-BJG6JA5U.js";
|
|
53
|
+
import {
|
|
54
|
+
__name
|
|
55
|
+
} from "./chunk-AFV74GK3.js";
|
|
56
|
+
|
|
57
|
+
// dist/app.js
|
|
58
|
+
var CONFIG = settingsFor(TG, { profile: { proxy: optional(proxySetting) } });
|
|
59
|
+
var { resolveSettings, configuredProfiles, changeSetting } = CONFIG;
|
|
60
|
+
|
|
61
|
+
// dist/commands/context.js
|
|
62
|
+
import { existsSync } from "node:fs";
|
|
63
|
+
import { dirname } from "node:path";
|
|
64
|
+
|
|
65
|
+
// dist/paths.js
|
|
66
|
+
import { join } from "node:path";
|
|
67
|
+
var APP = TG.appName;
|
|
68
|
+
var pathsFor = /* @__PURE__ */ __name((env = process.env) => resolvePaths({ appName: TG.appName, prefix: TG.envPrefix, env }), "pathsFor");
|
|
69
|
+
var isolated = /* @__PURE__ */ __name((env = process.env) => pathsAreOverridden({ appName: TG.appName, prefix: TG.envPrefix, env }), "isolated");
|
|
70
|
+
var sessionFile = /* @__PURE__ */ __name((profile, env = process.env) => join(pathsFor(env).state, "sessions", `${profile}.session`), "sessionFile");
|
|
71
|
+
var botSessionFile = /* @__PURE__ */ __name((profile, botId, env = process.env) => join(pathsFor(env).state, "bots", profile, `mtproto-${botId}.session`), "botSessionFile");
|
|
72
|
+
|
|
73
|
+
// dist/telegram/credentials.js
|
|
74
|
+
var parseApiId = /* @__PURE__ */ __name((typed) => {
|
|
75
|
+
const trimmed = typed.trim();
|
|
76
|
+
if (!/^\d{1,12}$/.test(trimmed))
|
|
77
|
+
throw new CliError("validation_error", "api_id is a number from my.telegram.org/apps");
|
|
78
|
+
return Number(trimmed);
|
|
79
|
+
}, "parseApiId");
|
|
80
|
+
var parseApiHash = /* @__PURE__ */ __name((typed) => {
|
|
81
|
+
const trimmed = typed.trim();
|
|
82
|
+
if (trimmed === "")
|
|
83
|
+
throw new CliError("validation_error", "api_hash is empty");
|
|
84
|
+
return trimmed;
|
|
85
|
+
}, "parseApiHash");
|
|
86
|
+
var apiCredentials = /* @__PURE__ */ __name(({ profile, env = process.env, keyring, warn }) => {
|
|
87
|
+
const store = new Credentials({
|
|
88
|
+
configDir: pathsFor(env).config,
|
|
89
|
+
service: APP,
|
|
90
|
+
isolated: isolated(env),
|
|
91
|
+
env,
|
|
92
|
+
...keyring ? { keyring } : {},
|
|
93
|
+
...warn ? { warn } : {}
|
|
94
|
+
});
|
|
95
|
+
const account = `${profile}:api`;
|
|
96
|
+
return {
|
|
97
|
+
read: /* @__PURE__ */ __name(() => {
|
|
98
|
+
if (env.TG_API_ID && env.TG_API_HASH) {
|
|
99
|
+
return { id: parseApiId(env.TG_API_ID), hash: parseApiHash(env.TG_API_HASH) };
|
|
100
|
+
}
|
|
101
|
+
const stored = store.read(account);
|
|
102
|
+
if (!stored)
|
|
103
|
+
return void 0;
|
|
104
|
+
const { id, hash } = JSON.parse(stored.secret);
|
|
105
|
+
return { id, hash };
|
|
106
|
+
}, "read"),
|
|
107
|
+
/** Where they are read from — never the values. */
|
|
108
|
+
source: /* @__PURE__ */ __name(() => {
|
|
109
|
+
if (env.TG_API_ID && env.TG_API_HASH)
|
|
110
|
+
return "environment";
|
|
111
|
+
const stored = store.read(account);
|
|
112
|
+
return stored ? stored.source === "keyring" ? "keyring" : "file" : void 0;
|
|
113
|
+
}, "source"),
|
|
114
|
+
write: /* @__PURE__ */ __name((credentials) => {
|
|
115
|
+
store.write(account, JSON.stringify(credentials));
|
|
116
|
+
}, "write")
|
|
117
|
+
};
|
|
118
|
+
}, "apiCredentials");
|
|
119
|
+
|
|
120
|
+
// dist/telegram/proxy.js
|
|
121
|
+
var PROXY_ENV = "TG_PROXY";
|
|
122
|
+
var proxySecrets = /* @__PURE__ */ __name(({ env = process.env, keyring }) => {
|
|
123
|
+
const store = new Credentials({
|
|
124
|
+
configDir: pathsFor(env).config,
|
|
125
|
+
service: APP,
|
|
126
|
+
isolated: isolated(env),
|
|
127
|
+
env,
|
|
128
|
+
...keyring ? { keyring } : {}
|
|
129
|
+
});
|
|
130
|
+
const account = /* @__PURE__ */ __name((profile) => profile === void 0 ? "proxy:defaults" : `proxy:profile:${profile}`, "account");
|
|
131
|
+
return {
|
|
132
|
+
read: /* @__PURE__ */ __name((profile) => store.read(account(profile))?.secret, "read"),
|
|
133
|
+
write: /* @__PURE__ */ __name((profile, secret) => store.write(account(profile), secret), "write"),
|
|
134
|
+
remove: /* @__PURE__ */ __name((profile) => store.remove(account(profile)), "remove")
|
|
135
|
+
};
|
|
136
|
+
}, "proxySecrets");
|
|
137
|
+
var resolveProxy = /* @__PURE__ */ __name((settings, { env = process.env, keyring, checks }) => {
|
|
138
|
+
const given = env[PROXY_ENV]?.trim();
|
|
139
|
+
if (given)
|
|
140
|
+
return { proxy: parseProxy(given, PROXY_ENV), from: PROXY_ENV };
|
|
141
|
+
const { value, from } = fromFile(settings, "proxy", void 0);
|
|
142
|
+
if (value === void 0)
|
|
143
|
+
return void 0;
|
|
144
|
+
const proxy = parseProxy(value, "the proxy setting");
|
|
145
|
+
const secrets = proxySecrets({ env, ...keyring ? { keyring } : {} });
|
|
146
|
+
const secret = secrets.read(settings.profile) ?? (from === "config defaults" ? secrets.read(void 0) : void 0);
|
|
147
|
+
if (proxy.kind === "mtproxy" && !secret)
|
|
148
|
+
throw new CliError("configuration_error", `no secret is stored for the MTProxy ${proxyLabel(proxy)} \u2014 run ${checks("config.set", "proxy -")} again`);
|
|
149
|
+
return { proxy: secret ? { ...proxy, secret } : proxy, from };
|
|
150
|
+
}, "resolveProxy");
|
|
151
|
+
|
|
152
|
+
// dist/commands/context.js
|
|
153
|
+
var sessionFiles = /* @__PURE__ */ __name((sessionPath) => privateFiles({ files: withSqliteSidecars(sessionPath), dirs: [dirname(sessionPath)] }), "sessionFiles");
|
|
154
|
+
var telegramOf = /* @__PURE__ */ __name((command, base) => {
|
|
155
|
+
const environment = environmentOf(command);
|
|
156
|
+
const { profile } = base.settings;
|
|
157
|
+
const sessionPath = sessionFile(profile, base.env);
|
|
158
|
+
const credentials = apiCredentials({
|
|
159
|
+
profile,
|
|
160
|
+
env: base.env,
|
|
161
|
+
warn: base.renderer.warn,
|
|
162
|
+
...environment.keyring ? { keyring: environment.keyring } : {}
|
|
163
|
+
});
|
|
164
|
+
const words = checkWords("tg", profile);
|
|
165
|
+
const proxy = /* @__PURE__ */ __name(() => resolveProxy(base.settings, {
|
|
166
|
+
env: base.env,
|
|
167
|
+
checks: words,
|
|
168
|
+
...environment.keyring ? { keyring: environment.keyring } : {}
|
|
169
|
+
}), "proxy");
|
|
170
|
+
const login = `\`tg ${asFirstWord(profile)}session start\``;
|
|
171
|
+
const setup = `\`tg ${asFirstWord(profile)}setup\``;
|
|
172
|
+
const desktop = "WireCat Desktop (Tools \u2192 Telegram \u2192 Manage)";
|
|
173
|
+
const open = /* @__PURE__ */ __name(async (given, connecting = {}) => {
|
|
174
|
+
const resolved = given ?? credentials.read();
|
|
175
|
+
if (!resolved) {
|
|
176
|
+
const loggedIn = existsSync(sessionPath);
|
|
177
|
+
const unreachable = loggedIn && command.name() === "serve" ? "provider_unavailable" : "authentication_error";
|
|
178
|
+
throw new CliError(unreachable, loggedIn ? `no Telegram app credentials found for profile "${profile}", although it has logged in on this machine \u2014 the keyring is probably out of reach (cron, ssh, an MCP client that trims the environment: set XDG_RUNTIME_DIR); \`tg ${asFirstWord(profile)}doctor\` shows it. Log in again only if they were removed` : `no Telegram app credentials for profile "${profile}" \u2014 run ${setup} in a local terminal first, or sign in from ${desktop}; agents: read \`tg skill show\``);
|
|
179
|
+
}
|
|
180
|
+
const options = { credentials: resolved, sessionPath, ...connecting };
|
|
181
|
+
return environment.adapter ? await environment.adapter(options) : await (await import("./adapter-M2HRSFFL.js")).TelegramAdapter.open({
|
|
182
|
+
...options,
|
|
183
|
+
...proxyOption(proxy()),
|
|
184
|
+
diagnostic: /* @__PURE__ */ __name((line) => base.streams.diagnostic(line), "diagnostic"),
|
|
185
|
+
note: /* @__PURE__ */ __name((line) => base.renderer.warn(line), "note"),
|
|
186
|
+
verbose: base.settings.trace,
|
|
187
|
+
login,
|
|
188
|
+
checks: words
|
|
189
|
+
});
|
|
190
|
+
}, "open");
|
|
191
|
+
const connect = /* @__PURE__ */ __name(async (options = {}) => {
|
|
192
|
+
if (!environment.adapter && !existsSync(sessionPath)) {
|
|
193
|
+
throw new CliError("authentication_error", `no session for profile "${profile}" \u2014 run ${setup} in a local terminal, or sign in from ${desktop}`);
|
|
194
|
+
}
|
|
195
|
+
return open(void 0, options);
|
|
196
|
+
}, "connect");
|
|
197
|
+
return { environment, sessionPath, credentials, open, connect, proxy };
|
|
198
|
+
}, "telegramOf");
|
|
199
|
+
var SKILL = new URL("../../skills/tg-cli/SKILL.md", new URL("../commands/context.js", import.meta.url).href);
|
|
200
|
+
var OWN_NUMBERING = ["channel", "supergroup", "gigagroup", "monoforum"];
|
|
201
|
+
var TELEGRAM = {
|
|
202
|
+
app: TG,
|
|
203
|
+
provider: "telegram",
|
|
204
|
+
counterFields: ["views", "reactions", "comments"],
|
|
205
|
+
name: "Telegram",
|
|
206
|
+
resolveSettings,
|
|
207
|
+
connect: /* @__PURE__ */ __name((command, base, options) => telegramOf(command, base).connect(options), "connect"),
|
|
208
|
+
// Bots sign in on a personal profile and keep their own session, so a tg profile is never a bot alone.
|
|
209
|
+
profileState: /* @__PURE__ */ __name((profile, env) => existsSync(sessionFile(profile, env)) ? "signed-in" : "signed-out", "profileState"),
|
|
210
|
+
chatArgument: "a chat: its title or part of it, its id, @username, or `me` for Saved Messages",
|
|
211
|
+
groupSettings: GROUP_SETTINGS,
|
|
212
|
+
mediaOptions: ["spoiler", "captionAbove", "fileName"],
|
|
213
|
+
personalBots: true,
|
|
214
|
+
pollQuiz: true,
|
|
215
|
+
pollVoters: true,
|
|
216
|
+
topicShow: true,
|
|
217
|
+
forwardTopic: true,
|
|
218
|
+
// mtcute's InputMedia.poll documents 5–600 seconds.
|
|
219
|
+
pollCloseSeconds: [5, 600],
|
|
220
|
+
inviteLinkUpdate: true,
|
|
221
|
+
html: true,
|
|
222
|
+
drafts: true,
|
|
223
|
+
folderRules: true,
|
|
224
|
+
chatMute: true,
|
|
225
|
+
chatArchive: true,
|
|
226
|
+
chatPin: true,
|
|
227
|
+
chatMarkUnread: true,
|
|
228
|
+
addsWithHistory: false,
|
|
229
|
+
officialStats: true,
|
|
230
|
+
serverSearch: true,
|
|
231
|
+
knowsAccountAge: false,
|
|
232
|
+
adminRights: ADMIN_RIGHTS,
|
|
233
|
+
// Saved Messages is the chat with yourself, so its id is the account's.
|
|
234
|
+
savedChatId: /* @__PURE__ */ __name((account) => account.account, "savedChatId"),
|
|
235
|
+
diagnose: /* @__PURE__ */ __name(async (command, base) => {
|
|
236
|
+
const { sessionPath, credentials, proxy } = telegramOf(command, base);
|
|
237
|
+
return {
|
|
238
|
+
session: { path: sessionPath, exists: existsSync(sessionPath), files: sessionFiles(sessionPath) },
|
|
239
|
+
proxy: proxyState(proxy),
|
|
240
|
+
app_credentials: appCredentialsState(() => credentials.read(), base.env),
|
|
241
|
+
// The one failure with no other symptom: a login made without these variables is invisible with them.
|
|
242
|
+
keyring_moved_by_environment: isolated(base.env)
|
|
243
|
+
};
|
|
244
|
+
}, "diagnose"),
|
|
245
|
+
// In Telegram a one-to-one chat's id is the other person's id.
|
|
246
|
+
partnerOf: /* @__PURE__ */ __name((chat) => chat.kind === "dialog" ? chat.id : void 0, "partnerOf"),
|
|
247
|
+
// Telegram names a deletion without its chat only where ids count per account. A chat stored by
|
|
248
|
+
// its id alone has no kind yet, but `-100…` marks a channel's or a supergroup's.
|
|
249
|
+
deletedWithoutChat: /* @__PURE__ */ __name((chat) => chat.kind !== "channel" && !(chat.kind === "unknown" && chat.id.startsWith("-100")) && !OWN_NUMBERING.includes(String(chat.providerMetadata?.chatType ?? "")), "deletedWithoutChat"),
|
|
250
|
+
skill: SKILL
|
|
251
|
+
};
|
|
252
|
+
var forCommand = /* @__PURE__ */ __name((command) => {
|
|
253
|
+
const context = messengerContext(command, TELEGRAM);
|
|
254
|
+
const { sessionPath, credentials, open, proxy } = telegramOf(command, context);
|
|
255
|
+
return {
|
|
256
|
+
...context,
|
|
257
|
+
sessionPath,
|
|
258
|
+
credentials,
|
|
259
|
+
open,
|
|
260
|
+
proxy,
|
|
261
|
+
withTelegram: context.withMessenger
|
|
262
|
+
};
|
|
263
|
+
}, "forCommand");
|
|
264
|
+
var appCredentialsState = /* @__PURE__ */ __name((read, env) => {
|
|
265
|
+
try {
|
|
266
|
+
if (!read())
|
|
267
|
+
return "missing";
|
|
268
|
+
return env.TG_API_ID ? "from TG_API_ID and TG_API_HASH" : "stored";
|
|
269
|
+
} catch {
|
|
270
|
+
return "unreadable";
|
|
271
|
+
}
|
|
272
|
+
}, "appCredentialsState");
|
|
273
|
+
var proxyOption = /* @__PURE__ */ __name((through) => through ? { proxy: through.proxy } : {}, "proxyOption");
|
|
274
|
+
var proxyState = /* @__PURE__ */ __name((resolve) => {
|
|
275
|
+
try {
|
|
276
|
+
const through = resolve();
|
|
277
|
+
if (!through)
|
|
278
|
+
return null;
|
|
279
|
+
return {
|
|
280
|
+
url: proxyLabel(through.proxy),
|
|
281
|
+
from: through.from,
|
|
282
|
+
bot_api: through.proxy.kind === "mtproxy" ? "direct: an MTProxy carries only Telegram's own protocol" : "through it"
|
|
283
|
+
};
|
|
284
|
+
} catch (error) {
|
|
285
|
+
return { error: error instanceof Error ? error.message : String(error) };
|
|
286
|
+
}
|
|
287
|
+
}, "proxyState");
|
|
288
|
+
|
|
289
|
+
// dist/commands/bot.js
|
|
290
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
291
|
+
|
|
292
|
+
// dist/bot/map.js
|
|
293
|
+
var KINDS = {
|
|
294
|
+
private: "dialog",
|
|
295
|
+
group: "group",
|
|
296
|
+
supergroup: "group",
|
|
297
|
+
channel: "channel"
|
|
298
|
+
};
|
|
299
|
+
var ENTITY = { bold: "bold", italic: "italic", strike: "strikethrough", code: "code" };
|
|
300
|
+
var nameOf = /* @__PURE__ */ __name((person) => person ? [person.first_name, person.last_name].filter(Boolean).join(" ") || null : null, "nameOf");
|
|
301
|
+
var iso = /* @__PURE__ */ __name((seconds) => new Date(seconds * 1e3).toISOString(), "iso");
|
|
302
|
+
var attachmentsOf = /* @__PURE__ */ __name((message) => {
|
|
303
|
+
const files = [
|
|
304
|
+
["photo", message.photo?.at(-1)],
|
|
305
|
+
["file", message.document],
|
|
306
|
+
["voice", message.voice],
|
|
307
|
+
["video", message.video],
|
|
308
|
+
["audio", message.audio]
|
|
309
|
+
];
|
|
310
|
+
return files.flatMap(([kind, file]) => {
|
|
311
|
+
if (!file)
|
|
312
|
+
return [];
|
|
313
|
+
const attachment = { kind, providerRef: { fileId: file.file_id } };
|
|
314
|
+
if (file.file_name)
|
|
315
|
+
attachment.name = file.file_name;
|
|
316
|
+
if (file.file_size !== void 0)
|
|
317
|
+
attachment.size = file.file_size;
|
|
318
|
+
if (file.duration !== void 0)
|
|
319
|
+
attachment.duration = file.duration;
|
|
320
|
+
return [attachment];
|
|
321
|
+
});
|
|
322
|
+
}, "attachmentsOf");
|
|
323
|
+
var quoted = /* @__PURE__ */ __name((message, selfId) => ({
|
|
324
|
+
id: String(message.message_id),
|
|
325
|
+
senderId: message.from ? String(message.from.id) : null,
|
|
326
|
+
senderName: nameOf(message.from),
|
|
327
|
+
timestamp: iso(message.date),
|
|
328
|
+
text: message.text ?? message.caption ?? "",
|
|
329
|
+
attachments: attachmentsOf(message),
|
|
330
|
+
outgoing: selfId === void 0 || !message.from ? null : String(message.from.id) === selfId
|
|
331
|
+
}), "quoted");
|
|
332
|
+
var toMessage = /* @__PURE__ */ __name((message, selfId) => {
|
|
333
|
+
const mapped = {
|
|
334
|
+
id: String(message.message_id),
|
|
335
|
+
chatId: String(message.chat.id),
|
|
336
|
+
senderId: message.from ? String(message.from.id) : null,
|
|
337
|
+
senderName: nameOf(message.from),
|
|
338
|
+
timestamp: iso(message.date),
|
|
339
|
+
editedAt: message.edit_date === void 0 ? null : iso(message.edit_date),
|
|
340
|
+
text: message.text ?? message.caption ?? "",
|
|
341
|
+
outgoing: selfId === void 0 || !message.from ? null : String(message.from.id) === selfId,
|
|
342
|
+
attachments: attachmentsOf(message),
|
|
343
|
+
replyTo: message.reply_to_message ? quoted(message.reply_to_message, selfId) : null,
|
|
344
|
+
forwardedFrom: null,
|
|
345
|
+
reactions: null
|
|
346
|
+
};
|
|
347
|
+
if (message.reply_to_message)
|
|
348
|
+
mapped.replyToId = String(message.reply_to_message.message_id);
|
|
349
|
+
return mapped;
|
|
350
|
+
}, "toMessage");
|
|
351
|
+
var toChat = /* @__PURE__ */ __name((chat) => ({
|
|
352
|
+
id: String(chat.id),
|
|
353
|
+
title: chat.title ?? nameOf(chat),
|
|
354
|
+
kind: KINDS[chat.type] ?? "unknown",
|
|
355
|
+
unreadCount: null,
|
|
356
|
+
lastMessageAt: null,
|
|
357
|
+
participantsCount: null,
|
|
358
|
+
providerMetadata: { type: chat.type, username: chat.username || null }
|
|
359
|
+
}), "toChat");
|
|
360
|
+
var entitiesOf = /* @__PURE__ */ __name((markup) => markup.map((span) => {
|
|
361
|
+
const base = { offset: span.from, length: span.length };
|
|
362
|
+
switch (span.type) {
|
|
363
|
+
case "bold":
|
|
364
|
+
case "italic":
|
|
365
|
+
case "strike":
|
|
366
|
+
case "code":
|
|
367
|
+
return { type: ENTITY[span.type], ...base };
|
|
368
|
+
case "underline":
|
|
369
|
+
case "spoiler":
|
|
370
|
+
case "blockquote":
|
|
371
|
+
return { type: span.type, ...base };
|
|
372
|
+
case "pre":
|
|
373
|
+
return { type: "pre", ...base, language: span.language ?? "" };
|
|
374
|
+
case "link":
|
|
375
|
+
return { type: "text_link", ...base, url: span.url };
|
|
376
|
+
default:
|
|
377
|
+
throw new CliError("validation_error", "Telegram does not support this formatting span");
|
|
378
|
+
}
|
|
379
|
+
}), "entitiesOf");
|
|
380
|
+
var ADMIN_RIGHT_FIELDS = {
|
|
381
|
+
members: "can_restrict_members",
|
|
382
|
+
admins: "can_promote_members",
|
|
383
|
+
info: "can_change_info",
|
|
384
|
+
pin: "can_pin_messages",
|
|
385
|
+
link: "can_invite_users",
|
|
386
|
+
post: "can_post_messages",
|
|
387
|
+
edit: "can_edit_messages",
|
|
388
|
+
delete: "can_delete_messages"
|
|
389
|
+
};
|
|
390
|
+
var BOT_ADMIN_RIGHTS = Object.keys(ADMIN_RIGHT_FIELDS);
|
|
391
|
+
var PROMOTE_FIELDS = [
|
|
392
|
+
"is_anonymous",
|
|
393
|
+
"can_manage_chat",
|
|
394
|
+
"can_delete_messages",
|
|
395
|
+
"can_manage_video_chats",
|
|
396
|
+
"can_restrict_members",
|
|
397
|
+
"can_promote_members",
|
|
398
|
+
"can_change_info",
|
|
399
|
+
"can_invite_users",
|
|
400
|
+
"can_post_stories",
|
|
401
|
+
"can_edit_stories",
|
|
402
|
+
"can_delete_stories",
|
|
403
|
+
"can_post_messages",
|
|
404
|
+
"can_edit_messages",
|
|
405
|
+
"can_pin_messages",
|
|
406
|
+
"can_manage_topics",
|
|
407
|
+
"can_send_welcome_messages"
|
|
408
|
+
];
|
|
409
|
+
var toAdmin = /* @__PURE__ */ __name(({ status, user, custom_title, ...rights }) => ({
|
|
410
|
+
id: String(user.id),
|
|
411
|
+
name: nameOf(user),
|
|
412
|
+
username: user.username ?? null,
|
|
413
|
+
role: status === "creator" ? "owner" : "admin",
|
|
414
|
+
rights: BOT_ADMIN_RIGHTS.filter((right) => status === "creator" || rights[ADMIN_RIGHT_FIELDS[right]] === true),
|
|
415
|
+
title: custom_title ?? null
|
|
416
|
+
}), "toAdmin");
|
|
417
|
+
var UPDATE_TYPES = [
|
|
418
|
+
"message",
|
|
419
|
+
"edited_message",
|
|
420
|
+
"channel_post",
|
|
421
|
+
"edited_channel_post",
|
|
422
|
+
"callback_query",
|
|
423
|
+
"my_chat_member",
|
|
424
|
+
"chat_member"
|
|
425
|
+
];
|
|
426
|
+
var inChat = /* @__PURE__ */ __name(({ status, is_member }) => status === "creator" || status === "administrator" || status === "member" || status === "restricted" && is_member === true, "inChat");
|
|
427
|
+
var personOf = /* @__PURE__ */ __name((user) => ({ id: String(user.id), name: nameOf(user), username: user.username ?? null }), "personOf");
|
|
428
|
+
var kindOf = /* @__PURE__ */ __name((update) => Object.keys(update).find((key) => key !== "update_id") ?? "unknown", "kindOf");
|
|
429
|
+
var toEvent = /* @__PURE__ */ __name((update, selfId) => ({
|
|
430
|
+
...decoded(update, selfId),
|
|
431
|
+
update: { id: String(update.update_id), kind: kindOf(update) }
|
|
432
|
+
}), "toEvent");
|
|
433
|
+
var decoded = /* @__PURE__ */ __name((update, selfId) => {
|
|
434
|
+
const created = update.message ?? update.channel_post;
|
|
435
|
+
if (created)
|
|
436
|
+
return { event: "message", message: { ...toMessage(created, selfId), chatTitle: null } };
|
|
437
|
+
const edited = update.edited_message ?? update.edited_channel_post;
|
|
438
|
+
if (edited)
|
|
439
|
+
return { event: "edit", message: { ...toMessage(edited, selfId), chatTitle: null } };
|
|
440
|
+
const press = update.callback_query;
|
|
441
|
+
if (press) {
|
|
442
|
+
return {
|
|
443
|
+
event: "callback",
|
|
444
|
+
callbackId: press.id,
|
|
445
|
+
chatId: press.message ? String(press.message.chat.id) : null,
|
|
446
|
+
messageId: press.message ? String(press.message.message_id) : null,
|
|
447
|
+
from: personOf(press.from),
|
|
448
|
+
data: press.data ?? ""
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
const change = update.chat_member;
|
|
452
|
+
if (change) {
|
|
453
|
+
const was = inChat(change.old_chat_member);
|
|
454
|
+
const is = inChat(change.new_chat_member);
|
|
455
|
+
const person = change.new_chat_member.user;
|
|
456
|
+
const self = change.from.id === person.id;
|
|
457
|
+
if (was !== is) {
|
|
458
|
+
return {
|
|
459
|
+
event: is ? self ? "joined" : "added" : self ? "left" : "removed",
|
|
460
|
+
chatId: String(change.chat.id),
|
|
461
|
+
person: personOf(person),
|
|
462
|
+
at: iso(change.date)
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
const kind = kindOf(update);
|
|
467
|
+
const chat = update[kind]?.chat;
|
|
468
|
+
return { event: "other", type: kind, chatId: chat ? String(chat.id) : null };
|
|
469
|
+
}, "decoded");
|
|
470
|
+
|
|
471
|
+
// dist/bot/adapter.js
|
|
472
|
+
var chatIdOf = /* @__PURE__ */ __name((chat) => chat.startsWith("user:") ? chat.slice("user:".length) : chat, "chatIdOf");
|
|
473
|
+
var halfDone = /* @__PURE__ */ __name((done, error) => {
|
|
474
|
+
if (!isCliError(error))
|
|
475
|
+
throw error;
|
|
476
|
+
throw new CliError(error.code, `${done}, but ${error.message}`, error.details);
|
|
477
|
+
}, "halfDone");
|
|
478
|
+
var DELETE_BATCH = 100;
|
|
479
|
+
var ACTIONS = {
|
|
480
|
+
typing: "typing",
|
|
481
|
+
photo: "upload_photo",
|
|
482
|
+
video: "upload_video",
|
|
483
|
+
voice: "upload_voice",
|
|
484
|
+
file: "upload_document"
|
|
485
|
+
};
|
|
486
|
+
var formatting = /* @__PURE__ */ __name((markup, html, field) => html ? { parse_mode: "HTML" } : markup && markup.length > 0 ? { [field]: entitiesOf(markup) } : {}, "formatting");
|
|
487
|
+
var telegramBotAdapter = /* @__PURE__ */ __name((transport) => {
|
|
488
|
+
let self;
|
|
489
|
+
const me = /* @__PURE__ */ __name(async () => {
|
|
490
|
+
const bot = await transport.call("getMe");
|
|
491
|
+
self = String(bot.id);
|
|
492
|
+
return {
|
|
493
|
+
id: self,
|
|
494
|
+
name: [bot.first_name, bot.last_name].filter(Boolean).join(" ") || null,
|
|
495
|
+
username: bot.username ?? null
|
|
496
|
+
};
|
|
497
|
+
}, "me");
|
|
498
|
+
const sent = /* @__PURE__ */ __name((answer) => toMessage(answer, self), "sent");
|
|
499
|
+
return {
|
|
500
|
+
me,
|
|
501
|
+
formatMarkdown: /* @__PURE__ */ __name(async (text) => formatMarkdown(text), "formatMarkdown"),
|
|
502
|
+
close: /* @__PURE__ */ __name(async () => {
|
|
503
|
+
}, "close"),
|
|
504
|
+
api: /* @__PURE__ */ __name((method, { files, ...input }, options) => transport.call(method, {}, {
|
|
505
|
+
...options,
|
|
506
|
+
...input,
|
|
507
|
+
files: files.map(({ field, name, bytes }) => ({ field, name, blob: new Blob([bytes]) }))
|
|
508
|
+
}), "api"),
|
|
509
|
+
send: /* @__PURE__ */ __name(async (chat, text, { replyTo, silent, markup, formatting: spans, html, attachments = [] }) => {
|
|
510
|
+
if (attachments.length > 1)
|
|
511
|
+
throw new CliError("validation_error", "a Telegram bot sends one file at a time");
|
|
512
|
+
const [attachment] = attachments;
|
|
513
|
+
const common = {
|
|
514
|
+
chat_id: chatIdOf(chat),
|
|
515
|
+
...replyTo ? { reply_parameters: { message_id: Number(replyTo) } } : {},
|
|
516
|
+
...silent ? { disable_notification: true } : {}
|
|
517
|
+
};
|
|
518
|
+
if (!attachment) {
|
|
519
|
+
return sent(await transport.call("sendMessage", { ...common, text, ...formatting(spans ?? markup, html, "entities") }, { reads: false }));
|
|
520
|
+
}
|
|
521
|
+
const [method, field] = attachment.kind === "photo" ? ["sendPhoto", "photo"] : attachment.kind === "voice" ? ["sendVoice", "voice"] : ["sendDocument", "document"];
|
|
522
|
+
const file = { field, name: attachment.name, blob: await uploadBlob(attachment.source) };
|
|
523
|
+
const caption = text ? { caption: text, ...formatting(spans ?? markup, html, "caption_entities") } : {};
|
|
524
|
+
return sent(await transport.call(method, { ...common, ...caption }, { reads: false, file }));
|
|
525
|
+
}, "send"),
|
|
526
|
+
edit: /* @__PURE__ */ __name(async (chat, messageId, text, { markup, formatting: spans, html }) => sent(await transport.call("editMessageText", {
|
|
527
|
+
chat_id: chatIdOf(chat),
|
|
528
|
+
message_id: Number(messageId),
|
|
529
|
+
text,
|
|
530
|
+
...formatting(spans ?? markup, html, "entities")
|
|
531
|
+
}, { reads: false })), "edit"),
|
|
532
|
+
delete: /* @__PURE__ */ __name(async (chat, messageIds) => {
|
|
533
|
+
for (let at = 0; at < messageIds.length; at += DELETE_BATCH) {
|
|
534
|
+
try {
|
|
535
|
+
await transport.call("deleteMessages", { chat_id: chatIdOf(chat), message_ids: messageIds.slice(at, at + DELETE_BATCH).map(Number) }, { reads: false });
|
|
536
|
+
} catch (error) {
|
|
537
|
+
if (at === 0)
|
|
538
|
+
throw error;
|
|
539
|
+
halfDone(`deleted the first ${at} of ${messageIds.length} messages`, error);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}, "delete"),
|
|
543
|
+
pin: /* @__PURE__ */ __name(async (chat, messageId, { notify }) => {
|
|
544
|
+
await transport.call("pinChatMessage", { chat_id: chatIdOf(chat), message_id: Number(messageId), disable_notification: !notify }, { reads: false });
|
|
545
|
+
}, "pin"),
|
|
546
|
+
unpin: /* @__PURE__ */ __name(async (chat, messageId) => {
|
|
547
|
+
await transport.call("unpinChatMessage", { chat_id: chatIdOf(chat), message_id: Number(messageId) }, { reads: false });
|
|
548
|
+
}, "unpin"),
|
|
549
|
+
chat: /* @__PURE__ */ __name(async (chat) => toChat(await transport.call("getChat", { chat_id: chatIdOf(chat) })), "chat"),
|
|
550
|
+
leave: /* @__PURE__ */ __name(async (chat) => {
|
|
551
|
+
await transport.call("leaveChat", { chat_id: chatIdOf(chat) }, { reads: false });
|
|
552
|
+
}, "leave"),
|
|
553
|
+
action: /* @__PURE__ */ __name(async (chat, action) => {
|
|
554
|
+
await transport.call("sendChatAction", { chat_id: chatIdOf(chat), action: ACTIONS[action] }, { reads: false });
|
|
555
|
+
}, "action"),
|
|
556
|
+
admins: /* @__PURE__ */ __name(async (chat) => (await transport.call("getChatAdministrators", { chat_id: chatIdOf(chat) })).map(toAdmin), "admins"),
|
|
557
|
+
addAdmin: /* @__PURE__ */ __name(async (chat, person, rights, { title }) => {
|
|
558
|
+
const granted = new Set(rights.map((right) => {
|
|
559
|
+
if (!(right in ADMIN_RIGHT_FIELDS))
|
|
560
|
+
throw new CliError("validation_error", `a Telegram bot cannot grant ${right}`);
|
|
561
|
+
return ADMIN_RIGHT_FIELDS[right];
|
|
562
|
+
}));
|
|
563
|
+
const target = { chat_id: chatIdOf(chat), user_id: Number(person) };
|
|
564
|
+
await transport.call("promoteChatMember", { ...target, ...Object.fromEntries(PROMOTE_FIELDS.map((field) => [field, granted.has(field)])) }, { reads: false });
|
|
565
|
+
if (title === void 0)
|
|
566
|
+
return;
|
|
567
|
+
await transport.call("setChatAdministratorCustomTitle", { ...target, custom_title: title }, { reads: false }).catch((error) => halfDone(`${person} is an admin now`, error));
|
|
568
|
+
}, "addAdmin"),
|
|
569
|
+
removeAdmin: /* @__PURE__ */ __name(async (chat, person) => {
|
|
570
|
+
await transport.call("promoteChatMember", {
|
|
571
|
+
chat_id: chatIdOf(chat),
|
|
572
|
+
user_id: Number(person),
|
|
573
|
+
...Object.fromEntries(PROMOTE_FIELDS.map((field) => [field, false]))
|
|
574
|
+
}, { reads: false });
|
|
575
|
+
}, "removeAdmin"),
|
|
576
|
+
// Telegram removes only by banning; without --block the ban is lifted at once, so the link lets them back.
|
|
577
|
+
menu: /* @__PURE__ */ __name(async () => (await transport.call("getMyCommands")).map(({ command, description }) => ({ name: command, description: description || null })), "menu"),
|
|
578
|
+
setMenu: /* @__PURE__ */ __name(async (entries) => {
|
|
579
|
+
if (entries.length === 0) {
|
|
580
|
+
await transport.call("deleteMyCommands", {}, { reads: false });
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
const bare = entries.find((entry) => !entry.description);
|
|
584
|
+
if (bare)
|
|
585
|
+
throw new CliError("validation_error", `a Telegram command needs a description: ${bare.name}=\u2026`);
|
|
586
|
+
await transport.call("setMyCommands", { commands: entries.map(({ name, description }) => ({ command: name, description })) }, { reads: false });
|
|
587
|
+
}, "setMenu"),
|
|
588
|
+
// Telegram's answer cannot change the message; --text is a second call, to the press `bot watch` kept.
|
|
589
|
+
answer: /* @__PURE__ */ __name(async (callbackId, { notification, text, press }) => {
|
|
590
|
+
if (text !== void 0 && !press) {
|
|
591
|
+
throw new CliError("validation_error", "a Telegram bot can replace the message only for a press `bot watch` saw \u2014 run it, then answer");
|
|
592
|
+
}
|
|
593
|
+
await transport.call("answerCallbackQuery", { callback_query_id: callbackId, ...notification === void 0 ? {} : { text: notification } }, { reads: false });
|
|
594
|
+
if (text === void 0 || !press)
|
|
595
|
+
return;
|
|
596
|
+
await transport.call("editMessageText", { chat_id: press.chatId, message_id: Number(press.messageId), text }, { reads: false }).catch((error) => halfDone("the button was answered", error));
|
|
597
|
+
}, "answer"),
|
|
598
|
+
webhooks: /* @__PURE__ */ __name(async () => {
|
|
599
|
+
const info = await transport.call("getWebhookInfo");
|
|
600
|
+
return info.url ? [{ url: info.url, types: info.allowed_updates ?? null }] : [];
|
|
601
|
+
}, "webhooks"),
|
|
602
|
+
setWebhook: /* @__PURE__ */ __name(async (url, { types, secret }) => {
|
|
603
|
+
await transport.call("setWebhook", { url, allowed_updates: types ?? UPDATE_TYPES, ...secret ? { secret_token: secret } : {} }, { reads: false });
|
|
604
|
+
}, "setWebhook"),
|
|
605
|
+
// Telegram's deleteWebhook names no address: refuse one that is not the address set.
|
|
606
|
+
deleteWebhook: /* @__PURE__ */ __name(async (url) => {
|
|
607
|
+
const info = await transport.call("getWebhookInfo");
|
|
608
|
+
if (info.url !== url)
|
|
609
|
+
throw new CliError("not_found", `this bot's webhook is not ${url}`);
|
|
610
|
+
await transport.call("deleteWebhook", {}, { reads: false });
|
|
611
|
+
}, "deleteWebhook"),
|
|
612
|
+
updates: /* @__PURE__ */ __name(async (cursor, { types, waitSeconds }) => {
|
|
613
|
+
if (self === void 0)
|
|
614
|
+
await me();
|
|
615
|
+
const updates = await transport.call("getUpdates", {
|
|
616
|
+
...cursor ? { offset: Number(cursor) } : {},
|
|
617
|
+
timeout: waitSeconds,
|
|
618
|
+
allowed_updates: types ?? UPDATE_TYPES
|
|
619
|
+
}, { timeoutMs: (waitSeconds + 15) * 1e3 });
|
|
620
|
+
const last = updates.at(-1);
|
|
621
|
+
return {
|
|
622
|
+
events: updates.map((update) => toEvent(update, self)),
|
|
623
|
+
cursor: last ? String(last.update_id + 1) : cursor
|
|
624
|
+
};
|
|
625
|
+
}, "updates"),
|
|
626
|
+
removeMember: /* @__PURE__ */ __name(async (chat, person, { block }) => {
|
|
627
|
+
const target = { chat_id: chatIdOf(chat), user_id: Number(person) };
|
|
628
|
+
await transport.call("banChatMember", target, { reads: false });
|
|
629
|
+
if (block)
|
|
630
|
+
return;
|
|
631
|
+
await transport.call("unbanChatMember", { ...target, only_if_banned: true }, { reads: false }).catch((error) => halfDone(`${person} is out of the chat and still blocked`, error));
|
|
632
|
+
}, "removeMember")
|
|
633
|
+
};
|
|
634
|
+
}, "telegramBotAdapter");
|
|
635
|
+
|
|
636
|
+
// dist/bot/proxy.js
|
|
637
|
+
var botDispatcher = /* @__PURE__ */ __name(async (proxy) => {
|
|
638
|
+
if (proxy.kind === "mtproxy")
|
|
639
|
+
return void 0;
|
|
640
|
+
const { ProxyAgent, Socks5ProxyAgent } = await importFrom(new URL("../bot/proxy.js", import.meta.url).href, "undici");
|
|
641
|
+
const uri = proxyAddress(proxy);
|
|
642
|
+
if (typeof ProxyAgent !== "function" || typeof Socks5ProxyAgent !== "function")
|
|
643
|
+
throw proxyError(proxy, "cannot carry the Bot API under this runtime \u2014 run tg with Node");
|
|
644
|
+
if (proxy.kind === "socks5")
|
|
645
|
+
return new Socks5ProxyAgent(uri, {
|
|
646
|
+
...proxy.user === void 0 ? {} : { username: proxy.user },
|
|
647
|
+
...proxy.secret === void 0 ? {} : { password: proxy.secret }
|
|
648
|
+
});
|
|
649
|
+
const basic = proxy.user === void 0 ? void 0 : `Basic ${Buffer.from(`${proxy.user}:${proxy.secret ?? ""}`).toString("base64")}`;
|
|
650
|
+
return new ProxyAgent({ uri, ...basic ? { token: basic } : {} });
|
|
651
|
+
}, "botDispatcher");
|
|
652
|
+
var proxiedFetch = /* @__PURE__ */ __name((proxy) => {
|
|
653
|
+
if (proxy.kind === "mtproxy")
|
|
654
|
+
return void 0;
|
|
655
|
+
let dispatcher;
|
|
656
|
+
return async (url, init) => {
|
|
657
|
+
dispatcher ??= botDispatcher(proxy);
|
|
658
|
+
const [undici, agent] = await Promise.all([importFrom(new URL("../bot/proxy.js", import.meta.url).href, "undici"), dispatcher]);
|
|
659
|
+
const body = init.body instanceof FormData ? copyForm(init.body, new undici.FormData()) : init.body;
|
|
660
|
+
try {
|
|
661
|
+
return await undici.fetch(url, {
|
|
662
|
+
...init,
|
|
663
|
+
body,
|
|
664
|
+
...agent ? { dispatcher: agent } : {}
|
|
665
|
+
});
|
|
666
|
+
} catch (error) {
|
|
667
|
+
throw proxyRefusal(proxy, error) ?? error;
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
}, "proxiedFetch");
|
|
671
|
+
var copyForm = /* @__PURE__ */ __name((form, into) => {
|
|
672
|
+
for (const [name, value] of form) {
|
|
673
|
+
if (typeof value === "string")
|
|
674
|
+
into.append(name, value);
|
|
675
|
+
else
|
|
676
|
+
into.append(name, value, value.name);
|
|
677
|
+
}
|
|
678
|
+
return into;
|
|
679
|
+
}, "copyForm");
|
|
680
|
+
var proxyRefusal = /* @__PURE__ */ __name((proxy, error) => {
|
|
681
|
+
for (let cause = error; cause instanceof Error; cause = cause.cause) {
|
|
682
|
+
const code = cause.code;
|
|
683
|
+
const status = /Proxy response \((\d+)\)/.exec(cause.message)?.[1];
|
|
684
|
+
const reason = status !== void 0 ? `refused the tunnel (HTTP ${status})` : typeof code === "string" && code.startsWith("UND_ERR_SOCKS5") ? `refused (${code})` : typeof code === "string" && /^(ECONN|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH)/.test(code) ? `cannot be reached (${code})` : void 0;
|
|
685
|
+
if (reason)
|
|
686
|
+
return proxyError(proxy, reason);
|
|
687
|
+
}
|
|
688
|
+
return void 0;
|
|
689
|
+
}, "proxyRefusal");
|
|
690
|
+
|
|
691
|
+
// dist/bot/transport.js
|
|
692
|
+
var API = "https://api.telegram.org";
|
|
693
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
694
|
+
var TelegramBotTransport = class {
|
|
695
|
+
static {
|
|
696
|
+
__name(this, "TelegramBotTransport");
|
|
697
|
+
}
|
|
698
|
+
#token;
|
|
699
|
+
#baseUrl;
|
|
700
|
+
#fetch;
|
|
701
|
+
#timeoutMs;
|
|
702
|
+
#signal;
|
|
703
|
+
#events;
|
|
704
|
+
constructor(options) {
|
|
705
|
+
this.#token = options.token;
|
|
706
|
+
this.#baseUrl = options.baseUrl ?? API;
|
|
707
|
+
this.#fetch = options.fetch ?? fetch;
|
|
708
|
+
this.#timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
709
|
+
this.#signal = options.signal;
|
|
710
|
+
this.#events = options.events;
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* `reads: false` for a write, so a write that got no answer is `outcome_unknown`, never retried by
|
|
714
|
+
* anyone. `file` goes up in the same request, as multipart: Telegram has no upload step of its own.
|
|
715
|
+
* `timeoutMs` replaces the transport's for one call — a long poll waits longer than any other request.
|
|
716
|
+
*/
|
|
717
|
+
async call(method, params = {}, { reads = true, file, files = [], body, secrets = [], timeoutMs = this.#timeoutMs } = {}) {
|
|
718
|
+
const end = providerRequest(method, this.#events ?? (() => {
|
|
719
|
+
}), {
|
|
720
|
+
method: "POST",
|
|
721
|
+
endpointTemplate: `/:token/${method}`,
|
|
722
|
+
transport: "http",
|
|
723
|
+
// A rate-limit retry is made above the transport (cli-core's `patiently`), which names the attempt itself.
|
|
724
|
+
...currentAttempt() ? {} : { attempt: 1 }
|
|
725
|
+
});
|
|
726
|
+
const signals = [AbortSignal.timeout(timeoutMs), ...this.#signal ? [this.#signal] : []];
|
|
727
|
+
let response;
|
|
728
|
+
try {
|
|
729
|
+
response = await this.#fetch(`${this.#baseUrl}/bot${this.#token}/${method}`, {
|
|
730
|
+
method: "POST",
|
|
731
|
+
...file || files.length ? {
|
|
732
|
+
headers: { Accept: "application/json" },
|
|
733
|
+
body: multipart(body === void 0 ? params : parseApiJson(body), file ? [file, ...files] : files)
|
|
734
|
+
} : {
|
|
735
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
736
|
+
body: body ?? apiJson(params)
|
|
737
|
+
},
|
|
738
|
+
signal: AbortSignal.any(signals)
|
|
739
|
+
});
|
|
740
|
+
} catch (error) {
|
|
741
|
+
const failure = this.#unanswered(method, error, reads, timeoutMs);
|
|
742
|
+
end({ errorCode: failure.code });
|
|
743
|
+
throw failure;
|
|
744
|
+
}
|
|
745
|
+
let text;
|
|
746
|
+
try {
|
|
747
|
+
text = await response.text();
|
|
748
|
+
} catch (error) {
|
|
749
|
+
const failure = this.#unanswered(method, error, reads, timeoutMs);
|
|
750
|
+
end({ status: response.status, errorCode: failure.code });
|
|
751
|
+
throw failure;
|
|
752
|
+
}
|
|
753
|
+
const answered = { status: response.status, bytes: Buffer.byteLength(text) };
|
|
754
|
+
let answer;
|
|
755
|
+
try {
|
|
756
|
+
answer = apiPlainJson(parseApiJson(text));
|
|
757
|
+
} catch {
|
|
758
|
+
end({ ...answered, errorCode: "invalid_response" });
|
|
759
|
+
throw new CliError("invalid_response", `Telegram answered ${method} with something that is not JSON`, {
|
|
760
|
+
operation: method,
|
|
761
|
+
status: response.status
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
if (answer.ok === true) {
|
|
765
|
+
end(answered);
|
|
766
|
+
return answer.result;
|
|
767
|
+
}
|
|
768
|
+
const secretValues = [this.#token, ...secrets];
|
|
769
|
+
if (answer.description) {
|
|
770
|
+
for (const secret of secretValues)
|
|
771
|
+
if (secret)
|
|
772
|
+
answer.description = answer.description.split(secret).join("[redacted]");
|
|
773
|
+
answer.description = answer.description.replace(/\b\d+:[A-Za-z0-9_-]{20,}\b/g, "[redacted]");
|
|
774
|
+
}
|
|
775
|
+
const refusal = refusalOf(method, answer, response.status);
|
|
776
|
+
end({ ...answered, errorCode: refusal.code });
|
|
777
|
+
throw refusal;
|
|
778
|
+
}
|
|
779
|
+
#unanswered(method, error, reads, timeoutMs) {
|
|
780
|
+
if (isCliError(error) && error.details.proxy !== void 0)
|
|
781
|
+
return error;
|
|
782
|
+
const timedOut = error?.name === "TimeoutError";
|
|
783
|
+
if (this.#signal?.aborted && this.#signal.reason?.name !== "TimeoutError") {
|
|
784
|
+
return new CliError("cancelled", `${method} was cancelled`, { operation: method });
|
|
785
|
+
}
|
|
786
|
+
if (!reads) {
|
|
787
|
+
return new CliError("outcome_unknown", `${method} got no answer; Telegram may or may not have carried it out \u2014 check before repeating it`, { operation: method, retryable: false });
|
|
788
|
+
}
|
|
789
|
+
return new CliError(timedOut ? "timeout" : "network_error", timedOut ? `${method} got no answer within ${timeoutMs} ms` : `${method} could not reach Telegram`, { operation: method, retryable: true });
|
|
790
|
+
}
|
|
791
|
+
};
|
|
792
|
+
var multipart = /* @__PURE__ */ __name((params, files) => {
|
|
793
|
+
const form = new FormData();
|
|
794
|
+
for (const [name, value] of Object.entries(params)) {
|
|
795
|
+
if (value !== void 0)
|
|
796
|
+
form.append(name, typeof value === "string" ? value : apiJson(value));
|
|
797
|
+
}
|
|
798
|
+
for (const file of files)
|
|
799
|
+
form.append(file.field, file.blob, file.name);
|
|
800
|
+
return form;
|
|
801
|
+
}, "multipart");
|
|
802
|
+
var refusalOf = /* @__PURE__ */ __name((method, answer, status) => {
|
|
803
|
+
const said = answer.description ?? `HTTP ${status}`;
|
|
804
|
+
const details = { operation: method, status };
|
|
805
|
+
const retryAfter = answer.parameters?.retry_after;
|
|
806
|
+
if (retryAfter !== void 0) {
|
|
807
|
+
return new CliError("rate_limited", `Telegram asks to wait ${retryAfter} s before ${method}: ${said}`, {
|
|
808
|
+
...details,
|
|
809
|
+
retry_after_ms: retryAfter * 1e3,
|
|
810
|
+
retryable: true
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
const migrated = answer.parameters?.migrate_to_chat_id;
|
|
814
|
+
if (migrated !== void 0) {
|
|
815
|
+
return new CliError("not_found", `this group became a supergroup with id ${migrated} \u2014 use that id from now on (${said})`, { ...details, migrated_chat_id: String(migrated) });
|
|
816
|
+
}
|
|
817
|
+
const code = status === 401 || status === 404 ? "authentication_error" : status === 403 ? "permission_error" : status >= 500 ? "provider_unavailable" : /not found/i.test(said) ? "not_found" : status === 400 ? "validation_error" : "provider_error";
|
|
818
|
+
const message = code === "authentication_error" ? `Telegram did not accept this bot token (${said})` : `${method}: ${said}`;
|
|
819
|
+
return new CliError(code, message, details);
|
|
820
|
+
}, "refusalOf");
|
|
821
|
+
|
|
822
|
+
// dist/commands/bot.js
|
|
823
|
+
var botMcpRun = /* @__PURE__ */ __name((run, extra = {}) => (argv, environment) => run(argv, { ...extra, ...environment }), "botMcpRun");
|
|
824
|
+
var botMcp = /* @__PURE__ */ __name((run) => ({ program: /* @__PURE__ */ __name(async () => botMcpRun(run), "program"), skill: SKILL }), "botMcp");
|
|
825
|
+
var TELEGRAM_BOT = {
|
|
826
|
+
app: TG,
|
|
827
|
+
provider: "telegram-bot",
|
|
828
|
+
name: "Telegram",
|
|
829
|
+
identity: true,
|
|
830
|
+
adminRights: BOT_ADMIN_RIGHTS,
|
|
831
|
+
resolveSettings,
|
|
832
|
+
fetching: {
|
|
833
|
+
page: 100,
|
|
834
|
+
pause: "1s",
|
|
835
|
+
maxPages: 10,
|
|
836
|
+
orderBy: "id",
|
|
837
|
+
from: "start at this message, by its t.me link, inclusive; otherwise the newest message already known"
|
|
838
|
+
},
|
|
839
|
+
connect: /* @__PURE__ */ __name(async (command, token, { stop, events, history, track } = {}) => {
|
|
840
|
+
const environment = environmentOf(command);
|
|
841
|
+
const env = environment.env ?? process.env;
|
|
842
|
+
const settings = resolveSettings(command.optsWithGlobals(), { env, kind: "bot" });
|
|
843
|
+
const { profile } = settings;
|
|
844
|
+
const words = checkWords("tg", profile);
|
|
845
|
+
const through = resolveProxy(settings, {
|
|
846
|
+
env,
|
|
847
|
+
checks: words,
|
|
848
|
+
...environment.keyring ? { keyring: environment.keyring } : {}
|
|
849
|
+
});
|
|
850
|
+
const fetch2 = environment.botFetch ?? (through ? proxiedFetch(through.proxy) : void 0);
|
|
851
|
+
const adapter = telegramBotAdapter(new TelegramBotTransport({
|
|
852
|
+
token,
|
|
853
|
+
...fetch2 ? { fetch: fetch2 } : {},
|
|
854
|
+
...stop ? { signal: stop } : {},
|
|
855
|
+
...events ? { events } : {}
|
|
856
|
+
}));
|
|
857
|
+
if (!history)
|
|
858
|
+
return adapter;
|
|
859
|
+
const readCredentials = /* @__PURE__ */ __name((profile2) => apiCredentials({ profile: profile2, env, ...environment.keyring ? { keyring: environment.keyring } : {} }).read(), "readCredentials");
|
|
860
|
+
const credentials = readCredentials(profile);
|
|
861
|
+
if (!credentials)
|
|
862
|
+
throw new CliError("authentication_error", `bot messages sync needs Telegram app credentials \u2014 run \`tg ${profile} session start\` first, or set TG_API_ID and TG_API_HASH`);
|
|
863
|
+
const botId = token.split(":", 1)[0] ?? "";
|
|
864
|
+
if (!/^\d+$/.test(botId))
|
|
865
|
+
throw new CliError("authentication_error", "the bot token has no valid bot id");
|
|
866
|
+
const reader = await (environment.botHistory ?? (await import("./bot-history-OUMVVG22.js")).openBotHistory)({
|
|
867
|
+
credentials,
|
|
868
|
+
sessionPath: botSessionFile(profile, botId, env),
|
|
869
|
+
token,
|
|
870
|
+
checks: words,
|
|
871
|
+
...history,
|
|
872
|
+
...proxyOption(through),
|
|
873
|
+
...stop ? { stop } : {},
|
|
874
|
+
...events ? { events } : {},
|
|
875
|
+
...track ? { track } : {},
|
|
876
|
+
newest: /* @__PURE__ */ __name(async (chat) => {
|
|
877
|
+
const copy = botCopy("telegram-bot");
|
|
878
|
+
const known = await copy.read((store) => store.messages.messages(copy.accountOf(botId), chat, { limit: 1 }));
|
|
879
|
+
if (known.items[0])
|
|
880
|
+
return known.items[0].id;
|
|
881
|
+
const personalPath = sessionFile(profile, env);
|
|
882
|
+
if (!existsSync2(personalPath) && !environment.adapter)
|
|
883
|
+
return void 0;
|
|
884
|
+
let personal;
|
|
885
|
+
try {
|
|
886
|
+
personal = environment.adapter ? await environment.adapter({ credentials, sessionPath: personalPath }) : await (await import("./adapter-M2HRSFFL.js")).TelegramAdapter.open({
|
|
887
|
+
credentials,
|
|
888
|
+
sessionPath: personalPath,
|
|
889
|
+
checks: words,
|
|
890
|
+
...proxyOption(through)
|
|
891
|
+
});
|
|
892
|
+
track?.(personal);
|
|
893
|
+
return (await personal.history?.(chat, { limit: 1 }))?.items[0]?.id;
|
|
894
|
+
} catch {
|
|
895
|
+
return void 0;
|
|
896
|
+
} finally {
|
|
897
|
+
await personal?.close();
|
|
898
|
+
}
|
|
899
|
+
}, "newest")
|
|
900
|
+
});
|
|
901
|
+
return { ...adapter, historyBefore: reader.historyBefore, close: reader.close };
|
|
902
|
+
}, "connect"),
|
|
903
|
+
tokenStore: /* @__PURE__ */ __name((command, profile) => {
|
|
904
|
+
const { keyring, env } = environmentOf(command);
|
|
905
|
+
return new BotTokenStore({ app: TG, profile, ...env ? { env } : {}, ...keyring ? { keyring } : {} });
|
|
906
|
+
}, "tokenStore")
|
|
907
|
+
};
|
|
908
|
+
|
|
909
|
+
export {
|
|
910
|
+
CONFIG,
|
|
911
|
+
resolveSettings,
|
|
912
|
+
proxiedFetch,
|
|
913
|
+
pathsFor,
|
|
914
|
+
parseApiId,
|
|
915
|
+
parseApiHash,
|
|
916
|
+
proxySecrets,
|
|
917
|
+
SKILL,
|
|
918
|
+
TELEGRAM,
|
|
919
|
+
forCommand,
|
|
920
|
+
botMcp,
|
|
921
|
+
TELEGRAM_BOT
|
|
922
|
+
};
|