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:
- A Telegram account.
- Python 3 installed on your local machine.
- An AWS account.
- A Telegram bot token
- An OpenAI account
Setting up the Telegram bot
To set up a Telegram bot, follow these steps:
- Open Telegram and search for the BotFather.
- Type "/start" to initiate the conversation.
- Type "/newbot" to create a new bot.
- Follow the instructions to choose a name and username for your bot.
- Once your bot is created, you'll be given a token. Copy this token to use later.
Setting up the AWS Lambda function
To set up the AWS Lambda function, follow these steps:
- Open the AWS Management Console and navigate to the Lambda service.
- Click on "Create function".
- Choose "Author from scratch".
- Enter a name for your function.
- Choose "Python 3.8" as the runtime.
- Under "Permissions", choose "Create a new role with basic Lambda permissions".
- Click on "Create function".
- 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
- 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:
- To create our API, look for API Gateway in the list of services and then click on “Create API”
- Choose these configuration while creating HTTP API
- Choose 'ANY' in Route and method.
- The API is now created, save the Invoke URL adress for later.
- Go to the lambda page click on add a trigger and choose the API Gateway you just created.
- 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=
- This will return us a success message
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.
- Open Telegram and search for your bot.
- Send a message to your bot.
- Your bot should respond with a message generated by ChatGPT.
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.
Top comments (0)