Integrate OpenAI API for generating Telegram responses - #4
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3c643a5f23
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const response = await this.client.chat.completions.create({ | ||
| model: "gpt-5.4-mini", | ||
| messages: [ |
There was a problem hiding this comment.
Cap OpenAI output length before sending to Telegram
The completion request is sent without any output-token/length cap, so the model can return text longer than Telegram accepts in a single sendMessage call (Telegram rejects oversized messages). In that case TelegramService.sendMessage throws, the webhook returns 500, and Telegram will retry the same update, causing failed or repeated processing for long prompts. Please bound the generated length (and/or split long replies) before posting to Telegram.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Pull request overview
Integrates OpenAI-backed reply generation into the Cloudflare Worker Telegram operator so that inbound messages from the allowed chat are forwarded to OpenAI and the model output is sent back to Telegram.
Changes:
- Added an
OpenAiServicewrapper around theopenaiSDK and corresponding unit tests. - Updated Telegram webhook handling to generate AI replies (with a fallback error message on OpenAI failure).
- Added
OPENAI_API_KEYto env validation and updated docs/deps accordingly.
Reviewed changes
Copilot reviewed 8 out of 9 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| README.md | Updates project description and adds dev command documentation. |
| pnpm-lock.yaml | Locks the newly added openai dependency. |
| apps/operator/src/types/env.ts | Adds OPENAI_API_KEY to validated worker bindings. |
| apps/operator/src/services/openai.ts | Introduces OpenAiService to call OpenAI chat completions. |
| apps/operator/src/services/openai.test.ts | Adds unit tests for OpenAI service behavior and error handling. |
| apps/operator/src/modules/telegram/routes.test.ts | Updates webhook tests to expect AI-generated responses and OpenAI failure behavior. |
| apps/operator/src/modules/telegram/controller.ts | Switches from echo replies to OpenAI-generated replies with error fallback. |
| apps/operator/README.md | Documents new OpenAI setup requirements and updated behavior. |
| apps/operator/package.json | Adds openai as a runtime dependency. |
Files not reviewed (1)
- pnpm-lock.yaml: Language not supported
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| let reply: string; | ||
| try { | ||
| const openai = new OpenAiService(c.env.OPENAI_API_KEY, logger); | ||
| reply = await openai.reply(message.text); | ||
| } catch (error) { | ||
| logger.error("openai request failed", { | ||
| error: error instanceof Error ? error.message : String(error), | ||
| }); |
There was a problem hiding this comment.
This webhook handler forwards the user's Telegram message text to OpenAI (a third-party). The PR description/security review says “Data handling / PII: not changed”, which is no longer accurate—please update the PR description/security notes accordingly so reviewers/operators understand the new data flow.
|
|
||
| await telegram.sendMessage({ | ||
| chat_id: chatId, | ||
| text: message.text, | ||
| text: reply, |
There was a problem hiding this comment.
OpenAI responses can be longer than Telegram’s max message size; if reply exceeds Telegram limits, telegram.sendMessage will throw and the webhook will return 500, causing Telegram retries and potentially repeated OpenAI calls/costs. Consider truncating/splitting the reply before sending, and/or catching sendMessage errors to still return 200 to Telegram after logging.
| const openaiCreateMock = vi.fn().mockResolvedValue({ | ||
| choices: [{ message: { content: "AI response" } }], | ||
| }); | ||
|
|
||
| vi.mock("openai", () => ({ | ||
| default: class { | ||
| chat = { completions: { create: openaiCreateMock } }; | ||
| }, | ||
| })); |
There was a problem hiding this comment.
openaiCreateMock isn’t reset between tests (and vi.restoreAllMocks() won’t reset plain vi.fn() mocks), which can make these tests order-dependent if you later add call-count/assertion checks. Consider adding openaiCreateMock.mockReset() (or mockClear()) in beforeEach to keep test state isolated.
What
Integrate the OpenAI API to generate responses for a Telegram bot. This change enhances the bot's functionality by allowing it to send AI-generated replies instead of echoing user messages. The implementation includes updates to the webhook handling and introduces a new service for interacting with the OpenAI API.
Updated the bot to send messages to OpenAI and return the generated responses.
Added a new
OpenAiServiceto handle API interactions.Modified environment variables to include
OPENAI_API_KEY.Updated tests to cover the new AI response functionality.
How to test
Run
pnpm installto ensure all dependencies are installed.Start the local development server with
pnpm dev.Set up the Telegram bot and ensure the
OPENAI_API_KEYis configured.Send a message to the bot and verify it responds with an AI-generated message.
Security review
Secrets / env vars: changed.
Auth / session: not changed.
Network / API calls: changed. (New calls to OpenAI API.)
Data handling / PII: not changed.
Dependencies: added. (Introduced
openaipackage for API integration.)No security-impacting changes identified.
The integration does not expose any new sensitive data.
All API keys are managed through environment variables.