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