Telegram cho Upload file 2Gb đối với tài khoản thường và 4Gb đối với tài khoản Premium, tận dụng chức năng này bạn có thể Upload file Backup Database và Website lên Telegram để lưu trữ. Bài viết này sẽ giới thiệu đến bạn một script tự động Database và Source Code website, sau đó gửi trực tiếp bản sao lưu lên Telegram. Giải pháp này không chỉ tiện lợi, an toàn mà còn giúp bạn dễ dàng theo dõi và quản lý các bản backup ngay trên App.
Tham gia kênh Telegram của AnonyViet 👉 Link 👈 |

Hướng Dẫn Backup Database và Website lên Telegram
Bây giờ chúng ta sẽ bắt đầu viết code Backup Database và Website lên Telegram. Tóm tắt quá trình gồm 3 bước:
- Tạo script upload file lên telegram
- Tạo script backup Website
- Hẹn giờ backup định kỳ
Scirpt gửi file lên Telegram
Bạn cần điền 4 thông tin này vào Script:
api_id = api_hash = phone_number = group_id =
Cách lấy thông tin như sau:
Trước tiên bạn cần vào trang https://my.telegram.org và đăng nhập để lấy api_id và api_hash và điền vào trong Code bên dưới
Sau đó bạn tạo 1 Group Telegram chỉ với 1 mình bạn trong Group đó, mục đích dùng Group để lưu trữ các File Backup.
trong phần group_id = : bạn lấy id của group mới tạo để điền vào. Nếu không biết ID group là bao nhiêu thì bạn add con bot này vào: @myidbot
Sau khi add xong, trong group bạn gõ lệnh /getgroupid@myidbot
để lấy ID Group (lưu ý copy luôn dấu – nhé)
Lưu file thành tele.py vào trong thư mục /root/code/
Ta có đường dẫn như sau: /root/code/tele.py
from telethon import TelegramClient import asyncio import os import sys from datetime import datetime, timezone, timedelta # --- Config thông tin đăng nhập --- api_id = xxx # Thay bằng xxx lấy ở https://my.telegram.org api_hash = 'xxxxxx' # Thay bằng xxxxxx lấy ở https://my.telegram.org phone_number = '+84913456789' # Số điện thoại Telegram của bạn (bao gồm mã quốc gia) group_id = -123456 # ID nhóm Telegram log_file = '/var/log/backup_telegram.log' # Hàm lấy giờ GMT+7 def get_vn_time(): utc_now = datetime.now(timezone.utc) vn_now = utc_now + timedelta(hours=7) return vn_now.strftime("%Y-%m-%d %H:%M:%S") # Ghi log ra file def write_log(message): with open(log_file, 'a') as f: f.write(f"{get_vn_time()} - {message}\n") async def main(upload_directory): client = TelegramClient('user_session', api_id, api_hash) await client.start(phone=phone_number) if not os.path.isdir(upload_directory): msg = f"❌ Không tìm thấy thư mục backup: {upload_directory}" write_log(msg) print(msg) return files = [os.path.join(upload_directory, f) for f in os.listdir(upload_directory) if os.path.isfile(os.path.join(upload_directory, f))] if not files: msg = "📂 Thư mục rỗng, không có file nào để upload." write_log(msg) print(msg) return write_log(f"📦 Bắt đầu upload {len(files)} file từ {upload_directory}") for idx, file_path in enumerate(files, start=1): filename = os.path.basename(file_path) upload_time = get_vn_time() file_size_mb = os.path.getsize(file_path) / (1024 * 1024) # Cảnh báo nếu file quá 1900MB if file_size_mb > 1900: warning = f"⚠️ File {filename} lớn ({file_size_mb:.2f} MB), có thể không upload được." write_log(warning) print(warning) try: print(f"🚀 [{idx}/{len(files)}] Upload {filename} ({file_size_mb:.2f}MB) lúc {upload_time}") await client.send_file( group_id, file_path, caption=f"📄 File: {filename}\n🕒 Upload lúc: {upload_time} (GMT+7)\n📦 Dung lượng: {file_size_mb:.2f} MB" ) write_log(f"✅ Upload {filename} thành công.") except Exception as e: error_message = f"❌ Upload lỗi {filename}: {e}" write_log(error_message) print(error_message) # Gửi thông báo lỗi về group Telegram await client.send_message(group_id, f"❌ Lỗi upload file: {filename}\nError: {e}") await client.disconnect() print("🎉 Đã hoàn tất upload tất cả các file.") write_log("🎉 Upload hoàn tất.") if __name__ == '__main__': if len(sys.argv) != 2: print("❌ Cần truyền vào đường dẫn thư mục backup.") sys.exit(1) upload_directory = sys.argv[1] asyncio.run(main(upload_directory))
Bây giờ bạn gõ lệnh:
cd /root/code echo "" > a.txt python3 tele.py
Ở lần chạy code đầu tiên, bạn sẽ được yêu cầu nhập mã OTP gửi về SĐT hoặc App Telegram để xác thực.
Nếu bạn thấy file a.txt được Upload lên Group Telegram của bạn là xem như thành công phần Upload File lên telegram. Chúng ta sẽ qua bước tiếp theo
Tạo Script Backup Website và Database
Đây là Script mình tham khảo từ HocVPS dùng để Backup dữ liệu Website trên Server Ubuntu:
Vào thư mục /root/code/ tạo file backup.sh có nội dung như sau:
(Thay zip -r $BACKUP_DIR/anonyviet.com.zip /home/anonyviet.com/public_html/ -q -x /home/anonyviet.com/public_html/wp-content/cache/**\* #Exclude cache ) thành đường dẫn đúng trong Server của bạn nhé)
#!/bin/bash TIMESTAMP=$(date +"%F") BACKUP_DIR="/root/backup/$TIMESTAMP" MYSQL=/usr/bin/mysql MYSQLDUMP=/usr/bin/mysqldump SECONDS=0 mkdir -p "$BACKUP_DIR/mysql" databases=`$MYSQL -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema|mysql)"` for db in $databases; do $MYSQLDUMP --force --opt $db | gzip > "$BACKUP_DIR/mysql/$db.gz" done # Loop through /home directory zip -r $BACKUP_DIR/anonyviet.com.zip /home/anonyviet.com/public_html/ -q -x /home/anonyviet.com/public_html/wp-content/cache/**\* #Exclude cache # Gọi file Python để upload cd /root/code/ python3 tele.py "$BACKUP_DIR" size=$(du -sh $BACKUP_DIR | awk '{ print $1}') duration=$SECONDS echo "Total $size, $(($duration / 60)) minutes and $(($duration % 60)) seconds elapsed."
Cấp quyền thực thi cho file backup.sh, bạn gõ lệnh:
cd /root/code/ chmod +x *
Thiết lập Cronjob sao lưu dữ liệu hàng ngày gửi lên Telegram
Chúng ta sẽ hiện cứ mỗi 01 giờ sáng hàng ngày sẽ Backup Database và Website lên Telegram.
Bạn gõ lệnh crontab -e
, thêm dòng này vào cuối file:
0 1 * * * /root/code/backup.sh 2>&1
Sau đó nhấn lần lượt các phím sau để lưu và thoát:
Ctrl X Y Enter
Việc sao lưu dữ liệu website tự động lên Telegram là giải pháp đơn giản nhưng hiệu quả cao, ngoài ra bạn nên Backup 1 bản lên Google Drive để tận dụng 15Gb miễn phí.