cf-workers-chatgpt-telegram-bot
Description
Serverless Telegram bot in webhook mode to quickly interface with OpenAI's Chat Completion API
This bot supports private chats, group chats and inline mode (tagging the bot in any chat with a query) with a confirmation button so as you don't consume tokens live.
Notes:
- Inline mode has been developed deliberately to not support using context KV even though it should technically be possible
- Inline mode is capped at a 64-character limit because of
callback_data
limits, but it can be solved by saving the query in KV if required - This is mainly for personal use, if you would like to add features, do fork the repository. Do perform PRs back if you would be so kind!
Prerequisites
- A Cloudflare account with Workers (at least free-tier) enabled
- The Telegram bot token of a bot created on Telegram via @BotFather
- An OpenAI API key that has the ability to use the Chat Completion API
Getting Started
Wrangler
- Clone this repository
- Run
npm ci
oryarn install
- Run
npx wrangler secret put TELEGRAM_BOT_TOKEN
and set the Telegram bot token - Run
npx wrangler secret put OPENAI_API_KEY
and set the OpenAI API key - Add space-delimited case-sensitive usernames to whitelist in
TELEGRAM_USERNAME_WHITELIST
in wrangler.toml - (Optional) To allow extra lines of context, run
npx wrangler kv:namespace create context
and replace the ID ofCHATGPT_TELEGRAM_BOT_KV
and increaseCONTEXT
to more than 0 in wrangler.toml (will consume a lot more tokens) - (Optional) To change the model, update
CHATGPT_MODEL
in wrangler.toml to whatever you want as documented at https://platform.openai.com/docs/api-reference/chat/create#chat/create-model - Run
npx wrangler publish
to deploy to Cloudflare Workers - (Optional) Enable
Inline Mode
for the bot on BotFather to allow inline query flow - Replace
{TELEGRAM_BOT_TOKEN}
and{WORKERS_NAMESPACE}
on the followinghttps://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/setWebhook?&allowed_updates=%5B%22message%22%2C%22inline_query%22%2C%22callback_query%22%5D&url=https%3A%2F%2Fcf-workers-chatgpt-telegram-bot.{WORKERS_NAMESPACE}.workers.dev%2F{TELEGRAM_BOT_TOKEN}
and access it on your browser
Other Optional Steps
Commands list (for BotFather as well)
chatgpt - Triggers use of the bot in group chats without toggling Private Mode
context - Shows stored context for the current chat
clear - Clears the stored context for the current chat and any ForceReply messages