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/Webhookendpoint receives updates from Telegram. - Contact Sharing: When a user shares their contact, the system extracts the
chat_idand themobile_number. - Global Registration: The
TelegramApiRepositoryperforms a “Multi-Database Scan”. Since our system is multi-tenant, it iterates through all society databases to find matching mobile numbers and updates theTelegramChatId.
2. Notification Flow (Outbound)
- Trigger: When a Notice or Member Statement is sent.
- Check Channel: The system checks the
whatsappOptInsetting. If it is NOT ‘Y’, the system defaults to Telegram for digital delivery. - Asynchronous Queue: Using
Coravelqueuing, the system generates the PDF report and callsTelegramApiController.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 fromReportsorDocsfolders.
NoticeBoardController.cs: Integrates Telegram logic withinNoticeBoardWhatsAppmethod.MemberStatementReportController.cs: Integrates Telegram logic withinMemberStatementWhatsAppmethod.
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
TelegramChatIdis consistently linked across the entire ecosystem without requiring per-society manual entry.
How it works:
- Fetch all active database names from the
Systemdatabase (ClientDbtable). - For each database, attempt an
UPDATEquery onMemberMstbased on the mobile number. - 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.
- Open Telegram: Search for @BotFather.
- Start Chat: Send the
/newbotcommand. - Choose Name: Provide a name for your bot (e.g.,
ErpCrystal_Notifications_Bot). - Choose Username: Provide a unique username ending in
bot(e.g.,erpcrystal_chs_bot). - Get Token: BotFather will provide an API Token.
- Copy this token to your
appsettings.jsonunderTelegramApi:BotToken.
- Copy this token to your
- Privacy Settings (Optional): To allow the bot to read messages in groups (if needed), send
/setprivacyto BotFather and set it toDisabled. 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:
TelegramApiControllerbecomesTelegramApi. - Action: The method
WebhookbecomesWebhook. - 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
cloudflaredto 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
MemberMsttable in the database to ensure theTelegramChatIdcolumn 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
.csvlog 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
/stopto the bot. - Verify: Check the database to ensure
TelegramChatIdis nowNULL.
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}