Skip to content

Integrate OpenAI API for generating Telegram responses - #4

Merged
valuecodes merged 3 commits into
mainfrom
ai-features
Apr 4, 2026
Merged

Integrate OpenAI API for generating Telegram responses#4
valuecodes merged 3 commits into
mainfrom
ai-features

Conversation

@valuecodes

Copy link
Copy Markdown
Owner

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 OpenAiService to 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 install to ensure all dependencies are installed.

  • Start the local development server with pnpm dev.

  • Set up the Telegram bot and ensure the OPENAI_API_KEY is 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 openai package 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.

Copilot AI review requested due to automatic review settings April 4, 2026 05:33

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +21 to +23
const response = await this.client.chat.completions.create({
model: "gpt-5.4-mini",
messages: [

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 OpenAiService wrapper around the openai SDK and corresponding unit tests.
  • Updated Telegram webhook handling to generate AI replies (with a fallback error message on OpenAI failure).
  • Added OPENAI_API_KEY to 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.

Comment on lines +46 to +53
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),
});

Copilot AI Apr 4, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
Comment on lines +57 to +60

await telegram.sendMessage({
chat_id: chatId,
text: message.text,
text: reply,

Copilot AI Apr 4, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
Comment on lines +4 to +12
const openaiCreateMock = vi.fn().mockResolvedValue({
choices: [{ message: { content: "AI response" } }],
});

vi.mock("openai", () => ({
default: class {
chat = { completions: { create: openaiCreateMock } };
},
}));

Copilot AI Apr 4, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
@valuecodes
valuecodes merged commit 78c1c2d into main Apr 4, 2026
7 checks passed
@valuecodes
valuecodes deleted the ai-features branch April 5, 2026 13:51
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.

2 participants