Simplify CHS - Telegram Integration Tech Doc

Simplify CHS - Telegram Integration Tech Doc

Overview

The Telegram integration allows society members to receive notifications (Notices, Member Statements) directly on their Telegram accounts. This serves as an alternative to WhatsApp and Email, providing a fast and cost-effective communication channel.

Architecture and Method Flow

The integration follows a multi-layered architecture consistent with the project standards:

1. Data Flow (Registration)

  • Telegram Webhook: The /api/TelegramApi/Webhook endpoint receives updates from Telegram.
  • Contact Sharing: When a user shares their contact, the system extracts the chat_id and the mobile_number.
  • Global Registration: The TelegramApiRepository performs a “Multi-Database Scan”. Since our system is multi-tenant, it iterates through all society databases to find matching mobile numbers and updates the TelegramChatId.

2. Notification Flow (Outbound)

  • Trigger: When a Notice or Member Statement is sent.
  • Check Channel: The system checks the whatsappOptIn setting. If it is NOT ‘Y’, the system defaults to Telegram for digital delivery.
  • Asynchronous Queue: Using Coravel queuing, the system generates the PDF report and calls TelegramApiController.UploadAndSendDocument.
  • Delivery: The document is uploaded to Telegram’s servers and sent to the member’s registered chat_id.

Technical Components

Controllers

  • TelegramApiController.cs:
    • Webhook: Entry point for Telegram events. Handles /start, /stop, and contact sharing.
    • SendTelegram: Basic text message delivery.
    • UploadAndSendDocument: Handles PDF file uploads from Reports or Docs folders.
  • NoticeBoardController.cs: Integrates Telegram logic within NoticeBoardWhatsApp method.
  • MemberStatementReportController.cs: Integrates Telegram logic within MemberStatementWhatsApp method.

Repositories

  • TelegramApiRepository.cs:
    • RegisterChatId: Logic to iterate through all client databases.
    • DeRegisterChatId: Logic to remove chat ID across all databases.

Models

  • TelegramApi.cs: POCO for transferring chat ID, messages, and document paths.

Why “Global Procedure” Logic is Added

For Telegram integration, we implemented a specific Multi-Database Procedure in the repository.

Reasoning:

  • User Experience: A member might belong to multiple societies managed by the same ERP. By scanning all databases during registration, the member only needs to share their contact ONCE to start receiving notifications from ALL their societies.
  • Data Integrity: Ensures that the TelegramChatId is consistently linked across the entire ecosystem without requiring per-society manual entry.

How it works:

  1. Fetch all active database names from the System database (ClientDb table).
  2. For each database, attempt an UPDATE query on MemberMst based on the mobile number.
  3. Catch and ignore errors for specific databases (e.g., if a DB is offline) to ensure the loop continues.


Creating a Telegram Bot (BotFather)

To get started, you need to create a bot on Telegram to receive a Token.

  1. Open Telegram: Search for @BotFather.
  2. Start Chat: Send the /newbot command.
  3. Choose Name: Provide a name for your bot (e.g., ErpCrystal_Notifications_Bot).
  4. Choose Username: Provide a unique username ending in bot (e.g., erpcrystal_chs_bot).
  5. Get Token: BotFather will provide an API Token.
    • Copy this token to your appsettings.json under TelegramApi:BotToken.
  6. Privacy Settings (Optional): To allow the bot to read messages in groups (if needed), send /setprivacy to BotFather and set it to Disabled. However, for direct contact sharing, default settings are usually sufficient.

Understanding the Webhook URL

The webhook URL is dynamically generated by ASP.NET Core based on the controller’s routing attributes.

  • Route Formula: [public-url]/api/[controller]/[action]
  • Controller: TelegramApiController becomes TelegramApi.
  • Action: The method Webhook becomes Webhook.
  • Final URL: https://<your-public-url>/api/TelegramApi/Webhook

You do not need to configure this URL in appsettings.json. The system automatically responds to requests at this endpoint.


Testing and Validation

Follow these steps to verify the Telegram integration:

1. Environment Setup

  • Expose Local API: Use cloudflared to provide a public URL for your local environment.
      winget install Cloudflare.cloudflared
      cloudflared tunnel --url https://localhost:7116 --no-tls-verify
    
  • Set Webhook:
    • You must manually register your public URL with Telegram.
    • Construct the URL as: https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook?url=<YOUR_PUBLIC_URL>/api/TelegramApi/Webhook
    • Open this URL in your web browser. You should see a JSON response: {"ok":true,"result":true,"description":"Webhook was set"}.

2. Registration Testing

  • Open the Telegram Bot and send /start.
  • Click the “Share Contact” button.
  • Verify: Check the MemberMst table in the database to ensure the TelegramChatId column is populated for your mobile number.

3. Delivery Testing (Notice Board)

  • Create a new Notice.
  • Click on “Send WhatsApp/Telegram” (ensure WhatsApp opt-in is disabled or set to Telegram mode).
  • Check Log: Monitor the .csv log file in \\CHSReports\\Docs\\{dbname}\\TelegramLog\\.
  • Check Telegram: Verify the PDF and caption are received in the bot chat.

4. Delivery Testing (Member Statement)

  • Navigate to Member Statement Report.
  • Select a member and click “Send WhatsApp/Telegram”.
  • Verify: Ensure the statement PDF is generated and delivered correctly.

5. De-registration Testing

  • Send /stop to the bot.
  • Verify: Check the database to ensure TelegramChatId is now NULL.

Code Architecture Reference (Simplified)

graph TD
    T[Telegram Webhook] --> C[TelegramApiController]
    C --> R[TelegramApiRepository]
    R --> D1[(Society DB 1)]
    R --> D2[(Society DB 2)]
    R --> DN[(Society DB N)]

    NC[NoticeBoardController] --> C
    MS[MemberStatementController] --> C
    C --> Bot{Telegram API}