Create Your Own Hilarious ChatGPT Bot in Telegram with Python: A Step-by-Step Guide

Eloise
9 min readJan 8, 2023
Illustration: Getty Images

Ready to bring some much-needed humor to your group chats? This guide shows you how to easily add the hilarious OpenAI ChatGPT bot to any Telegram group with just a few lines of Python code. Whether you’re a coding pro or just starting out, we’ve got you covered with a step-by-step guide. Get ready to revolutionize your chats and have a good laugh!

Feeling daring? Go ahead and skip the step-by-step guide and put it to the ultimate test by sending it a message using the link above.

1. To begin, ensure that Python is installed on your computer.

2. Next, obtain Telegram API authentication credentials.

First things first, you’ll need to create a new bot and snag its shiny API token. Don’t worry, it’s easy peasy! Just chat with the BotFather bot on Telegram and he’ll walk you through the process. Follow these steps and you’ll be on your way to bot greatness:

Source

Open a conversation with the BotFather bot on Telegram by searching for “@BotFather” in the Telegram search bar. Type “/newbot” to create a new bot. Follow the prompts to choose a name and username for your bot. The username must end in “bot” (e.g. “my_new_bot”).

https://core.telegram.org/bots/tutorial

Once the bot has been created, the BotFather will provide you with a token. This token is used to authenticate your bot and grant it access to the Telegram API. Copy the token and use it in your bot’s code to authenticate and access the API. Protect your bot’s secret token like it’s the crown jewels! Do not share your bot’s token with anyone.

You will then need to retrieve the chat ID of the channel you just created on Telegram. This ID is a unique identifier and is used when one wants to integrate Telegram with their own apps or services.

Send a message to this channel through the Bot API, using your channel name and access token. https://api.telegram.org/bot11234485678:AAElJxyzHCbiiZu7Vb_fGGhmk2tbFVr54n/sendMessage?chat_id=@TestChannel&text=123

{"ok":true,
"result":{
"message_id":191,
"sender_chat":{
"id":-1001527664788,
"title":"Test Channel Name",
"username":"TestChannel","type":"channel"
},
"chat":{
"id":-1001527664788,
"title":"",
"username":"TestChannel","type":"channel"
},
"date":1670434355,
"text":"123"
}
}

You will find the channel id under chat/id.

Make sure to promote your Bot as an ADMIN

It’s important to give your bot admin privileges in order to ensure it can perform all the necessary tasks.
Attention all coders! Those access token IDs might look nice, but they’re just for show. You’ll need your own for your app.

3. Time to get your API key and connect to the OpenAI engine, no sweat!

To obtain an API key from OpenAI, you will need to create an account on the OpenAI website (https://beta.openai.com/). Once you have an account, you can access your API keys by going to the “API Keys” tab on the user dashboard.

https://beta.openai.com/account/api-keys

From there, you can generate a new key and use it to authenticate your API requests. It is important to keep your API key secret and secure to protect your account.

https://beta.openai.com/account/usage

Keep in mind that OpenAI may limits the number of API calls you can make. With a personal account, you are given a grant of $18.00 to use towards API requests. Be sure to review the terms of service and pricing information on the OpenAI website before using the API.

Connecting to Text-davinci-003

https://beta.openai.com/docs/models/gpt-3

Text-davinci-003 is a large language model developed by OpenAI. It is considered one of the most capable language models currently available, due to its ability to generate human-like text and perform a wide range of language tasks. It was trained on a dataset of billions of words, and can generate text that is coherent and reads like it was written by a human.

All right, code warriors! It’s time to get your bot and Telegram group chatting like old friends. With a few easy steps and a dash of Python magic, you’ll be able to connect and deploy your very own ChatGPT bot in your group in no time. Let’s get coding!

4. Begin writing Python code

To begin, we will import necessary libraries and set the key authentication parameter.

# 1. Start by importing the necessary libraries and setting up the API clients 
import requests
import json
import os
import threading


# OpenAI secret Key
API_KEY = 'xxxxxxxxxxxsecretAPIxxxxxxxxxx'
# Models: text-davinci-003,text-curie-001,text-babbage-001,text-ada-001
MODEL = 'text-davinci-003'
# Telegram secret access bot token
BOT_TOKEN = 'xxxxxxbotapikeyxxxxx'
# Defining the bot's personality using adjectives
BOT_PERSONALITY = 'Answer in a funny tone, '

Introducing the BOT_PERSONALITY parameter — your ticket to a ChatGPT with character! Use this handy constant to give your bot a specific tone or manner of speaking, like friendly, professional, or humorous. By setting the BOT_PERSONALITY parameter, you can customize the way that ChatGPT talks to your users and create a more personalized and engaging experience.

Here are 15 specific tones that you can use to customize the personality
of ChatGPT:
1. Friendly
2. Professional
3. Humorous
4. Sarcastic
5. Witty
6. Sassy
7. Charming
8. Cheeky
9. Quirky
10. Laid-back
11. Elegant
12. Playful
13. Soothing
14. Intense
15. Passionate

Then, create a function that retrieves a response from the OpenAI chatbot.

# 2a. Function that gets the response from OpenAI's chatbot
def openAI(prompt):
# Make the request to the OpenAI API
response = requests.post(
'https://api.openai.com/v1/completions',
headers={'Authorization': f'Bearer {API_KEY}'},
json={'model': MODEL, 'prompt': prompt, 'temperature': 0.4, 'max_tokens': 300}
)

result = response.json()
final_result = ''.join(choice['text'] for choice in result['choices'])
return final_result

# 2b. Function that gets an AI Image from OpenAI
def openAImage(prompt):
# Make the request to the OpenAI API
resp = requests.post(
'https://api.openai.com/v1/images/generations',
headers={'Authorization': f'Bearer {API_KEY}'},
json={'prompt': prompt,'n' : 1, 'size': '1024x1024'}
)
response_text = json.loads(resp.text)

return response_text['data'][0]['url']
#Example print(openAI(“What is entropy ?”))

This function 2.a will send a POST request to the OpenAI API with a given input (like ‘What is entropy?’) for the API to analyze. The temperature parameter controls how random the generated response will be — lower values mean more predictable text. The max_tokens parameter sets a limit on the number of words and punctuation in the response. And presto! The function will return the generated response from the specified OpenAI model.

Next up, it’s time to build a function that sends a message to a specific Telegram group.

# 3a. Function that sends a message to a specific telegram group
def telegram_bot_sendtext(bot_message,chat_id,msg_id):
data = {
'chat_id': chat_id,
'text': bot_message,
'reply_to_message_id': msg_id
}
response = requests.post(
'https://api.telegram.org/bot' + BOT_TOKEN + '/sendMessage',
json=data
)
return response.json()

# 3b. Function that sends an image to a specific telegram group
def telegram_bot_sendimage(image_url, group_id, msg_id):
data = {
'chat_id': group_id,
'photo': image_url,
'reply_to_message_id': msg_id
}
url = 'https://api.telegram.org/bot' + BOT_TOKEN + '/sendPhoto'

response = requests.post(url, data=data)
return response.json()

The above 3.a sends a message to a specific Telegram group through the use of the Telegram API. The function takes three arguments: bot_messagewhich is the message to be sent, chat_idwhich is the unique identifier of the chat where the message will be sent, and msg_id which specifies the unique identifier of the message that you want to reply to. The function uses the requests library to send a GET request to the Telegram API with the necessary parameters, including the API key, chat ID, and message to be sent.

Now it’s time to get to the good stuff — building a function that retrieves the latest requests from users in a Telegram group, generates a clever response using OpenAI, and sends it back to the group. Let’s do this thing!

# 4. Function that retrieves the latest requests from users in a Telegram group, 
# generates a response using OpenAI, and sends the response back to the group.

def Chatbot():
# Retrieve last ID message from text file for ChatGPT update
cwd = os.getcwd()
filename = cwd + '/chatgpt.txt'
if not os.path.exists(filename):
with open(filename, "w") as f:
f.write("1")
else:
print("File Exists")

with open(filename) as f:
last_update = f.read()

# Check for new messages in Telegram group
url = f'https://api.telegram.org/bot{BOT_TOKEN}/getUpdates?offset={last_update}'
response = requests.get(url)
data = json.loads(response.content)

for result in data['result']:
try:
# Checking for new message
if float(result['update_id']) > float(last_update):
# Checking for new messages that did not come from chatGPT
if not result['message']['from']['is_bot']:
last_update = str(int(result['update_id']))

# Retrieving message ID of the sender of the request
msg_id = str(int(result['message']['message_id']))

# Retrieving the chat ID
chat_id = str(result['message']['chat']['id'])

# Checking if user wants an image
if '/img' in result['message']['text']:
prompt = result['message']['text'].replace("/img", "")
bot_response = openAImage(prompt)
print(telegram_bot_sendimage(bot_response, chat_id, msg_id))

# Checking that user mentionned chatbot's username in message
if '@ask_chatgptbot' in result['message']['text']:
prompt = result['message']['text'].replace("@ask_chatgptbot", "")
# Calling OpenAI API using the bot's personality
bot_response = openAI(f"{BOT_PERSONALITY}{prompt}")
# Sending back response to telegram group
print(telegram_bot_sendtext(bot_response, chat_id, msg_id))
# Verifying that the user is responding to the ChatGPT bot
if 'reply_to_message' in result['message']:
if result['message']['reply_to_message']['from']['is_bot']:
prompt = result['message']['text']
bot_response = openAI(f"{BOT_PERSONALITY}{prompt}")
print(telegram_bot_sendtext(bot_response, chat_id, msg_id))
except Exception as e:
print(e)

# Updating file with last update ID
with open(filename, 'w') as f:
f.write(last_update)

return "done"

But wait, there’s more! We’ll also make sure they’re from a real user (not a pesky bot), and sends them to the OpenAI API for analysis if they mention the bot’s username and are a reply to the bot. Ensure that you have renamed your bot in the script by replacing “@ask_chatgptbot” with your desired name.

Okay, final step! It’s time to add a scheduling component to your bot so it can regularly check for new messages in the group and send responses as needed. Python’s threading library can help you out with this.

# 5 Running a check every 5 seconds to check for new messages
def main():
timertime=5
Chatbot()

# 5 sec timer
threading.Timer(timertime, main).start()

# Run the main function
if __name__ == "__main__":
main()

Ta-da! Presenting the fruits of your labor: the final Python code for your fancy new chatbot. Just copy and paste this bad boy into your favorite code editor, plug in your API keys and chat group ID, and you’ll be chatting it up with ChatGPT in no time.

Full overview of the code (github link here):

https://raw.githubusercontent.com/Eloise1988/OPENAI/main/robot.py

And there you have it, folks! With a few simple steps and a bit of Python magic, you’ve successfully created a chatbot for your Telegram group using OpenAI. Congratulations! Time to sit back and watch the hilarious responses roll in. Or, you know, do some fine-tuning and customization to make your chatbot truly unique. Either way, the world (or at least your group chat) is now your chatbot-filled oyster.

Testing it out at https://t.me/askchatgpt

Let the chatbot shenanigans begin! Simply click on the link below and send a message to @ask_chatGPTbot

--

--