Electronic database directory in telegram bot format

The format of the interface between reference data and the user in the form of a telegram bot seems very attractive in the modern world. Let's say you want to provide your employees with reference data that will always be at hand. At the same time, it would be good to provide the ability to add data depending on the needs of employees. How to do this?

This is exactly the problem I propose to consider today.

We will install Python and PyCharm as standard. Using BotFather, we will create a bot and get a token. To ensure the token is protected, I store it in a separate file secrets.py and import it.

from secrets import secrets 

token = secrets.get('BOT_API_TOKEN')
bot = telebot.TeleBot(token)

Let's create a directory (Dictionary.py file), the data from which we will give to users on request. For example, I made a directory of memory chips. The data is a set of data: marking, annotation, file name with datasheet.

spisok=[["w25q128jv", "Последовательная Flash память на 128 Мбит с интерфейсом SPI.",  "1.pdf"],
        ["w25q128fv", "Последовательная Flash память на 128 Мбит с интерфейсом SPI.",  "2.pdf"],
        ["w25q128jw", "Последовательная Flash память на 128 Мбит с интерфейсом SPI.", "3.pdf"],
        ["w25q128bv", "Последовательная Flash память на 128 Мбит с интерфейсом SPI.", "4.pdf"],
        ["w25q128fw", "Последовательная Flash память на 128 Мбит с интерфейсом SPI.", "5.pdf"],
        ["w25q16jv",  "Последовательная Flash память на 16 Мбит с интерфейсом SPI.",  "6.pdf"],
        ["w25q32bv", "Последовательная Flash память на 32 Мбит с интерфейсом SPI.", "7.pdf"],
        ["w25q32fv", "Последовательная Flash память на 32 Мбит с интерфейсом SPI.", "8.pdf"],
        ["w25q32jv", "Последовательная Flash память на 32 Мбит с интерфейсом SPI.", "9.pdf"],
        ["w25q40ew", "Последовательная Flash память на 4 Мбит с интерфейсом SPI.", "10.pdf"],
        ["w25q64jv", "Последовательная Flash память на 64 Мбит с интерфейсом SPI.", "11.pdf"],
        ["w25x20cl", "Последовательная Flash память на 2 Мбит с интерфейсом SPI.", "12.pdf"],
        ["w9812g6kh", "Микросхема памяти SDRAM, 128 Мбит.", "14.pdf"],
        ["w25q64bv", "Последовательная Flash память на 64 Мбит с интерфейсом SPI.", "15.pdf"],
        ["w9825g6kh", "Микросхема памяти SDRAM, 256 Мбит.", "16.pdf"],
        ["w25q256jv", "Последовательная Flash память на 256 Мбит с интерфейсом SPI.", "17.pdf"],
        ["w25q80d", "Последовательная Flash память на 8 Мбит с интерфейсом SPI.", "18.pdf"],
        ["w25x40cl", "Последовательная Flash память на 4 Мбит с интерфейсом SPI.", "19.pdf"],
        ["w27c512", "Микросхема памяти EEPROM на 512 кбит.", "20.pdf"],
        ["w9864g6kh", "Микросхема памяти SDRAM, 64 Мбит.", "21.pdf"],
        ["w25q80ew", "Последовательная Flash память на 8 Мбит с интерфейсом SPI.", "22.pdf"],
        ["w25n01gv", "Последовательная Flash память на 1 Гбит с интерфейсом SPI.", "23.pdf"],
        ["w25q16jw", "Последовательная Flash память на 16 Мбит с интерфейсом SPI.", "24.pdf"],
        ["w25q20ew", "Последовательная Flash память на 2 Мбит с интерфейсом SPI.", "25.pdf"],
        ["w25q64fv", "Последовательная Flash память на 64 Мбит с интерфейсом SPI.", "26.pdf"],
        ["w25q80bv", "Последовательная Flash память на 8 Мбит с интерфейсом SPI.", "27.pdf"],
        ["w978h6kb", "Микросхема памяти SDRAM, 256 Мбит.", "28.pdf"],
        ["w978h2kb", "Микросхема памяти SDRAM, 256 Мбит.", "28.pdf"],
        ["w25q20cl", "Последовательная Flash память на 2 Мбит с интерфейсом SPI.", "29.pdf"],
        ["w25q40cl", "Последовательная Flash память на 4 Мбит с интерфейсом SPI.", "30.pdf"]]

We import this list into the project.

from Dictionary import spisok

Now we can start developing the help system operation algorithm. The code for processing the entered string is presented below.

@bot.message_handler(content_types=['text'])
def get_text_messages(message):
    global file_name
    global stroka3
    chec = 0
    stroka1 = message.text.lower()
    if message.text == "/start":
        bot.send_message(message.from_user.id, "Справочник по электронике. Введите маркировку.")
    else:
        for i in range(len(spisok)):
            #все в нижний регистр
            stroka = spisok[i][0].lower()
            fin_stroka = []
            if stroka.find(stroka1) >= 0 or stroka1.find(stroka) >= 0:
                chec += 1 # увеличиваем счетчик на 1
                file_name = spisok[i][2]
                fin_stroka.append("___"+spisok[i][0]+"___")
                fin_stroka.append(spisok[i][1])
                bot.send_message(message.chat.id, '\n'.join(fin_stroka))
        if chec == 1 :
            keyboard = types.InlineKeyboardMarkup()
            key_yes = types.InlineKeyboardButton(text="Да", callback_data="yes")
            keyboard.add(key_yes)
            key_no = types.InlineKeyboardButton(text="Нет", callback_data="no")
            keyboard.add(key_no)
            question = 'Загрузить даташит?'
            bot.send_message(message.from_user.id, text=question, reply_markup=keyboard)
        elif chec == 0:
            f = open('zayavka.txt', 'a')
            if stroka3 != stroka1:
                stroka3 = stroka1
                f.write(stroka1 + '\n')
                bot.send_message(message.from_user.id, "Данная позиция отсутствует в справочнике. Заявка на ее добавление принята.")

In response to the start message, the user is prompted to enter markings (lines 7,9).

Lines 10-19 search for the user-entered marking in the imported list. A very important point is that the search is performed by searching for the entered string in the string from the list and vice versa (line 14). This allows finding the chip when entering part of the marking, as well as when entering a marking that is redundant for the search (since the datasheet considers several variants by case, the marking written on the case will be more complete).

All found matches are displayed to the user as separate messages. Based on this information, the user can adjust their request to obtain a specific datasheet. If one match is found, the user is offered to download the datasheet (lines 20-27). To determine whether downloading is necessary, the user is shown the “yes” and “no” buttons.

Processing of clicks on these buttons in the form of code is described below.

@bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
    global file_name
    if call.data == "yes": #call.data это callback_data, которую мы указали при объявлении кнопки
        file = open("./Baza/"+file_name, "rb")
        bot.send_document(call.message.chat.id, file)
        bot.send_message(call.message.chat.id, "Справочник по электронике. Введите маркировку.")
    elif call.data == "no":
        bot.send_message(call.message.chat.id, "Справочник по электронике. Введите маркировку.")

If the user selects the “yes” button, the datasheet is unloaded from the Baza catalog (lines 4-7).

When starting to use this system, users will often encounter the absence of data in our help system. To solve this problem, saving the user's request in case of absence in the database (file zayavka.txt) is provided.

    f = open('zayavka.txt', 'a')
            if stroka3 != stroka1:
                stroka3 = stroka1
                f.write(stroka1 + '\n')
                bot.send_message(message.from_user.id, "Данная позиция отсутствует в справочнике. Заявка на ее добавление принята.")

The full text of the main file is presented below.

import telebot  # Импортируем telebot
from secrets import secrets  # Словарь с токеном из файла secrets.py
from Dictionary import spisok  # Импортируем словарь для Списка продуктов
from telebot import types  # для указания типов


# передаём значение переменной с кодом экземпляру бота
token = secrets.get('BOT_API_TOKEN')
bot = telebot.TeleBot(token)
global stroka3
stroka3 = ""

@bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
    global file_name
    if call.data == "yes": #call.data это callback_data, которую мы указали при объявлении кнопки
        file = open("./Baza/"+file_name, "rb")
        bot.send_document(call.message.chat.id, file)
        bot.send_message(call.message.chat.id, "Справочник по электронике. Введите маркировку.")
    elif call.data == "no":
        bot.send_message(call.message.chat.id, "Справочник по электронике. Введите маркировку.")

@bot.message_handler(content_types=['text'])
def get_text_messages(message):
    global file_name
    global stroka3
    chec = 0
    stroka1 = message.text.lower()
    if message.text == "/start":
        bot.send_message(message.from_user.id, "Справочник по электронике. Введите маркировку.")
    else:
        for i in range(len(spisok)):
            #все в нижний регистр
            stroka = spisok[i][0].lower()
            fin_stroka = []
            if stroka.find(stroka1) >= 0 or stroka1.find(stroka) >= 0:
                chec += 1 # увеличиваем счетчик на 1
                file_name = spisok[i][2]
                fin_stroka.append("___"+spisok[i][0]+"___")
                fin_stroka.append(spisok[i][1])
                bot.send_message(message.chat.id, '\n'.join(fin_stroka))
                #print(stroka.find(stroka1))
                #print(stroka1.find(stroka))
        if chec == 1 :
            keyboard = types.InlineKeyboardMarkup()
            key_yes = types.InlineKeyboardButton(text="Да", callback_data="yes")
            keyboard.add(key_yes)
            key_no = types.InlineKeyboardButton(text="Нет", callback_data="no")
            keyboard.add(key_no)
            question = 'Загрузить даташит?'
            bot.send_message(message.from_user.id, text=question, reply_markup=keyboard)
        elif chec == 0:
            f = open('zayavka.txt', 'a')
            if stroka3 != stroka1:
                stroka3 = stroka1
                f.write(stroka1 + '\n')
                bot.send_message(message.from_user.id, "Данная позиция отсутствует в справочнике. Заявка на ее добавление принята.")

# бесконечное выполнение кода
while True:
    try:
      bot.polling(none_stop=True, interval=0)
    except:
      continue

Lines 60-64 provide for continuous execution of the code, taking into account the elimination of errors.

Let's test our bot. After the start, the bot offers to enter the marking. Let's enter the query “128”. The bot gives out all the chips in the marking of which there is “128” and annotation on them.

We see that the database contains the microcircuit w25q128bv. Let's correct our request “w25q128bv”.

We agree to download the datasheet.

Let's try to enter the missing marking. For example, “qwert123”.

A line with missing marking has been added to the zayavka.txt file. This allows the directory administrator to add the necessary elements to the database when updating the database.

The article discusses the option of forming a reference system using a telegram bot. The convenience of this approach lies in the availability of up-to-date information using a messenger that is installed on almost all mobile gadgets.

Similar Posts

Leave a Reply

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