• Home
  • News
  • Software
  • Knowledge
  • MMO
  • Tips
  • Security
  • Network
  • Office
AnonyViet - English Version
  • Home
  • News
  • Software
  • Knowledge
  • MMO
  • Tips
  • Security
  • Network
  • Office
No Result
View All Result
  • Home
  • News
  • Software
  • Knowledge
  • MMO
  • Tips
  • Security
  • Network
  • Office
No Result
View All Result
AnonyViet - English Version
No Result
View All Result

Script backup database and website on telegram

AnonyViet by AnonyViet
May 2, 2025
in Network
0

Telegram Upload 2GB files for regular accounts and 4GB for Premium accounts, taking advantage of this function you can upload the backup database file and website to the Telegram to store. This article will introduce you to one Script automatically database and source code websiteLater Send the backup directly to the telegram. This solution is not only convenient and safe but also helps you easily track and manage backup versions right on the app.

Join the channel Telegram belong to Anonyviet 👉 Link 👈
Script backup database and source code website on telegram
Script backup database and source code website on telegram

Instructions for backup database and website on Telegram

Now we will start writing the code backup database and website on Telegram. The process summarizes 3 steps:

  1. Create script upload files to telegram
  2. Create website backup website
  3. Backup timer periodically

Scirpt sends files to telegram

You need to fill out these 4 information in the script:

api_id = 
api_hash = 
phone_number = 
group_id =

How to get the following information:

First you need to go to the page https://my.telegram.org and log in to get API_ID and API_HASH and fill in the code below

Then you create a group Telegram only with you in that group, the purpose of using the group to store backup files.

In Group_ID =: You take the new group ID to fill in. If you don’t know how much ID Group, add this bot to: @myidbot

After adding, in the group you type the command /getgroupid@myidbot To get ID Group (note that copy – okay)

Save the file into Tele.py into the folder /root/code/

We have the following path: /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))

Now you type the command:

cd /root/code
echo "" > a.txt
python3 tele.py

At the first code running, you will be asked to enter the OTP code to send to the phone number or app telegram app to authenticate.

If you see the A.Txt file uploaded to your Telegram Group is to see as successfully upload the file to the telegram. We will go through the next step

Create a script backup website and database

This is the script I refer to from hocvps used to backup website data on Ubuntu server:

Into the folder /root/code/ Create file Backup.sh The content is as follows:

(Replace zip -r $ backup_dir/anonyviet.com.zip /home/anonyviet.com/public_html/ -Q -x /home/anonyviet.com/public_html/wp-content/cache/**\* #Exclude cache) into the right path in your server)

#!/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."

Grant the right to execute for the backup.sh file, you type the command:

cd /root/code/
chmod +x *

Set Cronjob to back up daily data sent to Telegram

We will display every daily morning will backup database and website on Telegram.

You type the command crontab -eadd this line to the end of the file:

0 1 * * * /root/code/backup.sh 2>&1

Then press the following keys to save and escape:

Ctrl X
Y
Enter

Backup of automatic website data to Telegram is a simple but effective solution, in addition, you should back up 1 copy to Google Drive to take advantage of 15GB for free.

Tags: BackupDatabasescriptTelegramWebsite
Previous Post

Instructions for upgrading YouTube Premium for free to ignore ads

Next Post

Find out what is email bombing? What do you have to do when you meet your spam email

AnonyViet

AnonyViet

Related Posts

Create 64GB RAM 16 core for free on Google IDX
Network

Create 64GB RAM 16 core for free on Google IDX

April 13, 2025
What is VPS running Vietnamese software? What is the reason for installing Vietnamese software on VPS?
Network

What is VPS running Vietnamese software? What is the reason for installing Vietnamese software on VPS?

February 17, 2025
Create Ronin wallet to play pixels on VPS Windows
Network

Create Ronin wallet to play pixels on VPS Windows

February 17, 2025
What is Proxy Gradient Network? Instructions for using Proxy to suspend multiple Gradient accounts
Network

What is Proxy Gradient Network? Instructions for using Proxy to suspend multiple Gradient accounts

December 26, 2024
How to buy a .news domain for free for 0 VND at Namecheap
Network

How to buy a .news domain for free for 0 VND at Namecheap

December 22, 2024
Wayback Machine: Explore the old look of any website
Network

Wayback Machine: Explore the old look of any website

December 11, 2024
Next Post
Find out what is email bombing? What do you have to do when you meet your spam email

Find out what is email bombing? What do you have to do when you meet your spam email

0 0 votes
Article Rating
Subscribe
Login
Notify of
guest

guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Recent News

Lucida: Download SoundCloud, Tidal for free, no advertising

Lucida: Download SoundCloud, Tidal for free, no advertising

May 13, 2025
How to detect IRQ conflict – Hardware conflict on Windows

How to detect IRQ conflict – Hardware conflict on Windows

May 13, 2025
Learn about En81 safety standards for home elevators

Learn about En81 safety standards for home elevators

May 12, 2025
Change super easy Windows folder icon

Change super easy Windows folder icon

May 12, 2025
Lucida: Download SoundCloud, Tidal for free, no advertising

Lucida: Download SoundCloud, Tidal for free, no advertising

May 13, 2025
How to detect IRQ conflict – Hardware conflict on Windows

How to detect IRQ conflict – Hardware conflict on Windows

May 13, 2025
Learn about En81 safety standards for home elevators

Learn about En81 safety standards for home elevators

May 12, 2025
AnonyViet - English Version

AnonyViet

AnonyViet is a website share knowledge that you have never learned in school!

We are ready to welcome your comments, as well as your articles sent to AnonyViet.

Follow Us

Contact:

Email: anonyviet.com[@]gmail.com

Main Website: https://anonyviet.com

Recent News

Lucida: Download SoundCloud, Tidal for free, no advertising

Lucida: Download SoundCloud, Tidal for free, no advertising

May 13, 2025
How to detect IRQ conflict – Hardware conflict on Windows

How to detect IRQ conflict – Hardware conflict on Windows

May 13, 2025
  • Home
  • Home 2
  • Home 3
  • Home 4
  • Home 5
  • Home 6
  • Next Dest Page
  • Sample Page

©2024 AnonyVietFor Knowledge kqxs hôm nay xem phim miễn phí SHBET bongdaso

wpDiscuz
0
0
Would love your thoughts, please comment.x
()
x
| Reply
No Result
View All Result
  • Home
  • News
  • Software
  • Knowledge
  • MMO
  • Tips
  • Security
  • Network
  • Office

©2024 AnonyVietFor Knowledge kqxs hôm nay xem phim miễn phí SHBET bongdaso