chatgpt-telegram-bot

n3d1117GPL-2.0长期未更新

基于 Python 的 Telegram 机器人,接入 OpenAI 官方 API,在聊天窗口里直接提供 ChatGPT 问答、DALL·E 绘图和 Whisper 语音转写。

🤖 A Telegram bot that integrates with OpenAI's official ChatGPT APIs to provide answers, written in Python

0.4.2发布于 2024-12-28 11:20 UTC3,465star1,532fork同步于 2026-11-10 23:41 UTC

怎么上手

由 README 提炼,执行前请确认
git clone https://github.com/n3d1117/chatgpt-telegram-bot.git && cd chatgpt-telegram-bot
pip install -r requirements.txt
python bot/main.py
硬件要求按 README 说明

README 未说明硬件要求,仅要求 Python 3.9+;实际算力在 OpenAI 云端,本地无需 GPU 显存。

有 Docker 镜像
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

把 OpenAI 官方 ChatGPT、DALL·E、Whisper 接进 Telegram 的 Python 机器人,配置好就能用

基于 Python 的 Telegram 机器人,接入 OpenAI 官方 API,在聊天窗口里直接提供 ChatGPT 问答、DALL·E 绘图和 Whisper 语音转写。

核心能力

  • 用 /reset 重置对话,自动摘要控制 token 消耗
  • 用 /image 调 DALL·E 生成图片,用 Whisper 转写音视频
  • 按用户统计 token 用量,支持 /stats 与预算限制
  • 支持流式输出、GPT-4、GPT-4o、o1 及函数插件
  • 用 ALLOWED_TELEGRAM_USER_IDS 限制可访问用户

容易踩的坑

需先把 .env.example 复制为 .env 并填好 OPENAI_API_KEY 与 TELEGRAM_BOT_TOKEN;转写音视频可能需另装 ffmpeg;默认 ALLOWED_TELEGRAM_USER_IDS 为 * 即所有人可用,需自行收紧。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本0.4.2
  1. 0.4.2Release 0.4.2最新正式版2024-12-28 · 2024-12-28 11:20 UTC

    What's Changed

    New Contributors

    Full Changelog: https://github.com/n3d1117/chatgpt-telegram-bot/compare/0.4.1...0.4.2

  2. 0.4.1Release 0.4.12024-05-14 · 2024-05-14 15:13 UTC
    查看更新说明

    What's Changed

    New Contributors

    Full Changelog: https://github.com/n3d1117/chatgpt-telegram-bot/compare/0.4.0...0.4.1

  3. 0.4.0Release 0.4.02023-12-11 · 2023-12-11 19:49 UTC
    查看更新说明

    Support for GPT-4 Turbo, DALL·E 3, Text-to-Speech and Vision! 🎉

    What's Changed

    New Contributors

    Full Changelog: https://github.com/n3d1117/chatgpt-telegram-bot/compare/0.3.1...0.4.0

  4. 0.3.1Release 0.3.12023-08-05 · 2023-08-05 11:54 UTC
    查看更新说明

    What's Changed

    Full Changelog: https://github.com/n3d1117/chatgpt-telegram-bot/compare/0.3.0...0.3.1

  5. 0.3.0Release 0.3.02023-08-04 · 2023-08-04 16:42 UTC
    查看更新说明

    Plugins are here! 🎉

    You can now extend the bot's functionality with 3rd party services. See the updated README for more information!

    What's Changed

    New Contributors

    Full Changelog: https://github.com/n3d1117/chatgpt-telegram-bot/compare/0.2.6...0.3.0

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    ChatGPT Telegram Bot

    python-version openai-version license Publish Docker image

    A Telegram bot that integrates with OpenAI's official ChatGPT, DALL·E and Whisper APIs to provide answers. Ready to use with minimal configuration required.

    Screenshots

    Demo

    demo

    Plugins

    plugins

    Features

    • Support markdown in answers
    • Reset conversation with the /reset command
    • Typing indicator while generating a response
    • Access can be restricted by specifying a list of allowed users
    • Docker and Proxy support
    • Image generation using DALL·E via the /image command
    • Transcribe audio and video messages using Whisper (may require ffmpeg)
    • Automatic conversation summary to avoid excessive token usage
    • Track token usage per user - by @AlexHTW
    • Get personal token usage statistics via the /stats command - by @AlexHTW
    • User budgets and guest budgets - by @AlexHTW
    • Stream support
    • GPT-4 support
      • If you have access to the GPT-4 API, simply change the OPENAI_MODEL parameter to gpt-4
    • Localized bot language
      • Available languages :brazil: :cn: :finland: :de: :indonesia: :iran: :it: :malaysia: :netherlands: :poland: :ru: :saudi_arabia: :es: :taiwan: :tr: :ukraine: :gb: :uzbekistan: :vietnam: :israel:
    • Improved inline queries support for group and private chats - by @bugfloyd
      • To use this feature, enable inline queries for your bot in BotFather via the /setinline command
    • Support new models announced on June 13, 2023
    • Support functions (plugins) to extend the bot's functionality with 3rd party services
      • Weather, Spotify, Web search, text-to-speech and more. See here for a list of available plugins
    • Support unofficial OpenAI-compatible APIs - by @kristaller486
    • (NEW!) Support GPT-4 Turbo and DALL·E 3 announced on November 6, 2023 - by @AlexHTW
    • (NEW!) Text-to-speech support announced on November 6, 2023 - by @gilcu3
    • (NEW!) Vision support announced on November 6, 2023 - by @gilcu3
    • (NEW!) GPT-4o model support announced on May 12, 2024 - by @err09r
    • (NEW!) o1 and o1-mini model preliminary support

    Additional features - help needed!

    If you'd like to help, check out the issues section and contribute!
    If you want to help with translations, check out the Translations Manual

    PRs are always welcome!

    Prerequisites

    Getting started

    Configuration

    Customize the configuration by copying .env.example and renaming it to .env, then editing the required parameters as desired:

    ParameterDescription
    OPENAI_API_KEYYour OpenAI API key, you can get it from here
    TELEGRAM_BOT_TOKENYour Telegram bot's token, obtained using BotFather (see tutorial)
    ADMIN_USER_IDSTelegram user IDs of admins. These users have access to special admin commands, information and no budget restrictions. Admin IDs don't have to be added to ALLOWED_TELEGRAM_USER_IDS. Note: by default, no admin (-)
    ALLOWED_TELEGRAM_USER_IDSA comma-separated list of Telegram user IDs that are allowed to interact with the bot (use getidsbot to find your user ID). Note: by default, everyone is allowed (*)

    Optional configuration

    The following parameters are optional and can be set in the .env file:

    Budgets
    ParameterDescriptionDefault value
    BUDGET_PERIODDetermines the time frame all budgets are applied to. Available periods: daily (resets budget every day), monthly (resets budgets on the first of each month), all-time (never resets budget). See the Budget Manual for more informationmonthly
    USER_BUDGETSA comma-separated list of $-amounts per user from list ALLOWED_TELEGRAM_USER_IDS to set custom usage limit of OpenAI API costs for each. For *- user lists the first USER_BUDGETS value is given to every user. Note: by default, no limits for any user (*). See the Budget Manual for more information*
    GUEST_BUDGET$-amount as usage limit for all guest users. Guest users are users in group chats that are not in the ALLOWED_TELEGRAM_USER_IDS list. Value is ignored if no usage limits are set in user budgets (USER_BUDGETS=*). See the Budget Manual for more information100.0
    TOKEN_PRICE$-price per 1000 tokens used to compute cost information in usage statistics. Source: https://openai.com/pricing0.002
    IMAGE_PRICESA comma-separated list with 3 elements of prices for the different image sizes: 256x256, 512x512 and 1024x1024. Source: https://openai.com/pricing0.016,0.018,0.02
    TRANSCRIPTION_PRICEUSD-price for one minute of audio transcription. Source: https://openai.com/pricing0.006
    VISION_TOKEN_PRICEUSD-price per 1K tokens of image interpretation. Source: https://openai.com/pricing0.01
    TTS_PRICESA comma-separated list with prices for the tts models: tts-1, tts-1-hd. Source: https://openai.com/pricing0.015,0.030

    Check out the Budget Manual for possible budget configurations.

    Additional optional configuration options
    ParameterDescriptionDefault value
    ENABLE_QUOTINGWhether to enable message quoting in private chatstrue
    ENABLE_IMAGE_GENERATIONWhether to enable image generation via the /image commandtrue
    ENABLE_TRANSCRIPTIONWhether to enable transcriptions of audio and video messagestrue
    ENABLE_TTS_GENERATIONWhether to enable text to speech generation via the /ttstrue
    ENABLE_VISIONWhether to enable vision capabilities in supported modelstrue
    PROXYProxy to be used for OpenAI and Telegram bot (e.g. http://localhost:8080)-
    OPENAI_PROXYProxy to be used only for OpenAI (e.g. http://localhost:8080)-
    TELEGRAM_PROXYProxy to be used only for Telegram bot (e.g. http://localhost:8080)-
    OPENAI_MODELThe OpenAI model to use for generating responses. You can find all available models heregpt-4o
    OPENAI_BASE_URLEndpoint URL for unofficial OpenAI-compatible APIs (e.g., LocalAI or text-generation-webui)Default OpenAI API URL
    ASSISTANT_PROMPTA system message that sets the tone and controls the behavior of the assistantYou are a helpful assistant.
    SHOW_USAGEWhether to show OpenAI token usage information after each responsefalse
    STREAMWhether to stream responses. Note: incompatible, if enabled, with N_CHOICES higher than 1true
    MAX_TOKENSUpper bound on how many tokens the ChatGPT API will return1200 for GPT-3, 2400 for GPT-4
    VISION_MAX_TOKENSUpper bound on how many tokens vision models will return300 for gpt-4o
    VISION_MODELThe Vision to Speech model to use. Allowed values: gpt-4ogpt-4o
    ENABLE_VISION_FOLLOW_UP_QUESTIONSIf true, once you send an image to the bot, it uses the configured VISION_MODEL until the conversation ends. Otherwise, it uses the OPENAI_MODEL to follow the conversation. Allowed values: true or falsetrue
    MAX_HISTORY_SIZEMax number of messages to keep in memory, after which the conversation will be summarised to avoid excessive token usage15
    MAX_CONVERSATION_AGE_MINUTESMaximum number of minutes a conversation should live since the last message, after which the conversation will be reset180
    VOICE_REPLY_WITH_TRANSCRIPT_ONLYWhether to answer to voice messages with the transcript only or with a ChatGPT response of the transcriptfalse
    VOICE_REPLY_PROMPTSA semicolon separated list of phrases (i.e. Hi bot;Hello chat). If the transcript starts with any of them, it will be treated as a prompt even if VOICE_REPLY_WITH_TRANSCRIPT_ONLY is set to true-
    VISION_PROMPTA phrase (i.e. What is in this image). The vision models use it as prompt to interpret a given image. If there is caption in the image sent to the bot, that supersedes this parameterWhat is in this image
    N_CHOICESNumber of answers to generate for each input message. Note: setting this to a number higher than 1 will not work properly if STREAM is enabled1
    TEMPERATURENumber between 0 and 2. Higher values will make the output more random1.0
    PRESENCE_PENALTYNumber between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far0.0
    FREQUENCY_PENALTYNumber between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far0.0
    IMAGE_FORMATThe Telegram image receive mode. Allowed values: document or photophoto
    IMAGE_MODELThe DALL·E model to be used. Available models: dall-e-2 and dall-e-3, find current available models heredall-e-2
    IMAGE_QUALITYQuality of DALL·E images, only available for dall-e-3-model. Possible options: standard or hd, beware of pricing differences.standard
    IMAGE_STYLEStyle for DALL·E image generation, only available for dall-e-3-model. Possible options: vivid or natural. Check availbe styles here.vivid
    IMAGE_SIZEThe DALL·E generated image size. Must be 256x256, 512x512, or 1024x1024 for dall-e-2. Must be 1024x1024 for dall-e-3 models.512x512
    VISION_DETAILThe detail parameter for vision models, explained Vision Guide. Allowed values: low or highauto
    GROUP_TRIGGER_KEYWORDIf set, the bot in group chats will only respond to messages that start with this keyword-
    IGNORE_GROUP_TRANSCRIPTIONSIf set to true, the bot will not process transcriptions in group chatstrue
    IGNORE_GROUP_VISIONIf set to true, the bot will not process vision queries in group chatstrue
    BOT_LANGUAGELanguage of general bot messages. Currently available: en, de, ru, tr, it, fi, es, id, nl, zh-cn, zh-tw, vi, fa, pt-br, uk, ms, uz, ar. Contribute with additional translationsen
    WHISPER_PROMPTTo improve the accuracy of Whisper's transcription service, especially for specific names or terms, you can set up a custom message. Speech to text - Prompting-
    TTS_VOICEThe Text to Speech voice to use. Allowed values: alloy, echo, fable, onyx, nova, or shimmeralloy
    TTS_MODELThe Text to Speech model to use. Allowed values: tts-1 or tts-1-hdtts-1

    Check out the official API reference for more details.

    Functions
    ParameterDescriptionDefault value
    ENABLE_FUNCTIONSWhether to use functions (aka plugins). You can read more about functions heretrue (if available for the model)
    FUNCTIONS_MAX_CONSECUTIVE_CALLSMaximum number of back-to-back function calls to be made by the model in a single response, before displaying a user-facing message10
    PLUGINSList of plugins to enable (see below for a full list), e.g: PLUGINS=wolfram,weather-
    SHOW_PLUGINS_USEDWhether to show which plugins were used for a responsefalse
    Available plugins
    NameDescriptionRequired environment variable(s)Dependency
    weatherDaily weather and 7-day forecast for any location (powered by Open-Meteo)-
    wolframWolframAlpha queries (powered by WolframAlpha)WOLFRAM_APP_IDwolframalpha
    ddg_web_searchWeb search (powered by DuckDuckGo)-duckduckgo_search
    ddg_image_searchSearch image or GIF (powered by DuckDuckGo)-duckduckgo_search
    cryptoLive cryptocurrencies rate (powered by CoinCap) - by @stumpyfr-
    spotifySpotify top tracks/artists, currently playing song and content search (powered by Spotify). Requires one-time authorization.SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, SPOTIFY_REDIRECT_URIspotipy
    worldtimeapiGet latest world time (powered by WorldTimeAPI) - by @noriellecruzWORLDTIME_DEFAULT_TIMEZONE
    diceSend a dice in the chat!-
    youtube_audio_extractorExtract audio from YouTube videos-pytube
    deepl_translateTranslate text to any language (powered by DeepL) - by @LedyBacerDEEPL_API_KEY
    gtts_text_to_speechText to speech (powered by Google Translate APIs)-gtts
    whoisQuery the whois domain database - by @jnaskali-whois
    webshotScreenshot a website from a given url or domain name - by @noriellecruz-
    auto_ttsText to speech using OpenAI APIs - by @Jipok-
    Environment variables
    VariableDescriptionDefault value
    WOLFRAM_APP_IDWolfram Alpha APP ID (required only for the wolfram plugin, you can get one here)-
    SPOTIFY_CLIENT_IDSpotify app Client ID (required only for the spotify plugin, you can find it on the dashboard)-
    SPOTIFY_CLIENT_SECRETSpotify app Client Secret (required only for the spotify plugin, you can find it on the dashboard)-
    SPOTIFY_REDIRECT_URISpotify app Redirect URI (required only for the spotify plugin, you can find it on the dashboard)-
    WORLDTIME_DEFAULT_TIMEZONEDefault timezone to use, i.e. Europe/Rome (required only for the worldtimeapi plugin, you can get TZ Identifiers from here)-
    DUCKDUCKGO_SAFESEARCHDuckDuckGo safe search (on, off or moderate) (optional, applies to ddg_web_search and ddg_image_search)moderate
    DEEPL_API_KEYDeepL API key (required for the deepl plugin, you can get one here)-

    Installing

    Clone the repository and navigate to the project directory:

    git clone https://github.com/n3d1117/chatgpt-telegram-bot.git
    cd chatgpt-telegram-bot
    
    From Source
    1. Create a virtual environment:
    python -m venv venv
    
    1. Activate the virtual environment:
    # For Linux or macOS:
    source venv/bin/activate
    
    # For Windows:
    venv\Scripts\activate
    
    1. Install the dependencies using requirements.txt file:
    pip install -r requirements.txt
    
    1. Use the following command to start the bot:
    python bot/main.py
    
    Using Docker Compose

    Run the following command to build and run the Docker image:

    docker compose up
    
    Ready-to-use Docker images

    You can also use the Docker image from Docker Hub:

    docker pull n3d1117/chatgpt-telegram-bot:latest
    docker run -it --env-file .env n3d1117/chatgpt-telegram-bot
    

    or using the GitHub Container Registry:

    docker pull ghcr.io/n3d1117/chatgpt-telegram-bot:latest
    docker run -it --env-file .env ghcr.io/n3d1117/chatgpt-telegram-bot
    
    Docker manual build
    docker build -t chatgpt-telegram-bot .
    docker run -it --env-file .env chatgpt-telegram-bot
    
    Heroku

    Here is an example of Procfile for deploying using Heroku (thanks err09r!):

    worker: python -m venv venv && source venv/bin/activate && pip install -r requirements.txt && python bot/main.py
    

    Credits

    Disclaimer

    This is a personal project and is not affiliated with OpenAI in any way.

    License

    This project is released under the terms of the GPL 2.0 license. For more information, see the LICENSE file included in the repository.