chu-js
chu-js

Reputation: 163

Telegram Bot (coded in python) integration with AWS API Gateway

I just built a telegram bot using the python-telegram-bot package. I am trying to integrate it with AWS API Gateway such that every time user sends a message, it triggers & runs the Lambda function. I have set up the API gateway according to the instructions in this link. However, when I send message to the bot, the function doesn't get triggered & I don't receive any messages in return. It works though when I manually enter the "Invoke URL" of API gateway, ie. the API is indeed triggering the Lambda function, just that the telegram bot is not triggering the API even though I have already set the webhook. specifically, I used: curl --data "url=<INVOKE_URL>" "https://api.telegram.org/bot<ACCESS_TOKEN>/setWebhook"

I would really appreciate if someone could advise me on how to integrate API gateway to trigger Lambda code for telegram bot. It is my first Python project actually, but deployment on AWS has been such a huge hurdle!

import requests
import re
import os

def start(update, context):
    chat_id = update.message.chat_id
    context.bot.send_message(chat_id=chat_id, text="Beep boop dog! Type /bop to receive dog pics.")

def get_url():
    contents = requests.get('https://random.dog/woof.json').json()
    url = contents['url']
    return url

def get_image_url():
    allowed_extension = ['jpg','jpeg','png']
    file_extension = ''
    while file_extension not in allowed_extension:
        url = get_url()
        file_extension = re.search("([^.]*)$",url).group(1).lower()
    return url

def bop(update, context):
    url = get_image_url()
    chat_id = update.message.chat_id
    context.bot.send_photo(chat_id=chat_id, photo=url)

def main(event, context):
    TOKEN = os.environ['TOKEN']
    updater = Updater(token=TOKEN, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('start',start))
    dp.add_handler(CommandHandler('bop',bop))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Upvotes: 1

Views: 1210

Answers (1)

chu-js
chu-js

Reputation: 163

I used EC2 with process below. Set locale before I could invoke ‘sudo yum install’

[on EC2]

sudo vi /etc/environment

appended LANG=en_US.utf-8 /n LC_ALL=en_US.utf-8

sudo yum install python 37
curl -0 https://bootstrap.pypa.io/get-pip.py
python3 get-pip.py --user
pip install <package> --user

[on localhost]

scp -i beepboopdog.pem script.py ec2-user@<ec2-ip>.ap-southeast-1.compute.amazonaws.com:/home/ec2-user

[on EC2] Nohup: for script to run after terminating session

nohup python3 script.py &
ps -ef to list processID
kill <processID>

Upvotes: 0

Related Questions