Giter VIP home page Giter VIP logo

node-vk-bot's Introduction

Build Status

README на русском

VK BOTS

  • Create and control VK bots easily.
  • Uses LongPoll or Callback API to get new messages
npm install --save node-vk-bot

If you are cloning this repository, remember to run npm install to install dependencies.

Example

const { Bot, Keyboard } = require('node-vk-bot')

const bot = new Bot({
  token: 'YOUR TOKEN',
  group_id: 123456
}).start()

bot.get(/Hi|Hello|Hey/i, (message, exec, reply) => {
  const keyboard = new Keyboard().addButton('Hi!')
  const options =  { forward_messages: message.id, keyboard }

  reply('Hello!', options)
})

More examples (how to use webhooks, upload pictures, ...)

Bots created with this library

if you want your bot to be in this list, just make a pull request

Table of contents

Getting Started

In the example above you can see a super simple VK Bot. This bot will answer our greetings, that's all.

Let's explain the code, it's pretty simple.

  1. Then I create a bot instance with my group's token.
  2. By calling bot.start() the bot starts polling updates from the server.
  3. Then I simply listen on messages which pass the RegExp test, when I get such message, Then I send a new message with text 'Hello' to that chat with a forwarded message.

Bot

The class used to create new bots, it takes a single argument, an options object.

new Bot({
  token: 'TOKEN',
  group_id: 123456
  api: {
    v: 5.80, // >= 5.80
    lang: 'ru'
  }
})
Parameter Type Required
token String Yes
group_id Number Yes
api Object No
controllers String[] No

api is object with API settings: version and language. (both strings) (Read more)


Methods

start

Starts polling updates from API. Emits an update event after getting updates with the response from server. Update examples.


get

Listens on specific message matching the RegExp pattern.

bot.get(/Hello/i, (msg, exec, reply) => {
  console.log(msg)
  reply('Hi!')
})

The argument passed to callback is a Message object, result of pattern.exec(text) and a reply function.

reply takes text as first argument and optional message.send parameters as second.


getPayload

Listens for specific payload (used for keyboards) This is a syntactic sugar for the payload event

bot.getPayload('{"command": "start"}', (msg, reply) => console.log(msg))

Arguments: json string and listener


send

Sends message.

bot.send('text', peer_id, params)

uploadPhoto

Upload a photo.

The only parameter is an absolute path to picture or a stream object. Returns a Promise that resolves with a photo object

bot.uploadPhoto('~/kittens.png').then(photo => {
  console.log(photo)
})

let stream = fs.createReadStream('./kittens.png')
bot.uploadPhoto(stream).then(photo => {
  console.log(photo)
})

api

Access VK API.

bot.api('users.get', { user_ids: 1 })
  .then(res => console.log(res[0].first_name)) // Pavel

When using execute method, this function returns full response object. (Because there may be errors and responses in same object).


processUpdate

Process an update from Callback API. Example of usage may be found in examples folder


stop

Stops the bot from listening on updates.

bot.stop()

Events

update

The update event is emitted whenever there is a response from LongPoll.

bot.on('update', update => {
  if (update.from_id === 1) {
    console.log('Got a message from Pavel Durov!');
  }
})

voice

The voice event is emitted whenever there is a new voice message. (emits Message object)


sticker

The sticker event is emitted whenever there is a new incoming sticker. (emits Message object)


payload

Emitted when bot recieves a message with json payload (used in keyboards) Emits Message object and reply function


poll-error

The poll-error event is emitted whenever there is an error occurred in LongPoll.

bot.on('poll-error', error => {
  console.error('error occurred on a working with the Long Poll server ' +
    `(${util.inspect(error)})`)
})

command-notfound

This event is emitted whenever there's no .get() listeners matching

bot.on('command-notfound', msg => {
  bot.send('What?', msg.peer_id)
})

Keyboard

The class used to create keyboards in messages

bot.get(/Hi|Hello|Hey/i, message => {
  const keyboard = new Keyboard(true)
    .addButton('Red', KeyboardColor.NEGATIVE)
    .addButton('Green', KeyboardColor.POSITIVE)
    .addRow()
    .addButton('Blue', KeyboardColor.PRIMARY)
    .addButton('White')

  bot.send('Hello!', message.peer_id, keyboard)
});

Full example

The only argument - one_time If true, the keyboard hides after user replies

new Keyboard(true)

addButton

Add a button to the last row.

Parameters:

  • label (string) - Text on button (required)
  • color (string or KeyboardColor)
  • payload (any) - A parameter for Callback API

Maximum amount of buttons in one row is 4


addRow

Add a new row to the keyboard.

Maximum amount of rows is 10


toString

Get the keyboard as a JSON string


KeyboardColor

addButton('label', KeyboardColor.NEGATIVE)

Available colors:

  • PRIMARY - blue
  • DEFAULT - white
  • NEGATIVE - red
  • POSITIVE - green

The Message Object

interface Message {
  id: number,
  peer_id: number,
  date: number,
  text: string,
  from_id: number,
  attachments: any,
  important: boolean,
  conversation_message_id: number,
  fwd_messages: any
}

// Reference: https://vk.com/dev/objects/message

node-vk-bot's People

Contributors

codacy-badger avatar daggett206 avatar dmitrytarassov avatar panarama360 avatar renovate-bot avatar renovate[bot] avatar thewizardplusplus avatar uza-anna avatar vitalyavolyn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-vk-bot's Issues

Bot answers with recursion

Hi, I just tried this simple code and got an answer with recursion

bot.get(/hi|hello|hey/i, message => {
 
    bot.send('whats up man!', message.peer_id)
})

bot.on('command-notfound', msg => {
    console.log(msg);
    bot.send('What?', msg.peer_id)
})

image

it seems like 'whats up man!' is identified as 'command-notfound' and starts to send 'What?' and so on.
I think the bot shouldn't respond to its messages at all

Bot is not defined

Hi, I'm new at this.

but when I run node in my console and then try to create a bot with my token I get following error.

ReferenceError: Bot is not defined
    at repl:1:1
    at ContextifyScript.Script.runInThisContext (vm.js:50:33)
    at REPLServer.defaultEval (repl.js:240:29)
    at bound (domain.js:301:14)
    at REPLServer.runBound [as eval] (domain.js:314:12)
    at REPLServer.onLine (repl.js:442:10)
    at emitOne (events.js:121:20)
    at REPLServer.emit (events.js:211:7)
    at REPLServer.Interface._onLine (readline.js:282:10)
    at REPLServer.Interface._line (readline.js:631:8)

Ненужное приведение к json

if (JSON.stringify(JSON.parse(msg.payload)) === JSON.stringify(JSON.parse(jsonString))) {

вот тут.

 if (JSON.stringify(JSON.parse(msg.payload)) === (jsonString)){

корректный вариант. Иначе падает, так как вк изменил формат данных

Do nothing if send attachment without text

I think needs to add one more checking (for attachments in the message) in _update method.

const hasAttachments : boolean = !!Object.keys(update[7]).length;

and then add this to existing checking

if (!text && !hasAttachments) return

so now it won't break if I just forward any attachment without text to bot.

what do you think?

имеет ли лимиты вызов отправки сообщения методом reply

Я не совсем въехал в Long Pull.

есть ли лимиты в ответе сообщений с помощью вызова reply?
bot.get(/.*/i, async (message, exec, reply) => {
reply('Hello');
});

Я знаю, есть у вк лимит 20 запросов в секунду.

В моем боте необходимо отправлять много сообщений в секунду. Со своей оберткой на PHP я использовал метод execute в котором вызывал метод send несколько раз для многих юзеров.

Можешь сказать как здесь будет работать твой метод?

Pass `reply` function to callbacks as an argument

Right now, if command module is in another file, sending messages works like this

// index.ts
import module from './modules/hello'

const bot =  new Bot({...})
export default bot

bot.get(module.regex, module.callback)

// modules/hello.ts

import bot from '../'
export const regex = /Hi/i
export function callback (msg, exec) {
  bot.send('Hi', msg.peer_id)
}

There's a way to make it shorter - pass a reply fn that sends text to peer_id of the message

// index.ts
import module from './modules/hello'

const bot =  new Bot({...})

bot.get(module.regex, module.callback)

// modules/hello.ts
export const regex = /Hi/i
export function callback (msg, exec, reply) {
  reply('Hi')
}

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.