Giter Site home page Giter Site logo

sts0mrg0 / node-vk-bot-api Goto Github PK

View Code? Open in Web Editor NEW

This project forked from node-vk-bot-api/node-vk-bot-api

0.0 1.0 0.0 168 KB

๐Ÿค– VK bot framework for Node.js, based on Bots Long Poll API.

Home Page: https://npmjs.com/package/node-vk-bot-api

License: MIT License

JavaScript 100.00%

node-vk-bot-api's Introduction

node-vk-bot-api node-vk-bot-api node-vk-bot-api

node-vk-bot-api

๐Ÿค– VK bot framework for Node.js, based on Bots Long Poll API and Callback API.

Install

$ npm i node-vk-bot-api -S

Usage

const VkBot = require('node-vk-bot-api')

const bot = new VkBot(process.env.TOKEN)

bot.command('/start', (ctx) => {
  ctx.reply('Hello!')
})

bot.startPolling()

Webhooks

const express = require('express')
const bodyParser = require('body-parser')
const VkBot = require('node-vk-bot-api')

const app = express()
const bot = new VkBot({
  token: process.env.TOKEN,
  confirmation: process.env.CONFIRMATION,
})

bot.on((ctx) => {
  ctx.reply('Hello!')
})

app.use(bodyParser.json())

app.post('/', bot.webhookCallback)

app.listen(process.env.PORT)

Examples

There's a few simple examples.

Community support

Any questions you can ask in the telegram chat. [russian/english]

Tests

$ npm test

Methods

constructor(settings)

Create bot.

// Simple usage
const bot = new VkBot(process.env.TOKEN)

// Advanced usage
const bot = new VkBot({
  token: process.env.TOKEN,
  group_id: process.env.GROUP_ID,
  execute_timeout: process.env.EXECUTE_TIMEOUT, // in ms   (50 by default)
  polling_timeout: process.env.POLLING_TIMEOUT, // in secs (25 by default)

  // webhooks options only
  secret: process.env.SECRET,                   // secret key (optional)
  confirmation: process.env.CONFIRMATION,       // confirmation string
})

.use(middleware)

Add simple middleware.

bot.use((ctx, next) => {
  ctx.message.timestamp = new Date().getTime()
  
  next()
})

.command(triggers, ...middlewares)

Add middlewares with triggers for message_new event.

bot.command('start', (ctx) => {
  ctx.reply('Hello!')
})

.event(triggers, ...middlewares)

Add middlewares with triggers for selected events.

bot.event('message_edit', (ctx) => {
  ctx.reply('Your message was editted')
})

.on(...middlewares)

Add reserved middlewares without triggers.

bot.on((ctx) => {
  ctx.reply('No commands for you.')
})

.sendMessage(userId, message, attachment, keyboard, sticker)

Send message to user.

// Simple usage
bot.sendMessage(145003487, 'Hello!', 'photo1_1')

// Advanced usage
bot.sendMessage(145003487, {
  message: 'Hello!',
  lat: 59.939095,
  lng: 30.315868,
})

.startPolling([callback])

Start polling with optional callback.

bot.startPolling(() => {
  console.log('Bot started.')
})

.webhookCallback(...args)

Get webhook callback.

// express
bot.webhookCallback(req, res, next)

// koa
bot.webhookCallback(ctx, next)

Context Methods

.reply(message, attachment, markup, sticker)

Helper method for reply to the current user.

bot.command('start', (ctx) => {
  ctx.reply('Hello!')
})

Markup

Keyboards

  • Markup.keyboard(buttons, options): Create keyboard
  • Markup.button(label, color, payload): Create custom button
  • Markup.oneTime(): Set oneTime to keyboard

Simple usage

ctx.reply('Select your sport', null, Markup
  .keyboard([
    'Football',
    'Basketball',
  ])
  .oneTime()
)

Advanced usage

ctx.reply('How are you doing?', null, Markup
  .keyboard([
    [
      Markup.button('Normally', 'primary'),
    ],
    [
      Markup.button('Fine', 'positive'),
      Markup.button('Bad', 'negative'),
    ],
  ])
)

.keyboard(buttons, options)

Create keyboard with optional settings.

/*

  Each string has maximum 2 columns.

  | one   | two   |
  | three | four  |
  | five  | six   |

 */

Markup.keyboard([
  'one',
  'two',
  'three',
  'four',
  'five',
  'six',
], { columns: 2 });
/*

  By default, columns count for each string is 4.

  | one | two | three |

 */

Markup.keyboard([
  'one',
  'two',
  'three'
]);

.button(label, color, payload)

Create custom button.

Markup.button('Start', 'positive', {
  foo: 'bar',
});

.oneTime()

Helper method for create one time keyboard.

Markup
  .keyboard(['Start', 'Help'])
  .oneTime();

Sessions

Store anything for current user in local (or redis) memory.

Usage

const VkBot = require('node-vk-bot-api')
const Session = require('node-vk-bot-api/lib/session')

const bot = new VkBot(process.env.TOKEN)
const session = new Session()

bot.use(session.middleware())

bot.on((ctx) => {
  ctx.session.counter = ctx.session.counter || 0
  ctx.session.counter++

  ctx.reply(`You wrote ${ctx.session.counter} messages.`)
})

bot.startPolling()

API

Options

  • key: Context property name (default: session)
  • getSessionKey: Getter for session key
Default getSessionKey(ctx)
const getSessionKey = (ctx) => {
  const userId = ctx.message.from_id || ctx.message.user_id;

  return `${userId}:${userId}`;
};

Stage

Scene manager.

const VkBot = require('node-vk-bot-api')
const Scene = require('node-vk-bot-api/lib/scene')
const Session = require('node-vk-bot-api/lib/session')
const Stage = require('node-vk-bot-api/lib/stage')

const bot = new VkBot(process.env.TOKEN)
const scene = new Scene('meet',
  (ctx) => {
    ctx.scene.next()
    ctx.reply('How old are you?')
  },
  (ctx) => {
    ctx.session.age = +ctx.message.text

    ctx.scene.next()
    ctx.reply('What is your name?')
  },
  (ctx) => {
    ctx.session.name = ctx.message.text

    ctx.scene.leave()
    ctx.reply(`Nice to meet you, ${ctx.session.name} (${ctx.session.age} years old)`)
  },
)
const session = new Session()
const stage = new Stage(scene)

bot.use(session.middleware())
bot.use(stage.middleware())

bot.command('/meet', (ctx) => {
  ctx.scene.enter('meet')
})

bot.startPolling()

API

Stage

  • constructor(...scenes): Register scenes

Scene

  • constructor(name, ...middlewares): Create scene
  • .command(triggers, ...middlewares): Create commands for scene

Context

ctx.scene.enter(name, [step]) // Enter in scene
ctx.scene.leave()             // Leave from scene
ctx.scene.next()              // Go to the next step in scene
ctx.scene.step                // Getter for step in scene
ctx.scene.step=               // Setter for step in scene

License

MIT.

node-vk-bot-api's People

Contributors

antosik avatar chappa74 avatar handlerug avatar ibakaidov avatar nocell avatar pelmeh avatar seitbekir avatar spb-web avatar vope avatar

Watchers

 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.