Ho ngola bot ea thelekramo ho R (karolo ea 4): Ho aha moqoqo o tsitsitseng, o nang le kelello le bot.

Haeba u se u balile tse fetileng lihlooho tse tharo ho tsoa letotong lena, joale u se u ntse u tseba ho ngola bots ea telegraph e felletseng ka keyboard.

Sehloohong sena, re tla ithuta ho ngola bot e tla boloka puisano e tsitsitseng. Tseo. Bot e tla u botsa lipotso ebe e emela hore u kenye lintlha tse ling. Ho latela lintlha tseo u li kenyang, bot e tla etsa liketso tse itseng.

Hape sehloohong sena re tla ithuta ho sebelisa database tlas'a hood ea bot, mohlala oa rona e tla ba SQLite, empa u ka sebelisa DBMS efe kapa efe. Ke ngotse ka ho qaqileng haholoanyane mabapi le ho sebelisana le databases ka puo ea R ka sehlooho sena.

Ho ngola bot ea thelekramo ho R (karolo ea 4): Ho aha moqoqo o tsitsitseng, o nang le kelello le bot.

Lingoliloeng tsohle tse tsoang letotong la "Ho ngola bot ea thelekramo ka R"

  1. Re theha bot mme re e sebelisa ho romella melaetsa ka thelekramo
  2. Kenya tšehetso ea litaelo le li-filters tsa melaetsa ho bot
  3. Mokhoa oa ho eketsa tšehetso ea keyboard ho bot
  4. Ho aha puisano e tsitsitseng, e utloahalang le bot

Tse ka hare

Haeba u thahasella tlhahlobo ea data, u ka 'na ua thahasella ea ka thelekramo и mang youtube dikanale. Boholo ba litaba bo nehetsoe puong ea R.

  1. Selelekela
  2. Mokhoa oa ho haha ​​​​bot
  3. Bot sebopeho sa morero
  4. Bot config
  5. Etsa phetoho ea tikoloho
  6. Ho theha database
  7. Mesebetsi ea ho ngola ho sebetsa le database
  8. Mekhoa ea bot
  9. Lisefa tsa melaetsa
  10. Batshwari
  11. Bot qala khoutu
  12. fihlela qeto e

Selelekela

E le hore bot e kope data ho uena mme e emetse hore o kenye tlhahisoleseding leha e le efe, o tla hloka ho rekota boemo ba hona joale ba puisano. Mokhoa o motle oa ho etsa sena ke ho sebelisa mofuta o itseng oa database o kentsoeng, joalo ka SQLite.

Tseo. The logic e tla ba ka tsela e latelang. Re bitsa mokhoa oa bot, 'me bot ka tatellano e kopa tlhahisoleseding e itseng ho rona,' me mohato o mong le o mong o emetse hore tlhahisoleseding ena e kenngoe 'me e ka e hlahloba.

Re tla ngola bot e bonolo ka ho fetisisa, pele e tla botsa lebitso la hau, ebe lilemo tsa hau, 'me e tla boloka data e fumanoeng ho database. Ha u botsa lilemo, e tla hlahloba hore na data e kentsoeng ke nomoro eseng mongolo.

Puisano e bonolo joalo e tla ba le lipolelo tse tharo feela:

  1. qala ke boemo bo tloaelehileng ba bot, moo e sa lebellang tlhahisoleseling efe kapa efe ho uena
  2. wait_name - bolela moo bot e emelang hore lebitso le kenngoe
  3. wait_age ke boemo boo bot e emetseng hore lilemo tsa hau li kenngoe ho tsona, palo ea lilemo tse felletseng.

Mokhoa oa ho haha ​​​​bot

Nakong ea sengoloa, re tla haha ​​​​bot mohato ka mohato; ts'ebetso eohle e ka hlalosoa ka mokhoa o latelang:
Ho ngola bot ea thelekramo ho R (karolo ea 4): Ho aha moqoqo o tsitsitseng, o nang le kelello le bot.

  1. Re theha bot config moo re tla boloka litlhophiso tse ling. Tabeng ea rona, lets'oao la bot, le tsela ea faele ea database.
  2. Re theha phetoho ea tikoloho moo tsela ea morero e nang le bot e tla bolokoa.
  3. Re theha database ka boeona, le mesebetsi e mengata e le hore bot e ka sebelisana le eona.
  4. Re ngola mekhoa ea bot, i.e. mesebetsi eo e tla e etsa.
  5. Eketsoa lihloela tsa melaetsa. Ka thuso eo bot e tla fihlella mekhoa e hlokahalang, ho itšetlehile ka boemo ba hona joale ba moqoqo.
  6. Re eketsa li-handers tse tla hokahanya litaelo le melaetsa ka mekhoa e hlokahalang ea bot.
  7. Ha re qaleng bot.

Bot sebopeho sa morero

Bakeng sa boiketlo, re tla arola khoutu ea bot ea rona, le lifaele tse ling tse amanang le tsona, ka sebopeho se latelang.

  • bot.R - khoutu ea mantlha ea bot ea rona
  • db_bot_function.R - sebaka sa khoutu se nang le mesebetsi ea ho sebetsa le database
  • bot_methods.R - khoutu ea mekhoa ea bot
  • mesefe_molaetsa.R — disefe tsa melaetsa
  • batshwari.R - bahlokomeli
  • konopo.cfg - bot config
  • create_db_data.sql - Sengoloa sa SQL bakeng sa ho theha tafole e nang le data ea moqoqo sebakeng sa polokelo ea litaba
  • create_db_state.sql - Sengoloa sa SQL bakeng sa ho theha tafole ea boemo ba hajoale ba moqoqo sebakeng sa polokelo ea litaba
  • bot.db - database ea bot

U ka sheba projeke eohle ea bot, kapa скачать ho tloha ka polokelo ho GitHub.

Bot config

Re tla sebelisa e tloaelehileng joalo ka config ini file, foromo e latelang:

[bot_settings]
bot_token=ТОКЕН_ВАШЕГО_БОТА

[db_settings]
db_path=C:/ПУТЬ/К/ПАПКЕ/ПРОЕКТА/bot.db

Ho config re ngola letšoao la bot le tsela e eang ho database, i.e. ho faele ea bot.db; re tla iketsetsa faele mohatong o latelang.

Bakeng sa li-bots tse rarahaneng, o ka etsa li-configs tse rarahaneng, ntle le moo, ha ho hlokahale hore u ngole ini config, u ka sebelisa mofuta ofe kapa ofe o kenyelletsang JSON.

Etsa phetoho ea tikoloho

Ho PC e 'ngoe le e' ngoe, foldara e nang le projeke ea bot e ka fumaneha ka har'a li-directory tse fapaneng le ho li-drive tse fapaneng, ka hona, ka khoutu tsela e eang foldareng ea projeke e tla beoa ka ho feto-fetoha ha tikoloho. TG_BOT_PATH.

Ho na le mekhoa e mengata ea ho etsa phetoho ea tikoloho, e bonolo ka ho fetisisa ke ho e ngola faeleng .Renviron.

U ka etsa kapa ua hlophisa faele ena u sebelisa taelo file.edit(path.expand(file.path("~", ".Renviron"))). E phethe 'me u kenye mola o le mong faeleng:

TG_BOT_PATH=C:/ПУТЬ/К/ВАШЕМУ/ПРОЕКТУ

E latelang boloka faele .Renviron ebe o qala RStudio hape.

Ho theha database

Mohato o latelang ke ho theha database. Re tla hloka litafole tse 2:

  • chat_data - data eo bot e e kopileng ho mosebelisi
  • chat_state - boemo ba hajoale ba lipuisano tsohle

U ka etsa litafole tsena u sebelisa potso e latelang ea SQL:

CREATE TABLE chat_data (
    chat_id BIGINT  PRIMARY KEY
                    UNIQUE,
    name    TEXT,
    age     INTEGER
);

CREATE TABLE chat_state (
    chat_id BIGINT PRIMARY KEY
                   UNIQUE,
    state   TEXT
);

Haeba u khoasolla morero oa bot ho GitHub, ebe ho theha database o ka sebelisa khoutu e latelang ho R.

# Скрипт создания базы данных
library(DBI)     # интерфейс для работы с СУБД
library(configr) # чтение конфига
library(readr)   # чтение текстовых SQL файлов
library(RSQLite) # драйвер для подключения к SQLite

# директория проекта
setwd(Sys.getenv('TG_BOT_PATH'))

# чтение конфига
cfg <- read.config('config.cfg')

# подключение к SQLite
con <- dbConnect(SQLite(), cfg$db_settings$db_path)

# Создание таблиц в базе
dbExecute(con, statement = read_file('create_db_data.sql'))
dbExecute(con, statement = read_file('create_db_state.sql'))

Mesebetsi ea ho ngola ho sebetsa le database

Re se re ntse re e-na le faele ea tlhophiso e lokisitsoeng mme database e entsoe. Joale o hloka ho ngola mesebetsi ho bala le ho ngola data ho database ena.

Haeba u downloaded morero ho tloha GitHub, joale u ka fumana mesebetsi faeleng db_bot_function.R.

Khoutu ea ts'ebetso ea ho sebetsa le database

# ###########################################################
# Function for work bot with database

# получить текущее состояние чата
get_state <- function(chat_id) {

  con <- dbConnect(SQLite(), cfg$db_settings$db_path)

  chat_state <- dbGetQuery(con, str_interp("SELECT state FROM chat_state WHERE chat_id == ${chat_id}"))$state

  return(unlist(chat_state))

  dbDisconnect(con)
}

# установить текущее состояние чата
set_state <- function(chat_id, state) {

  con <- dbConnect(SQLite(), cfg$db_settings$db_path)

  # upsert состояние чата
  dbExecute(con, 
            str_interp("
            INSERT INTO chat_state (chat_id, state)
                VALUES(${chat_id}, '${state}') 
                ON CONFLICT(chat_id) 
                DO UPDATE SET state='${state}';
            ")
  )

  dbDisconnect(con)

}

# запись полученных данных в базу
set_chat_data <- function(chat_id, field, value) {

  con <- dbConnect(SQLite(), cfg$db_settings$db_path)

  # upsert состояние чата
  dbExecute(con, 
            str_interp("
            INSERT INTO chat_data (chat_id, ${field})
                VALUES(${chat_id}, '${value}') 
                ON CONFLICT(chat_id) 
                DO UPDATE SET ${field}='${value}';
            ")
  )

  dbDisconnect(con)

}

# read chat data
get_chat_data <- function(chat_id, field) {

  con <- dbConnect(SQLite(), cfg$db_settings$db_path)

  # upsert состояние чата
  data <- dbGetQuery(con, 
                     str_interp("
            SELECT ${field}
            FROM chat_data
            WHERE chat_id = ${chat_id};
            ")
  )

  dbDisconnect(con)

  return(data[[field]])

}

Re thehile mesebetsi e bonolo e 4:

  • get_state() - fumana boemo ba hajoale ba moqoqo ho tsoa polokelong ea litaba
  • set_state() - ngola boemo ba hajoale ba moqoqo sebakeng sa polokelo ea litaba
  • get_chat_data() - fumana data e rometsoeng ke mosebelisi
  • set_chat_data() - rekota data e amohetsoeng ho tsoa ho mosebelisi

Mesebetsi eohle e bonolo haholo, e ka ba ba bala data ho tswa ho database ba sebelisa taelo dbGetQuery(), kapa itlama UPSERT ts'ebetso (ho fetola data e teng kapa ho ngola data e ncha ho database), ho sebelisa ts'ebetso dbExecute().

Syntax ea ts'ebetso ea UPSERT e tjena:

INSERT INTO chat_data (chat_id, ${field})
VALUES(${chat_id}, '${value}') 
ON CONFLICT(chat_id) 
DO UPDATE SET ${field}='${value}';

Tseo. tšimong ea litafole tsa rona chat_id e na le tšitiso e ikhethang mme ke senotlolo sa mantlha sa litafole. Qalong, re leka ho eketsa tlhahisoleseding tafoleng, 'me re fumana phoso haeba data ea moqoqo oa morao-rao e se e ntse e le teng, moo re ntlafatsang tlhahisoleseding ea moqoqo ona feela.

Ka mor'a moo, re tla sebelisa mesebetsi ena ka mekhoa le li-filters tsa bot.

Mekhoa ea bot

Mohato o latelang oa ho aha bot ea rona ke ho theha mekhoa. Haeba u downloaded morero ho tloha GitHub, joale mekhoa eohle e ka har'a faele bot_methods.R.

Mokhoa oa bot khoutu

# ###########################################################
# bot methods

# start dialog
start <- function(bot, update) {

  # 

  # Send query
  bot$sendMessage(update$message$chat_id, 
                  text = "Введи своё имя")

  # переключаем состояние диалога в режим ожидания ввода имени
  set_state(chat_id = update$message$chat_id, state = 'wait_name')

}

# get current chat state
state <- function(bot, update) {

  chat_state <- get_state(update$message$chat_id)

  # Send state
  bot$sendMessage(update$message$chat_id, 
                  text = unlist(chat_state))

}

# reset dialog state
reset <- function(bot, update) {

  set_state(chat_id = update$message$chat_id, state = 'start')

}

# enter username
enter_name <- function(bot, update) {

  uname <- update$message$text

  # Send message with name
  bot$sendMessage(update$message$chat_id, 
                  text = paste0(uname, ", приятно познакомится, я бот!"))

  # Записываем имя в глобальную переменную
  #username <<- uname
  set_chat_data(update$message$chat_id, 'name', uname) 

  # Справшиваем возраст
  bot$sendMessage(update$message$chat_id, 
                  text = "Сколько тебе лет?")

  # Меняем состояние на ожидание ввода имени
  set_state(chat_id = update$message$chat_id, state = 'wait_age')

}

# enter user age
enter_age <- function(bot, update) {

  uage <- as.numeric(update$message$text)

  # проверяем было введено число или нет
  if ( is.na(uage) ) {

    # если введено не число то переспрашиваем возраст
    bot$sendMessage(update$message$chat_id, 
                    text = "Ты ввёл некорректные данные, введи число")

  } else {

    # если введено число сообщаем что возраст принят
    bot$sendMessage(update$message$chat_id, 
                    text = "ОК, возраст принят")

    # записываем глобальную переменную с возрастом
    #userage <<- uage
    set_chat_data(update$message$chat_id, 'age', uage) 

    # сообщаем какие данные были собраны
    username <- get_chat_data(update$message$chat_id, 'name')
    userage  <- get_chat_data(update$message$chat_id, 'age')

    bot$sendMessage(update$message$chat_id, 
                    text = paste0("Тебя зовут ", username, " и тебе ", userage, " лет. Будем знакомы"))

    # возвращаем диалог в исходное состояние
    set_state(chat_id = update$message$chat_id, state = 'start')
  }

}

Re entse mekhoa e 5:

  • qala — Qala moqoqo
  • state — Fumana boemo ba hajoale ba moqoqo
  • seta bocha — Seta bocha boemo ba moqoqo ba hajoale
  • enter_name - Bot e botsa lebitso la hau
  • enter_age - The bot e botsa lilemo tsa hau

Mokhoa start e botsa lebitso la hau, mme e fetola boemo ba moqoqo hore e be emela_lebitso, ke. ho ema bakeng sa ho kenya lebitso la hao.

Ka mor'a moo, u romela lebitso 'me le sebetsoa ke mokhoa enter_name, bot ea u lumelisa, e ngola lebitso le amohetsoeng sebakeng sa polokelo ea litaba, ebe e fetola moqoqo sebakeng ema_boleng.

Mothating ona, bot e lebelletse hore o kene lilemong tsa hau. U romella lilemo tsa hau, bot e hlahloba molaetsa, haeba u rometse mongolo sebakeng sa nomoro, e tla re: Ты ввёл некорректные данные, введи число, 'me e tla u emela hore u kenye lintlha tsa hau hape. Haeba u rometse nomoro, bot e tla tlaleha hore e amohetse lilemo tsa hau, ngola lintlha tse fumanoeng ho database, tlaleha lintlha tsohle tse fumanoeng ho uena le ho khutlisetsa boemo ba moqoqo sebakeng sa eona sa pele, ke hore. V start.

Ka ho bitsa mokhoa state o ka kopa boemo ba hajoale ba moqoqo ka nako efe kapa efe, 'me u sebelisa reset khutlisetsa moqoqo boemong ba ona ba pele.

Lisefa tsa melaetsa

Tabeng ea rona, ena ke e 'ngoe ea likarolo tsa bohlokoa ka ho fetisisa tsa ho haha ​​​​bot. Ke ka thuso ea li-filters tsa melaetsa moo bot e tla utloisisa hore na e lebeletse boitsebiso bofe ho uena le hore na e lokela ho sebetsoa joang.

Morerong oa GitHub li-filters li ngolisitsoe faeleng mesefe_molaetsa.R.

Khoutu ea sefe ea molaetsa:

# ###########################################################
# message state filters

# фильтр сообщений в состоянии ожидания имени
MessageFilters$wait_name <- BaseFilter(function(message) {
  get_state( message$chat_id )  == "wait_name"
}
)

# фильтр сообщений в состоянии ожидания возраста
MessageFilters$wait_age <- BaseFilter(function(message) {
  get_state( message$chat_id )   == "wait_age"
}
)

Ka li-filters re sebelisa mosebetsi o ngotsoeng pele get_state(), molemong oa ho kopa boemo ba hajoale ba moqoqo. Ts'ebetso ena e hloka khang e le 'ngoe feela, id ea moqoqo.

Sefe se latelang emela_lebitso e sebetsa melaetsa ha moqoqo o le boemong wait_name, 'me ho latela filthara ema_boleng e sebetsa melaetsa ha moqoqo o le boemong wait_age.

Batshwari

Faele e nang le li-handers e bitsoa batshwari.R, mme e na le khoutu e latelang:

# ###########################################################
# handlers

# command handlers
start_h <- CommandHandler('start', start)
state_h <- CommandHandler('state', state)
reset_h <- CommandHandler('reset', reset)

# message handlers
## !MessageFilters$command - означает что команды данные обработчики не обрабатывают, 
## только текстовые сообщения
wait_age_h  <- MessageHandler(enter_age,  MessageFilters$wait_age  & !MessageFilters$command)
wait_name_h <- MessageHandler(enter_name, MessageFilters$wait_name & !MessageFilters$command)

Ntlha ea pele, re theha li-handers tse tla u lumella ho sebelisa mekhoa ea ho qala puisano, ho e tsosolosa, le ho botsa boemo ba hona joale.

Ka mor'a moo, re theha litšoantšiso tsa melaetsa tse 2 re sebelisa li-filters tse entsoeng mohato o fetileng, ebe re eketsa sefe ho tsona !MessageFilters$command, e le hore re ka sebelisa litaelo sebakeng leha e le sefe sa moqoqo.

Bot qala khoutu

Hona joale re na le ntho e 'ngoe le e' ngoe e loketseng ho qala, khoutu e ka sehloohong ea ho qala bot e ka faeleng bot.R.

library(telegram.bot)
library(tidyverse)
library(RSQLite)
library(DBI)
library(configr)

# переходим в папку проекта
setwd(Sys.getenv('TG_BOT_PATH'))

# читаем конфиг
cfg <- read.config('config.cfg')

# создаём экземпляр бота
updater <- Updater(cfg$bot_settings$bot_token)

# Загрузка компонентов бота
source('db_bot_function.R') # функции для работы с БД
source('bot_methods.R')     # методы бота
source('message_filters.R') # фильтры сообщений
source('handlers.R') # обработчики сообщений

# Добавляем обработчики в диспетчер
updater <- updater +
  start_h +
  wait_age_h +
  wait_name_h +
  state_h +
  reset_h

# Запускаем бота
updater$start_polling()

Ka lebaka leo, re fumane bot ena:
Ho ngola bot ea thelekramo ho R (karolo ea 4): Ho aha moqoqo o tsitsitseng, o nang le kelello le bot.

Ka nako efe kapa efe sebelisa taelo /state re ka botsa boemo ba moqoqo ba hajoale, le ho sebelisa taelo /reset khutlisetsa moqoqo boemong ba ona ba pele mme o qale moqoqo hape.

fihlela qeto e

Sehloohong sena, re fumane mokhoa oa ho sebelisa database ka har'a bot, le mokhoa oa ho aha lipuisano tse hlakileng tse latellanang ka ho rekota boemo ba moqoqo.

Tabeng ena, re ile ra sheba mohlala oa khale ka ho fetisisa, e le hore ho ka ba bonolo ho uena ho utloisisa mohopolo oa ho aha li-bots tse joalo; ha e le hantle, u ka haha ​​​​lipuisano tse rarahaneng haholoanyane.

Sehloohong se latelang letotong lena, re tla ithuta mokhoa oa ho thibela litokelo tsa basebelisi ba bot ho sebelisa mekhoa e fapaneng ea eona.

Source: www.habr.com

Eketsa ka tlhaloso