DEV Community

Cover image for Telegram AI bot creation using ChatGPT and AWS Lambda (Python)
Ritesh Yadav for Python Discipline @EPAM India

Posted on

Telegram AI bot creation using ChatGPT and AWS Lambda (Python)

Amazon Web Services (AWS) is a collection of remote computing services (also called web services) that make up a cloud computing platform, offered by Amazon.com. These services operate from 12 geographical regions across the world. AWS offers a wide range of services such as computing power, storage options, networking, and databases, as well as developer tools and analytics.

Understanding serverless

To understand what AWS Lambda is, you have to first understand what serverless architecture is all about. Serverless applications in general are applications that don’t require any provisioning of servers for them to run. When you run a serverless application, you get the benefit of not worrying about OS setup, patching, or scaling of servers that you would have to consider when you run your application on a physical server.

Lambda (Serverless)

AWS Lambda is a serverless service provided by AWS. A Lambda function can be directly invoked by the Lambda console, Lambda API, AWS SDK, AWS CLI, and AWS toolkits. In AWS lambda Code is stored in S3 in encrypted form when it's resting .

Telegram and ChatGPT

Telegram is a popular messaging platform that allows users to exchange text, images, videos, and other media. Telegram bots are programs that can interact with Telegram users and respond to their messages. ChatGPT is an artificial intelligence language model that can generate text based on the input it receives.

In this blog, you are going to build a Telegram bot using ChatGPT and AWS Lambda.

Prerequisites

To follow along with this tutorial, you'll need the following:

  1. A Telegram account.
  2. Python 3 installed on your local machine.
  3. An AWS account.
  4. A Telegram bot token
  5. An OpenAI account

Setting up the Telegram bot
To set up a Telegram bot, follow these steps:

  1. Open Telegram and search for the BotFather.
  2. Type "/start" to initiate the conversation.
  3. Type "/newbot" to create a new bot.
  4. Follow the instructions to choose a name and username for your bot.
  5. Once your bot is created, you'll be given a token. Copy this token to use later.

Image description

Setting up the AWS Lambda function
To set up the AWS Lambda function, follow these steps:

  1. Open the AWS Management Console and navigate to the Lambda service.
  2. Click on "Create function".
  3. Choose "Author from scratch".
  4. Enter a name for your function.
  5. Choose "Python 3.8" as the runtime.
  6. Under "Permissions", choose "Create a new role with basic Lambda permissions".
  7. Click on "Create function".

Image description

  1. Scroll down to the "Function code" section and paste in the following Python code:
import json
import telebot
import openai
import logging

TELEGRAM_TOKEN = 'token'
OPENAI_API_KEY = "token"

openai.api_key = OPENAI_API_KEY
bot = telebot.TeleBot(TELEGRAM_TOKEN)

def generate_response(text):
    prompt = text
    response = openai.Completion.create(
        engine="davinci",
        prompt=prompt,
        temperature=0.7,
        max_tokens=150,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0
    )
    message = response.choices[0].text.strip()
    return message


def lambda_handler(event, context):
    try:
        message = json.loads(event['body'])['message']
        chat_id = message['chat']['id']
        text = message['text']
        logging.info(f"Received message from {chat_id}: {message}")
        if text[-1].isalpha():  # adding a dot, without a dot ChatGPT will try to complete the sentence.
            text = text + "."
        response = generate_response(text)
        bot.send_message(chat_id, response)

    except Exception as e:
        logging.error(str(e))
        pass

Enter fullscreen mode Exit fullscreen mode
  1. Replace "TELEGRAM_TOKEN" and "OPENAI_API_KEY" with your Telegram bot token and OpenAI API key, respectively.

Note: Add these package as a layers in lambda: openai, telebot or any other package you are using in your code.

HTTP API in the API Gateway service

To create a HTTP API follow these steps:

  1. To create our API, look for API Gateway in the list of services and then click on “Create API”
  2. Choose these configuration while creating HTTP API

Image description

  1. Choose 'ANY' in Route and method.
  2. The API is now created, save the Invoke URL adress for later.
  3. Go to the lambda page click on add a trigger and choose the API Gateway you just created.
  4. You now need to connect telegram to the API. You will set a Webhook so telegram will automatically forward every message to our API. To do that you will type the following address on our browser. Make sure to place here your bot token and your API invoke URL.

https://api.telegram.org/bot/setWebHook?url=

  1. This will return us a success message

Image description

Note: that the API gateway HTTP API and Lambda function must be in the same region.

To test the Telegram bot, follow these steps:

Now it’s all set. Every time the API is called the lambda function will be triggered.

  1. Open Telegram and search for your bot.
  2. Send a message to your bot.
  3. Your bot should respond with a message generated by ChatGPT.

Image description

Conclusion

In this blog, you have created a telegram blog using ChatGPT , AWS Lambda, Python.

Reference:

• AWS official documentation
• AWS Certified Cloud Practitioner Study Guide: CLF-C01 Exam Book
by Ben Piper and David Clinton
• Google
• chatgpt

Created By :
Ritesh Yadav
Software Engineer (EPAM SYSTEMS)

Disclaimer
This is a personal blog. The views and opinions expressed here are only those of the author and do not represent those of any organization or any individual with whom the author may be associated, professionally or personally.

Oldest comments (0)