Giter Club home page Giter Club logo

typedgram-bot's Introduction

Typedgram Bot

npm version Build Status dependencies

Interactive Telegram Bot API.

To start with a deploy-ready template see: typedgram-bot-openshift-template

Install

This project uses node-telegram-bot-api Node module. Make sure you have installed Node and npm.

$ npm install --save typedgram-bot

If you are using tsd, run tsd link to import the typings. This should import to your typings/tsd.d.ts:

/// <reference path="../node_modules/typedgram-bot/definitions/src/typedgram-bot.d.ts" />
/// <reference path="../node_modules/typedgram-bot/definitions/src/node-telegram-bot-api.d.ts"/>

Typescript Usage

This project interacts with Telegram using webhooks, so make sure you have access to your server ip, port and host.

Make sure you have installed Typescript:

npm install -g typescript
Token

Go talk to Telegram's official bot: @BotFather and ask for a token.

Setup

There are three default actions for every bot:

  • initializationAction: When the bot start and it's registered in Telegram servers.
  • missingAction: When someone executes a command / without associated action.
  • plainTextAction: When simple text (without commands /) is inputed.
Example
/// <reference path="../typings/tsd.d.ts"/>

import {TelegramTypedBot as Bot, IServerOptions, TelegramEvent} from 'typedgram-bot'

const PORT = process.env.PORT                     // do not choose 443
const TELEGRAM_TOKEN = process.env.TELEGRAM_TOKEN // from @botfather
const HOST = process.env.LOCAL_IP                 // Example: 127.0.0.1
const DOMAIN = process.env.LOCAL_URL              // mybot.domain.com

const server: IServerOptions = {
    host: HOST,
    port: PORT,
    domain: DOMAIN,
}

const bot = new Bot(TELEGRAM_TOKEN, server);

bot.onInitialization(me => {
    console.log(`
    ------------------------------
    Bot successfully deployed!
    ------------------------------
    Bot info:
    - ID: ${me.id}
    - Name: ${me.first_name}
    - Username: ${me.username}

    Server info:
    - Host: ${server.host}
    - Port: ${server.port}
    - Domain: ${server.domain}
    - Node version: ${process.version}
    ------------------------------
    `)
})

How to response to /commands

When you register a command the associated method will be called. You can declare associate multiple commands to the same action.

Example
bot.onCommand(['/hello_world', '/hello'], msg => {
    return bot.sendMessage(msg.chat.id, 'Hello world!')
}

Interactive Responses

To make the interactions with the API easier, after sending a message of any type, make the resolve promise of that operation to wait for the user reply with bot.waitResponse(msg) where msg is the message from the user who triggered the interactive operation. This works saving the userId and the chatId.

Also, there is a timeout of 10000ms that you can change by adding a second parameter, example: bot.waitResponse(msg, 20000).

You can change the default value:

bot.responseTimeout = 20000

On timeout the promise is rejected with a TimeoutError. See: Bluebird API reference.

Example
bot.onCommand(['/apps', '/applications'], msg => {
    return bot.sendMessage(msg.chat.id, 'Select an app', {
        reply_to_message_id: msg.message_id,
        reply_markup: {
            keyboard: [
                ['Telegram'],
                ['Whatsapp'],
            ],
            force_reply: true,
            one_time_keyboard: true,
            selective: true
        },
    })
    .then(bot.waitResponse(msg)) // Here!
    .then(response => {
        const keyboard = {
            reply_to_message_id: response.message_id,
            reply_markup: {
                hide_keyboard: true
            }
        }

        switch (response.text) {
            case 'Telegram': {
                return bot.sendPhoto(response.chat.id, './example/images/telegram.png', keyboard)
            }
            case 'Whatsapp': {
                return bot.sendPhoto(response.chat.id, './example/images/whatsapp.png', keyboard)
            }
            default: {
                return bot.sendMessage(response.chat.id, 'None selected', keyboard)
            }
        }
    })
})

See examples or check the definitions. There is a example showing how to use it on a Javascript project.

Development

To develop your bot locally, you need a secure connection to your local host. One way to achieve this is using a ngrok to create a tunnel to your computer.

Example

Once installed, create a tunnel to your app.

$ ngrok 8080

# Tunnel Status                 online
# Version                       1.7/1.7
# Forwarding                    http://SUBDOMAIN.ngrok.com -> 127.0.0.1:8080
# Forwarding                    https://SUBDOMAIN.ngrok.com -> 127.0.0.1:8080
# Web Interface                 127.0.0.1:4040
# # Conn                        0
# Avg Conn Time                 0.00ms

Then we set our development environment variables.

$ export TELEGRAM_TOKEN="TOKEN"
$ export PORT="8080"
$ export LOCAL_IP="127.0.0.1"
$ export LOCAL_URL="SUBDOMAIN.ngrok.com"

Run your bot and it everything is ok, the initializationAction should be executed.

typedgram-bot's People

Contributors

lopezjurip avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.