1 | #!/usr/bin/env node
|
2 | import d from 'debug';
|
3 | import parse from 'mri';
|
4 | import path from 'path';
|
5 | import { Telegraf } from './index.js';
|
6 | const debug = d('telegraf:cli');
|
7 | const helpMsg = `Usage: telegraf [opts] <bot-file>
|
8 |
|
9 | -t Bot token [$BOT_TOKEN]
|
10 | -d Webhook domain [$BOT_DOMAIN]
|
11 | -H Webhook host [0.0.0.0]
|
12 | -p Webhook port [$PORT or 3000]
|
13 | -l Enable logs
|
14 | -h Show this help message
|
15 | -m Bot API method to run directly
|
16 | -D Data to pass to the Bot API method`;
|
17 | const help = () => console.log(helpMsg);
|
18 |
|
19 |
|
20 |
|
21 | export async function main(argv, env = {}) {
|
22 | const args = parse(argv, {
|
23 | alias: {
|
24 |
|
25 | t: 'token',
|
26 | d: 'domain',
|
27 | m: 'method',
|
28 | D: 'data',
|
29 |
|
30 | H: 'host',
|
31 | p: 'port',
|
32 |
|
33 | l: 'logs',
|
34 | h: 'help',
|
35 | },
|
36 | boolean: ['h', 'l'],
|
37 | default: {
|
38 | H: '0.0.0.0',
|
39 | p: env.PORT || '3000',
|
40 | },
|
41 | });
|
42 | if (args.help) {
|
43 | help();
|
44 | return 0;
|
45 | }
|
46 | const token = args.token || env.BOT_TOKEN;
|
47 | const domain = args.domain || env.BOT_DOMAIN;
|
48 | if (!token) {
|
49 | console.error('Please supply Bot Token');
|
50 | help();
|
51 | return 1;
|
52 | }
|
53 | const bot = new Telegraf(token);
|
54 | if (args.method) {
|
55 | const method = args.method;
|
56 | console.log(await bot.telegram.callApi(method, JSON.parse(args.data || '{}')));
|
57 | return 0;
|
58 | }
|
59 | let [, , file] = args._;
|
60 | if (!file) {
|
61 | try {
|
62 | const packageJson = (await import(path.resolve(process.cwd(), 'package.json')));
|
63 | file = packageJson.main || 'index.js';
|
64 |
|
65 | }
|
66 | catch (err) { }
|
67 | }
|
68 | if (!file) {
|
69 | console.error('Please supply a bot handler file.\n');
|
70 | help();
|
71 | return 2;
|
72 | }
|
73 | if (file[0] !== '/')
|
74 | file = path.resolve(process.cwd(), file);
|
75 | try {
|
76 | if (args.logs)
|
77 | d.enable('telegraf:*');
|
78 | const mod = await import(file);
|
79 | const botHandler = mod.botHandler || mod.default;
|
80 | const httpHandler = mod.httpHandler;
|
81 | const tlsOptions = mod.tlsOptions;
|
82 | const config = {};
|
83 | if (domain) {
|
84 | config.webhook = {
|
85 | domain,
|
86 | host: args.host,
|
87 | port: Number(args.port),
|
88 | tlsOptions,
|
89 | cb: httpHandler,
|
90 | };
|
91 | }
|
92 | bot.use(botHandler);
|
93 | debug(`Starting module ${file}`);
|
94 | await bot.launch(config);
|
95 | }
|
96 | catch (err) {
|
97 | console.error(`Error launching bot from ${file}`, err === null || err === void 0 ? void 0 : err.stack);
|
98 | return 3;
|
99 | }
|
100 |
|
101 | process.once('SIGINT', () => bot.stop('SIGINT'));
|
102 | process.once('SIGTERM', () => bot.stop('SIGTERM'));
|
103 | return 0;
|
104 | }
|
105 | process.exitCode = await main(process.argv, process.env);
|