0.1.2 • Published 3 years ago

icq-bot-sdk v0.1.2

Weekly downloads
6
License
MIT
Repository
github
Last release
3 years ago

npm deps Build Status size

icq-bot-sdk

ICQ New Bot SDK for Node.js.

This client is build on top of the ICQ New bot API.

The full description of the bot api can be found on icq.com/botapi/ or agent.mail.ru/botapi/.

Getting Started

Create your own bot by sending the /newbot command to Metabot and follow the instructions.

Installation

$ npm install icq-bot-sdk --save

Usage

const ICQClient = require('icq-bot-sdk').default;

const icqBot = ICQClient({
  token: process.env.ICQ_BOT_TOKEN, // your bot token goes here
});

icqBot.on('error', (error) => {
  console.log(error);
  icq.stop(); // stop event loop or handle error some other way
});

icqBot.on('newMessage', (result) => {
  // do something with the result
});

icqBot.on('all', (result) => {
  // handle every new event here
});

icqBot.startPolling(); // start event loop

Construction

Usage:

const ICQClient = require('icq-bot-sdk').default;

const eventIdStorage = {
  id: 0,
  async getId() { return this.id; },
  async setId(id) { this.id = id; },
},

const icqBot = ICQClient({
  token: process.env.ICQ_BOT_TOKEN, // your bot token goes here
  pollTime: 2,
  timeout: 3,
  eventIdStorage,
});

Description:

Create a new instance of the ICQ Bot client.

Parameters:

NameTypeDescriptionNotes
tokenStringSecret token that you've recieved from the Metabot.required
pollTimeIntegerTime for keeping the connection alive (secs) during events polling.optional
timeoutIntegerTime for sleeping between long polling requests to the server (secs).optional
eventIdStorageObjectObject with two async methods getId and setId to track the last known server event id.optional

Instance methods

MethodDescription
startPollingStart polling events from the server
stopStop polling
onSubscribe to the event from server
offUnsubscribe from the event from server
chats.blockUserBlock a user in a chat
chats.getAdminsGet the list of admins
chats.getBlockedUsersGet the list of all users that have been banned in the chat
chats.getInfoGet the info about a chat
chats.getMembersGet the list of all members of a chat
chats.getPendingUsersGet the list of users waiting to be accepted into chat.
chats.pinMessagePin a missage in the chat
chats.resolvePendingDecide whether to accept or not pending users.
chats.sendActionsSend an action to a chat
chats.setAboutChange the description of a chat
chats.setRulesChange the rules for the chat
chats.setTitleChange the title of a chat
chats.unblockUserUnblock a user in a chat
chats.unpinMessageUnpin a message in a chat
events.getGet events
files.getInfoGet info about a file
messages.answerCallbackQueryA button click handler
messages.deleteMessagesDelete messages
messages.editTextEdit a message
messages.sendFileSend a previously loaded file
messages.sendVoiceSend a previously uploaded voice message
messages.sendTextSend a message
messages.uploadAndSendFileUpload and send a new file
messages.uploadAndSendVoiceUpload and send a new voice message
self.getGet info about the bot

General API

startPolling

Usage:

icqBot
  .startPolling({
    pollTime: 1, 
    timout: 3,
  });

Description:

Start polling events from the server.

Parameters:

NameTypeDescriptionNotes
pollTimeIntegerTime for keeping the connection alive (secs).optional
timeoutIntegerTime for sleeping between requests to the server (secs).optional

stop

Usage:

icqBot.stop();

Description:

Stop polling events from the server.

on

Usage:

icqBot
  .on('newMessage', function handler({ payload: { chat }}) {
      this.messages.sendVoice({
        chatId: chat.chatId,
        text: 'Some text',
      })
  });

Description:

Add event listener to an event from the server.

The instance of EventEmitter is actually in the prototype chain of the icqBot object. It means it's possible to use any method on EventEmitter including the on method.

The list of available events is: newMessage, editedMessage, deletedMessage, pinnedMessage, unpinnedMessage, newChatMembers, leftChatMembers, callbackQuery

The event object passed to the event handler is depends on the type of the event. See icq.com/botapi/ for more details.

on

Usage:

icqBot
  .off('newMessage', someHandler);

Description:

Remove event listener to an event from the server.

The instance of EventEmitter is actually in the prototype chain of the icqBot object. It means it's possible to use any method on EventEmitter including the off method.

The list of available events is: newMessage, editedMessage, deletedMessage, pinnedMessage, unpinnedMessage, newChatMembers, leftChatMembers, callbackQuery

Chats API

chats.blockUser

Usage:

icqBot
  .chats.blockUser({
    chatId: 'some-id',
    userId: 'some-id',
    delLastMessages: true,
  })
  .then(handleResult)
  .catch(handleError);

Description:

Block a user in a chat

If the user was a member of the chat, he is going to be removed from the chat and banned. It is also possible to delete the user's last messages delLastMessages. The bot has to be an admin of the chat in order to be able to perform these actions.

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, group id or channel id. Id can be obtained from events (chatId).required
userIdStringUnique user nick or id.required
delLastMessagesBooleanDelete last messages of the given user.optional

Result example:

{
    "ok": true // required
}

chats.getAdmins

Usage:

icqBot
  .chats.getAdmins({
    chatId: 'some-id',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Get the list of admins

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, group id or channel id. Id can be obtained from events (chatId).required

Result:

The list of admins.

Result example:

{
  "admins": [
    {
      "userId": "string", // required
      "creator": true // optional
    }
  ]
}

chats.getBlockedUsers

Usage:

icqBot
  .chats.getBlockedUsers({
    chatId: 'some-id',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Get the list of all users that have been banned in the chat

The bot has to be an admin of the chat in order to be able to perform this action.

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, group id or channel id. Id can be obtained from events (chatId).required

Result:

The list of blocked users.

Result example:

{
  "users": [
    {
      "userId": "string"
    }
  ]
}

chats.getInfo

Usage:

icqBot
  .chats.getInfo({
    chatId: 'some-id',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Get the info about a chat

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, chat id or user id. Id could be obtained from incoming events (поле chatId).required

Result:

The info about about the chat.

Result example:

{
  "type": "private",
  "firstName": "Name",
  "lastName": "Surname",
  "nick": "nickname",
  "about": "Information about user",
  "isBot": true
}

chats.getMembers

Usage:

icqBot
  .chats.getMembers({
    chatId: 'some-id',
    cursor: 'cursor',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Get the list of all members of the chat.

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, chat id or user id. Id could be obtained from incoming events (поле chatId).required
cursorStringIdentifier for obtaining the continuation of the users' list. The cursor can be obtained from the first/previous getMembers request.optional

Result:

The list of all members of the chat.

Result example:

{
  "members": [
    {
      "userId": "string",
      "creator": true
    }
  ]
}

chats.getPendingUsers

Usage:

icqBot
  .chats.getPendingUsers({
    chatId: 'some-id',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Get the list of users waiting to be accepted into chat.

The bot has to be an adming of the chat in order to be able to perform this action

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, chat id or user id. Id could be obtained from incoming events (поле chatId).required

Result:

The list of pending users.

Result example:

{
  "users": [
    {
      "userId": "string"
    }
  ]
}

chats.pinMessage

Usage:

icqBot
  .chats.pinMessage({
    chatId: 'some-id',
    msgId: 156,
  })
  .then(handleResult)
  .catch(handleError);

Description:

Pin a missage in the chat

The bot has to be an adming of the chat in order to be able to perform this action

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, chat id or user id. Id could be obtained from incoming events (поле chatId).required
msgIdIntegerMessage id.required

Result example:

{
    "ok": true // required
}

chats.resolvePending

Usage:

icqBot
  .chats.resolvePending({
    chatId: 'some-id',
    userId: 'some-id',
    approve: true,
  })
  .then(handleResult)
  .catch(handleError);

Description:

Decide whether to accept or not pending users.

One of the params userId or everyone has to be sent. You can`t send both these params. The bot has to be an adming of the chat in order to be able to perform this action.

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, chat id or user id. Id could be obtained from incoming events (поле chatId).required
approveBooleanApprove or reject.required
userIdStringUser nick or id who is waiting for joining the chat. Can't be sent with the everyone param.optional
everyoneBooleanDecision about all the users waiting for joining the chat. Can't be sent with the userId param.optional

Result example:

{
    "ok": true // required
}

chats.sendActions

Usage:

icqBot
  .chats.sendActions({
    chatId: 'some-id',
    actions: ['looking', 'typing'],
  })
  .then(handleResult)
  .catch(handleError);

Description:

Send an action to a chat

The method have to be called on every change of the action or every 10 seconds if the action hasn't been changed. After the request with action has been sent there is no point in sending message about the empty action.

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, chat id or user id. Id could be obtained from incoming events (поле chatId).required
actionsList of actions' stringsCurrent actions in the chat. Send empty if all actions have been finished.required

Result example:

{
    "ok": true // required
}

chats.setAbout

Usage:

icqBot
  .chats.setAbout({
    chatId: 'some-id',
    about: 'Info about the chat',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Change the description of a chat

The bot has to be an adming of the chat in order to be able to perform this action

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, chat id or user id. Id could be obtained from incoming events (поле chatId).required
aboutStringChat descriptionrequired

Result example:

{
    "ok": true // required
}

chats.setRules

Usage:

icqBot
  .chats.setRules({
    chatId: 'some-id',
    rules: 'Rules of the chat',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Change the rules for the chat

The bot has to be an adming of the chat in order to be able to perform this action

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, chat id or user id. Id could be obtained from incoming events (поле chatId).required
rulesStringChat rulesrequired

Result example:

{
    "ok": true // required
}

chats.setTitle

Usage:

icqBot
  .chats.setTitle({
    chatId: 'some-id',
    title: 'Title of the chat',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Change the title of a chat

The bot has to be an adming of the chat in order to be able to perform this action

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, chat id or user id. Id could be obtained from incoming events (поле chatId).required
titleStringChat titlerequired

Result example:

{
    "ok": true // required
}

chats.unblockUser

Usage:

icqBot
  .chats.unblockUser({
    chatId: 'some-id',
    userId: 'some-id',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Unblock a user in a chat

The bot has to be an adming of the chat in order to be able to perform this action

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, chat id or user id. Id could be obtained from incoming events (поле chatId).required
userIdStringUnique user nick or id.required

Result example:

{
    "ok": true // required
}

chats.unpinMessage

Usage:

icqBot
  .chats.unpinMessage({
    chatId: 'some-id',
    msgId: 149,
  })
  .then(handleResult)
  .catch(handleError);

Description:

Unpin a message in a chat

The bot has to be an adming of the chat in order to be able to perform this action

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, chat id or user id. Id could be obtained from incoming events (поле chatId).required
msgIdIntegerMessage id.required

Result example:

{
    "ok": true // required
}

Events API

events.get

Usage:

icqBot
  .events.get({
    lastEventId: 35,
    pollTime: 1,
  })
  .then(handleResult)
  .catch(handleError);

Description:

Get events

Every event has an identifier eventId. When you call the method you have to send the biggest knonw event id in the parameter lastEventId. For the first call set this param to 0. If there are no events on the server at the moment of the call, the connection is going to be kept alive. As soon as an event has occured the server will send it back and close the connection. If after pollTime seconds of waiting no events have been emitted, the server will return an empty array of events.

Parameters:

NameTypeDescriptionNotes
lastEventIdIntegerId of the last known event.required
pollTimeIntegerTime for keeping the connection alive (secs).required

Result:

A list of events since lastEventId.

Result example:

{
  "events": [
    {
      "eventId": 1,
      "type": "newMessage",
      "payload": {
        "msgId": "57883346846815032",
        "chat": {
          "chatId": "681869378@chat.agent",
          "type": "channel",
          "title": "The best channel"
        },
        "from": {
          "userId": "1234567890",
          "firstName": "Name",
          "lastName": "SurName"
        },
        "timestamp": 1546290000,
        "text": "Hello!",
        "parts": [
          {
            "type": "sticker",
            "payload": {
              "fileId": "2IWuJzaNWCJZxJWCvZhDYuJ5XDsr7hU"
            }
          }
        ]
      }
    }
  ]
}

Files API

files.getInfo

Usage:

icqBot
  .files.getInfo({
    fileId: 'some-id',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Get info about a file

Parameters:

NameTypeDescriptionNotes
fileIdStringId of the previously uploaded file.required

Result:

Information about a file.

Result example:

{
  "type": "video",
  "size": 20971520,
  "filename": "VIDEO.mkv",
  "url": "https://example.com/get/88MfCLBHphvOAOeuzYhZfW5b7bcfa31ab"
}

Messages API

messages.answerCallbackQuery

Usage:

icqBot
  .messages.answerCallbackQuery({
    chatId: 'some-id',
    userId: 'Some text',
    showAlert: true,
  })
  .then(handleResult)
  .catch(handleError);

Description:

A button click handler

Use the method whenever the event callbackQuery is received

Parameters:

NameTypeDescriptionNotes
queryIdStringId of the callback query received by the botrequired
textStringText that is going to be shown to a user. If not set, nothing will be shown.optional
showAlertBooleanIf it has been set to true, the alert is going to be shown instead of notification.optional
urlStringURL to open by a client appoptional

Result example:

{
    "ok": true // required
}

messages.deleteMessages

Usage:

icqBot
  .messages.deleteMessages({
    chatId: 'some-id',
    msgId: ['some-id'],
  })
  .then(handleResult)
  .catch(handleError);

Description:

Delete messages

There are some limitations when the method could be used. See the official docs for more details

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, group id or channel id. Id can be obtained from events (chatId).required
msgIdList of message idsMessages ids.required

Result example:

{
    "ok": true // required
}

messages.editText

Usage:

icqBot
  .messages.editText({
    chatId: 'some-id',
    msgId: 'some-id',
    text: 'Some text',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Edit a message

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, group id or channel id. Id can be obtained from events (chatId).required
msgIdIntegerMessage id.required
textStringMessage text. A user can be tagged in a format @userId.required

Result example:

{
    "ok": true // required
}

messages.sendFile

Usage:

icqBot
  .messages.sendFile({
    chatId: 'some-id',
    fileId: 'some-id',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Send a previously loaded file

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, group id or channel id. Id can be obtained from events (chatId).required
fileIdStringId of the previously uploaded file.required
captionStringFile caption.optional
replyMsgIdList of message idsId of a quoted message. Can't be sent with forwardChatId and forwardMsgId params.optional
forwardChatIdStringChat id from which a message is going to be forwarded. Set only with the forwardMsgId. Can't be set with the replyMsgId param.optional
forwardMsgIdList of message idsMessage id to forwaded. Set only with the forwardChatId. Can't be set with the replyMsgId param.optional

Result example:

{
  "msgId": "57883346846815032",
  "ok": true
}

messages.sendVoice

Usage:

icqBot
  .messages.sendVoice({
    chatId: 'some-id',
    fileId: 'some-id',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Send a previously uploaded voice message

The format of a message should be aac, ogg or m4a.

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, group id or channel id. Id can be obtained from events (chatId).required
fileIdStringId of the previously uploaded file.required
replyMsgIdList of message idsId of a quoted message. Can't be sent with forwardChatId and forwardMsgId params.optional
forwardChatIdStringChat id from which a message is going to be forwarded. Set only with the forwardMsgId. Can't be set with the replyMsgId param.optional
forwardMsgIdList of message idsMessage id to forwaded. Set only with the forwardChatId. Can't be set with the replyMsgId param.optional

Result example:

{
  "msgId": "57883346846815032",
  "ok": true
}

messages.sendText

Usage:

icqBot
  .messages.sendText({
    chatId: 'some-id',
    text: 'Some text',
  })
  .then(handleResult)
  .catch(handleError);

Description:

Send a message

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, group id or channel id. Id can be obtained from events (chatId).required
textStringMessage text. A user can be tagged in a format @userId.required
replyMsgIdList of message idsId of a quoted message. Can't be sent with forwardChatId and forwardMsgId params.optional
forwardChatIdStringChat id from which a message is going to be forwarded. Set only with the forwardMsgId. Can't be set with the replyMsgId param.optional
forwardMsgIdList of message idsMessage id to forwaded. Set only with the forwardChatId. Can't be set with the replyMsgId param.optional

Result example:

{
  "msgId": "57883346846815032",
  "ok": true
}

messages.uploadAndSendFile

Usage:

icqBot
  .messages.uploadAndSendFile({
    chatId: 'some-id',
    file: someFile,
  })
  .then(handleResult)
  .catch(handleError);

Description:

Upload and send a new file

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, group id or channel id. Id can be obtained from events (chatId).required
captionStringFile caption.optional
replyMsgIdList of message idsId of a quoted message. Can't be sent with forwardChatId and forwardMsgId params.optional
forwardChatIdStringChat id from which a message is going to be forwarded. Set only with the forwardMsgId. Can't be set with the replyMsgId param.optional
forwardMsgIdList of message idsMessage id to forwaded. Set only with the forwardChatId. Can't be set with the replyMsgId param.optional
fileFileFileoptional

Result example:

{
  "fileId": "0dC76vcKS3XZOtG5DVs9y15d1daefa1ae",
  "msgId": "57883346846815032",
  "ok": true
}

messages.uploadAndSendVoice

Usage:

icqBot
  .messages.uploadAndSendVoice({
    chatId: 'some-id',
    file: someFile,
  })
  .then(handleResult)
  .catch(handleError);

Description:

Upload and send a new voice message

The format of a message should be aac, ogg or m4a.

Parameters:

NameTypeDescriptionNotes
chatIdStringUnique nick, group id or channel id. Id can be obtained from events (chatId).required
replyMsgIdList of message idsId of a quoted message. Can't be sent with forwardChatId and forwardMsgId params.optional
forwardChatIdStringChat id from which a message is going to be forwarded. Set only with the forwardMsgId. Can't be set with the replyMsgId param.optional
forwardMsgIdList of message idsMessage id to forwaded. Set only with the forwardChatId. Can't be set with the replyMsgId param.optional
fileFileFileoptional

Result example:

{
  "fileId": "0dC76vcKS3XZOtG5DVs9y15d1daefa1ae",
  "msgId": "57883346846815032",
  "ok": true
}

Self API

self.get

Usage:

icqBot
  .self.get()
  .then(handleResult)
  .catch(handleError);

Description:

Get info about the bot

The method can be used to check if token is valid.

Result:

Information about the bot.

Result example:

{
  "userId": "747432131",
  "nick": "test_api_bot",
  "firstName": "TestBot",
  "about": "The description of the bot",
  "photo": [
    {
      "url": "https://example.com/expressions/getAsset?f=native&type=largeBuddyIcon&id=0110379ad781bcc4a969242f1f5a93144362"
    }
  ],
  "ok": true
}

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT