Telegram Bot - Documentation

In this user guide you will find all required information to run & edit Telegram Bot

Many thanks to all the mentors who taught me on the course:
Oleksii Klymenok
Vitalii Hrebennikov

and the school Robot_Dreams that gave impetus to become a switcher in IT industry.

Telegram Bot is written using Flask Application, NGROK, Postgres and NovaPoshta Api.
The code also contains AutoStart for a quick start of the Web application. The application uses the model view controller structure and OOP principles.




This Telegram Bot is part - of my Pet Project - Nike Shop Django.
User registration will take place on the website, and the Telegram Bot works with a ready-made User Database and helps users track their packages.
  • 1) Create you own environment file.

  • You need to create your environment variables. In file .env.template you can see example of your .env file:


    #FLASK
    SECRET_KEY - your secret key of Flask application.
    DEBUG - Bool value of Flask application.
    HOST - Address of your host of Flask application (default = 0.0.0.0)
    PORT - Address of your port of Flask application (default = 8443)
    #AUTO START POSTGRESQL SERVER AND NGROK WITH TELEGRAM WEBHOOK (TESTED ON UBUNTU)
    AUTO_START - Bool value Auto Start Postgres Server (you need to install Server on your operating system) and NGROK (inside app.start_postgresql_ngrok.StartNGROK you can see function "register_webhook" - this function set WebHook to Telegram API)
    #DATABASE
    DATABASE_URI - Database Uniform Resource Identifier
    SQLALCHEMY_TRACK_MODIFICATIONS - Bool variable of configuration keys for Flask application.
    #POSTGRESQL SERVER AUTOSTART
    USER_PASSWORD - Password of your Operational System User (inside app.start_postgresql_ngrok.StartProcess you can see function "startprocess" which start your Postgres Server from bash. So, to start Server App use "sudo", and password needs for this.)
    #TELEGRAM
    TG_TOKEN - Token of your Telegram Bot.
    #NOVA POSHTA
    NOVA_POSHTA_API_KEY - Your personal Nova Poshta Api Key (Get it!)
    COMPANY_TELEPHONE - Your personal or your company telephone number for tracking parcels using Nova Poshta Api method getStatusDocuments.


  • 2) Install server Postgres

  • For Linux:
        sudo apt update
                            
    sudo apt upgrade
    sudo apt install postgresql


    to check your server use:

        sudo service postgresql status 



    For Mac:


    1) Visit the Postgres downloads page


    2) Download and open the downloaded package (.dmg) file.


    3) Follow the on-screen instructions to run the installer and complete the installation process.


    to check your server use:

        psql --version 

    For Windows:


    1) Visit the Postgres downloads page


    2) Download and open the downloaded installer (.exe) file.


    3) Follow the on-screen instructions to run the installer and complete the installation process. Make sure to remember the password you set for the "postgres" user during the installation.
    to check your server use:
        psql --version 


    You can use Docker container instead installing Postgres on your OS.



  • 3) Set up server Postgres

  • 1) Open a command prompt or terminal and log in as a user with superuser privileges (such as a root user or a user with sudo privileges).
    Run the psql command to enter an interactive Postgres shell:

        sudo -u postgres psql
    2)Create a new table named tgbot:

        CREATE DATABASE tgbot;
    3)Create a new user with the CREATE USER command:

        CREATE USER "user" WITH PASSWORD "user";
    4)Assign the required privileges to the user. For example, to give it full rights to all databases, you can run the following command:

        GRANT ALL PRIVILEGES ON DATABASE tgbot TO "user";
    5)Connect to the tgbot database:

        \c tgbot
    6)Activate the uuid-ossp extension with the following command:

        CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
    7)Exit the interactive Postgres shell by typing \q or pressing Ctrl+D.

        \q
  • 4) Add test values in the database (possible via PyCharm or DataGrid)

  • Connect via:
    postgresql://user:user@localhost:5432/tgbot
    1) Add the user entity to the profile table (leave telegram_id empty, it will be filled in automatically)
    specify the phone number that will connect to the Telegram bot.

    2) Add to the order table an order with a real TTN of Nova Poshta for tests.

  • 5) Install NGROK
  • For all OS - on Web Site - download and install NGROK.


  • 6) Create Python Virtual Environment and install requirements.txt
  •     pip install -r requirements.txt



  • 7) Run Flask Web application
  •     python run.py

The code uses the standard Flask application structure with two additional files located in the app folder.

Structure of files

    Telegram-Bot (Main folder of the project)
  • tg_bot/ Folder of the Flask Application
  • .env.template Environment file example
  • .gitignore GitIgnore file
  • config.py Script loading environment variables
  • README.md GitHub ReadMe file
  • requirements.txt List of dependencies required by the project
  • run.py Program entry point
    tg_bot (Folder of the Flask Application)
  • app/ Additional scripts (services) folder
  • __init__.py Flask app initialization with configuration and database.
  • handlers.py Telegram message handling with sending and interaction logic.
  • models.py Models for SqlAlchemy ORM
  • views.py Routes and handlers for processing incoming messages and callback queries.
    app (Additional scripts (services) folder)
  • novaposhta.py Script of Nova Poshta Api for Parcel tracking
  • start_postgresql_ngrok.py Auto Start of Postgres Server and NGROK with setting WebHook

For package tracking, used the NovaPoshta API v.2 due to its versatility and convenience. First of all, program inside app.start_postgresql_ngrok.StartNGROK.register_webhook automatic set Webhook to TelegramBot api (if you use Auto Start) with your NGROK url and register it. Program send JSON to url: https://api.telegram.org/[BOT TOKEN]/setWebhook The request body for the setWebhook method in JSON format is as follows:


  •                                     {
                                        "url": "[YOUR NGROK URL]"
                                        }
                                    



And after that when "User" request for package tracking program used app.novaposhta.NovaPoshta method "get_status", which send request to method getStatusDocuments, and program have response with package tracking information. The request body for the getStatusDocuments method in JSON format is as follows:


  •                                 {
                                        "apiKey": "[YOUR KEY]",
                                        "modelName": "TrackingDocument",
                                        "calledMethod": "getStatusDocuments",
                                        "methodProperties": {
                                            "Documents" : [
                                                {
                                                    "DocumentNumber":"20400048799000",
                                                    "Phone":"380600000000"
                                                }
                                            ,
                                                {
                                                    "DocumentNumber":"20400048799001",
                                                    "Phone":"380600000000"
                                                }
                                            ]
                                        }
                                    }
                                



All the functionality of the telegram bot and its capabilities are in the file handler.py

Class User

Class TelegramHandler

Class MessageHandler

Class CallbackHandler

Class User

authentification

    Function of authentication user inside of DataBase. This code is executed after receiving the User's phone number, if there is no user, the MessageHandler class initialization code will be executed, and the user will receive a notification with a request to register on the site: Pet Project - Nike Shop Django.

register_t_bot_user_id

    Function of registration User - user_chat_id The user_chat_id variable is the user's chat id. Thanks to this variable, the Bot understands what chat it is. The bot enters the user_chat_id into the Database and uses it to identify the User.



    If the variable is not entered into the bot for some reason, the bot will always ask the user for a phone number.

Class TelegramHandler

send_markup

    Function send_markup allows you to send custom markup for user.

send_message

    Function send_message allows you to send a custom message for user.

get_data_for_send_contact

    Function get_data_for_send_contact returns a markup with a request to send a phone number to the bot.

send_contact

    Function send_contact sends a message to the user asking them to send a phone number to the bot using function get_data_for_send_contact

send_start_massage

    Function send_start_massage sends a start markup message with a choice of further actions when user authorized.

to_main_page

    Function to_main_page used to redirect on the main route.

Class MessageHandler

handle

    Function handle in MessageHandler used when the user launched the bot for the first time. Telegram automatically sends the message '/start' which is processed in this function.

Class CallbackHandler

handle

    Function handle in CallbackHandler is responsible for processing the callback data and performing the corresponding actions based on the data received. It follows a pattern-matching approach to determine the action to be taken.
    When the callback data matches a specific pattern, the method executes the associated logic. Here are the key actions performed:

      1 Route Matching:

    • The method matches the callback data with the pattern {'route': url}.
    • If a match is found, it further matches the url to perform specific actions.

      2 Processing '/orders' Route:

    • If the url is /orders, the method checks if the user exists in the database.
    • If the user exists, it retrieves the user's orders from the database.
    • It generates an inline keyboard for pagination and displays the orders to the user in pages.
    • If there are no orders available, it sends a message indicating the absence of orders.
    • The method also provides navigation options to view the next or previous page of orders.

      3 Processing '/site' Route:

    • If the url is /site, the method sends a message containing a link to a specific website.

      4 Processing '/main' Route:

    • If the url is /main, the method sends a start message to the user.

      5 Processing Order ID:

    • If the callback data matches {'order_id': order_id}, the method retrieves the corresponding order based on the order_id.
    • It generates an inline keyboard with options to track the shipment or go back to the orders route.

      6 Processing Tracking Data:

    • If the callback data matches {'tracking': ttn}, the method utilizes an external API to retrieve the status of the shipment based on the tracking number (ttn).
    • If tracking is successful, it constructs a response message containing details about the shipment and sends it to the user.
    • If there is an error during tracking, it sends an error message to the user.
    The handle() method serves as the central point for processing callback data and executing the appropriate actions based on the matched patterns.



I use Data Base structure from my Pet Project - Nike Shop Django and add telegram_id for table Profile,

telegram_id needs for save chat_id for user and authorized him.


I used Flask with SQLAlchemy to create my models in file app.models and Postgres Server like Database Management System.


Relational Schema:





Project Сomponents

API

  • Nova Poshta API v.2 (devcenter.novaposhta.ua)
  • Telegram Bot API (core.telegram.org)
  • Data Base

  • PostgreSQL 15 (www.postgresql.org)
  • Flask SQLAlchemy 3.0.3 (flask-sqlalchemy.palletsprojects.com)
  • SQLAlchemy 2.0.9 (docs.sqlalchemy.org)
  • In conclusion, this documentation provides a comprehensive overview of the Telegram bot.
    Through the use of Flask, a lightweight and versatile web framework, and Flask-SQLAlchemy, a powerful extension for integrating an SQL database with Flask applications, we have created a seamless and efficient user experience.
    By following this documentation, you have learned how to set up the necessary environment, configure the bot settings, implement commands and callbacks, handle user interactions, and leverage the database capabilities for storing and retrieving data.
    Remember, this is just the beginning of what you can achieve with this Telegram bot. Feel free to explore the possibilities and customize it according to your needs. Experiment with additional features, integrate external APIs, and create unique functionalities that will make your bot stand out.
    Thank you for choosing this documentation as your guide. To further expand your knowledge and discover more exciting projects, be sure to check out my GitHub repository. There, you'll find wealth of interesting resources and open-source projects to explore.

    Happy coding and best of luck with your Telegram bot journey!

    Check out my GitHub to see another project:  
    Or check out my GitHub Pages to see my CV: