Giter Site home page Giter Site logo

tgapi's Introduction

tgapi

Telegram bot API. Flow-compatible. Without unnecessary explicit dependencies in runtime.

Installation

npm install --save tgapi

Usage

import BotClient from 'tgapi';
import sendRequest from 'tgapi/sendRequest';

const token = 'bla-bla-bla';

const bot = new BotClient(token, sendRequest);

bot.getMe()
  .then(userObject => console.log(userObject));

bot.getUpdates({ offset: 100500 })
  .then(updatesArray => console.log(updatesArray));

sendRequest is the default implementation of the method of sending http requests to Telegram server. You can to use another. sendRequest must receive the bot token as first argument and Telegram API method parameters and must returns Promise.

Advansed usage

bot.on('updateReceived', update => console.log(update));

bot.startWatchUpdates(1);
// Will check updates each 1 second and emit updateReceived event
// after each one update.

Webhooks

If you want to use webhooks, you can use this http-server:

import BotClient from 'tgapi';
import sendRequest from 'tgapi/sendRequest';
import pureServer from 'tgapi/pureServer';

const bot = new BotClient('your token', sendRequest);

const server = pureServer(bot, 'your/webhook/path');

server.listen(80, () => console.log(
  'Webhook are available on http://localhost/your/webhook/path'
));

bot.on('updateReceived', update => console.log(update));

BotClient methods

createReaction method

Creates a promise that will be resolved if the update predicate returns true or will be rejected if the timeout has expired. Timeout default value is 300000 ms (5 min). You can disable timeout by setting this value to 0, but it creates memory leak danger.

const predicate = (update) => (
  update.message &&
  update.message.text === 'Hello'
);

                // Set timeout to 10 min
bot.createReaction(1000 * 60 * 10)(predicate)
  .then(update => bot.sendMessage({
    chat_id: update.message.chat.id,
    text: 'Hi!',
  }))
  .catch(() => console.log('Nobody wants to greet me. =('));

createInlineButton method

type CreateInlineButton =
  (text: string, timeout?: number = 1000 * 60 * 5) =>
    (buttonId?: string) => {
      markup: InlineKeyboardButton,
      promise: Promise<CertainButtonPressedEvent>,
    };

Creates a InlineKeyboardButton markup and Promice that pending the press event. Promise resolves with inlineButtonPressed/<buttonId> event:

const createHelloButton = bot.createButton('Hi!', 1000 * 60 * 10);
const createOkButton = bot.createButton('OK!');
const createNoButton = bot.createButton('No, sorry.');

const helloButton = createHelloButton(Math.random());
const okButton = createOkButton();
const noButton = createNoButton();

bot.sendMessage({
  chat_id, text: 'Hello?',
  reply_markup: { inline_keyboard: [[helloButton.markup]] },
});

helloButton.promise
  .then(() => bot.sendMessage({
    chat_id, text: 'Let\'s talk?',
    reply_markup: { inline_keyboard: [[
      okButton.markup,
      noButton.markup,
    ]] },
  }));

okButton.promise.then(() => bot.sendMessage({ chat_id, text: 'What\'s your name?' }));
noButton.promise.then(() => bot.sendMessage({ chat_id, text: 'OK... =(' }));

Events

updateReceived event

Emitted each any update. Receives Update type.

commandReceived event

Emitted each any bot command. Receives CommandEvent type.

commandReceived/<command> event

Emitted each specific bot command. Receives CommandEvent type. Example:

bot.on('commandReceived/start', sendHelloMessage);

inlineButtonPressed event

Emitted each callback_query update. Receives ButtonPressedEvent type.

inlineButtonPressed/<buttonId> event

Emitted each callback_query update with specified buttonId. Receives CertainButtonPressedEvent type. For emit this event callback_query.data must be JSON object winth string or number buttonId property:

{ "buttonId": 1,
  "anyAnotherProperty": "value" }

Types

Native API methods support

  • getUpdates
  • setWebhook
  • deleteWebhook
  • getWebhookInfo
  • getMe
  • sendMessage
  • forwardMessage
  • sendPhoto
  • sendAudio
  • sendDocument
  • sendSticker
  • sendVideo
  • sendVoice
  • sendLocation
  • sendVenue
  • sendContact
  • sendChatAction
  • getUserProfilePhotos
  • getFile
  • kickChatMember
  • leaveChat
  • unbanChatMember
  • getChat
  • getChatAdministrators
  • getChatMembersCount
  • getChatMember
  • answerCallbackQuery
  • answerInlineQuery
  • sendGame
  • setGameScore
  • getGameHighScores

tgapi's People

Contributors

bigslycat 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.