← Back to Home 🌐 বাংলা সংস্করণ
Automation & Cloud Engineering

Build a Free Automated Reminder System with Telegram Bot & Firebase!

Published by Bidyut.Tech • October 2026

1. Introduction & Objectives

Telegram is a highly popular social media platform. Most users simply treat it as a basic messaging application, but its capabilities are virtually endless. For general users, most of these power features remain unknown. Today, I am excited to present a useful Telegram project for you. If this proves even slightly helpful to you, my effort will be worthwhile.

In today's fast-paced automated era, human busywork has increased manifold. Concurrently, new technologies and their applications are scaling up to meet these demands. Amid daily routines, we often forget important tasks. Have you ever wished there was an assistant to remind you at the exact moment? You can achieve this seamlessly using Telegram—completely free of charge. Below is the step-by-step procedure to set up this complete automated reminder system.

2. System Prerequisites

Note: You must have Python and Google Cloud SDK Shell installed on your computer before proceeding.

3. Step 1: Telegram Bot Setup

4. Step 2: Firebase Project & Firestore Database Setup

Setting up Firebase with your Gmail account is straightforward and quick.

  1. Go to the Firebase Console and log in using your Google account.
  2. Click Add project to create a new project (Analytics can be toggled off if desired).
  3. From the left menu under the project dashboard, navigate to Build > Firestore Database.
  4. Click Create database, choose your location, and initialize the database in Test Mode (this serves as our NoSQL database to store reminders).
  5. Go to Project settings (Gear Icon) > Service Accounts tab.
  6. Click Generate new private key to download a JSON file. Save this file inside your Python project directory as serviceAccountKey.json (Create a new folder on your computer, e.g., telegram_reminder_bot).

5. Step 3: Local Project Folder & Python Environment Setup

Open the folder created on your computer (e.g., telegram_reminder_bot). Type cmd in the Windows File Explorer address bar and press Enter to launch the terminal directly inside the directory.

Next, run the following command in terminal or command prompt to install the required libraries:

pip install python-telegram-bot firebase-admin apscheduler pytz

6. Step 4: Writing Python Code (`main.py`)

Create a file named main.py inside your project folder and paste the following Python code:

from datetime import datetime
import os
import re  # For parsing date, time, and AM/PM accurately
import firebase_admin
from firebase_admin import credentials, firestore
import functions_framework
import pytz
import requests

# Insert your Telegram Bot Token here
TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"

# Set Bangladesh Timezone
BD_TZ = pytz.timezone("Asia/Dhaka")

# Firebase Initialization
if not firebase_admin._apps:
    cred = credentials.Certificate("serviceAccountKey.json")
    firebase_admin.initialize_app(cred)

db = firestore.client()

@functions_framework.http
def telegram_webhook(request):
    """Handles both Telegram webhooks and Cloud Scheduler periodic check requests"""

    request_json = request.get_json(silent=True)

    # Triggered by Cloud Scheduler (checks every 1 minute)
    if (
        not request_json
        or "message" not in request_json
        and "callback_query" not in request_json
    ):
        now_bd = datetime.now(BD_TZ)
        current_date_str = now_bd.strftime("%Y-%m-%d")
        current_time_24 = now_bd.strftime("%H:%M")
        current_time_12 = now_bd.strftime("%I:%M %p").upper()

        reminders_ref = (
            db.collection("reminders").where("status", "==", "Pending").stream()
        )

        for doc in reminders_ref:
            data = doc.to_dict()
            doc_id = doc.id
            target_date = data.get("date_str", "")
            target_time = data.get("time_str", "").strip().upper()
            chat_id = data.get("chat_id")
            task_name = data.get("task_name")

            time_matched = (
                current_time_24 == target_time
                or current_time_12 == target_time
                or current_time_24 == target_time.replace(" ", "")
            )

            if time_matched:
                if not target_date or target_date == current_date_str:
                    send_reminder_alert(
                        chat_id, task_name, doc_id, target_time, target_date
                    )
                    db.collection("reminders").document(doc_id).update({"status": "Sent"})

        return "Scheduler checked successfully", 200

    # 1. Triggered when the Inline Button (Done) is clicked
    if "callback_query" in request_json:
        callback_query = request_json["callback_query"]
        data = callback_query["data"]
        chat_id = callback_query["message"]["chat"]["id"]
        message_id = callback_query["message"]["message_id"]
        original_text = callback_query["message"].get("text", "")

        if data.startswith("done_"):
            doc_id = data.split("_")[1]
            db.collection("reminders").document(doc_id).update({"status": "Done"})

            updated_text = (
                f"{original_text}\n\n─────────────────\n✅ **Status:** Task Completed"
            )

            edit_url = f"https://api.telegram.org/bot{TOKEN}/editMessageText"
            payload = {
                "chat_id": chat_id,
                "message_id": message_id,
                "text": updated_text,
                "parse_mode": "Markdown",
                "reply_markup": {"inline_keyboard": []},
            }
            requests.post(edit_url, json=payload)

            answer_url = f"https://api.telegram.org/bot{TOKEN}/answerCallbackQuery"
            requests.post(
                answer_url,
                json={"callback_query_id": callback_query["id"], "text": "Done!"},
            )

    # 2. Triggered when a new text message arrives from Telegram
    elif "message" in request_json:
        message = request_json["message"]
        chat_id = message["chat"]["id"]
        text = message.get("text", "")

        if text.startswith("/remind") or text.startswith("রিমাইন্ডার"):
            # Use Regex to match Date (YYYY-MM-DD), Time (HH:MM), and AM/PM
            # Examples: 2026-11-05 03:30 PM, 03:30 PM, or 15:30

            # Match Date first (YYYY-MM-DD)
            date_match = re.search(r"\b\d{4}-\d{2}-\d{2}\b", text)
            date_str = date_match.group(0) if date_match else ""

            # Match Time and AM/PM (e.g. 03:30 PM or 15:30)
            time_match = re.search(
                r"\b\d{1,2}:\d{2}\s*(?:AM|PM|am|pm)?\b", text, re.IGNORECASE
            )

            if time_match:
                time_str = time_match.group(0).upper()

                # Extract task description by stripping command, date, and time
                task_name = text
                if date_str:
                    task_name = task_name.replace(date_str, "")
                task_name = task_name.replace(time_match.group(0), "")
                
                # Strip out /remind or reminder keywords
                task_name = re.sub(
                    r"^(/remind|রিমাইন্ডার)", "", task_name, flags=re.IGNORECASE
                ).strip()

                reminder_data = {
                    "chat_id": chat_id,
                    "task_name": task_name,
                    "date_str": date_str,
                    "time_str": time_str,
                    "status": "Pending",
                }
                db.collection("reminders").add(reminder_data)

                date_display = f"\n\n📅 **Date:** `{date_str}`" if date_str else ""
                send_telegram_message(
                    chat_id,
                    f"👍 **Reminder Saved Successfully!**{date_display}\n\n🕒 **Time:** `{time_str}`\n\n📝 **Task:** {task_name}\n\n🔔 *You will be alerted at the scheduled time.*",
                )
            else:
                send_telegram_message(
                    chat_id,
                    "⚠️ Invalid format. Example:\n👉 `/remind 03:30 PM Meeting`\nOr with date:\n👉 `/remind 2026-11-05 03:30 PM Meeting`",
                )

    return "OK", 200

def send_telegram_message(chat_id, text):
    url = f"https://api.telegram.org/bot{TOKEN}/sendMessage"
    payload = {"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}
    requests.post(url, json=payload)

def send_reminder_alert(chat_id, task_name, doc_id, time_str, date_str):
    url = f"https://api.telegram.org/bot{TOKEN}/sendMessage"
    date_info = f"\n\n📅 **Date:** `{date_str}`" if date_str else ""
    payload = {
        "chat_id": chat_id,
        "text": (
            f"🔔 **Reminder Alert!**{date_info}\n\n🕒 **Time:** `{time_str}`\n\n📋 **Task:** {task_name}"
        ),
        "parse_mode": "Markdown",
        "reply_markup": {
            "inline_keyboard": [[
                {"text": "✅ Done (Completed)", "callback_data": f"done_{doc_id}"}
            ]]
        },
    }
    requests.post(url, json=payload)
In the Python script, replace TOKEN = "YOUR_TELEGRAM_BOT_TOKEN" with your bot's actual token.

7. Step 5: Creating Requirements File (`requirements.txt`)

Create a file named requirements.txt in your project directory (telegram_reminder_bot) to list required Python packages. Paste the following dependencies and save:

functions-framework==3.*
requests
firebase-admin
pytz

8. Step 6: Google Cloud CLI Authentication

Google Cloud CLI (gcloud CLI) must be installed on your system. Run these commands inside your project folder using terminal:

  1. gcloud auth login (Authenticate via browser pop-up.)
  2. Set current project:
    gcloud config set project YOUR_PROJECT_ID
    (Replace YOUR_PROJECT_ID with your Google Cloud project ID)

9. Step 7: Registering Telegram Webhook

Once deployed, you will receive a Trigger URL from Cloud Functions. Register this Trigger URL with Telegram by opening the following webhook URL in your web browser or Postman:

https://api.telegram.org/bot/setWebhook?url=

If your browser outputs {"ok":true,"result":true,"description":"Webhook was set"}, your webhook registration is successfully configured!

10. Step 8: Deploying to Google Cloud Functions

Execute this command in your terminal to deploy the Function:

gcloud functions deploy telegram_webhook --gen2 --runtime=python310 --region=us-central1 --source=. --entry-point=telegram_webhook --trigger-http --allow-unauthenticated

11. Step 9: Environment Variable Setup for Timezone

12. Step 10: Setting Up Google Cloud Scheduler

Setup Complete! 🎉 From now on, Google Cloud Scheduler will automatically ping your telegram_webhook function every minute. The function will evaluate Firebase Firestore records and dispatch instant alerts to Telegram when time matches. This fully automated system operates 24/7 even when your PC is powered off!

You can now send commands like /remind 2026-10-31 03:30 PM Team Meeting directly to your Telegram bot and observe the real-time automated workflow. An inline Done button will accompany alerts for easy task management.