I followed this tutorial to create a Telegram bot in Python. In the end, I ran it locally on my machine with ngrok. To test the bot I sent messages to it in Telegram and it worked, so that was a good tutorial.
However, now I want to host the bot on the cloud because I certainly don't want to have my PC always turned on with a terminal running.
I've been reading many tutorials on the web on how to host a serverless Telegram bot. I've tried hosting it in AWS Lambda, Heroku, Google Cloud Platform and Glitch.com. But I still haven't managed to host it successfully. There was always something that prevented me from hosting it: either my code was not properly accepted, the tutorial was not descriptive enough or I was not understanding something important.
When following tutorials I sometimes had to adapt my code to the platform I was trying to host the bot in. I still couldn't make it work.
What am I doing wrong? How can I successfully host my Telegram bot written in Python on the cloud (for free)?
This is my code:
import requests
import os
from bottle import Bottle, response, request as bottle_request
from unidecode import unidecode
# get credentials
bot_url = os.environ['BOT_URL']
class BotChangei:
def get_chat_id(self, data):
chat_id = data['message']['chat']['id']
return chat_id
def get_message(self, data):
message_text = data['message']['text']
return message_text
def send_message(self, prepared_data):
"""
Prepared data should be json which includes at least `chat_id` and `text`
"""
message_url = self.bot_url + 'sendMessage'
requests.post(message_url, json=prepared_data)
class TelegramBot(BotChangei, Bottle):
def __init__(self, *args, **kwargs):
super(TelegramBot, self).__init__()
self.route('/', callback=self.post_handler, method="POST")
def is_vowel(self, letter):
return unidecode(letter) in {'a', 'e', 'o', 'u'}
def is_capital(self, letter):
return unidecode(letter) in {'A', 'E', 'O', 'U'}
def change_text_message(self, text):
mutable_list = list(text)
i = 0
for letter in mutable_list:
if self.is_vowel(letter):
mutable_list[i] = 'i'
elif self.is_capital(letter):
mutable_list[i] = 'I'
i += 1
return "".join(mutable_list)
def prepare_data_for_answer(self, data):
message = self.get_message(data)
answer = self.change_text_message(message)
chat_id = self.get_chat_id(data)
json_data = {
"chat_id": chat_id,
"text": answer,
}
return json_data
def post_handler(self):
data = bottle_request.json
answer_data = self.prepare_data_for_answer(data)
self.send_message(answer_data)
return response
if __name__ == '__main__':
app = TelegramBot()
app.run(host='localhost', port=8080)