Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
anasty17
GitHub Repository: anasty17/mirror-leech-telegram-bot
Path: blob/master/update.py
1619 views
1
from sys import exit
2
from importlib import import_module
3
from logging import (
4
FileHandler,
5
StreamHandler,
6
INFO,
7
basicConfig,
8
error as log_error,
9
info as log_info,
10
getLogger,
11
ERROR,
12
)
13
from os import path, remove, getenv
14
from pymongo.mongo_client import MongoClient
15
from pymongo.server_api import ServerApi
16
from subprocess import run as srun
17
from typing import Dict, Any
18
19
getLogger("pymongo").setLevel(ERROR)
20
21
if path.exists("log.txt"):
22
with open("log.txt", "r+") as f:
23
f.truncate(0)
24
25
if path.exists("rlog.txt"):
26
remove("rlog.txt")
27
28
basicConfig(
29
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
30
handlers=[FileHandler("log.txt"), StreamHandler()],
31
level=INFO,
32
)
33
34
35
def load_config() -> Dict[str, Any]:
36
"""Load configuration from config module or environment variables."""
37
try:
38
39
settings = import_module("config")
40
return {
41
key: value.strip() if isinstance(value, str) else value
42
for key, value in vars(settings).items()
43
if not key.startswith("__")
44
}
45
except ModuleNotFoundError:
46
log_info("Config module not found, loading from environment variables...")
47
return {
48
"BOT_TOKEN": getenv("BOT_TOKEN", ""),
49
"DATABASE_URL": getenv("DATABASE_URL", ""),
50
"DATABASE_NAME": getenv("DATABASE_NAME", "mltb"),
51
"UPSTREAM_REPO": getenv("UPSTREAM_REPO", ""),
52
"UPSTREAM_BRANCH": getenv("UPSTREAM_BRANCH", "master"),
53
}
54
55
56
config_file = load_config()
57
58
BOT_TOKEN = config_file.get("BOT_TOKEN", "")
59
if not BOT_TOKEN:
60
log_error("BOT_TOKEN variable is missing! Exiting now")
61
exit(1)
62
63
BOT_ID = BOT_TOKEN.split(":", 1)[0]
64
65
DATABASE_NAME = config_file.get("DATABASE_NAME", "mltb")
66
67
if DATABASE_URL := config_file.get("DATABASE_URL", "").strip():
68
try:
69
conn = MongoClient(DATABASE_URL, server_api=ServerApi("1"))
70
db = conn[DATABASE_NAME]
71
old_config = db.settings.deployConfig.find_one({"_id": BOT_ID}, {"_id": 0})
72
config_dict = db.settings.config.find_one({"_id": BOT_ID})
73
if (
74
old_config is not None and old_config == config_file or old_config is None
75
) and config_dict is not None:
76
config_file["UPSTREAM_REPO"] = config_dict["UPSTREAM_REPO"]
77
config_file["UPSTREAM_BRANCH"] = config_dict["UPSTREAM_BRANCH"]
78
conn.close()
79
except Exception as e:
80
log_error(f"Database ERROR: {e}")
81
82
UPSTREAM_REPO = config_file.get("UPSTREAM_REPO", "").strip()
83
84
UPSTREAM_BRANCH = config_file.get("UPSTREAM_BRANCH", "").strip() or "master"
85
86
if UPSTREAM_REPO:
87
if path.exists(".git"):
88
srun(["rm", "-rf", ".git"])
89
90
update = srun(
91
[
92
f"git init -q \
93
&& git config --global user.email [email protected] \
94
&& git config --global user.name mltb \
95
&& git add . \
96
&& git commit -sm update -q \
97
&& git remote add origin {UPSTREAM_REPO} \
98
&& git fetch origin -q \
99
&& git reset --hard origin/{UPSTREAM_BRANCH} -q"
100
],
101
shell=True,
102
)
103
104
if update.returncode == 0:
105
log_info("Successfully updated with latest commit from UPSTREAM_REPO")
106
else:
107
log_error(
108
"Something went wrong while updating, check UPSTREAM_REPO if valid or not!"
109
)
110
111