Connect Telegram Bot API with AI Chat, Voice Notes and Media in Perfex CRM
Connecting the official Telegram Bot API to Perfex CRM through PolyUtilities for Perfex CRM takes under 2 minutes, costs $0 in API or relay fees, requires zero Meta App Review, and runs 100% natively on standard PHP and MySQL hosting. Engineered by HeadRandom, PolyUtilities v3.7.0 secures every incoming Telegram webhook via the cryptographic X-Telegram-Bot-Api-Secret-Token header, automatically fetches .ogg/Opus voice notes, photos, videos, and documents via getFile through a 10-layer File Security and GD Image CDR pipeline, and powers instant Whisper or Gemini Voice STT, AI Vision, and outbound AI auto-replies directly from your Perfex CRM Unified Inbox.

Why Telegram Bot API Is the Fastest Omnichannel AI Gateway for Perfex CRM
While Meta platforms require business verification and App Review before public launch, Telegram's official Bot API activates globally in seconds with zero per-conversation fees. Technical teams, SaaS support desks, crypto/fintech agencies, and international B2B organizations frequently launch Telegram first inside PolyUtilities v3.7.0 OmniChat to validate AI Copilot prompts, voice transcription, and 1-click CRM workflows immediately.
| Technical Specification | PolyUtilities v3.7.0 Telegram Bot Adapter (Poly_omnichat_telegram_adapter) |
|---|---|
| API & Relay Cost | $0 (100% free official Telegram Bot API, zero third-party SaaS fees) |
| Webhook Endpoint | https://your-crm-domain.com/poly_utilities/omnichat/webhook/telegram |
| Multi-Bot Routing | Append ?account_id=your_bot_username per bot to run unlimited bots |
| Authentication Header | Constant-time hash_equals() check on X-Telegram-Bot-Api-Secret-Token |
| Payload & Rate Protection | 2 MB body cap (2097152 bytes) + 120 req/min/IP webhook rate limit |
| Supported Inbound Media | .ogg/Opus Voice Notes (voice), MP3 Audio (audio), Photos (photo), Videos (video), Documents (document) |
| Media Download Pipeline | 2-step getFile lookup -> SSRF allowlist (api.telegram.org) -> 15 MB cap -> 10-layer File Security + GD Image CDR (up to 25 MP) |
| Outbound Delivery | POST https://api.telegram.org/bot{token}/sendMessage (15s cURL timeout, TLS verified) |
If you are setting up PolyUtilities for the first time, check our PolyUtilities for Perfex CRM installation guide before creating your bot.
Step 1: Create a Free Telegram Bot via @BotFather in Under 2 Minutes
You do not need a developer portal account or credit card to create an official Telegram Bot:
- Open @BotFather on Telegram (confirm the official blue verification checkmark beside
@BotFather). - Send the command
/newbot. - Enter a customer-facing Display Name for your bot (for example,
HeadRandom Support Assistant). - Enter a unique Bot Username ending in
bot(for example,acme_support_bot). @BotFatherimmediately replies with your HTTP API Bot Token formatted like123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxxxx. Treat this token like a root password and never commit it to public repositories.- Optionally send
/setdescriptionand/setuserpicto@BotFatherto brand your support bot before sharinghttps://t.me/your_bot_usernamewith clients.
Step 2: Configure the 3 Credential Fields in Perfex CRM
Open PolyUtilities > OmniChat Settings > Channels, confirm External Channels is enabled under General Settings, select Telegram Bot as the Channel Type, and fill in these three fields:
| Perfex CRM Setting Field | Exact Value Required | Format / Example | Security Storage |
|---|---|---|---|
| Account ID | Bot username (without @) or blank for a single bot |
acme_support_bot |
Used for multi-bot ?account_id= routing |
| Token / API Key | HTTP API Bot Token from @BotFather |
123456789:AAH... |
Stored encrypted at rest with AES-256-CBC (bot_token) |
| App Secret / Webhook Secret | Random alphanumeric secret (A-Z, a-z, 0-9, _, -) |
tg_sec_94f8a2c7e1b6d305 |
Matched against X-Telegram-Bot-Api-Secret-Token header |
Select your preferred Default Department and Default Assignee, then click Save Channel BEFORE registering the webhook URL with Telegram.
Step 3: Register Your Signed Webhook with setWebhook
Telegram signs every webhook POST by attaching your secret_token inside the X-Telegram-Bot-Api-Secret-Token HTTP header (see the official Telegram Bot API setWebhook documentation). Poly_omnichat_telegram_adapter::verify_signature() strictly requires a non-empty webhook_secret and rejects any unsigned or mismatched request with HTTP 403.
Option A: Register in Your Browser (Single Bot)
Replace YOUR_BOT_TOKEN, your-crm-domain.com, and YOUR_SECRET (matching the Webhook Secret saved in Step 2), then open this URL once in your browser:
https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook?url=https://your-crm-domain.com/poly_utilities/omnichat/webhook/telegram&secret_token=YOUR_SECRET
Option B: Register Multiple Bots via cURL (Multi-Bot Routing)
When running separate bots for Sales (sales_bot) and Technical Support (support_bot), append ?account_id=sales_bot (URL-encoded inside the url parameter) so Perfex resolves the exact bot token and department automatically:
curl -s -X POST "https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook" \
-d "url=https://your-crm-domain.com/poly_utilities/omnichat/webhook/telegram?account_id=sales_bot" \
-d "secret_token=YOUR_SECRET"
A successful registration immediately returns:
{"ok":true,"result":true,"description":"Webhook was set"}
To inspect live webhook health or diagnose delivery errors anytime, visit https://api.telegram.org/botYOUR_BOT_TOKEN/getWebhookInfo and confirm pending_update_count is 0 and last_error_message is empty.
Step 4: Automatic getFile Local Media Download and 10-Layer Security
Telegram never embeds raw file URLs inside webhook JSON (to protect your Bot Token from leaking). Instead, webhooks deliver an opaque file_id. When a customer sends an .ogg/Opus voice note, a high-resolution photo (OmniChat automatically selects the highest-resolution variant from Telegram's photo array), a video, or a PDF invoice, Poly_omnichat_media_service::download_telegram_media() executes a hardened 2-step pipeline:
- Authenticated
getFileResolution: CallsGET https://api.telegram.org/bot{token}/getFile?file_id={file_id}and explicitly blocks path traversal patterns (..) insideresult.file_path. - SSRF-Hardened Stream Download: Downloads
https://api.telegram.org/file/bot{token}/{file_path}strictly over HTTPS port 443 to allowlistedapi.telegram.org, pins public IPv4 DNS resolution viaCURLOPT_RESOLVE, and enforces your configured max file cap (default15 MB). - 10-Layer File Security & GD Image CDR: Before saving to
uploads/poly_utilities/omnichat/inbound/YYYY/MM/under a128-bitrandom filename, every file passes OmniChat's 10-layer anti-malware and Image CDR engine:- JPEG, PNG, and WebP photos are rebuilt pixel-by-pixel via PHP GD (up to
25 MPcap) to erase EXIF/GPS metadata and destroy embedded PHP/script polyglots. - PDF files and ZIP/Office archives are scanned for
/JavaScript,/Launch, Zip Bombs (> 50 MBor> 100:1compression ratio), Zip Slip (../), and VBA macros. - Optional ClamAV daemon streaming over TCP
3310or Unix socket adds real-time antivirus signature scanning with zero shell execution.
- JPEG, PNG, and WebP photos are rebuilt pixel-by-pixel via PHP GD (up to
Step 5: Pair Telegram with Multi-Provider AI Chat, Voice STT, and Key Rotation
Because Telegram voice notes arrive in native audio/ogg (Opus codec), OmniChat pairs seamlessly with both OpenAI Whisper and Google Gemini Native Audio. Open PolyUtilities > OmniChat Settings > AI Hub to configure your provider and multi-key pool (see the full Multi-Provider AI Hub and Key Rotation guide).

- Zero-Cost Voice STT + Vision Stack: Add 2 or 3 Google AI Studio keys into the Gemini Key Pool with Priority Failover or Round Robin rotation and select
gemini-2.5-flashfor both Chat/Vision and Voice Transcription Model. If one free-tier key hits HTTP429, OmniChat places it on automatic cooldown and fails over in the same request. - Enterprise Whisper + GPT-4o Mini Stack: Combine
gpt-4o-mini($0.15/$0.60 per 1M tokens) withgpt-4o-mini-transcribe($0.003/min) orwhisper-1($0.006/min) for 99+ language accuracy on audio files up to25 MBand Vision images up to5 MB. - 24/7 AI Auto-Reply + Cooldown Protection: Enable AI Auto-Reply and Multimodal Auto-Reply so your Telegram bot answers customer questions based on typed text, transcribed
.oggvoice notes, and analyzed screenshots automatically, guarded by a10sper-conversation cooldown and hard Daily Cost Budget Limit (USD).
Practical Perfex CRM Workflows Using Telegram Bot + Unified Inbox
Inside the Perfex CRM Unified Inbox, Telegram conversations live side-by-side with internal staff chats, client portal tickets, and social channels:

- Instant Technical Support Triage: Customers snap a photo of a server error or record a 30-second Telegram voice note. OmniChat transcribes the audio, summarizes the screenshot via AI Vision, and lets an Automation Rule auto-assign high-priority issues or auto-create a Perfex Support Ticket when keywords like
outageorinvoiceappear inside the voice transcript. - 1-Click Lead and Task Capture: Click Create Lead, Create Ticket, Create Task, or Create Event in the right-hand CRM Context Panel to save the Telegram username (
@handle), customer name, and the last 12 messages straight into Perfex CRM. - Slash Macros and CrossTag Teamwork: Use internal notes with
@mentionsand$/#Invoice or Project tags to collaborate privately with billing or engineering staff; whenever you reply to the customer, OmniChat strips internal CrossTag markup cleanly before delivering via TelegramsendMessage.
Want to expand beyond Telegram? Read our step-by-step guides for WhatsApp Business Cloud API v21.0, Facebook Messenger and Instagram DM, and Zalo OA API v3, or explore all features on the PolyUtilities for Perfex CRM product page.
Telegram Bot Troubleshooting Quick Reference
| Error / Behavior | Cause | Resolution |
|---|---|---|
getWebhookInfo shows 403 Forbidden |
secret_token in setWebhook does not match Perfex Webhook Secret, or channel is inactive |
Re-save Webhook Secret (alphanumeric, _, - only) in Perfex and re-run setWebhook with the exact same secret_token |
getWebhookInfo shows SSL error |
Self-signed certificate or missing intermediate chain on HTTPS domain | Install full certificate chain on your web server (Telegram requires trusted TLS on port 443, 80, 88, or 8443) |
Voice notes show [Voice Note] without playable audio |
Auto-Download Inbound Channel Media Locally is OFF or uploads/poly_utilities/omnichat/ is not writable |
Enable local download in OmniChat Settings > AI Hub and set 0755 permissions on uploads/poly_utilities/omnichat/ |
Outbound reply fails with 400 Bad Request: chat not found |
Customer blocked the bot or bot_token belongs to a different bot |
Verify the active Bot Token matches the bot that received the inbound message |
Frequently Asked Questions (FAQ)
Is the Telegram Bot API completely free to connect to Perfex CRM?
Yes. Telegram charges $0 for bot creation, unlimited inbound webhooks, getFile media downloads, and outbound sendMessage replies. With PolyUtilities for Perfex CRM, your integration runs 100% natively on your PHP hosting with zero third-party relay subscriptions.
Can OmniChat transcribe Telegram .ogg voice notes automatically?
Yes. Telegram sends voice messages as audio/ogg (Opus). OmniChat downloads the file securely via getFile, normalizes application/ogg MIME detection automatically, and transcribes speech to text using OpenAI Whisper (whisper-1 / gpt-4o-mini-transcribe) or Google Gemini 2.5 Flash Native Audio (up to 25 MB), saving the transcript permanently in the message record.
How does PolyUtilities protect my Telegram webhook from spoofed POST requests?
Every incoming request to poly_utilities/omnichat/webhook/telegram must pass three defenses before ingestion: a 120 req/min/IP rate limit, a 2 MB payload body cap, and constant-time hash_equals() validation of the X-Telegram-Bot-Api-Secret-Token header against your encrypted webhook_secret.
Can I run multiple Telegram bots for different Perfex CRM departments?
Yes. Create a separate Telegram Bot channel entry per bot in OmniChat Settings, enter each bot's username as its Account ID, assign its target department/staff member, and include ?account_id=YOUR_BOT_USERNAME in each bot's setWebhook URL so OmniChat routes inbound and outbound messages cleanly per bot.
What happens if a Telegram user sends a malicious file disguised as a photo or PDF?
Every file fetched via getFile is staged into a temporary file and inspected by OmniChat's 10-layer Poly_omnichat_file_security engine before final storage. Images are rebuilt via PHP GD Image CDR (up to 25 MP), executable extensions (.php, .svg, .html, .exe) are rejected, and malicious PDFs or Zip Bombs are deleted immediately with zero clickable link exposed in the Inbox.
PolyUtilities boosts Perfex CRM with powerful customization and workflow enhancements. Create multi-level menus, group menus by purpose, embed iframe links, open content in popups, and reorganize system navigation with drag-and-drop. Add dynamic widgets across dozens of display positions, use right-click navigation, manage custom JS/CSS, support multi-company and multi-address structures, and convert selected text into tasks instantly. Combined with banners, announcements, quick-access shortcuts, and many smart utilities, PolyUtilities turns Perfex CRM into a faster, cleaner, and highly personalized workspace for every team member.
Need a Custom Perfex CRM Module, Bug Fix, or CodeIgniter 4 Upgrade?
Avoid broken updates, PHP 8.2-8.4 errors, and risky core edits. HeadRandom provides custom Perfex CRM module development, upgrade, and bug-fixing services for any third-party or custom module on your Perfex CRM installation, plus upgrading Perfex CRM from CodeIgniter 3 to CodeIgniter 4 via IgniteCore for Perfex CRM.
Develop new custom modules from scratch, patch bugs or hook conflicts on existing client modules, and update legacy code for clean PHP 8.2-8.4 compatibility with zero core file hacks. View Perfex CRM module development scope.
Migrate your Perfex CRM runtime to CodeIgniter 4 (4.7.6) using IgniteCore for Perfex CRM (independent module by HeadRandom) with Dual-Mode CI3 fallback, 32% to 75% lower latency, 50% less RAM, and custom CI4 porting for third-party modules. See CI3 to CI4 upgrade options.
Combine 2+ HeadRandom services (Custom Module, IgniteCore CI4 Upgrade, or Website Care) to save 30% automatically.