Skip to content

feat: add Telegram backend#65

Open
nxm wants to merge 2 commits intopinpox:masterfrom
nxm:master
Open

feat: add Telegram backend#65
nxm wants to merge 2 commits intopinpox:masterfrom
nxm:master

Conversation

@nxm
Copy link
Copy Markdown

@nxm nxm commented Apr 30, 2026

Adds a Telegram Bot API backend using long-polling getUpdates so no public webhook endpoint is needed. Implements the full Backend interface: text replies (with reply_parameters), document uploads via multipart, typing indicators, and incoming attachment download (photo/document/audio/video/ voice/video_note) saved under /attachments.

  • telegram/: new package, stdlib-only (net/http + encoding/json)
  • config.go / main.go: wire backendTelegram, env vars (OPENCROW_TELEGRAM_TOKEN[_FILE], _API_BASE, _POLL_TIMEOUT, _ALLOWED_USERS), validation, and createTelegramBackend
  • nix/module.nix: telegram in OPENCROW_BACKEND enum, env options, assertion that the token is provided when backend is telegram
  • README.md / docs/configuration.md: backend listing and Telegram configuration reference
  • tests: backend-level (httptest fake API: send, getUpdates flow, allowlist, attachment download) and config-level (defaults, token file, allowlist override)

Summary by CodeRabbit

Release Notes

  • New Features

    • Telegram is now a supported messaging backend alongside existing options.
    • Telegram backend includes message sending/receiving, file sharing, and typing indicators with long-polling support.
    • Added configurable user allowlist for Telegram conversations.
  • Documentation

    • Updated configuration guide with Telegram setup and environment variable options.
  • Tests

    • Added comprehensive test suite for Telegram backend functionality.

Adds a Telegram Bot API backend using long-polling getUpdates so no public
webhook endpoint is needed. Implements the full Backend interface: text
replies (with reply_parameters), document uploads via multipart, typing
indicators, and incoming attachment download (photo/document/audio/video/
voice/video_note) saved under <session>/attachments.

- telegram/: new package, stdlib-only (net/http + encoding/json)
- config.go / main.go: wire backendTelegram, env vars
  (OPENCROW_TELEGRAM_TOKEN[_FILE], _API_BASE, _POLL_TIMEOUT,
  _ALLOWED_USERS), validation, and createTelegramBackend
- nix/module.nix: telegram in OPENCROW_BACKEND enum, env options,
  assertion that the token is provided when backend is telegram
- README.md / docs/configuration.md: backend listing and Telegram
  configuration reference
- tests: backend-level (httptest fake API: send, getUpdates flow,
  allowlist, attachment download) and config-level (defaults, token
  file, allowlist override)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@nxm nxm marked this pull request as draft April 30, 2026 14:55
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 30, 2026

Warning

Rate limit exceeded

@nxm has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 49 minutes and 13 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9494f383-c2b3-4f0d-b9a7-f6237f11a391

📥 Commits

Reviewing files that changed from the base of the PR and between d319c20 and fa64680.

📒 Files selected for processing (4)
  • telegram/backend.go
  • telegram/backend_test.go
  • telegram/markdown.go
  • telegram/markdown_test.go
📝 Walkthrough

Walkthrough

This pull request adds Telegram as a new messaging backend to the OpenCrow system. It includes configuration loading for Telegram tokens and settings, implements a complete Telegram Bot API backend using long-polling, and integrates the backend into the application factory. Configuration, documentation, and tests are updated accordingly.

Changes

Cohort / File(s) Summary
Documentation & Configuration Reference
README.md, docs/configuration.md
Updated README architecture diagram and added new Telegram configuration documentation section covering token input, polling timeout, and user allowlist options.
Configuration & Validation
config.go, config_test.go, nix/module.nix
Extended Config struct with TelegramConfig field; added token loading from file or environment variable, poll timeout parsing, and user allowlist handling; added validation tests and nix module assertions for Telegram backend requirements.
Backend Integration
main.go
Added Telegram backend case to createBackend factory function with configuration wiring and error handling.
Telegram Backend Implementation
telegram/backend.go, telegram/backend_test.go
Implemented complete Telegram Bot API backend with long-polling Run loop, message delivery to handler with user/conversation filtering, outbound SendMessage/SendFile/SetTyping operations, and file attachment downloading with local storage; comprehensive test suite covering configuration validation, polling, message routing, allowlist enforcement, and attachment handling.

Sequence Diagram(s)

sequenceDiagram
    participant Backend as Telegram Backend
    participant TelegramAPI as Telegram Bot API
    participant Handler as Message Handler
    participant Storage as Attachments Storage
    
    loop Long-Polling Loop
        Backend->>TelegramAPI: getUpdates(offset)
        TelegramAPI-->>Backend: updates[]
        alt Has Updates
            loop For each update
                alt Has Message
                    Backend->>Backend: Validate AllowedUsers & ConversationID
                    alt Validation passes
                        alt Has attachment
                            Backend->>TelegramAPI: getFile(file_id)
                            TelegramAPI-->>Backend: file_path
                            Backend->>TelegramAPI: Download file binary
                            TelegramAPI-->>Backend: file content
                            Backend->>Storage: Save to SessionBaseDir/attachments
                            Backend->>Handler: Deliver message + attachment marker
                        else Text only
                            Backend->>Handler: Deliver message
                        end
                    end
                    Backend->>Backend: Advance offset
                end
            end
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Poem

🐰 A telegram arrives with a hop and a bound,
Through long-polling loops, new messages are found,
With files attached and users approved,
The Telegram backend is smoothly grooved,
Now four roads lead to OpenCrow's destination! 📱✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.04% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: add Telegram backend' accurately summarizes the main change: implementing a new Telegram backend for the project. It is clear, concise, and directly related to the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 49 minutes and 13 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

@nxm nxm marked this pull request as ready for review April 30, 2026 14:59
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
telegram/backend.go (1)

635-642: 💤 Low value

Comment mentions "n runes" but implementation truncates by bytes.

The function counts bytes via len(s), not runes. For ASCII this works fine, but multi-byte UTF-8 characters could be cut mid-sequence.

Suggested fix for rune-accurate truncation
 // truncate returns s shortened to n runes with an ellipsis suffix when cut.
 func truncate(s string, n int) string {
-	if len(s) <= n {
+	runes := []rune(s)
+	if len(runes) <= n {
 		return s
 	}
 
-	return s[:n] + "..."
+	return string(runes[:n]) + "..."
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@telegram/backend.go` around lines 635 - 642, The truncate function currently
measures and slices by bytes (using len(s) and s[:n]) which can split multi-byte
UTF-8 runes; update truncate to operate on runes instead: convert the string to
a rune slice (or use utf8.RuneCountInString to check length) and then slice the
rune slice to at most n runes before converting back to string and appending
"..." when truncated; keep the function name truncate and preserve behavior for
short strings (return original) and for truncated strings (return first n runes
+ "...").
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@telegram/backend.go`:
- Around line 635-642: The truncate function currently measures and slices by
bytes (using len(s) and s[:n]) which can split multi-byte UTF-8 runes; update
truncate to operate on runes instead: convert the string to a rune slice (or use
utf8.RuneCountInString to check length) and then slice the rune slice to at most
n runes before converting back to string and appending "..." when truncated;
keep the function name truncate and preserve behavior for short strings (return
original) and for truncated strings (return first n runes + "...").

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e6e97e40-948a-4fa1-9e3c-08819ccfe543

📥 Commits

Reviewing files that changed from the base of the PR and between 2815f11 and d319c20.

📒 Files selected for processing (8)
  • README.md
  • config.go
  • config_test.go
  • docs/configuration.md
  • main.go
  • nix/module.nix
  • telegram/backend.go
  • telegram/backend_test.go

Pi's replies often include CommonMark formatting (**bold**, `code`,
fenced blocks, [links](url), bullets). Telegram does not interpret
markdown without a parse_mode hint, so those characters previously
showed up literally.

Convert markdown to the HTML subset Telegram accepts (b/i/s/code/pre/
a/blockquote, "•" for bullets, headings → bold) and send with
parse_mode=HTML. If Telegram rejects the rendered HTML (unbalanced
markup slipping through the converter), retry once as plain text
without parse_mode so messages still get through.

Switch MarkdownFlavor to MarkdownFull and update SystemPromptExtra so
pi knows it can use markdown freely.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant