Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Telegram group bot

A Telegram bot deployed as a Cloudflare Worker. It responds to five commands in private chats and groups:

Command Purpose
/start Welcomes the user and lists the available commands
/services Shares the services page
/resources Shares the resources page
/contact Shares the contact page
/processlatest Publishes the latest Word document from Drive to a configured Telegram channel (authorized users/chats only)

All other messages are ignored. Change the reply text and example links in the messages object in src/index.js.

Drive documents to Telegram

/processlatest queues a job to select the most recently modified .docx directly inside one Drive folder. It converts the document body into Telegram rich posts using sendRichMessage, preserving supported formatting and embedded images in document order. Long documents are split into independently valid posts without breaking formatting tags, Unicode characters, or HTML entities.

Formatting and images

Word content Published result
Bold, italic, underline, strikethrough Matching Telegram formatting, including inherited Word styles
Headings, title, quote styles Headings and quotations
Highlight, subscript, superscript Marked, subscript, and superscript text; highlight colors are not retained
Paragraphs, line breaks, hyperlinks Paragraphs, breaks, and safe HTTP/HTTPS/mail/phone links
Bullets and numbered lists Lists with starting numbers and common letter/Roman numbering; nested indentation is approximated
Tables Native table rows/cells, header rows, and horizontal merged cells
Embedded JPEG/PNG Inline media blocks when the dimensions meet Telegram photo limits
Other embedded image formats or oversized photo dimensions Original image files attached within the post

Images in table cells appear immediately after their row, with a placeholder in the cell, because Telegram table cells cannot contain media blocks. Floating images appear at their document anchor position. Image-only documents are supported. Repeated image placements remain repeated, but Word's alternative modern/legacy copies are not posted twice. Images are uploaded directly from the document; no public image URLs are required. Linked external images must first be embedded in Word; missing/linked images cause validation to fail before anything is posted.

Exact fonts, font sizes/colors, page layout, positioning, image cropping/rotation, vertical table merges, custom list-marker patterns, headers/footers, footnotes, charts and equations are not reproduced. Nested tables and tables wider than 20 columns are rejected before posting. Extremely long blocks/tables can continue in another post. Legacy .doc files and native Google Docs are not supported.

Downloads are limited to 5 MB, each parsed XML part to 2 MB, each image to 10 MB, total extracted parts to 24 MB, extracted text to 100,000 characters, and image occurrences to 100. Posts use conservative limits of 24,000 UTF-8 text bytes, 180 generated tags, and 10 image occurrences per post. The implementation follows Telegram's rich message API.

D1 stores a permanent record keyed by Drive file ID. Completed files are never posted again, even if edited. Each /processlatest command searches newest to oldest by modification time, across all Drive result pages, and selects the first eligible file. Completed files, files currently processing, and files awaiting review are skipped. Files whose download/extraction failed remain eligible for retry. When none are eligible, the bot reports that no unprocessed documents are available. A new Drive file ID is treated as a new document even if its content is identical.

An atomic database claim prevents concurrent processing. Download/extraction failures are retryable. Once posting begins, a failure or ambiguous response puts the file in needs_review, preventing automatic duplicate posts. Each confirmed Telegram message ID and the number of posted parts are recorded. If execution stops abruptly, a subsequent attempt marks claims older than 15 minutes for review. Telegram and D1 cannot commit atomically, so this deliberately prefers manual review over potentially posting twice. Never reset a record without checking the channel, including posts whose responses may have been lost. Notification delivery to the requesting chat can retry separately without reposting a completed document.

One-time setup

  1. Enable the Google Drive API in a Google Cloud project, create a service account and download its JSON key. Share the source Drive folder with the service account email as Viewer. Your organization's sharing policy must permit this.

  2. Add the Telegram bot as a channel administrator with permission to post messages.

  3. Create Cloudflare resources:

    npx.cmd wrangler d1 create mytestbot-documents
    npx.cmd wrangler queues create mytestbot-documents
    npx.cmd wrangler queues create mytestbot-documents-failed
  4. Replace the placeholder database_id in wrangler.jsonc with the ID returned by D1. Apply the migration:

    npx.cmd wrangler d1 migrations apply DB --remote
  5. Set these Worker secrets with npx.cmd wrangler secret put NAME:

    Name Value
    GOOGLE_SERVICE_ACCOUNT_JSON Complete service-account key JSON, on one line
    GDRIVE_FOLDER_ID Folder ID from its Drive URL
    TELEGRAM_CHANNEL_ID @channel_username, or numeric -100... ID for a private channel
    ALLOWED_TELEGRAM_USER_IDS Comma-separated numeric Telegram user IDs allowed to run the command
    ALLOWED_TELEGRAM_CHAT_IDS Comma-separated chat IDs where the command is allowed; for a private conversation this is the user's ID

    Both allowlists must match; an empty allowlist denies access. Keep existing TELEGRAM_BOT_TOKEN and WEBHOOK_SECRET secrets configured. Do not commit the downloaded Google key.

  6. Run npm.cmd test, npm.cmd run deploy:check, npm.cmd run deploy, and npm.cmd run setup to update the command menu. Send /processlatest from an authorized chat. The channel is the publication destination; the requesting chat receives status messages.

For local development put Worker secrets in ignored .dev.vars (Wrangler does not use the setup script's .env) and apply npx.cmd wrangler d1 migrations apply DB --local. Tests use an in-memory SQLite database and mocked APIs; they do not send real posts. Node.js 24 is recommended for the test suite's built-in SQLite support.

Jobs retry up to three times and exhausted jobs go to mytestbot-documents-failed. Inspect Worker logs and D1 records before manually retrying a job. Inspect records with:

npx.cmd wrangler d1 execute DB --remote --command "SELECT file_id, file_name, status, next_part, message_ids, last_error FROM processed_files ORDER BY started_at DESC LIMIT 20"

Implementation references: Google service-account authentication, Drive file search, Cloudflare D1, and Cloudflare Queues.

How it works

sequenceDiagram
    participant U as Telegram user
    participant T as Telegram
    participant W as Cloudflare Worker
    participant API as Telegram Bot API

    U->>T: Sends /services in a group
    T->>W: POST /webhook with secret header
    W->>W: Validate secret and read command
    W->>API: sendMessage(chat_id, reply)
    API-->>U: Show reply in the same group
    W-->>T: 200 OK
Loading
  1. Telegram sends each message update to the public /webhook route.
  2. The Worker checks Telegram's secret header before accepting the update.
  3. handleUpdate extracts the first word and removes an optional group suffix such as @MyBot.
  4. A supported command is mapped to its reply; every other message is ignored.
  5. The Worker calls Telegram's sendMessage API with the original chat ID, so the reply appears in the same chat.

The GET / route is a health check and returns Telegram bot is running.

Configuration

Use Node.js 24 or newer. Create .env in the project directory:

TELEGRAM_BOT_TOKEN=token-from-botfather
WEBHOOK_SECRET=a-long-random-secret
WEBHOOK_URL=https://mytestbot.example.workers.dev

Keep .env private. scripts/setup-webhook.js automatically uses the /webhook path.

Add the same token and secret to the deployed Worker:

npx.cmd wrangler secret put TELEGRAM_BOT_TOKEN
npx.cmd wrangler secret put WEBHOOK_SECRET

Deploy and connect Telegram

npm.cmd install
npm.cmd test
npm.cmd run deploy:check
npm.cmd run deploy
npm.cmd run setup

Run setup after the first deployment or whenever the Worker URL, webhook secret, or command menu changes. Then add the bot to a Telegram group and send /start.

For local development, run npm.cmd run dev. Telegram requires a public HTTPS webhook, so receiving real updates requires a public tunnel or a deployed Worker URL.

Project structure

src/          Cloudflare Worker, Drive access, document parsing, and processing
scripts/      Webhook setup and deployment checks
test/         Automated tests
migrations/   D1 database migrations
wrangler.jsonc  Cloudflare Worker deployment settings

The Worker entry point is src/index.js. Run setup and tests from the project root with npm.cmd run setup and npm.cmd test.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages