Telegram Bot 1: Stock Tracking

Simon Law
3 min readJun 6, 2020

Python + AWS EC2

0. Demo

List of commands
Set alert on stock price
Set alert on exchange rate
  1. Setup

- create AWS account
- install FileZilla and PuTTY
https://filezilla-project.org/download.php?type=client
https://www.putty.org/

- 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 main.py
https://github.com/simonlaw101/tg_bot

token = 'YOUR_TOKEN'

2. Start server

- login AWS Management Console
- choose “Services” and “EC2”
- click “Launch Instance”
- choose “Ubuntu Server 18.04 LTS (HVM)”
- click “Review and Launch”, and “Launch”
- choose option “Create a new key pair”
- input “Key pair name”, e.g. python-server
- click “Download Key Pair”, e.g. python-server.pem will be downloaded
- click “Launch Instances”
- click “View Instances” and check the “Instance State” until it changes from “pending” to “running”

3. Connect to server

- open PuTTYgen (PuTTY Key Generator)
- click “Load”
- click All Files (*.*) and open python-server.pem
- click “Save private key”, and “Yes”
- save as python-server-key.ppk

- copy Public DNS (IPv4) from AWS Instance Description, e.g.
ec2–11–11–11–11.us-east-2.compute.amazonaws.com

- open PuTTY
Host Name: ubuntu@ec2–11–11–11–11.us-east-2.compute.amazonaws.com
- go to Category => Connection => SSH => Auth
- go to “Private key file for authentication”, click “Browse…”

- open python-server-key.ppk
- go back to Category => Session
- Saved Session: python-server
- Save
- double click “python-server”, click “Yes”
- make sure everything is up to date

$ sudo apt-get update

4. Install external library

- install pip

$ sudo apt install python3-pip
$ y

- install external library

$ pip install beautifulsoup4
$ pip install requests

5. File transfer to server

- open FileZilla
=> File
=> Site Manager…
=> New site
Protocol: SFTP — SSH File Transfer Protocol
Host: ec2–11–11–11–11.us-east-2.compute.amazonaws.com
Logon Type: Key file
User: ubuntu

- Key file => Browse…
- open python-server-key.ppk
- Connect
- drag and drop your files to Remote site: /home/ubuntu

6. Start program

- run “screen” command in PuTTY

$ screen

- click enter, go to your folder and run the python script

$ cd tg_bot
$ python3 main.py

- press “Ctrl-a” + “d” (detach from the screen session)
- close PuTTY

7. Terminate program

- reattach to the screen session

$ screen -r

- press “Ctrl-c” to terminate the program

Note:

1. In case you have multiple screen sessions running on your machine, you will need to append the screen session ID after the r switch, e.g.

$ screen –r 19011

2. To close a particular screen session:

$ screen –XS 19011 quit

3. To close all screen sessions:

$ killall screen

4. To resume attached screen

$ screen –rd 19011

Next Article:
Telegram Bot 2: OCR

--

--