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:
- To clear or list Inline Mode context, tag the bot in chat without a query and tap on the appropriate button
- Inline mode is capped at a 64-character limit because of
callback_datalimits, 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!
- 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
- Clone this repository
- Run
npm cioryarn install - Run
npx wrangler secret put TELEGRAM_BOT_TOKENand set the Telegram bot token - Run
npx wrangler secret put OPENAI_API_KEYand set the OpenAI API key - Add space-delimited case-sensitive usernames to whitelist in
TELEGRAM_USERNAME_WHITELISTin wrangler.toml - (Optional) To allow extra lines of context, run
npx wrangler kv:namespace create contextand replace the ID ofCHATGPT_TELEGRAM_BOT_KVand increaseCONTEXTto more than 0 in wrangler.toml (will consume a lot more tokens), else removekv_namespacesblock entirely from wrangler.toml - (Optional) To change the model, update
CHATGPT_MODELin wrangler.toml to whatever you want as documented at https://platform.openai.com/docs/api-reference/chat/create#chat/create-model - (Optional) To include a
systemmessage to set the AI's behavior, updateCHATGPT_BEHAVIORin wrangler.toml - Run
npx wrangler publishto deploy to Cloudflare Workers - (Optional) Enable
Inline Modefor 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
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


