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

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

There are Telegram channels that track certain events in the world. And we monitor their messages so as not to miss anything important. If you collect and analyze data manually, the process will take a lot of time and require a lot of human concentration. To solve this problem, our partner and front-end developer Vladylen Minin created a Telegram bot that automates the process and issues a resume based on the collected information.

This article describes how to use a neural network to create a bot that collects and processes information from messages and deploys it to a cloud server.

You may also be interested in these texts:

→ Introduction
→ Authorization
→ Implementation of functionality
→ We pass messages through a neural network
→ Deploy

Introduction


As an example, consider a robot that monitors the movement of cryptocurrencies:

/sum – the command to call the bot, whale_alert_io – the channel ID (any can be substituted), the rest of the text is an arbitrary command for the robot.

Authorization


You must first authorize your account to access the bot’s messages. Due to the robot, such functionality is not available, so we will use the GramJS library.

Go to my.telegram.org, open API development tools and create an application.

In the response, we receive the parameters apiId and apiHash. We 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 line. It must be saved so that you do not 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.

Do you like detectives? Complete the quest “In Search of the Missing Links”! Register on the site and try yourself as a detective: find hidden links on Selectel pages and be the first to reach the final. Win exclusive merch and a promotional code for Selectel services.

Implementation of functionality

Let’s add the function of searching for unread messages to the Telegram bot. To do this, initialize the client with already saved sessions. 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] }))
}

Pass 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 values ​​of ClientID and ClientSecret.

To do this, register on the GigaChat API website and create a project. Simply copy the Client ID value from the field in the panel on the right.

Client ID field. Source.

And we press Get Client Secretto create a new secret.

A window with Client Secret. Source.

The 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 existing token. 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 }

We 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 function 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

So that the Telegram bot is always at hand, let’s 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

. Let’s move on from

Cloud platform

in

Servers

and press

Create a server

.

Next, configure the server parameters.

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

After the server is initialized, it needs to be configured. We install Git and download the repository.

apt update
apt install git
git clone REPO_NAME

After that, install Node.js and NPM via NVM. It was told in more detail in

Academies

.

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

nvm install 20
nvm use 20
cd REPO_NAME
npm install

Next, we install PM2 for the robot to work in the background:

npm install pm2 -g
pm2 start main

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

You can find more Vladylen Minin content on his YouTube channel.

Related posts