Giới thiệu
Mình vốn dĩ là một tay đam mê cờ bạc, coin, chứng khoán. Năm đó mình báo nhà cả trăm tỉ nhưng rồi có một người bạn chỉ cho mình cách code python, sau nhiều ngày cắp sách đi học mình đã viết được 1 con bot giám sát và thông báo kết quả coin theo khoảng giá được chỉ định, chính vì thế sau 1 năm cố gắng mình báo nhà tiếp lần thứ 2. Chính vì thế mình quyết định chia sẻ cho anh em mê coin cách để dựng 1 con bot thông báo kết quả coin bằng python =))
Đối tượng nên đọc
- Tất cả các anh em còn xa bờ
- Để tham khảo và viết những con tool phục vụ công việc, cá nhân
- Chỉ để đọc cho vui
Yêu cầu
- Biết cơ bản python, không biết cũng chẳng sao google ra hết
- Biết cơ bản docker, hoặc thôi cứ cho nó chạy đã rồi học sau
Chi tiết
Công việc đầu tiên để tạo 1 con bot tele thì tất nhiên chúng ta phải tải telegram về và tạo bot rồi
- Mở telegram ở thanh tìm kiếm chúng ta tìm BotFather
- Nhập /newbot để tạo bot, và nhập tên bot bạn muốn như hình là thành công, hãy lưu token ra 1 file bí mật nhé chúng ta sẽ dùng nó để connect tới bot
Bắt tay vào code
Đầu tiên chúng ta sẽ tạo 1 file requirements.txt để chứa các thư viện cần thiết cho bot
APScheduler==3.6.3 beautifulsoup4==4.11.1 cachetools==4.2.2 certifi==2021.10.8 charset-normalizer==2.0.12 click==8.1.2 Cython==0.29.28 Flask==2.1.1 idna==3.3 importlib-metadata==4.11.3 itsdangerous==2.1.2 Jinja2==3.1.1 MarkupSafe==2.1.1 python-crontab==2.6.0 python-dateutil==2.8.2 python-telegram-bot==13.11 pytz==2022.1 pytz-deprecation-shim==0.1.0.post0 requests==2.27.1 six==1.16.0 soupsieve==2.3.2.post1 tornado==6.1 tzdata==2022.1 tzlocal==4.2 urllib3==1.26.9 Werkzeug==2.1.1 zipp==3.8.0
Gõ pip3 install -r requirements.txt để tải các thư viện cần thiết về local phục vụ cho việc test
Tiếp theo chúng ta tạo file tele.py mục đích của file này sẽ chứa các xử lý gửi và nhận message từ bot
import json import requests import time TOKEN = "5447920895:AAG-6RLAgjj7Ejly1P8XvUTItof984f4pBg" # token lúc tạo bot URL = "https://api.telegram.org/bot{}/".format(TOKEN) def get_url(url): response = requests.get(url) content = response.content.decode("utf8") return content def get_json_from_url(url): content = get_url(url) js = json.loads(content) return js def get_updates(): url = URL + "getUpdates" js = get_json_from_url(url) return js def get_last_chat_id_and_text(updates): num_updates = len(updates["result"]) last_update = num_updates - 1 text = updates["result"][last_update]["message"]["text"] chat_id = updates["result"][last_update]["message"]["chat"]["id"] return (text, chat_id) def send_message(text, chat_id): url = URL + "sendMessage?text={}&chat_id={}".format(text, chat_id) get_url(url)
Tiếp theo đó chúng ta tạo thêm file Constaint.py có nhiệm vụ chưa các config mặc định của bot
class Constaint: LIST_COIN=["BTC", "SHIB", "EOS", "ANC", "EXP","MIR","XEC", "JASMY", "PEOPLE","BTTC","WIN","SPELL","DENT","VTHO","HOT","NBS","MBL","TROY","REEF","KEY","XVG","CKB","SLP"] LIST_FAVOURITE = [] RATE_DOWN=-10 RATE_UP=10 CHAT_ID ="1625452249" LAST_CHAT=(None, None) TIME_AUTO=5
Cuối cùng tạo 1 file main.py có nhiệm vụ chưa xử lý bắt tín hiệu và gửi message về bot
import sys import os from coin import * from Constaint import * from tele import * from threading import Thread def getPriceCoin(): while True: try: text, chat = get_last_chat_id_and_text(get_updates()) if (text, chat) != Constaint.LAST_CHAT: if configData(text,chat): continue if (text, chat) != Constaint.LAST_CHAT and len(text) < 10: send_message(get_biance_price(text), chat) Constaint.LAST_CHAT = (text, chat) time.sleep(0.5) except Exception as e: print(e) def getPriceCoinAuto(): while True: result = get_list_coin_price(True) if(result != ""): send_message(result, Constaint.CHAT_ID) time.sleep(Constaint.TIME_AUTO) def configData(text,chat): if text.upper() == "DSYT": #lệnh xem danh sách yêu thích send_message("\n".join(str(x) for x in Constaint.LIST_FAVOURITE), chat) Constaint.LAST_CHAT = (text, chat) return True elif "ADD" in text.upper(): # thêm đồng coin vào danh sách yêu thích coinName = text.upper().split(" ")[1].strip() if coinName in Constaint.LIST_FAVOURITE: send_message("Đồng coin {} đã tồn tại".format(coinName), chat) Constaint.LAST_CHAT = (text, chat) return True Constaint.LIST_FAVOURITE.append(coinName) send_message("Thêm thành công coin {}".format(coinName), chat) Constaint.LAST_CHAT = (text, chat) return True elif "REMOVE" == text.upper().split(" ")[0].strip(): #Xóa đồng coin khỏi danh sách theo dõi coinName = text.upper().split(" ")[1].strip() Constaint.LIST_FAVOURITE.remove(coinName) send_message("Xóa thành công coin {}".format(coinName), chat) Constaint.LAST_CHAT = (text, chat) return True elif "RATE_UP" in text.upper(): # set thông báo nếu đồng coin trong danh sách tăng theo % (vd RATE_UP 10 thì khi đồng coin tăng 10% sẽ báo về bot) rate = text.upper().split(" ")[1] Constaint.RATE_UP = float(rate.strip()) send_message("setting rate up = {}".format(Constaint.RATE_UP), chat) Constaint.LAST_CHAT = (text, chat) return True elif "RATE_DOWN" in text.upper(): # Tương tự set thông số % giảm của đồng coin rate = text.upper().split(" ")[1] Constaint.RATE_DOWN = float(rate.strip()) send_message("setting rate down = {}".format(Constaint.RATE_DOWN), chat) Constaint.LAST_CHAT = (text, chat) return True elif "AUTO" == text.upper().split(" ")[0]: # thời gian quét giá đồng coin vd 10 giây 1 lần quét rate = text.upper().split(" ")[1] Constaint.TIME_AUTO = int(rate.strip()) send_message("setting time auto = {} giây".format(Constaint.TIME_AUTO), chat) Constaint.LAST_CHAT = (text, chat) return True elif "AUTOALL" in text.upper(): # Theo dõi tất cả các đồng coin được chỉ định trong Constaint.py Constaint.LIST_FAVOURITE+=Constaint.LIST_COIN send_message("Theo dõi all list thành công.!", chat) Constaint.LAST_CHAT = (text, chat) return True elif "REMOVEALL" in text.upper(): #Xóa tất cả danh sách theo dõi Constaint.LIST_FAVOURITE = [] send_message("Xóa theo dõi thành công.!", chat) Constaint.LAST_CHAT = (text, chat) return True elif text.upper() == "CONFIG": #Xem tất cả các config view_setting = "List coin yêu thích: {} \n RATE_UP = {}, RATE_DOWN = {} \n TIME_AUTO: {} giây".format("\n".join(str(x) for x in Constaint.LIST_FAVOURITE), Constaint.RATE_UP, Constaint.RATE_DOWN, Constaint.TIME_AUTO) send_message(view_setting, chat) Constaint.LAST_CHAT = (text, chat) return True else: return False def main(): Constaint.LAST_CHAT = (None, None) Thread(target = getPriceCoinAuto).start() Thread(target = getPriceCoin).start() if __name__ == '__main__': main()
Sau cùng chạy ứng dụng vừa code mở cmd python3 main.py vào lại telegram thanh tìm kiếm gõ tìm con bot đã tạo ở trên, ở đây mình gõ thangnotes.name.vn là tên con bot mình tạo và nhập AUTOALL, RATE_DOWN -2 nghĩa là cứ đồng coin nào trong danh sách có giá giảm quá 2% thì sẽ báo về bot mỗi 5 giây 1 lần. Ngoài ra bạn có thể dùng lệnh ADD <TÊN ĐỒNG COIN> để thêm vào danh sách theo dõi
Như vậy là đã xong các bạn có thể chạy ở máy cá nhân hoặc deploy lên server để chạy 24/7
Deploy lên server
Tạo file Dockerfile với nội dung như sau
FROM python:latest WORKDIR /app COPY . . RUN pip3 install -r requirements.txt CMD ["python3", "main.py"]
Tiếp theo chúng ta tạo 1 file build.sh để chứa các lệnh build Dockerfile và run app
docker rmi -f $(docker images -aq) docker rm -f $(docker ps -a -q) docker rmi coin docker image build -t coin /root/coin docker run -d -p 80:80 coin
sửa docker image build -t coin /root/coin thành docker image build -t coin <thư mục chứa source code>
Ok vậy là đã xong giờ chúng ta sẽ kiếm 1 con vps đẩy source code lên và chạy sh build.sh để deploy ở đây mình dùng ec2 của aws về cách đăng ký và sử dụng tương đối đơn giản các bạn tham khảo google nhé. Step deploy như sau
- SSH vào ec2 centos
- cài đặt git yum install git
- git clone https://github.com/katothang/coin.git để tải source về
- cd coin sau đó pwd để xem thư mục đường dẫn của source trên server mục đích là để sửa file build.sh
- chạy lệnh sh build.sh đợi cho quá trình cài đặt hiện lên như hình là thành công
Link download source: Bot telegram
Cảm ơn các bạn đã đọc bài.