Build an automated, AI-powered Telegram Chatbot with ChatGPT using Flask

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

Step 1: Create a Telegram Bot

To automate messages with ChatGPT, we just need to create Telegram Bot. Please follow the instructions in our blog post on setting up Telegram Bot step 1 to step 11. Please confirm that you have followed the blog instructions before continuing.

Step 2: ChatGPT API

Please see our blog post: WhatsApp Chatbot With ChatGPT Step 2 “ChatGPT API” which has instructions for setting up and using ChatGPT.

Step 3: Integrate the ChatGPT API with the Flask application

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

However, the ChatGPT API will continue to run in the background of the Firefox browser, which may interfere with receiving responses from the ChatGPT API, so we need to end the process that is currently running in the browser.

def process():
        # iterating through each instance of the process
        for line in os.popen("ps ax | grep firefox | grep -v grep"):
            fields = line.split()
            # extracting Process ID from the output
            pid = fields[0]
            # terminating process
            os.kill(int(pid), signal.SIGKILL)
        print("Process Successfully terminated")
        print("Error Encountered while running script")

The Flask app we developed step 1 must be changed now. To get a ChatGPT response to user messages, replace the existing code in your Flask application with the following code.

import requests
import os, signal

from flask import Flask
from flask import request
from flask import Response
from chatgpt_wrapper import ChatGPT


app = Flask(__name__)

def parse_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'{TOKEN}/sendMessage'
    payload = {
                'chat_id': chat_id,
                'text': text
    response =,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)
        bot = ChatGPT()
        response = bot.ask(txt)
        print("ChatGPT response: ",response) 
        return Response('ok', status=200)
        return "<h1>Welcome!</h1>"
if __name__ == '__main__':


Run the flask application in the terminal. python
Run ngrok in terminal. ngrok http 5000

Step 4: Test the Telegram Chatbot

Please send multiple messages to the Telegram bot to receive a response generated by ChatGPT. You will also receive a response on the server.

Here is the response from ChatGPT on our server.

We will get the answer shown below in Telegram Bot.

Let us know if you have any problems configuring or using the script. We will be happy to help. Contact us or write your request 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 series of blog posts where we provided a tutorial on how to create a chatbot for different platforms. You can explore these blogs and learn how you can define different types of rich responses that can increase user engagement in your chatbot.

Telegram: Create a Telegram bot using Python tutorial with examples

Facebook Messenger. Create a Facebook Messenger bot using Python tutorial with examples

Slack: Create a Slack Bot using Python tutorial with examples

Discord: Create a Discord bot using Python tutorial with examples

Source link