The simplest guide to creating a bot for analyzing messages in Telegram

There are Telegram channels that monitor certain events in the world. And we follow their messages so as not to miss anything important. If you collect and analyze data manually, the process will be time-consuming and require high human concentration. To solve this problem, our partner and front-end developer Vladilen Minin created a Telegram bot that automates the process and provides a summary of the collected information.

In this article we tell you how to use a neural network to create a bot that collects and processes information from messages, and deploy it to a cloud server.

Perhaps these texts will also interest you:

Introduction
Authorization
Implementation of functionality
Passing messages through a neural network
Deploy

Introduction


As an example, consider a bot that tracks the movement of cryptocurrencies:

/sum is the command to contact the bot, whale_alert_io is the channel ID (you can substitute any one), the rest of the text is an arbitrary command for the robot.

Authorization


The first step is to authorize your account to gain access to the bot's messages. This functionality is not available through a bot, so we will use
GramJS library.

Let's go to my.telegram.orgopen API development tools and create an application.

In the response we receive the apiId and apiHash parameters. Substitute the data into the authorization code:

const { TelegramClient } = require('telegram')
const input = require('input')
const { StringSession } = require('telegram/sessions')
const session = new StringSession('')
const apiId = 123 // подставляем данные из Telegram
const apiHash="abc" // подставляем данные из Telegram
;(async () => {
  console.log('Loading interactive example...')
  const client = new TelegramClient(session, apiId, apiHash, {
    connectionRetries: 5,
  })
  await client.start({
    phoneNumber: async () => await input.text('Please enter your number: '),
    password: async () => await input.text('Please enter your password: '),
    phoneCode: async () =>
      await input.text('Please enter the code you received: '),
    onError: (err) => console.log(err),
  })
  console.log('You should now be connected.')
  console.log(client.session.save()) // в консоли получим строчку, которую нужно будет сохранить
})()

The console will ask for a phone number, password and confirmation code – fill in the data and get a session string. You need to save it so you don’t have to log in every time.

We run the node auth function on Node.js to get the authorization key and continue working with requests to Telegram.

Implementation of functionality

Let's add a function to search for unread messages to the Telegram bot. To do this, we initialize the client with an already saved session. After that, we use the getUnreadMessages method:

const { TelegramClient } = require('telegram')
const { NewMessage } = require('telegram/events')
const { session, apiId, apiHash} = require('./config')
const client = new TelegramClient(session, apiId, apiHash, {})
async function getUnreadMessages(channelId, limit = 10) {
  const dialogs = await client.getDialogs({}) // получаем все чаты
  const channel = dialogs.find((d) => d.entity.username === channelId) // находим нужный по ID
  if (channel) { // если канал найдет
    const messages = await client.getMessages(channel.entity, { // получаем список сообщений
      // limit: channel.unreadCount, // можем прочесть количество непрочитанных сообщений
      limit, // сколько сообщений получаем
    })
          console.log(messages.map((m) => m.message).join(' ')) // выводим в консоль
  } else {
    console.log('Канал не найден')
  }
}
;(async function run() {
  // const channel="whale_alert_io"
  // watchNewMessages(channel) // важно, чтоб метод был до client.connect
  await client.connect()
  await getUnreadMessages(channelId, 10)
})()

In order for the bot to analyze not only unread, but also new messages in chats, you can use the watchNewMessages method:

function watchNewMessages(channelId) {
  client.addEventHandler((event) => {
    console.log('new message', event.message.message)
  }, new NewMessage({ fromUsers: [channelId] }))
}

Passing messages through a neural network

We will use the GPT model

GigaChat

, which provides up to 1 million tokens for free. To get started with the API, you need to know the ClientID and ClientSecret values.

To do this, register on the site GigaChat API and create a project. We simply copy the Client ID value from the corresponding field in the panel on the right.

Client ID field. Source.

And press Get Client Secretto generate a new secret.

Window with Client Secret. Source.

The operating algorithm of the model is simple. First we send a request to receive a token. Then we make a request to the chat with the available tokens. Below is an example of how the functionality is implemented in our bot:

const { gigaAuth } = require('./config')
const { v4: uuidv4 } = require('uuid')
const axios = require('axios')
const qs = require('qs')

// метод для получение токена
async function getToken() {
// конфиг запроса
  const config = {
    method: 'post',
    maxBodyLength: Infinity,
    url: '<https://ngw.devices.sberbank.ru:9443/api/v2/oauth>',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
      RqUID: uuidv4(),
      Authorization: `Basic ${gigaAuth}`,
    },
    data: qs.stringify({
      scope: 'GIGACHAT_API_PERS'
    }),
  }

  try {
    const response = await axios(config)
    const { access_token: accessToken, expires_at: expiresAt } = response.data

    return { accessToken, expiresAt }
  } catch (error) {
    console.log(error)
  }
}

// выполняем запрос к модели уже с токеном
async function giga(content="", system = '') {
  if (!content) return

  // получаем токен
  const token = await getToken()

  const messages = []

	// если передавали контекст, то добавляем его как системное сообщение.
  // здесь мы говорим как чату себя вести
  if (system) {
    messages.push({ role: 'system', content: system })
  }

	// формируем данные для обращения
  const data = JSON.stringify({
    model: 'GigaChat',
    messages: messages.concat([
      {
        role: 'user',
        content,
      },
    ]),
    temperature: 1,
    top_p: 0.1,
    n: 1,
    stream: false,
    max_tokens: 512,
    repetition_penalty: 1,
    update_interval: 0,
  })

	// настраиваем запрос
  const config = {
    method: 'post',
    maxBodyLength: Infinity,
    url: '<https://gigachat.devices.sberbank.ru/api/v1/chat/completions>',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      Authorization: `Bearer ${token.accessToken}`,
    },
    data,
  }

	// выполняем запрос возвращая ответ самого чата
  try {
    const response = await axios(config)
    const message = response.data.choices[0].message
    return message.content
  } catch (e) {
    console.log(e)
  }
}

module.exports = { giga }

Install Telegraf to add the program interface to the Telegram bot:

npm i telegraf

Next we get a token for

@BotFather

and create a Telegram bot. Here is an example of the final functionality file:

const { TelegramClient } = require('telegram')
const { Telegraf } = require('telegraf')
const { NewMessage } = require('telegram/events')
const { session, apiId, apiHash, botToken } = require('./config')
const { giga } = require('./giga')

<h3> создаем бота</h3>
const bot = new Telegraf(botToken)
const client = new TelegramClient(session, apiId, apiHash)
async function getUnreadMessages(channelId, limit = 10) {
  const dialogs = await client.getDialogs({})
  const channel = dialogs.find((d) => d.entity.username === channelId)
  if (channel) {
    const messages = await client.getMessages(channel.entity, {
      limit,
    })
    return messages.map((m) => m.message).join(' ')
  } else {
    console.log('Канал не найден')
  }
}
;(async function run() {
  await client.connect()
        // слушаем команду sum
  bot.command('sum', async (ctx) => {
                // получаем как параметры ID-канала и сообщение для GPT
    const [, channelId, ...task] = ctx.message.text.split(' ')
    if (!channelId) {
      return ctx.reply(`Вы не указали канал`)
    }
                // получаем строку из сообщений в канале
    const messagesString = await getUnreadMessages(channelId, 10)
                // передаем роль и сообщения из канала в GigaChat
    const gigaResponse = await giga(messagesString, task.join(' '))
                // отправляем пользователю ответ от GigaChat с анализом
    await ctx.reply(gigaResponse)
  })
  bot.launch()
})()

Deploy

To ensure that the Telegram bot is always at hand, we will deploy it in

Selectel cloud

. To do this, transfer the code template to Git:

git init
git add .
git commit -m “init”
git push -u origin master

Next we go to

Selectel control panel

. Moving from

Cloud platform

V

Servers

and press

Create a server

.

Next, configure the server parameters.

  • Source: Ubuntu 22.04 LTS 64-bit;
  • Configuration: fixed, Shared;
  • vCPU share: 20% (4 vCPU, 8 GB RAM).

After initializing the server, you need to configure it. Install Git and upload the repository.

apt update
apt install git
git clone REPO_NAME

Afterwards we install Node.js and NPM via NVM. This was discussed in more detail in

Academy

.

To run the program, install Node.js on Ubuntu 20.04:

nvm install 20
nvm use 20
cd REPO_NAME
npm install

Next, install PM2 to run the bot in the background:

npm install pm2 -g
pm2 start main

Ready. Now the bot is working and you can analyze Telegram channels and correspondence!

You will find more content from Vladilen Minin on his YouTube channel.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *