TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Build a Shipment Tracking Tool with a Telegram Bot with Python

Design a Telegram Bot with Python that interacts with truck drivers, tracks your shipments and provides real-time visibility.

Samir Saci
TDS Archive
Published in
7 min readMar 9, 2021

--

A diagram illustrating the process of building a shipment tracking tool using a Telegram bot with Python. The image shows a truck driver icon on the left, a Telegram logo in the center, and a smartphone on the right displaying a Telegram chat. Red arrows indicate the communication flow from the driver to the Telegram bot and then to the user’s smartphone. This visual represents how a Telegram bot can be used to track shipments and provide real-time transportation visibility.
(Image by Author)

Retailers and FMCG companies face increasing pressure to improve their supply chain, increase flexibility and reduce costs.

Using Distribution Centers (DC) is an effective solution, as they allow a single location to stock a vast range of products from suppliers close to the final customer.

How can you automate transportation monitoring using Python?

However, it should be coupled with efficient shipment tracking to ensure transparency of delivery processes and measure performance.

In this article, we will design and deploy a transportation tracking tool using a Telegram bot built with Python.

I. Limitation of TMS & Tracking Tools
1. Scenario
2. What kind of obstacles can you face?
II. What do we need here?
III. What is a Telegram Bot?
1. Definition
2. How do you interact with a Telegram Bot?
IV. Create your Tracking Assistant Bot
1. Standard Operating Procedure (SOP)
V. Demo: Shipment Delivery confirmation
1. Step 1: DRIVER opens telegram and starts a discussion with BOT
2. Step 2: DRIVER shares its GPS Location (= Store Location)
3. Step 3, 4 and 5: Confirmation of the delivery with pictures
VI. Design your bot
VII. Conclusion
1. Add a Container Loading Optimization Module

Limitation of TMS & Tracking Tools

Scenario

You are a medium-sized retailer operating in a market where the transportation industry is immature.

You would like to implement a Transport Management System (TMS) proposed by an external provider to get full visibility and real-time tracking of your shipments.

What kind of obstacles can you face?

  • System Interface: you have multiple carriers with different systems
  • Maturity of Carriers: they manage their fleet with manual processes (Excel)
  • Local Specifics: carriers do not operate their fleet (sub-contracting)
  • Limited Capacity to Negotiate: because your volumes are low compared to other customers, carriers refuse to adapt their processes and use your system to record status

If you face these obstacles, the solution presented in this article will probably answer your needs.

What do we need here?

A simple, cheap and easy-to-implement solution to track your shipments that

  • Does not require additional IT development for your carriers
  • Easily integrates into the current transportation processes
  • Reduces admin workload for your logistics team
  • Does not impact drivers’ productivity
  • Does not require additional equipment
  • Provides visibility, real-time tracking and transparency
An icon of a robot interacting with a laptop, sitting in front of a large Telegram logo. The robot symbolizes automation, while the Telegram logo signifies the platform used for building a shipment tracking bot. This image emphasizes the role of automation in using Telegram bots to monitor and track shipments in real-time.
Telegram Bot: your best ally to improve your logistics performance

What is a Telegram Bot?

Telegram

Telegram is a cross-platform, secure, convenient messaging app that works on all devices.

With over 500 million users worldwide, Telegram has an open API and free protocol.

With this API, we can build our tools, including a bot.

What’s a Bot?

A bot is a 3rd party application that can interact with users by sending them messages, commands and inline requests. With Telegram, you can design and control your Telegram bot by sending HTTPS requests to their bot API.

Your bot can send/receive messages, photos, videos and GPS locations — enough to build our shipment tracking tool.

How do you interact with a Telegram Bot?

Add him and start a conversation :)

Create your Tracking Assistant Bot

Standard Operating Procedure(SOP)

For the first version of our bot, let's use a light version of SOP to record delivery time.

Confirm Unloading at Destination

  1. STORE TEAM finished unloading your shipment from the truck
  2. DRIVER shares Shipment Number, GPS location and a picture of the shipment with your Telegram BOT to confirm delivery
  3. Telegram BOT sends a delivery notification by email to your logistics team with the information listed above

Demo: Shipment Delivery confirmation

Your shipment has been unloaded in your store. DRIVER wants to send delivery confirmation before leaving for his next destination.

Step 1: DRIVER opens telegram and starts a discussion with BOT

A screenshot of a Telegram chat between a truck driver and a shipment tracking bot. The bot welcomes the driver and provides commands, such as “/start_tracking” to initiate the tracking process. The driver begins by typing “/start_tracking,” and the bot responds by asking for the driver’s GPS location. This image demonstrates the first step in confirming a shipment delivery through the Telegram bot.
DRIVER starts the process | BOT asks for GPS location — (Image by Author)

Step 2: DRIVER shares its GPS Location (= Store Location)

A continuation of the Telegram chat, where the driver shares their GPS location, represented by a map with a red pin. The bot confirms that the GPS location has been recorded and asks the driver to enter the delivery number. This image illustrates how the driver uses the Telegram bot to provide location information during the delivery confirmation process.
DRIVER share its GPS Location | BOT asks for the delivery number — (Image by Author)

Step 3: DRIVER shares a delivery number

In this part of the Telegram chat, the driver enters the delivery number, “1254270–147.” The bot confirms that the delivery number has been recorded and requests a picture of the shipment. This image shows how the driver continues the shipment confirmation by sharing a unique delivery number with the Telegram bot.
DRIVER share its Delivery Number | BOT asks for shipment picture — (Image by Author)

Step 4: DRIVER shares a picture of the shipment

The driver uploads a picture of the shipment in the Telegram chat, and the bot confirms that the photo has been successfully uploaded. The bot thanks the driver for their cooperation, completing the delivery confirmation process. This image showcases the final step in the delivery tracking workflow, where the driver provides visual proof of the shipment.
DRIVER share shipment photo | BOT stop the process and send an email (Image by Author)

Step 5: Your logistics teams receive a shipment confirmation

A screenshot of an email sent to the logistics team, providing delivery confirmation for shipment number “1254270–147.” The email includes the GPS location and a photo of the shipment. This image demonstrates how the Telegram bot sends a notification email with the necessary shipment details to the logistics team after the delivery is confirmed.
BOT send delivery confirmation by mail to the transportation team (Image by Author)

🏫 Discover 70+ case studies using Python and VBA to automate manual tasks 🤖 and optimize your supply chain 🚚 in this Cheat Sheet

Find the source code in this repository 👇

Design your Telegram Bot

Create your bot with another bot :)

@ BotFather is a Telegram bot that will help you create your own bot

  1. Search @ BotFather on Telegram and send him ‘/start’
  2. Answer ‘/newbot’ message and follow the instructions to set up a name and a username
  3. Your bot is now ready, and an API token has been created. Please keep a copy of this token!
A screenshot of the Telegram chat with BotFather, used to create and manage new Telegram bots. The user initiates the conversation by sending “/start,” followed by “/newbot” to create a new bot. The user names the bot “My Personal Assistant” and attempts different usernames before successfully creating the bot with the username “droidansmesbot.” The bot provides an HTTP API token for accessing and controlling the newly created bot.
Create your Telegram in three steps with @ BotFather (Image by Author)

Installing Python packages

Package to manage your telegram bot

pip install python-telegram-bot

Import Libraries and enable logging

Import Libraries and Init your Telegram Bot

TOKEN: shared by @ BotFather when you created your bot
APP_NAME: address of your Heroku application (see steps below)

Main function with Conversation handler

To simplify the process for the DRIVER, your BOT will ask for information in sequence using the ConversationHandler function of the Telegram API

A simple black-and-white diagram showing the communication flow between a bot and a user. The image depicts a robot icon on the left representing the Telegram bot and a user icon on the right representing the driver. Arrows point between them, symbolizing the interaction and data exchange during shipment tracking via the bot.
Shipment Information Collection Process handled by ConversationHandler Function of Telegram API (Image by Author)
Conversation Handler creates a sequence of instructions for the driver with the cancel function

Example of photo function

  1. photo_file: extract the last photo uploaded in the messages written by the user
  2. link1: link created by Telegram API where we can extract photo file id
  3. link2: web page created by Telegram API that hosts this photo
  4. mail function: send an email with delivery_number, gps_location and embedded photo using HTML
Example of photo function

For more details regarding Telegram API, check the list of reference links at the end of the article.

Mail Function

The transportation team will be notified by email after collecting the delivery number, GPS location, and shipment picture.

The bot uses the smtplib Python package and Gmail account.

You can find the mail function in the script mail.py.

Host your bot on the cloud.

Heroku is a cloud-based service that allows you to host your web application.

The free hosting provides enough resources to run your app.

Procfile
requirements.txt

Two files listed above are needed to set up your app on Heroku.

Conclusion

This is a very light version to show the potential of what can be done with a Telegram Bot.

We can improve it by adding

  • Real-Time GPS Location Tracking
  • Store records in a database /OR/Google sheet
  • Add scanning function (Bar Code/QR Code) to avoid manual entry of delivery number by DRIVER.
  • A function to get store and driver comments in case of late delivery?
  • Seals management in case of shipping sensitive goods

What about maximizing trucks’ filling rate?

Containers Loading Optimization with Python

As freight costs increase, you are under more pressure than ever to maximize the use of your trucks and containers.

Side-by-side 3D renderings of two sea containers showing the difference between an initial pallet packing solution (right) and an optimized solution (left). The left container is packed more efficiently with both European and North American pallets, while the right container leaves space unused. The blue pallets inside the containers represent a more optimized arrangement in the left solution, which results in higher space utilization.
Example of two methods for pallet loading — (Image by author)

The picture above shows two containers loaded with two different strategies.

  • The container on the right side used an optimized algorithm
  • The left one has two pallets on the side that could not be loaded.

Could we implement the right solution in our telegram bot?

Yes, this algorithm built with Python using the 2d-knapsack problem maximizes the number of pallets loaded.

A 2D schematic showing the layout of pallets inside a container. The image uses dashed lines to outline the pallets, with black lines representing European pallets (80x120 cm) and red lines for North American pallets (100x120 cm). The layout illustrates how different pallet sizes are packed into the container, ensuring an optimal configuration for efficient space usage in the container loading process.
Example of results provided by the algorithm — (Image by Author)

It can be easily included in the bot's workflow to help drivers maximize the trucks’ filling rate.

For more details, have a look at this article 👇

Can we use this tool for last-mile delivery optimization?

Last-mile delivery is a major operational challenge for e-commerce companies as it is costly and complex.

Optimize E-Commerce Last-Mile Delivery with Python

If you travel to first and second-tier cities of China, you will find small warehouses called customer service centres (客户服务中心) located in each neighbourhood.

A map of a neighborhood in a city, showing various numbered red and blue markers representing delivery points. The markers are scattered across streets and near a green park area in the center of the map. Red markers indicate delivery locations, while a blue marker highlights a central delivery hub or service center. The map represents delivery locations that need to be optimized for last-mile delivery, showcasing how geographical data can be used to plan efficient delivery routes.
Example of the coverage of a last-mile delivery center in Shanghai — (Image by Author)

Courrier drivers deliver final customers from there.

How can you use Python to optimize the routing from these centres?

In another article, I designed a solution to reduce costs and ensure a uniform workload distribution to each driver.

The bot can include this to allocate deliveries to drivers and create optimal routes.

For more information, check the article linked below 👇

About Me

Let’s connect on Linkedin and Twitter, I am a Supply Chain Engineer who uses data analytics to improve logistics operations and reduce costs.

For consulting or advice on analytics and sustainable supply chain transformation, feel free to contact me via Logigreen Consulting.

If you are interested in Data Analytics and Supply Chain, look at my website.

💌 New articles straight in your inbox for free: Newsletter
📘 Your complete guide for Supply Chain Analytics: Analytics Cheat Sheet

--

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Samir Saci
Samir Saci

Written by Samir Saci

Top Supply Chain Analytics Writer — Case studies using Data Science for Supply Chain Sustainability 🌳 and Productivity: https://bit.ly/supply-chain-cheat

No responses yet