├── .env ├── LICENSE ├── README.md └── botGPT.py /.env: -------------------------------------------------------------------------------- 1 | BOT_API_KEY= 2 | OPENAI_API_KEY= 3 | USER_KEY= 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2022, juan-miii 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | 3. Neither the name of the copyright holder nor the names of its 16 | contributors may be used to endorse or promote products derived from 17 | this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 23 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 25 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 26 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 27 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GPT Telegram Bot 2 | Script for a Telegram bot that uses [OpenAI API](https://beta.openai.com/overview) similar to ChatGPT. It has all its capabilities plus the fact that by using the API directly, there is no waiting time prior to using this bot. The current downside to this project is that the script has to be running for the bot to work. _Anyone willing to contribute to this project in anyway, particularly by making it work forever, please visit the [Contribution](#contribution) section._ 3 | 4 | ## Features 5 | - [ ] Use OpenAI API through Telegram 6 | - [ ] Get text replies by default 7 | - [ ] Get code responses by starting your messages with `>>>` 8 | - [ ] Get code related answers by using the word `code` in your meessage 9 | - [ ] Make your bot private for personal use 10 | 11 | ## How to install 12 | ### 1. Install Python 13 | Get Python installed in the most recent version together with the following packages: 14 | 15 | ``` 16 | pip install openai 17 | pip install pyTelegramBotAPI 18 | pip install python-dotenv 19 | ``` 20 | 21 | ### 2. Install Telegram 22 | If you do not already have Telegram in any device or web browser, create an account as it is needed. 23 | 24 | ### 3. Create an OpenAI account 25 | If you do not already have an account, create one at [OpenAI website](https://beta.openai.com/signup). 26 | 27 | ### 4. Gather your keys 28 | Once you have your Telegram and OpenAI accounts, gather the keys. 29 | 30 | **OpenAI API key:** 31 | 1. Log-in in [OpenAI keys](https://beta.openai.com/account/api-keys) 32 | 2. Create a new secret key and copy it to the clipboard. This is your **OPENAI_API_KEY**. It should look like this: `xx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx` 33 | 3. Paste it in your .env file in the field **OPENAI_API_KEY** 34 | 4. Set! 35 | _Be aware that you will be using your own OpenAI credit so charges might be applied._ 36 | 37 | **Telegram Bot key:** 38 | 1. Open Telegram in any of your devices 39 | 2. Open a chat with [@BotFather](https://web.telegram.org/k/#@BotFather). It is your go-to for all things bot, from creation to settings 40 | 3. Type `/newbot` to begin. The BotFather will ask you to pick a bot name (which must be universally unique) and a username, it then generates an authentication token for your new bot. This token is your **BOT_API_KEY**. It should look like this: `0123456789:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx` 41 | 4. Paste it in your .env file in the field **BOT_API_KEY** 42 | 5. Done! 43 | 44 | **Telegram user key:** 45 | 1. Head back to Telegram and open a chat with [@userinfobot](https://web.telegram.org/k/#@userinfobot) 46 | 2. Type `/start` to begin. It will reply with your info. 47 | 3. Copy the ID, that should look like this: `0123456789` 48 | 4. Paste it in your .env file in the field **USER_KEY** 49 | 5. Nice! This way only you can talk with the bot. 50 | _Notice that if you would like the bot to reply to many people you should modify the code to stop rejecting other peoples' messages._ 51 | 52 | Make sure your .env file has the three KEYs obtained during this step. Save the file. It might dissapear but it is still there. 53 | 54 | ### 5. Decide which engine suits you 55 | The script is intended to be used for natural and code responses, if either the message starts with `>>>` or contains `code` or `python` keywords. If you are willing to use other engine rather than the ones included, just change it by the one that suits you. Not sure on which engine suits you? Check the official website to see what each model offers [here](https://beta.openai.com/docs/models/overview). 56 | 57 | ### 6. Run the script 58 | Now you can use the bot as long as the script is running. Just type Hello! and make sure it responds. 59 | 60 | ## Contribution 61 | > Notice that this section is not precise, as I am not a senior developer and I neither have in depth knowledge on the Telegram API nor python packages that might be usefull to make the bot better, but I believe that some changes are needed to reach the full potential of this script. 62 | 63 | I encourage anyone with knowledge on the topic to help me in any way considered appropiate. If any bug, failure or error is detected, feel free to communicate or try to solve it. Here is a list of features I believe that should be worked on in order to improve the repository, but suggestions are as well accepted: 64 | - Make the script run forever 65 | - Enable through chat command to modify the engine used for the response 66 | 67 | ## Credits 68 | - Creator [@juan-miii](https://github.com/juan-miii) (GitHub), [@juanmiiix](https://twitter.com/juanmiiix) on Twitter 69 | - Contributor [@han3on](https://github.com/han3on) (GitHub) 70 | - Based on [@browneye1826](https://gist.github.com/browneye1826)'s Gists on a [_Telegram bot to communicate with Codex by OpenAI_](https://gist.github.com/browneye1826/4890211188170a43087dfc586afc962b#file-codex_bot-py) 71 | -------------------------------------------------------------------------------- /botGPT.py: -------------------------------------------------------------------------------- 1 | # Telegram Bot to communicate with OpenAI API 2 | # forked from juan-miii, modified by han3on 3 | 4 | import logging 5 | from os import environ as env 6 | from dotenv import load_dotenv 7 | 8 | import telebot 9 | import openai 10 | 11 | 12 | logger = telebot.logger 13 | telebot.logger.setLevel(logging.DEBUG) 14 | 15 | load_dotenv() 16 | bot = telebot.TeleBot(env["BOT_API_KEY"]) 17 | openai.api_key = env["OPENAI_API_KEY"] 18 | user_id = int(env["USER_KEY"]) 19 | 20 | 21 | @bot.message_handler(func=lambda message: True) 22 | def get_response(message): 23 | if int(message.chat.id) != user_id: 24 | bot.send_message("This bot is not for public but private use only.") 25 | else: 26 | response = "" 27 | if message.text.startswith(">>>"): 28 | # Use Codex API for code completion 29 | response = openai.Completion.create( 30 | engine="code-davinci-002", 31 | prompt=f'```\n{message.text[3:]}\n```', 32 | temperature=0, 33 | max_tokens=4000, 34 | top_p=1, 35 | frequency_penalty=0, 36 | presence_penalty=0, 37 | stop=["\n", ">>>"], 38 | ) 39 | else: 40 | # Use GPT API for text completion 41 | # Check if the question is about code or not 42 | if "code" in message.text.lower() or "python" in message.text.lower(): 43 | # Use Codex API for code-related questions 44 | response = openai.Completion.create( 45 | engine="code-davinci-002", 46 | prompt=f'"""\n{message.text}\n"""', 47 | temperature=0, 48 | max_tokens=4000, 49 | top_p=1, 50 | frequency_penalty=0, 51 | presence_penalty=0, 52 | stop=['"""'], 53 | ) 54 | else: 55 | # Use GPT API for non-code-related questions 56 | response = openai.Completion.create( 57 | engine="text-davinci-003", 58 | prompt=f'"""\n{message.text}\n"""', 59 | temperature=0, 60 | max_tokens=2000, 61 | top_p=1, 62 | frequency_penalty=0, 63 | presence_penalty=0, 64 | stop=['"""'], 65 | ) 66 | 67 | bot.send_message(message.chat.id, f'{response["choices"][0]["text"]}', parse_mode="None") 68 | 69 | bot.infinity_polling() 70 | --------------------------------------------------------------------------------