Repository: telegraf/micro-bot Branch: master Commit: 84a50fe6d404 Files: 11 Total size: 11.6 KB Directory structure: gitextract_lhu_y2lb/ ├── .editorconfig ├── .eslintignore ├── .eslintrc ├── .gitignore ├── .travis.yml ├── LICENSE ├── bin/ │ └── micro-bot ├── examples/ │ └── bot.js ├── index.js ├── package.json └── readme.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # editorconfig.org root = true [*] indent_style = space indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.md] trim_trailing_whitespace = false [*.txt] trim_trailing_whitespace = false ================================================ FILE: .eslintignore ================================================ node_modules/ ================================================ FILE: .eslintrc ================================================ { "extends": ["standard"] } ================================================ FILE: .gitignore ================================================ # Logs logs *.log npm-debug.log* # Runtime data pids *.pid *.seed # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt # node-waf configuration .lock-wscript # Compiled binary addons (http://nodejs.org/api/addons.html) build/Release # Dependency directory node_modules # Optional npm cache directory .npm # Optional REPL history .node_repl_history .nyc_output coverage _docpress package-lock.json ================================================ FILE: .travis.yml ================================================ language: node_js node_js: - 8 - 9 ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2016 Vitaly Domnikov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: bin/micro-bot ================================================ #!/usr/bin/env node const { existsSync } = require('fs') const path = require('path') const parse = require('minimist') const dotenv = require('dotenv') const { start } = require('../') const help = () => { console.log(`Usage: micro-bot [opts] -t Bot token -d Webhook domain [$BOT_DOMAIN or $NOW_URL] -H Webhook host [0.0.0.0] -p Webhook port [$PORT or 3000] -e Load env vars from file. [.env]' -s Silent mode -h Show this help message -v Show version information`) } const args = parse(process.argv, { alias: { d: 'domain', e: 'dotenv', h: 'help', H: 'host', p: 'port', s: 'silent', t: 'token', v: 'version' }, boolean: ['h', 'v', 's'], default: { H: '0.0.0.0', p: process.env.PORT || 3000 } }) if (args.help) { help() process.exit(0) } if (args.version) { const packageData = require('../package.json') console.log(`v${packageData.version}`) process.exit(0) } if (args.dotenv) { const dotenvFileName = typeof args.dotenv === 'string' ? args.dotenv : '.env' if (!existsSync(dotenvFileName)) { console.error(`μ-bot: -e flag is set but ${dotenvFileName} file is missing`) help() process.exit(1) } dotenv.config({ path: dotenvFileName }) } const token = args.token || process.env.BOT_TOKEN if (!token) { console.error(`μ-bot: Please supply Bot token`) help() process.exit(1) } let [,, file] = args._ if (!file) { try { const packageJson = require(path.resolve(process.cwd(), 'package.json')) file = packageJson.main || 'index.js' } catch (err) { if (err.code === 'MODULE_NOT_FOUND') { console.error(`μ-bot: Could not read \`package.json\`: ${err.message}`) process.exit(1) } } } if (!file) { console.error('μ-bot: Please supply a file with bot handler.') help() process.exit(1) } if (file[0] !== '/') { file = path.resolve(process.cwd(), file) } let botModule try { botModule = require(file) } catch (err) { console.error(`μ-bot: Error when importing ${file}: ${err.stack}`) process.exit(1) } const domain = args.domain || process.env.BOT_DOMAIN || process.env.NOW_URL const botOptions = { token, domain, botModule, port: args.port, host: args.host } start(botOptions).catch((err) => { console.warn(`μ-bot: Failed to start: ${err}`) }) ================================================ FILE: examples/bot.js ================================================ const { Composer } = require('micro-bot') const bot = new Composer() bot.start((ctx) => ctx.reply('Welcome')) bot.help((ctx) => ctx.reply('Help message')) bot.hears('hi', ({ reply }) => reply('Hello')) bot.on('sticker', ({ reply }) => reply('👍')) bot.on('message', ({ reply }) => reply('👋')) module.exports = bot ================================================ FILE: index.js ================================================ const Telegraf = require('telegraf') const Stage = require('telegraf/stage') const Scene = require('telegraf/scenes/base') const WizardScene = require('telegraf/scenes/wizard') const defaultInit = () => Promise.resolve() const defaultCb = (req, res) => { res.statusCode = 404 res.end() } function start ({ token, domain, hookPath, botModule, port, host, silent }) { const webhook = typeof domain === 'string' || typeof hookPath === 'string' ? { domain, hookPath, port, host, tlsOptions: botModule.tlsOptions, cb: botModule.server || botModule.requestHandler || defaultCb } : null const bot = new Telegraf(token, botModule.options) const init = botModule.init || botModule.initialize || defaultInit bot.catch((err) => console.error('μ-bot: Unhandled error', err)) bot.use(botModule.bot || botModule.botHandler || botModule) return init(bot) .then(() => bot.launch({ webhook })) .then(() => !silent && console.log(`μ-bot: Bot started`)) } module.exports = Object.assign(Telegraf, { Stage, Scene, WizardScene, start: start }) ================================================ FILE: package.json ================================================ { "name": "micro-bot", "version": "2.5.3", "description": "Zero-configuration Telegram bot runner", "author": "Vitaly Domnikov ", "license": "MIT", "homepage": "https://github.com/telegraf/micro-bot#readme", "repository": { "type": "git", "url": "git+ssh://git@github.com/telegraf/micro-bot.git" }, "bugs": { "url": "https://github.com/telegraf/micro-bot/issues" }, "main": "index.js", "scripts": { "test": "eslint ." }, "engines": { "node": ">=8.1" }, "bin": { "micro-bot": "./bin/micro-bot" }, "dependencies": { "dotenv": "^6.0.0", "minimist": "^1.2.0", "telegraf": "^3.25.4" }, "devDependencies": { "eslint": "^5.4.0", "eslint-config-standard": "^12.0.0", "eslint-plugin-import": "^2.2.0", "eslint-plugin-node": "^8.0.0", "eslint-plugin-promise": "^4.0.0", "eslint-plugin-standard": "^4.0.0" }, "keywords": [ "telegraf", "telegram", "bot" ] } ================================================ FILE: readme.md ================================================ # ⚠️ This package is deprecated. Use [telegraf](https://github.com/telegraf/telegraf)'s builtin CLI instead. [![NPM Version](https://img.shields.io/npm/v/micro-bot.svg?style=flat-square)](https://www.npmjs.com/package/micro-bot) [![node](https://img.shields.io/node/v/micro-bot.svg?style=flat-square)](https://www.npmjs.com/package/micro-bot) [![Build Status](https://img.shields.io/travis/telegraf/micro-bot.svg?branch=master&style=flat-square)](https://travis-ci.org/telegraf/micro-bot) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/) # μ-bot > 🤖 Zero-configuration Telegram bot runner ## Documentation `micro-bot` was built on top of [`Telegraf`](https://github.com/telegraf/telegraf) library. [Telegraf API documentation](http://telegraf.js.org). ## Installation Install from NPM: ```bash $ npm install micro-bot ``` ## Scaffolding If you have installed latest `yarn` or `npm` you can use [`create-bot`](https://github.com/telegraf/create-bot) scaffolding tool: ```bash $ npm init bot smart-bot $ cd smart-bot ``` Or using `yarn`: ```bash $ yarn create bot smart-bot $ cd smart-bot ``` ## Quick start The following example will answer with important information about everything. ```bash $ mkdir smart-bot $ cd smart-bot $ npm init $ npm install micro-bot --save ``` Then write your `index.js`. ```js module.exports = ({ reply }) => reply('42') ``` Then in your `package.json`: ```js "main": "index.js", "scripts": { "start": "micro-bot" } ``` To run the bot, use the `micro-bot` command: ```bash $ BOT_TOKEN='TOKEN' npm start ``` or ```bash $ micro-bot -t TOKEN index.js ``` To run the bot with webhook support, provide webhook domain name: ```bash $ micro-bot -t TOKEN -d yourdomain.tld echo.js ``` Supported environment variables: * `process.env.BOT_TOKEN` - Bot token * `process.env.BOT_DOMAIN` - Webhook domain ## Deployment to `now` Let's deploy your `micro-bot` with Realtime global deployments by Zeit. First, install [`now`](https://zeit.co/now) ```bash $ npm install now -g $ now login ``` Finally use `now` to deploy: ```bash $ now -e BOT_TOKEN='YOUR BOT TOKEN' ``` Congratulations, your bot is alive! 🎉 ## Deployment to Heroku Okay, now we will deploy our `micro-bot` to Heroku. Why not?! First, install [`heroku binaries`](https://devcenter.heroku.com/articles/getting-started-with-nodejs#set-up) and login via console. Then, init new git repo: ```bash $ git init $ heroku create ``` Afterwards, update Heroku config: ```bash $ heroku config:set --app YourAppId BOT_TOKEN='YOUR BOT TOKEN' $ heroku config:set --app YourAppId BOT_DOMAIN='https://YourAppId.herokuapp.com' ``` Then add `Procfile` into the root of your project, with one line: ```Procfile web: micro-bot -p $PORT ``` Finally use git to deploy: ```bash $ git add index.js package.json $ git commit -m 'initial commit' $ git push heroku master ``` #### Example μ-bots * [ 🔥 Glitch example](https://glitch.com/edit/#!/dashing-light) * [`@uncover_bot`](https://telegram.me/uncover_bot) - [Source code](https://uncover.now.sh/_src) * [`@epub2mobi_bot`](https://telegram.me/epub2mobi_bot) - [Source code](https://epub2mobi.now.sh/_src) * [`@gorchichkabot`](https://bot.gorchichka.com) - [Source code](https://github.com/agudulin/gorchichkabot) * [`@aloudbot`](https://telegram.me/aloudbot) - [Source code](https://github.com/shrynx/aloudbot) ## Advanced Examples ```js const { mount, reply } = require('micro-bot') module.exports = mount('sticker', reply('👍')) ``` ```js const { readFileSync } = require('fs') const { Composer } = require('micro-bot') const bot = new Composer() bot.start((ctx) => ctx.reply('Welcome')) bot.help((ctx) => ctx.reply('Help message')) bot.hears('hi', ({ reply }) => reply('Hello')) bot.on('sticker', ({ reply }) => reply('👍')) // Export bot handler module.exports = bot // Or you can export hash with handlers and options module.exports = { bot: bot, init: (bot) => { console.log('Bot initialization hook') }, server: (req, res, next) => { console.log('Http request hook') }, options: { telegram: { agent: new HttpsProxyAgent('proxy url') } }, tlsOptions: { key: readFileSync('server-key.pem'), cert: readFileSync('server-cert.pem'), ca: [ // This is necessary only if the client uses the self-signed certificate. readFileSync('client-cert.pem') ] } } ``` ### Stages & Scenes ```js const { Composer, Stage, Scene, session } = require('micro-bot') // Greeter scene const greeter = new Scene('greeter') greeter.enter((ctx) => ctx.reply('Hi')) greeter.leave((ctx) => ctx.reply('Buy')) greeter.hears(/hi/gi, (ctx) => ctx.scene.leave()) greeter.on('message', (ctx) => ctx.reply('Send `hi`')) const stage = new Stage() stage.register(greeter) const bot = new Composer() bot.use(session()) bot.use(stage) bot.command('greeter', (ctx) => ctx.scene.enter('greeter')) bot.command('cancel', (ctx) => ctx.scene.leave()) module.exports = bot ``` ## Credits `micro-bot` is highly inspired by [`Micro`](https://github.com/zeit/micro/)