Unleashing ChatGPT’s Full Potential: How to Enhance OpenAI’s Telegram Bot with Memory

Eloise
9 min readFeb 7, 2023
Source: AI Generated

Are you tired of having a ChatGPT Telegram bot that forgets every conversation as soon as you turn off your computer? Do you yearn for a bot that can keep up with your wit and humor, and remember every joke and pun you’ve ever told? Well, hold onto your keyboards because we’ve got the solution for you!

In our previous publication, “Create Your Own Hilarious ChatGPT Bot in Telegram with Python: A Step-by-Step Guide”, we showed you how to take OpenAI’s ChatGPT for a spin and create a bot that could make your friends and followers ROFL. But while that bot was funny, it was also forgetful, like a comedian who always forgets their punchlines.

But we’re here to fix that. In this publication, we’re going to show you how to give your ChatGPT Telegram bot a memory upgrade and make it the life of the virtual party. Say goodbye to forgetful bots and hello to endless laughter with your very own memory-enhanced ChatGPT Telegram bot!

1. Experience the Power of Memory: ChatGPT Telegram Bot in Action

Example 1: The ChatGPT with Memory

Bot with memory

Question 1: Can you explain what reactance is in terms of electricity?
Answer 1: Reactance is an electrical property that represents the opposition to the flow of AC current in an electrical circuit.

Question 2: Can you give me the formula?
Answer 2: The formula for reactance is X = 2πfL, where f is the frequency of the AC current and L is the inductance of the circuit.

Wow, talk about a quick learner! Our memory-enhanced bot not only remembered the topic of reactance from the first question, but it also provided the formula requested in the second question. Impressive, isn’t it?

Example 2: The ChatGPT without Memory

Bot without memory

Question 1: Can you explain what reactance is in terms of electricity?
Answer 1: Reactance is an electrical property that represents the opposition to the flow of AC current in an electrical circuit.

Question 2: Can you give me the formula?
Answer 2: The formula for the area of a triangle is A = 1/2bh.

Oops, looks like our forgetful friend didn’t retain any information from the first question. The answer provided is completely unrelated to reactance, which is a clear indication that the bot is lacking memory.

2. Code Set-Up

It’s time to put on your coding cap and unleash the full potential of ChatGPT! Ye be embarking on a grand adventure to enhance OpenAI’s Telegram Bot with the power of memory. So gather ye code snippets and let’s set sail towards Pythonic seas! With a little elbow grease and a dash of magic, we’ll make sure that this bot never forgets a message or a joke! Arrrr!

Don’t worry, it’s as easy as making a PB&J sandwich (well, maybe just a little more complicated). If you followed along with our previous publication, “Create Your Own Hilarious ChatGPT Bot in Telegram with Python: A Step-by-Step Guide”, you’re in luck because the setup for our memory-enhanced bot, robotv2.py, is almost exactly the same.

Full overview of the robotv2.py code (github link here):

RobotV2.py is the general code that creates a chatbot, capable of answering questions and even generating images. It’s like the lovechild of AI and a personal secretary! The chatbot interacts with Telegram groups by using their API and can answer based on a tone set by the user. It’s like having a moody boss that can change personalities at any given moment!

The code imports various libraries, including requests for making API calls, json for processing JSON data, re for regular expression operations, and asyncio for asynchronous operations. It's like having a whole toolbox ready to tackle any task thrown its way!

The code then sets some global variables like the OpenAI API Key, Telegram API key, the allowed group IDs for the bot to respond to, the ChatBot handle, and a file name to retrieve the last message ID. It’s like having a secret handshake with the API gods and Telegram, and a secret diary to keep track of the latest gossip!

The code then defines various functions, starting with openAI which makes a request to the OpenAI API and returns a completion based on the given prompt and maximum number of tokens. It's like sending a love letter to OpenAI, asking it to complete a sentence with all the love in the world.

The openAImage function makes a request to the OpenAI API to generate an image based on a prompt. It's like asking OpenAI to paint a picture of what's in your mind.

The telegram_bot_sendtext function sends a message to a specific Telegram group. It's like sending a telegram to your friends, letting them know you're thinking about them.

The telegram_bot_sendimage function sends an image to a specific Telegram group. It's like sending a postcard from your vacation, making your friends jealous.

The checkTone function checks the tone of the message, allowing the bot to respond with a different personality. It's like giving your chatbot a mood ring, letting it know how to act depending on the situation.

The ChatGPTbot function ties everything together, reading the last message ID from the specified file, checking for new messages, processing them, and sending the appropriate response. It's like the conductor of an AI orchestra, making sure everything runs smoothly and in harmony.

And that’s the code, ready to make you laugh, answer your questions, and even generate images. What more could you ask for in a chatbot?

Reminder Authentication in robotV2.py :

Before we run this code snippet for robotV2.py, we’ve got a few things to take care of. It’s like preparing a treasure map before embarking on a pirate adventure. Just fill in the blanks, so to speak!

Enter all specifications

First, we have the API_KEY, which is the OpenAI secret Key. Next, we have the BOT_TOKEN, which is the Telegram secret access bot token. The ALLOWED_GROUP_ID is a list of allowed groups, just like a pirate’s log of trusted shipmates. The CHATBOT_HANDLE is like the bot’s pirate name, a moniker for all to remember it by. And finally, we have the FILENAME, this be like the bot’s treasure chest, where it stores the historical thread number, so it never forgets the last message it replied to!

So, make sure ye have all these filled out, and let’s set sail towards bot building glory!

1. OpenAI secret Key
API_KEY = ‘xxxxxxxxxxxsecretAPIxxxxxxxxxx’

2. Telegram secret access bot token
BOT_TOKEN = ‘xxxxxxbotapikeyxxxxx’

3. Specify all groups ID the bot can respond to
ALLOWED_GROUP_ID = [‘-100xxxxxxxx’, ‘-1001xxxxxxxx1’]

You can find the by sending a message to the bot:

https://api.telegram.org/bot{BOT_ACCESS_TOKEN}/sendMessage?chat_id=@{CHANNELNAME}&text=123

Ye can always consult the swashbuckling updates on this scallywag link with all yer bot specifications fit for a pirate king or queen!
https://api.telegram.org/bot{BOT_ACCESS_TOKEN}/getUpdates

4. Specify your Chat Bot handle
CHATBOT_HANDLE = ‘@ask_chatgptbot’

example @ask_chatGPTbot

5. Create a file called chatgpt.txt
In order to retrieve the last ID messages, 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

FILENAME = ‘/xxxxxx/xxxxxxx/xxxxx/chatgpt.txt’

NB: Without the proper privileges, this bot be walkin’ the plank, unable to hoist the anchor and answer yer questions. Make sure ye’ve granted it admin status, or ye’ll be stuck with a powerless parrot for company!

Well done, matey! Ye have correctly entered all the important specifications for robotV2.py . Ye have found the treasure map, and now it’s time to set off on a new quest!

3. Adding the memory python file

With the power of Python, we’ll equip our bot with the historical memory of the group chat. It’ll be like giving the bot a magic compass, so it can navigate the rough seas of conversation with ease.

Full overview of the memory.py code (github link here):

This code is all about getting some messages from a Telegram channel.

First, we import all the necessary libraries like asyncio, TelegramClient, and json for our ride. Then we have a super cool asynchronous function get_channel_messages which is going to help us retrieve all the messages with the help of the TelegramClient.

To connect with the Telegram API, we need to provide some crucial information such as the api_id, api_hash, and session_hash. Then we create a TelegramClient object with the given session string.

If you don’t have a session hash yet, you will need to obtain one in order to use the TelegramClient with this custom session type.

To generate a session hash using Telethon, you will need to log in to your Telegram account using the Telethon library. Here is an example of how to do this:

from telethon import TelegramClient

api_id = 123456 # Your API ID
api_hash = 'your_api_hash' # Your API Hash

# Create a new TelegramClient instance and start the client
async with TelegramClient('session_file', api_id, api_hash) as client:
# Connect to the Telegram servers and log in
await client.start()

# After logging in, the session hash will be automatically generated and stored
# in the 'session_file' file, which you can use in future runs to log in with
# the same session:
session_hash = client.session.save()

print(str(session_hash))

Next, we retrieve the reply number of the message using reply_number variable and build the message history using a while loop and store it in my_dict. Then we iterate through my_dict and build the message history in the format "A: message" or "Q: message" depending on whether the message is from the bot or a telegram user. To maximize token optimization in OpenAI, our memory-enhanced bot is configured to retain a maximum of 3 past interactions in max_memory_message . So, let’s make every conversation count!

Remember to identify your bot’s ID number my_bot_idso a proper memory thread can be established. You can find the bot’s ID by forwarding one of its messages to the bot at https://t.me/userinfobot.

@userinfobot

And finally, the function returns the message history. Wow, what a wild ride that was!

Pro Tip:

To maximize token optimization in OpenAI, our memory-enhanced bot is configured to retain a maximum of 3 past interactions in max_memory_message. So, let’s make every conversation count!

Conclusion:

Ta-da! Presenting the fruits of your labor: the final Python code for your fancy new chatbot. Just copy and paste those bad boys (robotV2.py &memory.py) into your favorite code editor, plug in your API keys and chat group ID, and run robotV2.py . You’ll be chatting it up with ChatGPT in no time.

If ye be wantin’ to test the bot’s skills or need info, drop anchor in our Telegram group! And if ye be needin’ a custom bot to take care of yer dirty work, just send a message in a bottle my way and I’ll be ready to help ye shiver yer timbers!

And, remember this rule of thumb: ye want to reply to his messages and not directly message him, else ye’ll miss out on all the juicy information he’s stored in his memory. Otherwise, ye’ll be sendin’ him on wild goose chases with each new conversation! So, heave ho, and start replyin’ to unleash the true power of ChatGPT!

If I feel there’s enough interest from ye landlubbers, the next publication I’ll be unleashing upon ye will be on how to connect ChatGPT to the vast ocean of the internet!

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job

--

--