Create a Telegram chat bot that uses gpt 3.5 in python

sangres

Corrado Cionini

Posted on April 6, 2023

Create a Telegram chat bot that uses gpt 3.5 in python

Overview

Hi everyone! I am Corrado and today I'll be sharing with you how to create a Telegram chat bot that integrates with the OpenAI API. In this dev.to post, we'll go through the step-by-step process of building a fully functional chatbot that uses artificial intelligence to respond to user inputs. Here's what we're going to cover:

  1. Setting up a Flask app on your local machine
  2. Create a Telegram Bot
  3. Connecting the Flask app to the Telegram Bot
  4. Writing a function to make requests to OpenAI API
  5. Deploying the app on Deta.space

By following these steps, you'll be able to create a Telegram bot that can hold intelligent conversations with users by leveraging the power of OpenAI. So let's get started!

1. Creating the App locally

mkdir telegrambot
cd telegrambot
touch main.py

# Open the file in the editor that u prefer
Enter fullscreen mode Exit fullscreen mode

Now you can decide if you want to work in a virtual environment or just install all modules directly on your machine.
Just to show you how to do that, these are the commands that we can use to setup the virtual env:

python -m venv <name_of_virtual_environment>

# if you use bash
source <name_of_virtual_environment>

# if you use fish
source <name_of_virtual_environment>/bin/activate.fish
Enter fullscreen mode Exit fullscreen mode

Let's now open the main.py file and write a basic flask app
main.py

from flask import Flask, request

app = Flask(__name__)

@app.route("/", methods=["GET"])
def index():
    return "Hello World!"


if __name__ == "__main__":
    port = 5000
    app.run(debug=True, host='0.0.0.0', port=port)
Enter fullscreen mode Exit fullscreen mode

And now we need to install flask trough pip: pip3 install flask.
After installing we can just run the app with: python3 main.py

We see that we successfully created the app! Nice job

localhost test

2. Create the telegram bot

To connect our Flask app to Telegram Bot API, we first need to create a new bot on Telegram. We can easily do so by following these simple steps:

  1. Open Telegram and search for "@botfather" in the search bar.

  2. Start a conversation with BotFather by sending the command "/start".

  3. To create a new bot, type the command "/newbot" and follow the instructions provided by BotFather.

  4. Give your bot a name and a unique username that ends with "bot".

  5. Once you've successfully created your bot, BotFather will give you an authorization token that you'll need to use to communicate with the Telegram Bot API.

Conversation with BotFather

By creating a new bot on Telegram, we can now link it to our Flask app and start building the chatbot's functionalities.

3. After creating the bot and getting a bot token, we can now link it with our Flask app.

In order to achieve that, we can use the requests module. We can easily install this package by running the command pip3 install requests.

Here is the updated code of main.py:

import requests
from flask import Flask, request

app = Flask(__name__)

BOT_TOKEN = <your_token_value>

def sendmessage(chatid, message):
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    payload = {
        "text": message,
        "chat_id": chatid
    }

    print(requests.get(url, params=payload))

@app.route("/", methods=["POST", "GET"])
def index():
    if (request.method == "POST"):
        resp = request.get_json()
        print(resp)
        # We get the content of the message
        msgtext = resp["message"]["text"]
        # We get the id of the chat
        chatid = resp["message"]["chat"]["id"]
        # The message is sent back
        sendmessage(chatid, msgtext)
        return "Done"
    else:
        return "Hello World!"

if __name__ == "__main__":
    port = 5000
    app.run(debug=True, host='0.0.0.0', port=port)
Enter fullscreen mode Exit fullscreen mode

Before trying out if the bot works we need to use ngrok to setup an http tunnel to localhost. We can do that using the command ngrok http 5000

ngrok http 5000

We can see that the url works by using curl

# telegrambot> curl https://a577-131-114-63-2.eu.ngrok.io
Hello World!⏎
Enter fullscreen mode Exit fullscreen mode

Now we can set the webHook of the telegram bot:

curl "https://api.telegram.org/bot<TOKEN>/setwebHook?url=https://a577-131-114-63-2.eu.ngrok.io"
{"ok":true,"result":true,"description":"Webhook was set"}
Enter fullscreen mode Exit fullscreen mode

And we can see that the bot now works perfectly
test telegram bot

4. Writing a function that calls the openai API

In order to get an API KEY we need to create an account on OpenAI. After that we go to this url https://platform.openai.com/account/api-keys
to get our own key.

Now we can update the function sendmessage to be like this:

def sendmessage(chatid, message):
    headers = {"Content-Type": "application/json",
               "Authorization": f"Bearer {OPEN_AI}"}
    info = {
        # The model used (you can use gpt-4 if you have access to it)
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": message}],
        # Randomness of the result
        "temperature": 0.7,
        "max_tokens": 1024
    }
    post_request = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=info)

    response_api = post_request.json()["choices"][0]["message"]["content"]
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    payload = {
        "text": response_api,
        "chat_id": chatid
    }
Enter fullscreen mode Exit fullscreen mode

openai telegram test

Deploy on deta.space

In order to deploy on deta.space we need to follow these steps that we can see on the documentation

  • Create an account
  • Download the Space Cli curl -fsSL https://get.deta.dev/space-cli.sh | sh
  • Login on the cli with space login
  • Create the project with space new
  • Updated a few lines of the code to be like this
 import os
 OPEN_AI = os.getenv("OPEN_AI")
 BOT_TOKEN = os.getenv("BOT_TOKEN")
Enter fullscreen mode Exit fullscreen mode
  • Creating a Spacefile how to run the app
# Spacefile Docs: https://go.deta.dev/docs/spacefile/v0
v: 0
app_name: telegrambot
micros:
    - name: telegrambot
      src: .
      engine: python3.9
      primary: true
      public_routes:
        - "/"
      presets:
        env:
          - name: BOT_TOKEN
            description: Telegram Bot Key
            default: "<BOT_TOKEN>"
          - name: OPEN_AI
            description: Open AI Key
            default: "<OPEN_AI_API>"
Enter fullscreen mode Exit fullscreen mode
  • Push the app to deta.space with space push
  • Changing the telegram hook with the same commands but with the url of the deta.space app

Finished

Great job, guys! We've created a beautiful bot that uses artificial intelligence to assist you. If you have any questions or projects that you'd like to suggest, please leave a comment below to let me know. Bye for now! :D

💖 💪 🙅 🚩
sangres
Corrado Cionini

Posted on April 6, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related