import os
import re
import sys
import asyncio
import subprocess
from asyncio import sleep
from git import Repo
from pyrogram.types import Message
from driver.filters import command
from pyrogram import Client, filters
from os import system, execle, environ
from driver.decorators import bot_creator
from git.exc import InvalidGitRepositoryError
from config import UPSTREAM_REPO, BOT_USERNAME
from driver.database.dbqueue import get_active_chats, remove_active_chat
def gen_chlog(repo, diff):
upstream_repo_url = Repo().remotes[0].config_reader.get("url").replace(".git", "")
ac_br = repo.active_branch.name
ch_log = ""
tldr_log = ""
ch = f"updates for [{ac_br}]:"
ch_tl = f"updates for {ac_br}:"
d_form = "%d/%m/%y || %H:%M"
for c in repo.iter_commits(diff):
ch_log += (
f"\n\nš¬ {c.count()} š [{c.committed_datetime.strftime(d_form)}]\n"
f"[{c.summary}] šØāš» {c.author}
"
)
tldr_log += f"\n\nš¬ {c.count()} š [{c.committed_datetime.strftime(d_form)}]\n[{c.summary}] šØāš» {c.author}"
if ch_log:
return str(ch + ch_log), str(ch_tl + tldr_log)
return ch_log, tldr_log
def updater():
try:
repo = Repo()
except InvalidGitRepositoryError:
repo = Repo.init()
origin = repo.create_remote("upstream", UPSTREAM_REPO)
origin.fetch()
repo.create_head("main", origin.refs.main)
repo.heads.main.set_tracking_branch(origin.refs.main)
repo.heads.main.checkout(True)
ac_br = repo.active_branch.name
if "upstream" in repo.remotes:
ups_rem = repo.remote("upstream")
else:
ups_rem = repo.create_remote("upstream", UPSTREAM_REPO)
ups_rem.fetch(ac_br)
changelog, tl_chnglog = gen_chlog(repo, f"HEAD..upstream/{ac_br}")
return bool(changelog)
@Client.on_message(command(["update", f"update@{BOT_USERNAME}"]) & ~filters.edited)
@bot_creator
async def update_bot(_, message: Message):
chat_id = message.chat.id
msg = await message.reply("š `processing update...`")
update_avail = updater()
if update_avail:
await msg.edit("ā
Update finished !\n\nā¢ Bot restarting, back active again in 1-2 minutes.")
os.system("git pull -f && pip3 install --no-cache-dir -r requirements.txt")
execle(sys.executable, sys.executable, "main.py", environ)
return
await msg.edit(f"bot is **up-to-date** with [main]({UPSTREAM_REPO}/tree/main)", disable_web_page_preview=True)
@Client.on_message(command(["restart", f"restart@{BOT_USERNAME}"]) & ~filters.edited)
@bot_creator
async def restart_bot(_, message: Message):
served_chats = []
try:
chats = await get_active_chats()
for chat in chats:
served_chats.append(int(chat["chat_id"]))
except Exception as e:
pass
for x in served_chats:
try:
await bot.send_message(
x,
f"š” Bot server has just restarted !\n\nā¢ Sorry for the inconveniences due to bot maintenance.",
)
await remove_active_chat(x)
except Exception:
pass
msg = await message.reply("`restarting bot...`")
args = [sys.executable, "main.py"]
await msg.edit("ā
Bot restarted\n\nā¢ now bot is working again.")
execle(sys.executable, *args, environ)
return