├── PNG ├── test.txt └── askgpt.jpeg ├── LICENSE.md ├── asyncV2 ├── memory.py ├── README.md └── robotV2.py ├── README.md └── robot.py /PNG/test.txt: -------------------------------------------------------------------------------- 1 | vefe 2 | -------------------------------------------------------------------------------- /PNG/askgpt.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Eloise1988/OPENAI/HEAD/PNG/askgpt.jpeg -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Eloisa 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /asyncV2/memory.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from telethon import TelegramClient, sync 3 | from telethon.tl.functions.messages import GetHistoryRequest 4 | from telethon.tl.types import InputPeerChannel 5 | from telethon.sessions import StringSession 6 | from telethon.tl.types import PeerUser, PeerChat, PeerChannel 7 | import json 8 | 9 | 10 | async def get_channel_messages(chat_id, msg_id): 11 | # Telegram API ID and Hash (you can get it from my.telegram.org) 12 | api_id = 'xxxxxxxx' 13 | api_hash = 'xxxxxxxxxxxxxx' 14 | session_hash='0KSDgh9xxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxx1dfsHNVugzasdHRShvewqWla889BH=' 15 | # Identify your bot with his ID number, can be found using this link 16 | my_bot_id = 'xxxxxxxxx_my-bot-id-number_xxxxxxxx' 17 | # Storing max 3 past messages 18 | max_memory_message = 3 19 | 20 | chat_id = int(chat_id) 21 | data = {} 22 | # Create a Telegram client with the given session string 23 | async with TelegramClient(StringSession(session_hash), api_id, api_hash) as client: 24 | # Connect to Telegram 25 | await client.connect() 26 | 27 | # Get the channel by its username 28 | channel = await client.get_entity(PeerChannel(chat_id)) 29 | messages = await client.get_messages(channel, limit=100, offset_id=0) 30 | 31 | for x in messages: 32 | try: 33 | if x.text != "": 34 | if x.text is not None: 35 | try: 36 | replied = x.reply_to.reply_to_msg_id 37 | except: 38 | replied = x.reply_to 39 | # The code stores the following information for each message in a dictionary: message id, date, user id of the sender, the message content, id of the message it was replied to, and if the message was pinned. 40 | data[str(x.id)] = [x.id, int(x.date.timestamp()), x.from_id.user_id, x.text, replied, x.pinned] 41 | except: 42 | print(x.text) 43 | 44 | reply_number = data[msg_id][4] 45 | my_dict = [] 46 | write_history = '' 47 | try: 48 | #Checking for past replies given msg id 49 | while reply_number is not None: 50 | my_dict.append([reply_number, data[str(reply_number)][2]]) 51 | reply_number = data[str(reply_number)][4] 52 | #Storing max 3 past messages 53 | if len(my_dict) > max_memory_message + 1: 54 | break 55 | except Exception as e: 56 | print(e) 57 | 58 | #Checking for history 59 | if len(my_dict) > 1: 60 | #Building message history/memory 61 | for i in range(len(my_dict) - 1, -1, -1): 62 | if str(my_dict[i][1]) == my_bot_id: 63 | #If message comes from bot -> message is treated as response from person A 64 | write_history += "A: " + data[str(my_dict[i][0])][3] + "\n" 65 | else: 66 | #Else-> message is treated as response from telegram user 67 | write_history += "Q: " + data[str(my_dict[i][0])][3] + "\n" 68 | 69 | 70 | return write_history 71 | 72 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Telegram Chatbot using OpenAI - GPT 3-5 Turbo 2 | ![AskGpt](https://github.com/Eloise1988/OPENAI/blob/main/PNG/askgpt.jpeg) 3 | This is a python script for a Telegram chatbot that uses the OpenAI API to generate responses to user input 4 | 5 | ## [Medium Publication](https://levelup.gitconnected.com/create-your-own-hilarious-chatgpt-bot-in-telegram-with-python-a-step-by-step-guide-466e8a510c0d) + [Testing](https://t.me/askchatgpt) 6 | 7 | ## Requirements 8 | * A Telegram bot API key, obtained by creating a bot on Telegram. 9 | * An OpenAI API key, obtained by creating an account on OpenAI. 10 | * Python 3 and the following libraries: requests, json, os, threading 11 | 12 | ## How to use 13 | 1. Clone the repository and navigate to the directory 14 | 2. Fill in the API_KEY, MODEL, BOT_TOKEN, CHATBOT_HANDLE and BOT_PERSONALITY in the script with your own API keys and desired settings 15 | 3. Run the script with the command python chatbot.py 16 | 4. Add the bot to a Telegram group, make sure he has ADMIN priviledges, and mention the bot's username in a message to generate a response from the OpenAI API 17 | 18 | ## Functionality 19 | ### Imports and setup 20 | 1. The script starts by importing the necessary libraries and setting up the API clients. 21 | ### openAI function 22 | 2. The openAI() function is defined, which takes a user input (prompt) and sends a request to the OpenAI API to generate a response. The function then returns the response. 23 | ### telegram_bot_sendtext function 24 | 3. The telegram_bot_sendtext() function is defined, which takes a message, a chat ID, and a message ID, and sends the message as a response to the Telegram group using the Telegram Bot API. 25 | ### Chatbot function 26 | 4. The Chatbot() function is defined which retrieves the latest requests from users in a Telegram group, generates a response using the OpenAI API, and sends the response back to the group. The function retrieves the last ID message from the text file for the ChatGPT update, check for new messages in Telegram group, check that user mentionned chatbot's username in message, calling OpenAI API using the bot's personality and sending back response to telegram group. 27 | 28 | ## Global Variables 29 | The script also uses a few global variables such as the API key for OpenAI, the model to use with the OpenAI API, the Telegram bot API key, and the bot's personality as defined by a set of adjectives. 30 | 31 | ## Note 32 | This script is provided as a starting point, and can be further customized and expanded upon as needed. 33 | How to use Ask_ChatGPTbot: 34 | 35 | 1. Type "@ask_yourchatgptbotname ___" to interact with the bot and ask a question 36 | 2. Type "/img ___" to get an AI generated image related to your question or statement 37 | 3. Type "/setTone(serious) @ask_yourchatgptbotname ___" in order to specify the tone for the bot's response 38 | 39 | 40 | ## Version 1 Debug: 41 | 1. Continuous printing of "file exists" is NORMAL. I will change the code so it doesn't write it anymore as it seems to be confusing. 42 | 2. Ensure that `chatbot.txt` exists and has the correct path. If the file is empty, write `1` on the first line. 43 | 3. Verify that your BOT has ADMIN access to your group. 44 | 4. Ensure in the code that you have replaced `ask_chatgptbot` with your BOT NAME. 45 | 5. Check `https://api.telegram.org/bot{ACCESS TOKEN}/getUpdates` to make sure you can see all messages sent to your bot and that there are no 404 errors. If you encounter errors, check with Telegram or recreate a new bot. 46 | 47 | ## Version 2 Debug: 48 | 1. Error: "Could not convert string to float: ''" Ensure that `chatbot.txt` exists and has the correct path. If the file is empty, clear it and write `1` on the first line. 49 | 2. Ensure in the code that you have replaced `ask_chatgptbot` with your BOT NAME. 50 | 3. Check `https://api.telegram.org/bot{ACCESS TOKEN}/getUpdates` to make sure you can see all messages sent to your bot and that there are no 404 errors. If you encounter errors, check with Telegram or recreate a new bot. 51 | 4. Make sure you have set the correct `ALLOWED_GROUP_ID=['-100xxxxxxxx', '-1001xxxxxxxx1']`. You can check the group ID in `data['result']` or directly on `https://api.telegram.org/bot{ACCESS TOKEN}/getUpdates`. 52 | 53 | ## License 54 | This project is licensed under the MIT License. 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /asyncV2/README.md: -------------------------------------------------------------------------------- 1 | # Telegram Chatbot with Memory using OpenAI - GPT 3-5 Turbo 2 | ![AskGpt](https://github.com/Eloise1988/OPENAI/blob/main/PNG/askgpt.jpeg) 3 | This is an asyncronous function that serves as a Telegram bot using OpenAI's GPT-3 language model. 4 | This is a python script for a Telegram chatbot that uses the OpenAI API to generate responses to user input. 5 | 6 | ## [Medium Publication](https://levelup.gitconnected.com/create-your-own-hilarious-chatgpt-bot-in-telegram-with-python-a-step-by-step-guide-466e8a510c0d) + [Testing](https://t.me/askchatgpt) 7 | 8 | ## Requirements 9 | * A Telegram bot API key, obtained by creating a bot on Telegram. 10 | * An OpenAI API key, obtained by creating an account on OpenAI. 11 | * Python 3 and the following libraries: requests, json, os, threading, asyncio and memory (in the current folder: gets last messages in the group) 12 | 13 | ## How to use 14 | 1. Clone the repository and navigate to the directory. 15 | 2. A. Fill in the following in the `robotV2.py` script with your own API keys and desired settings. 16 | - `BOT_TOKEN`: The token you get from Telegram when you create your bot. 17 | - `ALLOWED_GROUP_ID` : the list of allowed group_ids 18 | - `API_KEY` : OpenAI secret Key 19 | - `CHATBOT_HANDLE` : Bot name 20 | - `BOT_ID` : Bot name 21 | 22 | B. Fill in the following in the `memory.py` script with your own settings and authentication. 23 | - `api_id`: Telegram API ID and Hash (you can get it from my.telegram.org) 24 | - `api_hash` : Telegram API Hash (you can get it from my.telegram.org) 25 | - `session_hash` : Telegram Session Hash 26 | ``` 27 | async with TelegramClient('session_file', api_id, api_hash) as client: 28 | # Connect to the Telegram servers and log in 29 | await client.start() 30 | 31 | # After logging in, the session hash will be automatically generated and stored 32 | # in the 'session_file' file, which you can use in future runs to log in with 33 | # the same session: 34 | session_hash = client.session.save() 35 | 36 | print(str(session_hash)) 37 | ``` 38 | - `my_bot_id` : Bot ID number 39 | - `max_memory_message` : Stored number of max messages 40 | 41 | 3. Run the script with the command `python robotV2.py` 42 | 4. Add the bot to a Telegram group, make sure he has ADMIN priviledges, and mention the bot's username in a message to generate a response from the OpenAI API. 43 | 44 | ## Functionality 45 | 46 | 1. This bot limits access to only a group of initially specified groups in variable `ALLOWED_GROUP_ID` 47 | 2. This bot has a list of pre-defined tones (e.g. friendly, professional, humorous) stored in the `tone_list` variable that it can respond in. 48 | 3. This function checks for new messages in a Telegram group by sending a GET request to the Telegram API and parsing the response data using the `requests` and `json` modules. 49 | 4. This bot sends greeting messages to new participants 50 | 5. This bot can also respond to commands such as '/img' for generating image captions and the bot's username for answering questions. 51 | 6. This bot also has an option to include the user's historical message to the context of the chatbot response using the `write_history` variable. 52 | 53 | ## Variables 54 | 55 | - `filename`: a string variable that stores the filepath and name of the text file where the last ID message is stored. 56 | - `bot_personality`: a string variable that stores the personality of the bot. 57 | - `write_history`: a string variable that stores the historical message of the user. 58 | - `tone_list`: a list variable that stores the pre-defined tones for the bot to respond in. 59 | - `last_update`: a variable that stores the last ID message from the text file. 60 | - `url`: a variable that stores the URL for the Telegram API to retrieve updates. 61 | - `response`: the response data from the Telegram API. 62 | - `data`: the parsed JSON data from the Telegram API response. 63 | - `result`: the last message in the Telegram group. 64 | - `msg_id`: the id of the message received 65 | - `boolean_active`: a boolean flag to check if the bot is active 66 | - `prompt1`: The prompt after checking the tone 67 | - `prompt`: the user's message 68 | 69 | ## Functions 70 | 71 | - `openAI` : function to call the OpenAI API to generate the text response. 72 | - `openAImage` : function to call the OpenAI API to generate image caption. 73 | - `telegram_bot_sendtext` : function to send the text response to the user through Telegram API. 74 | - `telegram_bot_sendimage` : function to send the image caption to the user through Telegram API. 75 | - `checkTone` : function to check the tone of the question and set the bot_personality accordingly. 76 | - `memory.get_channel_messages` : function to retrieve the user's historical messages from the Telegram group. 77 | -------------------------------------------------------------------------------- /robot.py: -------------------------------------------------------------------------------- 1 | # 1. Start by importing the necessary libraries and setting up the API clients 2 | import requests 3 | import json 4 | import os 5 | import threading 6 | 7 | # OpenAI secret Key 8 | API_KEY = 'xxxxxxxxxxxsecretAPIxxxxxxxxxx' 9 | # Models: text-davinci-003,text-curie-001,text-babbage-001,text-ada-001 10 | MODEL = 'gpt-3.5-turbo' 11 | # Telegram secret access bot token 12 | BOT_TOKEN = 'xxxxxxbotapikeyxxxxx' 13 | # Defining the bot's personality using adjectives 14 | BOT_PERSONALITY = 'Answer in a funny tone, ' 15 | # Specify your Chat Bot handle 16 | CHATBOT_HANDLE = '@ask_chatgptbot' 17 | 18 | # 2a. Function that gets the response from OpenAI's chatbot 19 | def openAI(prompt): 20 | # Make the request to the OpenAI API 21 | response = requests.post( 22 | 'https://api.openai.com/v1/chat/completions', 23 | headers={'Authorization': f'Bearer {API_KEY}'}, 24 | json={'model': MODEL, 'messages': [{"role": "user", "content": prompt}], 'temperature': 0.5, 'max_tokens': 300}, 25 | timeout=10 26 | ) 27 | 28 | result=response.json() 29 | 30 | final_result='' 31 | for i in range(0,len(result['choices'])): 32 | final_result+=result['choices'][i]['message']['content'] 33 | 34 | return final_result 35 | 36 | # 2b. Function that gets an Image from OpenAI 37 | def openAImage(prompt): 38 | # Make the request to the OpenAI API 39 | resp = requests.post( 40 | 'https://api.openai.com/v1/images/generations', 41 | headers={'Authorization': f'Bearer {API_KEY}'}, 42 | json={'prompt': prompt,'n' : 1, 'size': '1024x1024'}, 43 | timeout=10 44 | ) 45 | response_text = json.loads(resp.text) 46 | 47 | return response_text['data'][0]['url'] 48 | 49 | # 3a. Function that sends a message to a specific telegram group 50 | def telegram_bot_sendtext(bot_message,chat_id,msg_id): 51 | data = { 52 | 'chat_id': chat_id, 53 | 'text': bot_message, 54 | 'reply_to_message_id': msg_id 55 | } 56 | response = requests.post( 57 | 'https://api.telegram.org/bot' + BOT_TOKEN + '/sendMessage', 58 | json=data, 59 | timeout=5 60 | ) 61 | return response.json() 62 | 63 | # 3b. Function that sends an image to a specific telegram group 64 | def telegram_bot_sendimage(image_url, group_id, msg_id): 65 | data = { 66 | 'chat_id': group_id, 67 | 'photo': image_url, 68 | 'reply_to_message_id': msg_id 69 | } 70 | url = 'https://api.telegram.org/bot' + BOT_TOKEN + '/sendPhoto' 71 | 72 | response = requests.post(url, data=data, timeout=5) 73 | return response.json() 74 | 75 | # 4. Function that retrieves the latest requests from users in a Telegram group, 76 | # generates a response using OpenAI, and sends the response back to the group. 77 | def Chatbot(): 78 | # Retrieve last ID message from text file for ChatGPT update 79 | cwd = os.getcwd() 80 | filename = cwd + '/chatgpt.txt' 81 | if not os.path.exists(filename): 82 | with open(filename, "w") as f: 83 | f.write("1") 84 | else: 85 | does_file_exist="File Exists" 86 | 87 | with open(filename) as f: 88 | last_update = f.read() 89 | f.close() 90 | 91 | # Check for new messages in Telegram group 92 | url = f'https://api.telegram.org/bot{BOT_TOKEN}/getUpdates?offset={last_update}' 93 | response = requests.get(url, timeout=5) 94 | data = json.loads(response.content) 95 | print(data) 96 | 97 | for result in data['result']: 98 | try: 99 | # Checking for new message 100 | if float(result['update_id']) > float(last_update): 101 | # Checking for new messages that did not come from chatGPT 102 | if not result['message']['from']['is_bot']: 103 | last_update = str(int(result['update_id'])) 104 | 105 | # Retrieving message ID of the sender of the request 106 | msg_id = str(int(result['message']['message_id'])) 107 | 108 | # Retrieving the chat ID 109 | chat_id = str(result['message']['chat']['id']) 110 | 111 | # Checking if user wants an image 112 | if '/img' in result['message']['text']: 113 | prompt = result['message']['text'].replace("/img", "") 114 | bot_response = openAImage(prompt) 115 | print(telegram_bot_sendimage(bot_response, chat_id, msg_id)) 116 | # Checking that user mentionned chatbot's username in message 117 | if CHATBOT_HANDLE in result['message']['text'] or "/ask" in result['message']['text']: 118 | prompt = result['message']['text'].replace(CHATBOT_HANDLE, "") 119 | # Calling OpenAI API using the bot's personality 120 | bot_response = openAI(f"{BOT_PERSONALITY}{prompt}") 121 | # Sending back response to telegram group 122 | print(telegram_bot_sendtext(bot_response, chat_id, msg_id)) 123 | # Verifying that the user is responding to the ChatGPT bot 124 | if 'reply_to_message' in result['message']: 125 | if result['message']['reply_to_message']['from']['username'] == CHATBOT_HANDLE[1:]: 126 | prompt = result['message']['text'] 127 | bot_response = openAI(f"{BOT_PERSONALITY}{prompt}") 128 | print(telegram_bot_sendtext(bot_response, chat_id, msg_id)) 129 | except Exception as e: 130 | print(e) 131 | 132 | # Updating file with last update ID 133 | with open(filename, 'w') as f: 134 | f.write(last_update) 135 | f.close() 136 | 137 | return "done" 138 | 139 | # 5 Running a check every 5 seconds to check for new messages 140 | def main(): 141 | timertime=5 142 | Chatbot() 143 | # 5 sec timer 144 | threading.Timer(timertime, main).start() 145 | 146 | # Run the main function 147 | if __name__ == "__main__": 148 | main() 149 | -------------------------------------------------------------------------------- /asyncV2/robotV2.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | import os 4 | import re 5 | import random 6 | import memory 7 | import asyncio 8 | 9 | # OpenAI secret Key 10 | API_KEY = 'xxxxxxxxxxxsecretAPIxxxxxxxxxx' 11 | # Models: text-davinci-003,text-curie-001,text-babbage-001,text-ada-001 12 | MODEL = 'gpt-3.5-turbo' 13 | # Telegram secret access bot token 14 | BOT_TOKEN = 'xxxxxxbotapikeyxxxxx' 15 | # Specify all group ID the bot can respond too 16 | ALLOWED_GROUP_ID = ['-100xxxxxxxx', '-1001xxxxxxxx1'] 17 | # Specify your Chat Bot handle 18 | CHATBOT_HANDLE = '@ask_chatgptbot' 19 | # Retrieve last ID message : Create an empty text file named chatgpt.txt, write 1 on the first line of the text file and save it, write the full path of your file below 20 | FILENAME = '/xxxxxx/xxxxxxx/xxxxx/chatgpt.txt' 21 | 22 | 23 | # 2a. Function that gets the response from OpenAI's chatbot 24 | async def openAI(prompt, max_tokens): 25 | # Make the request to the OpenAI API 26 | response = requests.post( 27 | 'https://api.openai.com/v1/chat/completions', 28 | headers={'Authorization': f'Bearer {API_KEY}'}, 29 | json={'model': MODEL, 'messages': [{"role": "user", "content": prompt}], 'temperature': 0.5, 'max_tokens': max_tokens}, 30 | timeout=10 31 | ) 32 | 33 | result=response.json() 34 | final_result='' 35 | for i in range(0,len(result['choices'])): 36 | final_result+=result['choices'][i]['message']['content'] 37 | 38 | return final_result 39 | 40 | # 2b. Function that gets an Image from OpenAI 41 | async def openAImage(prompt): 42 | # Make the request to the OpenAI API 43 | resp = requests.post( 44 | 'https://api.openai.com/v1/images/generations', 45 | headers={'Authorization': f'Bearer {API_KEY}'}, 46 | json={'prompt': prompt,'n' : 1, 'size': '256x256'}, 47 | timeout=10 48 | ) 49 | 50 | response_text = json.loads(resp.text) 51 | #print(response_text['data'][0]['url']) 52 | 53 | return response_text['data'][0]['url'] 54 | 55 | 56 | # Sending a message to a specific telegram group 57 | async def telegram_bot_sendtext(bot_message,chat_id,msg_id): 58 | 59 | data = { 60 | 'chat_id': chat_id, 61 | 'text': bot_message, 62 | 'reply_to_message_id': msg_id 63 | } 64 | response = requests.post( 65 | 'https://api.telegram.org/bot' + BOT_TOKEN + '/sendMessage', 66 | json=data, 67 | timeout=5 68 | ) 69 | 70 | return response.json() 71 | 72 | # Sending a image to a specific telegram group 73 | async def telegram_bot_sendimage(image_url,group_id, msg_id): 74 | data = {'chat_id': group_id, 'photo': image_url,'reply_to_message_id': msg_id} 75 | url = 'https://api.telegram.org/bot' + BOT_TOKEN + '/sendPhoto' 76 | 77 | response = requests.post(url, data=data, timeout=5) 78 | return response.json() 79 | 80 | # Checking for specific tone for message 81 | async def checkTone(user_message): 82 | bot_personality='' 83 | match = re.search(r"/setTone\((.*?)\)", user_message, flags=re.IGNORECASE) 84 | if match: 85 | substring = match.group(1) 86 | bot_personality = 'Answer in a '+ substring +' tone, ' 87 | user_message=user_message.replace('/setTone('+substring+')','') 88 | 89 | 90 | return [user_message,bot_personality] 91 | 92 | 93 | async def ChatGPTbot(): 94 | # Give your bot a personality using adjectives from the tone list 95 | bot_personality = '' 96 | # Leave write_history BLANK 97 | write_history= '' 98 | 99 | tone_list=['Friendly','Professional','Humorous','Sarcastic','Witty','Sassy','Charming','Cheeky','Quirky','Laid-back','Elegant','Playful','Soothing','Intense','Passionate'] 100 | 101 | with open(FILENAME) as f: 102 | last_update = f.read() 103 | f.close() 104 | 105 | 106 | 107 | # Check for new messages in Telegram group 108 | url = f'https://api.telegram.org/bot{BOT_TOKEN}/getUpdates?offset={last_update}' 109 | response = requests.get(url, timeout=5) 110 | data = json.loads(response.content) 111 | print(data) 112 | 113 | result=data['result'][len(data['result'])-1] 114 | 115 | 116 | try: 117 | # Checking for new message 118 | if float(result['update_id']) > float(last_update): 119 | # Checking for new messages that did not come from chatGPT 120 | if not result['message']['from']['is_bot']: 121 | last_update = str(int(result['update_id'])) 122 | # Retrieving the chat ID of the sender of the request 123 | chat_id = str(result['message']['chat']['id']) 124 | 125 | 126 | if chat_id in ALLOWED_GROUP_ID: 127 | msg_id = str(int(result['message']['message_id'])) 128 | 129 | try: 130 | # Greeting message for new participants 131 | if 'new_chat_participant' in result['message']: 132 | prompt = 'Write in a '+random.choice(tone_list)+' tone: ' + "I am here to assist you. Nice to meet you, "+result['message']['new_chat_participant']['first_name'] 133 | 134 | bot_response = await openAI(prompt, 200) 135 | # Sending back response to telegram group 136 | x = await telegram_bot_sendtext(bot_response, chat_id, msg_id) 137 | 138 | except Exception as e: 139 | print(e) 140 | try: 141 | if '/img' in result['message']['text']: 142 | prompt = result['message']['text'].replace("/img", "") 143 | bot_response = await openAImage(prompt) 144 | x = await telegram_bot_sendimage(bot_response, chat_id, msg_id) 145 | except Exception as e: 146 | print(e) 147 | 148 | boolean_active=False 149 | # Checking that user mentionned chatbot's username in message 150 | if CHATBOT_HANDLE in result['message']['text']: 151 | prompt = result['message']['text'].replace(CHATBOT_HANDLE, "") 152 | boolean_active=True 153 | 154 | # Verifying that the user is responding to the ChatGPT bot 155 | if 'reply_to_message' in result['message']: 156 | if result['message']['reply_to_message']['from']['username'] == CHATBOT_HANDLE[1:]: 157 | prompt = result['message']['text'] 158 | 159 | #Getting historical messages from user 160 | write_history = await memory.get_channel_messages(chat_id,msg_id) 161 | 162 | boolean_active=True 163 | 164 | 165 | if boolean_active: 166 | try: 167 | prompt1=await checkTone(prompt) 168 | prompt=prompt1[0] 169 | 170 | bot_personality=prompt1[1] 171 | boolean_active=True 172 | except Exception as e: 173 | print(e) 174 | try: 175 | if write_history!='': 176 | prompt=write_history+"\n\nQ : "+prompt+"\n\n###\n\n" 177 | 178 | bot_response = await openAI(f"{bot_personality}{prompt}",300) 179 | if bot_response =='' : 180 | bot_response = await openAI(f"{bot_personality}{vague_prompt}",300) 181 | 182 | x = await telegram_bot_sendtext(bot_response, chat_id, msg_id) 183 | 184 | except Exception as e: 185 | print(e) 186 | except Exception as e: 187 | print(e) 188 | 189 | # Updating file with last update ID 190 | with open(FILENAME, 'w') as f: 191 | f.write(last_update) 192 | 193 | return "done" 194 | 195 | async def main(): 196 | while True: 197 | await ChatGPTbot() 198 | await asyncio.sleep(5) 199 | 200 | loop = asyncio.get_event_loop() 201 | loop.run_until_complete(main()) 202 | 203 | --------------------------------------------------------------------------------