January 10, 2023 No Comments

This blog describes how you can integrate Telegram and create a python application based on the Flask web framework that can receive user Telegram messages and utilize ChatGPT to respond to those messages in detail.

Step 1: Create Telegram Bot

In order to automate the messages with ChatGPT, we just need to create the Telegram Bot. Please follow the instructions in our blog post Telegram Bot setup from step 1 to step 11. Please confirm that you followed the blog’s instructions before proceeding. 

Step 2: ChatGPT API

Please take a look at our blog post, WhatsApp Chatbot With ChatGPT Step 2 “ChatGPT API” which has instructions for setting up and using ChatGPT. 

Step 3: Integrate ChatGPT API with Flask Application

After our ChatGPT API got installed successfully, it is time to integrate it with the flask application. 

The flask application we developed in step 1 has to be modified now. To receive ChatGPT’s response to user messages, replace the existing code in your Flask app with the following code.

				
					import requests
import os, signal

from flask import Flask
from flask import request
from flask import Response
import openai

openai.api_key = '<YOUR OPENAI API KEY>'

TOKEN = "<Your BOT TOKEN>"

app = Flask(__name__)


def parse_message(message):
    print("message-->",message)
    chat_id = message['message']['chat']['id']
    txt = message['message']['text']
    print("Text :", txt)
    return chat_id,txt
 
def tel_send_message(chat_id, text):
    url = f'https://api.telegram.org/bot{TOKEN}/sendMessage'
    payload = {
                'chat_id': chat_id,
                'text': text
                }
   
    response = requests.post(url,json=payload)
    return response

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        msg = request.get_json()
       
        chat_id,txt = parse_message(msg)
        
        completion = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "user", "content": txt}]
            )
        response = completion['choices'][0]['message']['content']
        print("ChatGPT response: ",response) 
        tel_send_message(chat_id,response)
        process()
        return Response('ok', status=200)
    else:
        return "<h1>Welcome!</h1>"
 
if __name__ == '__main__':
   app.run(debug=True)
				
			

Note:

Run the flask application in the terminal: python SCRIPT_NAME.py
Run the ngrok on terminal: ngrok http 5000

Please send some messages to the Telegram bot to receive the ChatGPT-generated response. You will also get a response on a server.

Here is the ChatGPT response on our server.

We will get the below response in the Telegram Bot.

Do let us know if you face any issues in setting up or using the script. We would be happy to help! Contact us or post your query in the comments.

Also, check out our other tutorials to learn how to build a ChatGPT chatbot on different platforms.

WhatsApp with ChatGPT: Build An Automated, AI-Powered WhatsApp Chatbot With ChatGPT Using Flask

Facebook Messenger with ChatGPT: Build An Automated, AI-Powered Facebook Messenger Chatbot With ChatGPT Using Flask

Slack Chatbot with ChatGPT: Build An Automated, AI-Powered Slack Chatbot With ChatGPT Using Flask

We have already created a blog post series where we have provided a tutorial on how to create a chatbot for different platforms. You can explore these blogs and learn how you can set different kinds of rich responses which can increase user engagement on your chatbot.

Telegram: Create Telegram Bot Using Python Tutorial With Examples

Facebook Messanger: Create Facebook Messenger Bot Using Python Tutorial With Examples

Slack: Create Slack Bot Using Python Tutorial With Examples

Discord: Create Discord Bot Using Python Tutorial With Examples

Dialogflow ES API: How To Integrate Dialogflow ES API To Add NLP Capabilities In Your Chatbot?

Dialogflow CX API: How to integrate Dialogflow CX API to add NLP capabilities in your Chatbot?

Dialogflow ES with Twilio: Setup Twilio Integration On Your Server To Connect Google Dialogflow ES 

Write a comment

Your email address will not be published. Required fields are marked *

Want to talk to an Expert Developer?

Our experts in Generative AI, Python Programming, and Chatbot Development can help you build innovative solutions and scale your business faster.