UNPKG

3.05 kBJavaScriptView Raw
1#!/usr/bin/env node
2import d from 'debug';
3import parse from 'mri';
4import path from 'path';
5import { Telegraf } from './index.js';
6const debug = d('telegraf:cli');
7const 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`;
17const help = () => console.log(helpMsg);
18/**
19 * Runs the cli program and returns exit code
20 */
21export async function main(argv, env = {}) {
22 const args = parse(argv, {
23 alias: {
24 // string params, all optional
25 t: 'token',
26 d: 'domain',
27 m: 'method',
28 D: 'data',
29 // defaults exist
30 H: 'host',
31 p: 'port',
32 // boolean params
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 // eslint-disable-next-line no-empty
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 // Enable graceful stop
101 process.once('SIGINT', () => bot.stop('SIGINT'));
102 process.once('SIGTERM', () => bot.stop('SIGTERM'));
103 return 0;
104}
105process.exitCode = await main(process.argv, process.env);