Telegram Bot 2: OCR

Simon Law
4 min readJan 10, 2021

--

Python + AWS Lambda + AWS API Gateway

Previous Article:
Telegram Bot 1: Stock Tracking

0. Demo

  1. Setup

- create AWS account

- talk to BotFather in telegram and create a bot. You will receive an authorization token. https://core.telegram.org/bots
- download the script and fill in the token in lambda_function.py
https://github.com/simonlaw101/tg_bot

token = 'YOUR_TOKEN'

2. Create a Lambda function

- set a longer timeout (Optional)

3. Add a Layer for external library dependencies (Optional)

- create a new folder named “python” & install the required external library inside

pip3 install --target . YOUR_LIBRARY

- select “python” folder and add to archive (e.g. layer.zip)

*Note that the library must be in the following structure (inside python folder), otherwise you will get import module error during runtime

AWS official example file structure for the Pillow library:

pillow.zip
│ python/PIL
└ python/Pillow-5.3.0.dist-info

- go to your function

- layer is immutable
- upload new version for any changes

4. Deploy code to Lambda

- create a folder including all your source code files

- select all files and add to archive (e.g. lambda_function.zip)

- upload the .zip file to lambda

5. Create an API Gateway

6. Set Webhook

- place the following URL in the browser and hit enter

https://api.telegram.org/bot<YOUR_TOKEN>/setWebHook?url=<INVOKE_URL>

- you should receive the following response:

{"ok":true,"result":true,"description":"Webhook was set"}

- to view the Webhook information:

https://api.telegram.org/bot<YOUR_TOKEN>/getWebhookInforesponse:
{"ok":true,"result":{"url":"https://9XXXXXXXXh.execute-api.us-east-2.amazonaws.com/v1","has_custom_certificate":false,"pending_update_count":0,"max_connections":40,"ip_address":"10.10.10.10"}}

Reference:

https://dev.to/nqcm/-building-a-telegram-bot-with-aws-api-gateway-and-aws-lambda-27fg

https://docs.aws.amazon.com/lambda/latest/dg/python-package.html

https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html#configuration-layers-compile

--

--