def restart_dynos(app_name, dyno_prefix): heroku_conn = heroku3.from_key(os.getenv('HEROKU_API_KEY')) app = heroku_conn.apps()[app_name] dynos = app.dynos() for dyno in dynos: if dyno.name.startswith(dyno_prefix): dyno.restart() print u"restarted {} on {}!".format(dyno.name, app_name)
def num_dynos(job_type): heroku_conn = heroku3.from_key(os.getenv("HEROKU_API_KEY")) num_dynos = 0 try: dynos = heroku_conn.apps()[HEROKU_APP_NAME].dynos()[process_name(job_type)] num_dynos = len(dynos) except (KeyError, TypeError) as e: pass return num_dynos
def scale_dyno(n, job_type): logger.info(u"starting with {} dynos".format(num_dynos(job_type))) logger.info(u"setting to {} dynos".format(n)) heroku_conn = heroku3.from_key(os.getenv("HEROKU_API_KEY")) app = heroku_conn.apps()[HEROKU_APP_NAME] app.process_formation()[process_name(job_type)].scale(n) logger.info(u"sleeping for 2 seconds while it kicks in") sleep(2) logger.info(u"verifying: now at {} dynos".format(num_dynos(job_type)))
def set_heroku_config(application_name, key, value): conn = heroku3.from_key(env['HEROKU_API_KEY']) # Try at most 5 times to do this for _ in range(5): if conn.apps().get(application_name): app = conn.apps()[application_name] app.config()[key] = value # this actually saves itself when you set it! return True time.sleep(5) return False
def print_idle_dynos(job_type): heroku_conn = heroku3.from_key(os.getenv("HEROKU_API_KEY")) app = heroku_conn.apps()[HEROKU_APP_NAME] running_dynos = [] try: running_dynos = [dyno for dyno in app.dynos() if dyno.name.startswith(process_name(job_type))] except (KeyError, TypeError) as e: pass dynos_still_working = get_sql_answers(db, "select dyno from {} where started is not null and finished is null".format(table_name(job_type))) dynos_still_working_names = [n for n in dynos_still_working] logger.info(u"dynos still running: {}".format([d.name for d in running_dynos if d.name in dynos_still_working_names]))
async def upstream(ups): await ups.edit(f"`SedenBot için güncellemeler denetleniyor...`") conf = extract_args(ups) off_repo = UPSTREAM_REPO_URL force_update = False try: txt = f"`Güncelleme başarısız oldu!" txt += f"Bazı sorunlarla karşılaştık.`\n\n**LOG:**\n" repo = Repo() except NoSuchPathError as error: await ups.edit(f'{txt}\n`{error} klasörü bulunamadı.`') repo.__del__() return except GitCommandError as error: await ups.edit(f'{txt}\n`Git hatası! {error}`') repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await ups.edit(f"`{error} klasörü bir git reposu gibi görünmüyor.\ \nFakat bu sorunu .update now komutuyla botu zorla güncelleyerek çözebilirsin.`" ) return repo = Repo.init() origin = repo.create_remote('upstream', off_repo) origin.fetch() force_update = True repo.create_head('master', origin.refs.seden) repo.heads.seden.set_tracking_branch(origin.refs.sql) repo.heads.seden.checkout(True) ac_br = repo.active_branch.name if ac_br != 'seden': await ups.edit( f'**[SedenBot Güncelleyici]:**`Galiba botunun branch ismini değiştirdin. Kullandığın branch ismi: ({ac_br}). ' f'Böyle olursa botunu güncelleyemem. Çünkü branch ismi uyuşmuyor..' f'Lütfen botunu SedenBot resmi repodan kullan.`') repo.__del__() return try: repo.create_remote('upstream', off_repo) except BaseException: pass ups_rem = repo.remote('upstream') ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}') if not changelog and not force_update: await ups.edit(f'\n`Botun` **tamamen güncel!** `Branch:` **{ac_br}**\n' ) repo.__del__() return if conf != "now" and not force_update: changelog_str = f'**{ac_br} için yeni güncelleme mevcut!\n\nDeğişiklikler:**\n`{changelog}`' if len(changelog_str) > 4096: await ups.edit( f"`Değişiklik listesi çok büyük, dosya olarak görüntülemelisin.`" ) file = open("degisiklikler.txt", "w+") file.write(changelog_str) file.close() await ups.client.send_file( ups.chat_id, "degisiklikler.txt", reply_to=ups.id, ) remove("degisiklikler.txt") else: await ups.edit(changelog_str) await ups.respond( f'`Güncellemeyi yapmak için \".update now\" komutunu kullan.`') return if force_update: await ups.edit(f'`Güncel SedenBot kodu zorla eşitleniyor...`') else: await ups.edit(f'`Bot güncelleştiriliyor lütfen bekle...`') if HEROKU_APIKEY is not None: heroku = heroku3.from_key(HEROKU_APIKEY) heroku_app = None heroku_applications = heroku.apps() if not HEROKU_APPNAME: await ups.edit( f'`SedenBot Güncelleyiciyi kullanabilmek için HEROKU_APPNAME değişkenini tanımlamalısın. Aksi halde güncelleyici çalışmaz.`' ) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APPNAME: heroku_app = app break if heroku_app is None: await ups.edit( f'{txt}\n`Heroku değişkenleri yanlış veya eksik tanımlanmış.`') repo.__del__() return await ups.edit(f'`SedenBot Güncelleniyor..\ \nBu işlem 4-5 dakika sürebilir, lütfen sabırla bekle. Beklemene değer :)`' ) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except GitCommandError as error: await ups.edit(f'{txt}\n`Karşılaşılan hatalar burada:\n{error}`') repo.__del__() return await ups.edit( f'`Güncelleme başarıyla tamamlandı!\n' f'SedenBot yeniden başlatılıyor sabırla beklediğin için teşekkür ederiz :)`' ) else: try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") await update_requirements() await ups.edit( f'`Güncelleme başarıyla tamamlandı!\n' f'SedenBot yeniden başlatılıyor sabırla beklediğin için teşekkür ederiz :)`' ) args = [sys.executable, "seden.py"] execle(sys.executable, *args, environ) return
def get_heroku_client(access_token): return heroku3.from_key(access_token)
ALLOWED_COMMANDS: Set[str] = set() if Config.SUDO_TRIGGER == Config.CMD_TRIGGER: _LOG.info("Invalid SUDO_TRIGGER!, You can't use `%s` as SUDO_TRIGGER", Config.CMD_TRIGGER) sys.exit() if not os.path.isdir(Config.DOWN_PATH): _LOG.info("Creating Download Path...") os.mkdir(Config.DOWN_PATH) if Config.HEROKU_API_KEY: _LOG.info("Checking Heroku App...") for heroku_app in heroku3.from_key(Config.HEROKU_API_KEY).apps(): if heroku_app and Config.HEROKU_APP_NAME and \ heroku_app.name == Config.HEROKU_APP_NAME: _LOG.info("Heroku App : %s Found...", heroku_app.name) Config.HEROKU_APP = heroku_app Config.HEROKU_GIT_URL = heroku_app.git_url.replace( "https://", "https://*****:*****@") if not os.path.isdir(os.path.join(os.getcwd(), '.git')): tmp_heroku_git_path = os.path.join(os.getcwd(), 'tmp_heroku_git') _LOG.info("Cloning Heroku GIT...") Repo.clone_from(Config.HEROKU_GIT_URL, tmp_heroku_git_path) shutil.move(os.path.join(tmp_heroku_git_path, '.git'), os.getcwd()) shutil.rmtree(tmp_heroku_git_path) break
# """ Heroku manager for your userbot """ import heroku3 import asyncio import os import requests import math from userbot import CMD_HELP, HEROKU_APP_NAME, HEROKU_API_KEY from userbot.events import register from userbot.utils.prettyjson import prettyjson Heroku = heroku3.from_key(HEROKU_API_KEY) heroku_api = "https://api.heroku.com" @register(outgoing=True, pattern=r"^.(set|get|del) var(?: |$)(.*)(?: |$)") async def variable(var): """ Manage most of ConfigVars setting, set new var, get current var, or delete var... """ if HEROKU_APP_NAME is not None: app = Heroku.app(HEROKU_APP_NAME) else: return await var.edit("`[HEROKU]:" "\nPlease setup your` **HEROKU_APP_NAME**") exe = var.pattern_match.group(1)
async def upstream(ups): await ups.edit("`Checking for updates, please wait....`") conf = ups.pattern_match.group(1) off_repo = UPSTREAM_REPO_URL force_update = False try: txt = "`Oops.. Updater cannot continue due to " txt += "some problems occured`\n\n**LOGTRACE:**\n" repo = Repo() except NoSuchPathError as error: await ups.edit(f'{txt}\n`directory {error} is not found`') repo.__del__() return except GitCommandError as error: await ups.edit(f'{txt}\n`Early failure! {error}`') repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await ups.edit( f"`Unfortunately, the directory {error} does not seem to be a git repository.\ \nBut we can fix that by force updating the userbot using .update now.`" ) return repo = Repo.init() origin = repo.create_remote('upstream', off_repo) origin.fetch() force_update = True repo.create_head('master', origin.refs.master) repo.heads.master.set_tracking_branch(origin.refs.master) repo.heads.master.checkout(True) ac_br = repo.active_branch.name if ac_br != 'master': await ups.edit( f'**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). ' 'in that case, Updater is unable to identify ' 'which branch is to be merged. ' 'please checkout to any official branch`') repo.__del__() return try: repo.create_remote('upstream', off_repo) except BaseException: pass ups_rem = repo.remote('upstream') ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}') if not changelog and not force_update: await ups.edit( f'\n`Your BOT is` **up-to-date** `with` **{ac_br}**\n') repo.__del__() return if conf != "now" and not force_update: changelog_str = f'**New UPDATE available for [{ac_br}]:\n\nCHANGELOG:**\n`{changelog}`' if len(changelog_str) > 4096: await ups.edit("`Changelog is too big, view the file to see it.`") file = open("output.txt", "w+") file.write(changelog_str) file.close() await ups.client.send_file( ups.chat_id, "output.txt", reply_to=ups.id, ) remove("output.txt") else: await ups.edit(changelog_str) await ups.respond('`do \".update now\" to update`') return if force_update: await ups.edit( '`Force-Syncing to latest stable userbot code, please wait...`') else: await ups.edit('`Updating userbot, please wait....`') # We're in a Heroku Dyno, handle it's memez. if HEROKU_APIKEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_APIKEY) heroku_app = None heroku_applications = heroku.apps() if not HEROKU_APPNAME: await ups.edit( '`[HEROKU UPDATER] Please set up the HEROKU_APPNAME variable to be able to update userbot.`' ) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APPNAME: heroku_app = app break if heroku_app is None: await ups.edit( f'{txt}\n`Invalid Heroku credentials for updating userbot dyno.`' ) repo.__del__() return await ups.edit('**[HEROKU UPDATER]**\ \n`Userbot dyno build in progress, please wait for it to complete.`' ) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except GitCommandError as error: await ups.edit(f'{txt}\n`Here is the error log:\n{error}`') repo.__del__() return await ups.edit('`Successfully Updated!\n' 'Restarting, please wait...`') else: # Classic Updater, pretty straightforward. try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") await ups.edit('`Successfully Updated!\n' 'Bot is restarting... Wait for a second!`') # Spin a new instance of bot args = [sys.executable, "-m", "userbot"] execle(sys.executable, *args, environ) return
async def upstream(ups): "For .update command, check if the bot is up to date, update if specified" await ups.edit('**🔎 Ricerca update in corso...**') conf = ups.pattern_match.group(1) off_repo = UPSTREAM_REPO_URL force_update = False try: txt = "`Oops.. Updater cannot continue due to " txt += "some problems occured`\n\n**LOGTRACE:**\n" repo = Repo() except NoSuchPathError as error: await ups.edit(f'{txt}\n`directory {error} is not found`') repo.__del__() return except GitCommandError as error: await ups.edit(f'{txt}\n`Early failure! {error}`') repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await ups.edit( f"Unfortunately, the directory {error} does not seem to be a git repository.\ \nBut we can fix that by force updating the userbot using `.update now.`" ) return repo = Repo.init() origin = repo.create_remote('upstream', off_repo) origin.fetch() force_update = True repo.create_head('master', origin.refs.master) repo.heads.master.set_tracking_branch(origin.refs.master) repo.heads.master.checkout(True) ac_br = repo.active_branch.name if ac_br != 'master': await ups.edit( f'**[UPDATER]: Sembra che stai utilizzando un ramo custom** ({ac_br}). ' '**in tal caso, Updater è in grado di identificare**' '**quale ramo deve essere unito.**' '**Per favore aggiorna a qualsiasi branch ufficiale**') repo.__del__() return try: repo.create_remote('upstream', off_repo) except BaseException: pass ups_rem = repo.remote('upstream') ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}') if not changelog and not force_update: await ups.edit(f'\n`Il tuo UbOT è` **up-to-date** **{ac_br}**\n') repo.__del__() return if conf != "now" and not force_update: changelog_str = f'**New UPDATE avviabile per [{ac_br}]:\n\nCHANGELOG:**\n`{changelog}`' if len(changelog_str) > 4096: await ups.edit( '**Il changelog delle modifiche è troppo grande,leggi il file.**' ) file = open("output.txt", "w+") file.write(changelog_str) file.close() await ups.client.send_file( ups.chat_id, "output.txt", reply_to=ups.id, ) remove("output.txt") else: await ups.edit(changelog_str) await ups.respond('Premi \"`.update now`\" per aggiornare') return if force_update: await ups.edit( '**Forza aggiornamento ubot code stabile, attendere...**') else: await ups.edit('**🔄 Userbot in aggiornamento attendere...**') # We're in a Heroku Dyno, handle it's memez. if HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API_KEY) heroku_app = None heroku_applications = heroku.apps() if not HEROKU_APP_NAME: await ups.edit( '**Invalid APP Name. Inserisci il nome del bot nella Var `HEROKU_APP_NAME.**' ) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APP_NAME: heroku_app = app break if heroku_app is None: await ups.edit( f'{txt}\n**Credenziali heroku invalide per aggiornare Ubot.**') repo.__del__() return await ups.edit( f'**✅ Userbot aggiornato correttamente, riavvio in corso.**\n**⏰ Tempo stimato: 5 minuti**' ) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except GitCommandError as error: await ups.edit(f'{txt}\n`Here is the error log:\n{error}`') repo.__del__() return await ups.edit('**Update in corso...**\n' '**Riavvio, attendi 5 secondi e premi `.alive`**') else: # Classic Updater, pretty straightforward. try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") reqs_upgrade = await update_requirements() await ups.edit('**Update in corso...**\n' '**Attendi 5 secondi e premi `.alive`**') # Spin a new instance of bot args = [sys.executable, "-m", "userbot"] execle(sys.executable, *args, environ) return
async def deploy(event, repo, ups_rem, ac_br, txt): if HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API_KEY) heroku_app = None heroku_applications = heroku.apps() if HEROKU_APP_NAME is None: await event.edit("`Please set up the` **HEROKU_APP_NAME** `Var`" " to be able to deploy your userbot...`") repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APP_NAME: heroku_app = app break if heroku_app is None: await event.edit( f"{txt}\n" "`Invalid Heroku credentials for deploying userbot dyno.`") return repo.__del__() await event.edit( "`Userbot dyno build in progress, please wait until the process finishes it usually takes 4 to 5 minutes .`" ) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except Exception as error: await event.edit(f"{txt}\n`Here is the error log:\n{error}`") return repo.__del__() build = app.builds(order_by="created_at", sort="desc")[0] if build.status == "failed": await event.edit("`Build failed!\n" "Cancelled or there were some errors...`") await asyncio.sleep(5) return await event.delete() await event.edit("`Successfully deployed!\n" "Restarting, please wait...`") else: await event.edit("`Please set up` **HEROKU_API_KEY** ` Var...`") return
async def upstream(ups): ".update komutu ile botunun güncel olup olmadığını denetleyebilirsin." await ups.edit("`Güncellemeler denetleniyor...`") conf = ups.pattern_match.group(1) off_repo = UPSTREAM_REPO_URL force_update = False try: txt = "`Güncelleme başarısız oldu!" txt += "Bazı sorunlarla karşılaştık.`\n\n**LOG:**\n" repo = Repo() except NoSuchPathError as error: await ups.edit(f'{txt}\n`{error} klasörü bulunamadı.`') repo.__del__() return except GitCommandError as error: await ups.edit(f'{txt}\n`Git hatası! {error}`') repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await ups.edit(f"`{error} klasörü bir git reposu gibi görünmüyor.\ \nFakat bu sorunu .update now komutuyla botu zorla güncelleyerek çözebilirsin.`" ) return repo = Repo.init() origin = repo.create_remote('upstream', off_repo) origin.fetch() force_update = True repo.create_head('master', origin.refs.seden) repo.heads.seden.set_tracking_branch(origin.refs.sql) repo.heads.seden.checkout(True) ac_br = repo.active_branch.name if ac_br != 'master': await ups.edit( f'**[Güncelleyici]:**` Galiba Asena botunu modifiye ettin ve kendi branşını kullanıyorsun: ({ac_br}). ' 'Bu durum güncelleyicinin kafasını karıştırıyor,' 'Güncelleme nereden çekilecek?' 'Lütfen seden botunu resmi repodan kullan.`') repo.__del__() return try: repo.create_remote('upstream', off_repo) except BaseException: pass ups_rem = repo.remote('upstream') ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}') if not changelog and not force_update: await ups.edit(f'\n`Botun` **tamamen güncel!** `Branch:` **{ac_br}**\n' ) repo.__del__() return if conf != "now" and not force_update: changelog_str = f'**{ac_br} için yeni güncelleme mevcut!\n\nDeğişiklikler:**\n`{changelog}`' if len(changelog_str) > 4096: await ups.edit( "`Değişiklik listesi çok büyük, dosya olarak görüntülemelisin.`" ) file = open("degisiklikler.txt", "w+") file.write(changelog_str) file.close() await ups.client.send_file( ups.chat_id, "degisiklikler.txt", reply_to=ups.id, ) remove("degisiklikler.txt") else: await ups.edit(changelog_str) await ups.respond( '`Güncellemeyi yapmak için \".update now\" komutunu kullan.`') return if force_update: await ups.edit('`Güncel stabil userbot kodu zorla eşitleniyor...`') else: await ups.edit('`Bot güncelleştiriliyor...`') # Bot bir Heroku dynosunda çalışıyor, bu da bazı sıkıntıları beraberinde getiriyor. if HEROKU_APIKEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_APIKEY) heroku_app = None heroku_applications = heroku.apps() if not HEROKU_APPNAME: await ups.edit( '`[HEROKU MEMEZ] Güncelleyiciyi kullanabilmek için HEROKU_APPNAME değişkenini tanımlamalısın.`' ) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APPNAME: heroku_app = app break if heroku_app is None: await ups.edit( f'{txt}\n`Heroku değişkenleri yanlış veya eksik tanımlanmış.`') repo.__del__() return await ups.edit('`[HEROKU MEMEZ]\ \nUserBot Heroku dynosuna aktarılıyor, lütfen bekle...`' ) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except GitCommandError as error: await ups.edit(f'{txt}\n`Karşılaşılan hatalar burada:\n{error}`') repo.__del__() return await ups.edit('`Güncelleme başarıyla tamamlandı!\n' 'Yeniden başlatılıyor...`') else: # Klasik güncelleyici, oldukça basit. try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") await update_requirements() await ups.edit('`Güncelleme başarıyla tamamlandı!\n' 'Yeniden başlatılıyor...`') # Bot için Heroku üzerinde yeni bir instance oluşturalım. args = [sys.executable, "main.py"] execle(sys.executable, *args, environ) return
async def upstream(ups): "For .update command, check if the bot is up to date, update if specified" conf = ups.pattern_match.group(1) await ups.edit("Checking for updates, please wait....") off_repo = UPSTREAM_REPO_URL force_update = False try: txt = "Oops.. Updater cannot continue due to " txt += "some problems occured`\n\n**LOGTRACE:**\n" repo = Repo() except NoSuchPathError as error: await ups.edit(f'{txt}\ndirectory {error} is not found') repo.__del__() return except GitCommandError as error: await ups.edit(f'{txt}\nEarly failure! {error}') repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await ups.edit( f"**Hey ßoss!!!**😁😁\n__To get the Latest update of__ \n©BLACK_SNAKE_SUPPORT\n\n do |`.update now`| 😎😎 " ) return repo = Repo.init() origin = repo.create_remote('upstream', off_repo) origin.fetch() force_update = True repo.create_head('master', origin.refs.master) repo.heads.master.set_tracking_branch(origin.refs.master) repo.heads.master.checkout(True) ac_br = repo.active_branch.name if ac_br != 'master': await ups.edit( f'**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). ' 'in that case, Updater is unable to identify ' 'which branch is to be merged. ' 'please checkout to any official branch`') repo.__del__() return try: repo.create_remote('upstream', off_repo) except BaseException: pass ups_rem = repo.remote('upstream') ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}') if not changelog and not force_update: await ups.edit( f'\n**{ac_br} master your bot is already up to date..**\n') repo.__del__() return if conf != "now" and not force_update: changelog_str = f'**New UPDATE available for [{ac_br}]:\n\nCHANGELOG:**\n`{changelog}`' if len(changelog_str) > 4096: await ups.edit("`Changelog is too big, view the file to see it.`") file = open("output.txt", "w+") file.write(changelog_str) file.close() await ups.client.send_file( ups.chat_id, "output.txt", reply_to=ups.id, ) remove("output.txt") else: await ups.edit(changelog_str) await ups.respond("do `.update now` to update") return if force_update: await ups.edit( 'Force-Syncing to latest stable userbot code, please wait master...' ) else: await ups.edit( '`Updating userbot, please wait....you are my best boss🤗🤗') if HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API_KEY) heroku_app = None heroku_applications = heroku.apps() if not HEROKU_APP_NAME: await ups.edit( 'Please set up the `HEROKU_APP_NAME` variable to be able to update userbot.' ) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APP_NAME: heroku_app = app break if heroku_app is None: await ups.edit( f'{txt}\n`Invalid Heroku credentials for updating userbot dyno.`' ) repo.__del__() return ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) await ups.edit("`⬛⬛⬛⬛ \n⬛✳️✳️⬛ \n⬛✳️✳️⬛ \n⬛⬛⬛⬛`") await asyncio.sleep(1) await ups.edit("`⬛⬛⬛⬛ \n⬛🔴🔴⬛ \n⬛🔴🔴⬛ \n⬛⬛⬛⬛`") await asyncio.sleep(1) await ups.edit("`⬛⬛⬛⬛ \n⬛🌕🌕⬛ \n⬛🌕🌕⬛ \n⬛⬛⬛⬛`") await asyncio.sleep(1) await ups.edit("`⬛⬛⬛⬛ \n⬛🔵🔵⬛ \n⬛🔵🔵⬛ \n⬛⬛⬛⬛`") await asyncio.sleep(1) await ups.edit("`⬛⬛⬛⬛ \n⬛❇️❇️⬛ \n⬛❇️❇️⬛ \n⬛⬛⬛⬛`") await asyncio.sleep(1) await ups.edit( "`🔶Updating BLACKSNAKE🔶\n\nPlease wait for 3-5min\nAfter that try .alive or .help to check`me! \n\n**Powered by :-**\n©BLACK_SANKE_SUPPORT " ) remote.push(refspec="HEAD:refs/heads/master", force=True) else: try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") reqs_upgrade = await update_requirements() await ups.edit('`Successfully Updated!\n' 'Bot is restarting... Wait for a second!`') # Spin a new instance of bot args = [sys.executable, "-m", "userbot"] execle(sys.executable, *args, environ) return
async def upstream(ups): "For .update command, check if the bot is up to date, update if specified" await ups.edit( "`Wanna check New update!! Wait A second.... I'll do that for you😉`") conf = ups.pattern_match.group(1) off_repo = UPSTREAM_REPO_URL force_updateme = False try: txt = "`Oops.. Updater cannot continue as " txt += "some problems occured`\n\n**LOGTRACE:**\n" repo = Repo() except NoSuchPathError as error: await ups.edit(f'{txt}\n`directory {error} is not found`') repo.__del__() return except GitCommandError as error: await ups.edit(f'{txt}\n`Early failure! {error}`') repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await ups.edit( f"**Unfortunately, the directory {error} does not seem to be a git repository.\ \nOr Maybe it just needs a sync verification with {GIT_REPO_NAME}\ \nBut we can fix that by force updating the userbot using** `.update now`." ) return repo = Repo.init() origin = repo.create_remote('upstream', off_repo) origin.fetch() force_updateme = True repo.create_head('master', origin.refs.master) repo.heads.master.set_tracking_branch(origin.refs.master) repo.heads.master.checkout(True) ac_br = repo.active_branch.name if ac_br != 'master': await ups.edit( f'**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). ' 'in that case, Updater is unable to identify ' 'which branch is to be merged. ' 'Please checkout the official branch of THUGSUSERBOT`') repo.__del__() return try: repo.create_remote('upstream', off_repo) except BaseException: pass ups_rem = repo.remote('upstream') ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}') if not changelog and not force_updateme: await ups.edit( f'\n`Your` __THUGUSERBOT__ `is` **up-to-date** `with` **[[{ac_br}]]({UPSTREAM_REPO_URL}/tree/{ac_br})**\n' ) repo.__del__() return if conf != "now" and not force_updateme: changelog_str = f'**New UPDATE available for [[{ac_br}]]({UPSTREAM_REPO_URL}/tree/{ac_br}):**\n\n' + '**CHANGELOG**\n\n' + f'{changelog}' if len(changelog_str) > 4096: await ups.edit("`Changelog is too big, view the file to see it.`") file = open("output.txt", "w+") file.write(changelog_str) file.close() await ups.client.send_file( ups.chat_id, "output.txt", reply_to=ups.id, ) remove("output.txt") else: await ups.edit(changelog_str) await ups.respond(f'Do `.update now` to update') return if force_updateme: await ups.edit( '`Force-Updating to latest stable THUGS code, please wait sur😅😅...`' ) else: await ups.edit( '`Updating your` **THUGUSERBOT** `please wait for 10 mins then type .alive/.ping/.awake/.help/.test to see if I am On... \n\n _THUGSBOT_' ) # We're in a Heroku Dyno, handle it's memez. if Var.HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(Var.HEROKU_API_KEY) heroku_app = None heroku_applications = heroku.apps() if not Var.HEROKU_APP_NAME: await ups.edit( '`Please set up the HEROKU_APP_NAME variable to be able to update THUGUSERBOT.`' ) repo.__del__() return for app in heroku_applications: if app.name == Var.HEROKU_APP_NAME: heroku_app = app break if heroku_app is None: await ups.edit( f'{txt}\n`Invalid Heroku credentials for updating THUGBOT dyno.`' ) repo.__del__() return await ups.edit('`Updating your THUGUSERBOT.... .`') ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except GitCommandError as error: await ups.edit(f'{txt}\n`Here is the error log:\n{error}`') repo.__del__() return await ups.edit( '`Updated THUGBOT Successfully Sur🔥🔥\n' 'Restarting, please wait...5 mins...then type .ping to check if I am On!!!😐`' ) else: # Classic Updater, pretty straightforward. try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") await updateme_requirements() await ups.edit('`Successfully Updated!\n' 'Bot is restarting... Wait for a minute!`') # Spin a new instance of bot args = [sys.executable, "-m", "userbot"] execle(sys.executable, *args, environ) return
async def updater(client, message): await message.edit("__Checking update...__") initial = False try: repo = Repo() except NoSuchPathError as error: await message.edit( f"**Update failed!**\n\nError:\n`directory {error} is not found`") return except InvalidGitRepositoryError: repo = Repo.init() initial = True except GitCommandError as error: await message.edit(f'**Update failed!**\n\nError:\n`{error}`') return if initial: if len(message.text.split()) != 2: await message.edit( 'Your git workdir is missing!\nBut i can repair and take new latest update for you.\nJust do `update ' 'now` to repair and take update!') return elif len(message.text.split()) == 2 and message.text.split( )[1] == "now": try: await initial_git(repo) except Exception as err: exc_type, exc_obj, exc_tb = sys.exc_info() await message.edit(f'**Error:**\n{err}') await except_hook(exc_type, exc_obj, exc_tb) return await message.edit('Successfully Updated!\nBot is restarting...') await update_changelog( "-> **WARNING**: Bot has been created a new git and sync to latest version, your old files is in " "nana-old") await restart_all() return brname = repo.active_branch.name if brname not in OFFICIAL_BRANCH: await message.edit( f'**[UPDATER]:** Looks like you are using your own custom branch ({brname}). in that case, Updater is unable to identify which branch is to be merged. please checkout to any official branch' ) return try: repo.create_remote('upstream', REPOSITORY) except BaseException: pass upstream = repo.remote('upstream') upstream.fetch(brname) try: changelog = await gen_chlog(repo, f'HEAD..upstream/{brname}') except Exception as err: if "fatal: bad revision" in str(err): try: await initial_git(repo) except Exception as err: exc_type, exc_obj, exc_tb = sys.exc_info() await message.edit(f'**Error:**\n{err}') await except_hook(exc_type, exc_obj, exc_tb) return await message.edit('Successfully Updated!\nBot is restarting...') await update_changelog( "-> **WARNING**: Bot has been created a new git and sync to latest version, your old files is in " "nana-old") await restart_all() return exc_type, exc_obj, exc_tb = sys.exc_info() await message.edit( 'An error has accured!\nPlease see your Assistant for more information!' ) await except_hook(exc_type, exc_obj, exc_tb) return if not changelog: await message.edit(f'Nana is up-to-date with branch **{brname}**\n') return if len(message.text.split()) != 2: changelog_str = f'To update latest changelog, do\n-> `update now`\n\n**New UPDATE available for [{brname}]:\n' \ f'\nCHANGELOG:**\n`{changelog}` ' if len(changelog_str) > 4096: await message.edit( "`Changelog is too big, view the file to see it.`") file = open("nana/cache/output.txt", "w+") file.write(changelog_str) file.close() await client.send_document(message.chat.id, "nana/cache/output.txt", reply_to_message_id=message.message_id, caption="`Changelog file`") os.remove("nana/cache/output.txt") else: await message.edit(changelog_str) return elif len(message.text.split()) == 2 and message.text.split()[1] == "now": await message.edit('`New update found, updating...`') if HEROKU_API is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API) heroku_applications = heroku.apps() if len(heroku_applications) >= 1: heroku_app = heroku_applications[0] heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) remote.push(refspec="HEAD:refs/heads/master") else: await message.reply( "no heroku application found, but a key given? 😕 ") await message.edit( "Build Unsuccess, Check heroku build log for more detail") return try: upstream.pull(brname) await message.edit('Successfully Updated!\nBot is restarting...') except GitCommandError: repo.git.reset('--hard') repo.git.clean('-fd', 'nana/modules/') repo.git.clean('-fd', 'nana/assistant/') repo.git.clean('-fd', 'nana/helpers/') await message.edit('Successfully Updated!\nBot is restarting...') await update_changelog(changelog) await restart_all() else: await message.edit( "Usage:\n-> `update` to check update\n-> `update now` to update latest commits\nFor more information " "check at your Assistant")
# ================= import asyncio import math import os import heroku3 import requests from userbot import CMD_HELP from userbot.config import config from userbot.utils import admin_cmd Heroku = heroku3.from_key(config.HEROKU_API_KEY) Heroku = heroku3.from_key(Var.HEROKU_API_KEY) heroku_api = "https://api.heroku.com" HEROKU_APP_NAME = config.HEROKU_APP_NAME HEROKU_API_KEY = config.HEROKU_API_KEY Heroku = heroku3.from_key(Var.HEROKU_API_KEY) heroku_api = "https://api.heroku.com" @borg.on( admin_cmd(pattern=r"(set|get|del) var(?: |$)(.*)(?: |$)([\s\S]*)", outgoing=True) ) async def variable(var): """ Manage most of configVars setting, set new var, get current var,
async def wl_update(ups): conf = ups.pattern_match.group(1) if ups.is_reply: reply = await ups.get_reply_message() reply_user = await ups.client.get_entity(reply.from_id) ren = reply_user.id if ren == MYID: "whitelist Bot Güncelleme" usp = await ups.reply(LANG['DETECTING']) off_repo = UPSTREAM_REPO_URL force_update = False try: txt = "`Güncelleme başarısız oldu! Bazı sorunlarla karşılaştık.`\n\n**LOG:**\n" repo = Repo() except NoSuchPathError as error: await usp.edit(f'{txt}\n`{error} {LANG["NOT_FOUND"]}.`') repo.__del__() return except GitCommandError as error: await usp.edit(f'{txt}\n`{LANG["GIT_ERROR"]} {error}`') repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await usp.edit( f"`{error} {LANG['NOT_GIT']}`" ) return repo = Repo.init() origin = repo.create_remote('upstream', off_repo) origin.fetch() force_update = True repo.create_head('master', origin.refs.master) repo.heads.master.set_tracking_branch(origin.refs.sql) repo.heads.master.checkout(True) ac_br = repo.active_branch.name if ac_br != 'master': await usp.edit(LANG['INVALID_BRANCH']) repo.__del__() return try: repo.create_remote('upstream', off_repo) except BaseException: pass ups_rem = repo.remote('upstream') ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}') if not changelog and not force_update: await usp.edit(LANG['UPDATE'].format(ac_br)) repo.__del__() return if force_update: await usp.edit(LANG['FORCE_UPDATE']) else: await usp.edit(LANG['UPDATING']) # Bot bir Heroku dynosunda çalışıyor, bu da bazı sıkıntıları beraberinde getiriyor. if HEROKU_APIKEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_APIKEY) heroku_app = None heroku_applications = heroku.apps() if not HEROKU_APPNAME: await usp.edit(LANG['INVALID_APPNAME']) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APPNAME: heroku_app = app break if heroku_app is None: await usp.edit( LANG['INVALID_HEROKU'].format(txt) ) repo.__del__() return await usp.edit(LANG['HEROKU_UPDATING']) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except GitCommandError as error: await usp.edit(f'{txt}\n`{LANG["ERRORS"]}:\n{error}`') repo.__del__() return await usp.edit(LANG['SUCCESSFULLY']) else: # Klasik güncelleyici, oldukça basit. try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") await update_requirements() await usp.edit(LANG['SUCCESSFULLY']) # Bot için Heroku üzerinde yeni bir instance oluşturalım. args = [sys.executable, "main.py"] execle(sys.executable, *args, environ) return else: if conf != 'all' or AUTO_UPDATE == False: return "Whitelist tüm botları güncelliyor" usp = await ups.reply(LANG['DETECTING']) off_repo = UPSTREAM_REPO_URL force_update = False try: txt = "`Güncelleme başarısız oldu! Bazı sorunlarla karşılaştık.`\n\n**LOG:**\n" repo = Repo() except NoSuchPathError as error: await usp.edit(f'{txt}\n`{error} {LANG["NOT_FOUND"]}.`') repo.__del__() return except GitCommandError as error: await usp.edit(f'{txt}\n`{LANG["GIT_ERROR"]} {error}`') repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await usp.edit( f"`{error} {LANG['NOT_GIT']}`" ) return repo = Repo.init() origin = repo.create_remote('upstream', off_repo) origin.fetch() force_update = True repo.create_head('master', origin.refs.master) repo.heads.master.set_tracking_branch(origin.refs.sql) repo.heads.master.checkout(True) ac_br = repo.active_branch.name if ac_br != 'master': await usp.edit(LANG['INVALID_BRANCH']) repo.__del__() return try: repo.create_remote('upstream', off_repo) except BaseException: pass ups_rem = repo.remote('upstream') ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}') if not changelog and not force_update: await usp.edit(LANG['UPDATE'].format(ac_br)) repo.__del__() return if force_update: await usp.edit(LANG['FORCE_UPDATE']) else: await usp.edit(LANG['UPDATING']) # Bot bir Heroku dynosunda çalışıyor, bu da bazı sıkıntıları beraberinde getiriyor. if HEROKU_APIKEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_APIKEY) heroku_app = None heroku_applications = heroku.apps() if not HEROKU_APPNAME: await usp.edit(LANG['INVALID_APPNAME']) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APPNAME: heroku_app = app break if heroku_app is None: await usp.edit( LANG['INVALID_HEROKU'].format(txt) ) repo.__del__() return await usp.edit(LANG['HEROKU_UPDATING']) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except GitCommandError as error: await usp.edit(f'{txt}\n`{LANG["ERRORS"]}:\n{error}`') repo.__del__() return await usp.edit(LANG['SUCCESSFULLY']) else: # Klasik güncelleyici, oldukça basit. try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") await update_requirements() await usp.edit(LANG['SUCCESSFULLY']) # Bot için Heroku üzerinde yeni bir instance oluşturalım. args = [sys.executable, "main.py"] execle(sys.executable, *args, environ) return else: return
def manage_env(client, message): action = extract_args(message).split(' ', 1) if len(action) < 2 or action[0] not in [ 'get', 'set', 'rem', 'copy', 'move' ]: edit(message, f"`{get_translation('wrongCommand')}`") return heroku_mode = False if HEROKU_KEY: heroku_mode = True heroku = from_key(HEROKU_KEY) heroku_app = None heroku_applications = heroku.apps() if not HEROKU_APPNAME: edit( message, f'`{get_translation("updateHerokuVariables", ["HEROKU_APPNAME "])}`' ) for app in heroku_applications: if app.name == HEROKU_APPNAME: heroku_app = app heroku_env = app.config() break if heroku_app is None: edit( message, f'`{get_translation("updateHerokuVariables", ["HEROKU_APPNAME "])}`' ) return reload_env() if action[0] == 'set': items = action[1].split(' ', 1) if len(items) < 2 or len( items[1]) < 1 or items[0].upper() in ENV_RESTRICTED_KEYS: edit(message, f"`{get_translation('wrongCommand')}`") return key, value = items key = key.upper() if heroku_mode: heroku_env[key] = value else: set_local_env(key, value) edit(message, get_translation('envSetSuccess', ['`', '**', key])) sleep(2) restart(client, message) elif action[0] == 'get': items = action[1].split(' ', 1) if len(items[0]) < 1 or items[0].upper() in ENV_RESTRICTED_KEYS: edit(message, f"`{get_translation('wrongCommand')}`") return items[0] = items[0].upper() if heroku_mode and items[0] in heroku_env: value = heroku_env[items[0]] elif not heroku_mode and (value := environ.get(items[0], None)): pass else: edit(message, get_translation('envNotFound', ['`', '**', items[0]])) return edit(message, get_translation('envGetValue', ['`', '**', items[0], value]))
async def upstream(ups): "For .update command, check if the bot is up to date, update if specified" await ups.edit("`Searching for new updates, if any...`") conf = ups.pattern_match.group(1) off_repo = UPSTREAM_REPO_URL force_updateme = False try: txt = "`Oops.. Updater cannot continue as " txt += "some problems occured`\n\n**LOGTRACE:**\n" repo = Repo() except NoSuchPathError as error: await ups.edit(f"{txt}\n`directory {error} is not found`") repo.__del__() return except GitCommandError as error: await ups.edit(f"{txt}\n`Early failure! {error}`") repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await ups.edit( f"**Unfortunately, the directory {error} does not seem to be a git repository.\ \nOr Maybe it just needs a sync verification with {GIT_REPO_NAME}\ \nBut we can fix that by force updating the TamilBot using** `.update now`." ) return repo = Repo.init() origin = repo.create_remote("upstream", off_repo) origin.fetch() force_updateme = True repo.create_head("master", origin.refs.master) repo.heads.master.set_tracking_branch(origin.refs.master) repo.heads.master.checkout(True) ac_br = repo.active_branch.name if ac_br != "master": await ups.edit( f"**[TamilBot]:**` Looks like you are using your own custom branch ({ac_br}). " "in that case, Updater is unable to identify " "which branch is to be merged. " "Please checkout the official branch of TamilBot`") repo.__del__() return try: repo.create_remote("upstream", off_repo) except BaseException: pass ups_rem = repo.remote("upstream") ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f"HEAD..upstream/{ac_br}") if not changelog and not force_updateme: await ups.edit( f"\n`Your BOT is` **up-to-date** `with` **[[TamilBot🇮🇳]]({UPSTREAM_REPO_URL}/tree/{ac_br})**\n" ) repo.__del__() return if conf != "now" and not force_updateme: changelog_str = ( f"**New UPDATE available for [[TamilBot🇮🇳]]({UPSTREAM_REPO_URL}/tree/{ac_br}):**\n\n" + "**CHANGELOG**\n\n" + f"{changelog}") if len(changelog_str) > 4096: await ups.edit("`Changelog is too big, view the file to see it.`") file = open("output.txt", "w+") file.write(changelog_str) file.close() await ups.client.send_file( ups.chat_id, "output.txt", reply_to=ups.id, ) remove("output.txt") else: await ups.edit(changelog_str) await ups.respond(f"Do `.update now` to update") return if force_updateme: await ups.edit( "`Force-Syncing to latest stable TamilBot code, please wait...`") else: await ups.edit("`Updating TamilBot, Please Wait....`") # We're in a Heroku Dyno, handle it's memez. if Var.HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(Var.HEROKU_API_KEY) heroku_app = None heroku_applications = heroku.apps() if not Var.HEROKU_APP_NAME: await ups.edit( "`Please set up the HEROKU_APP_NAME variable to be able to update TamilBot.`" ) repo.__del__() return for app in heroku_applications: if app.name == Var.HEROKU_APP_NAME: heroku_app = app break if heroku_app is None: await ups.edit( f"{txt}\n`Invalid Heroku credentials for updating TamilBot dyno.`" ) repo.__del__() return await ups.edit( "`TamilBot dyno build in progress, please wait for it to complete.`" ) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except GitCommandError as error: await ups.edit(f"{txt}\n`Here is the error log:\n{error}`") repo.__del__() return await ups.edit("`Successfully Updated!\n" "Restarting, please wait...`") else: # Classic Updater, pretty straightforward. try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") await updateme_requirements() await ups.edit("`Successfully Updated!\n" "Bot is restarting... Wait for a second!`") # Spin a new instance of bot args = [sys.executable, "-m", "UserBot"] execle(sys.executable, *args, environ) return
async def updater(message): try: repo = git.Repo() except git.exc.InvalidGitRepositoryError as e: repo = git.Repo.init() origin = repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) origin.fetch() repo.create_head(IFFUCI_ACTIVE_BRANCH_NAME, origin.refs.master) repo.heads.master.checkout(True) active_branch_name = repo.active_branch.name if active_branch_name != IFFUCI_ACTIVE_BRANCH_NAME: await message.edit( IS_SELECTED_DIFFERENT_BRANCH.format(branch_name=active_branch_name) ) return False try: repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) except Exception as e: print(e) pass temp_upstream_remote = repo.remote(REPO_REMOTE_NAME) temp_upstream_remote.fetch(active_branch_name) changelog = generate_change_log( repo, DIFF_MARKER.format(remote_name=REPO_REMOTE_NAME, branch_name=active_branch_name)) if not changelog: await message.edit( "**ï¹ï¹Updating LegendBOTt* \n**Version** : `2.0` \n**Telethon** : `1.15.0` \n**Status** : `«Pulling Updates»` \nã**Thank You For Using LegendBOT !**ã" ) await asyncio.sleep(5) message_one = NEW_BOT_UP_DATE_FOUND.format(branch_name=active_branch_name, changelog=changelog) message_two = NEW_UP_DATE_FOUND.format(branch_name=active_branch_name) if len(message_one) > 4095: with open("change.log", "w+", encoding="utf8") as out_file: out_file.write(str(message_one)) await bot.send_message(message.chat_id, document="change.log", caption=message_two) os.remove("change.log") else: await message.edit(message_one) temp_upstream_remote.fetch(active_branch_name) repo.git.reset("--hard", "FETCH_HEAD") if Var.HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(Var.HEROKU_API_KEY) heroku_applications = heroku.apps() if len(heroku_applications) >= 1: if Var.HEROKU_APP_NAME is not None: heroku_app = None for i in heroku_applications: if i.name == Var.HEROKU_APP_NAME: heroku_app = i if heroku_app is None: await message.edit( "Invalid APP Name. Please set the name of your bot in heroku in the var HEROKU_APP_NAME." ) return heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) asyncio.get_event_loop().create_task( deploy_start(bot, message, HEROKU_GIT_REF_SPEC, remote)) else: await message.edit( "Please create the var HEROKU_APP_NAME as the key and the name of your bot in heroku as your value." ) return else: await message.edit(NO_HEROKU_APP_CFGD) else: await message.edit("No heroku api key found in HEROKU_API_KEY var")
class Config: """ Configs to setup Userge """ API_ID = int(os.environ.get("API_ID")) API_HASH = os.environ.get("API_HASH") WORKERS = min(32, int(os.environ.get("WORKERS")) or os.cpu_count() + 4) BOT_TOKEN = os.environ.get("BOT_TOKEN", None) HU_STRING_SESSION = os.environ.get("HU_STRING_SESSION", None) OWNER_ID = int(os.environ.get("OWNER_ID", 0)) LOG_CHANNEL_ID = int(os.environ.get("LOG_CHANNEL_ID")) DB_URI = os.environ.get("DATABASE_URL") LANG = os.environ.get("PREFERRED_LANGUAGE") DOWN_PATH = os.environ.get("DOWN_PATH") CMD_TRIGGER = os.environ.get("CMD_TRIGGER") SUDO_TRIGGER = os.environ.get("SUDO_TRIGGER") FINISHED_PROGRESS_STR = os.environ.get("FINISHED_PROGRESS_STR") UNFINISHED_PROGRESS_STR = os.environ.get("UNFINISHED_PROGRESS_STR") ALIVE_MEDIA = os.environ.get("ALIVE_MEDIA", None) CUSTOM_PACK_NAME = os.environ.get("CUSTOM_PACK_NAME") INSTA_ID = os.environ.get("INSTA_ID") INSTA_PASS = os.environ.get("INSTA_PASS") UPSTREAM_REPO = os.environ.get("UPSTREAM_REPO") UPSTREAM_REMOTE = os.environ.get("UPSTREAM_REMOTE") SCREENSHOT_API = os.environ.get("SCREENSHOT_API", None) SPAM_WATCH_API = os.environ.get("SPAM_WATCH_API", None) CURRENCY_API = os.environ.get("CURRENCY_API", None) OCR_SPACE_API_KEY = os.environ.get("OCR_SPACE_API_KEY", None) OPEN_WEATHER_MAP = os.environ.get("OPEN_WEATHER_MAP", None) REMOVE_BG_API_KEY = os.environ.get("REMOVE_BG_API_KEY", None) WEATHER_DEFCITY = os.environ.get("WEATHER_DEFCITY", None) TZ_NUMBER = os.environ.get("TZ_NUMBER", 1) G_DRIVE_CLIENT_ID = os.environ.get("G_DRIVE_CLIENT_ID", None) G_DRIVE_CLIENT_SECRET = os.environ.get("G_DRIVE_CLIENT_SECRET", None) G_DRIVE_PARENT_ID = os.environ.get("G_DRIVE_PARENT_ID", None) G_DRIVE_INDEX_LINK = os.environ.get("G_DRIVE_INDEX_LINK", None) GOOGLE_CHROME_DRIVER = os.environ.get("GOOGLE_CHROME_DRIVER", None) GOOGLE_CHROME_BIN = os.environ.get("GOOGLE_CHROME_BIN", None) HEROKU_API_KEY = os.environ.get("HEROKU_API_KEY", None) HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME", None) G_DRIVE_IS_TD = os.environ.get("G_DRIVE_IS_TD") == "true" LOAD_UNOFFICIAL_PLUGINS = os.environ.get( "LOAD_UNOFFICIAL_PLUGINS") == "true" THUMB_PATH = DOWN_PATH + "thumb_image.jpg" TMP_PATH = "userge/plugins/temp/" MAX_MESSAGE_LENGTH = 4096 MSG_DELETE_TIMEOUT = 120 WELCOME_DELETE_TIMEOUT = 120 EDIT_SLEEP_TIMEOUT = 10 AUTOPIC_TIMEOUT = 300 ALLOWED_CHATS = filters.chat([]) ALLOW_ALL_PMS = True USE_USER_FOR_CLIENT_CHECKS = False SUDO_ENABLED = False SUDO_USERS: Set[int] = set() ALLOWED_COMMANDS: Set[str] = set() ANTISPAM_SENTRY = False RUN_DYNO_SAVER = False HEROKU_APP = heroku3.from_key(HEROKU_API_KEY).apps()[HEROKU_APP_NAME] \ if HEROKU_API_KEY and HEROKU_APP_NAME else None STATUS = None BOT_FORWARDS = False BOT_MEDIA = os.environ.get("BOT_MEDIA", None) ### Spotify SPOTIFY_CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID', None) SPOTIFY_CLIENT_SECRET = os.environ.get('SPOTIFY_CLIENT_SECRET', None) SPOTIFY_INITIAL_TOKEN = os.environ.get('SPOTIFY_INITIAL_TOKEN', None) SPOTIFY_MODE = False ### MEME Generator IMGFLIP_ID = os.environ.get('IMGFLIP_ID', None) IMGFLIP_PASS = os.environ.get('IMGFLIP_PASS', None) ALLOW_NSFW = os.environ.get("ALLOW_NSFW", "False") pmlog_grp = os.environ.get("PM_LOG_GROUP_ID") PM_LOG_GROUP_ID = int(pmlog_grp) if pmlog_grp else None PM_LOGGING = False DEEP_AI = os.environ.get("DEEP_AI", None)
import time from slackclient import SlackClient import heroku3 import requests SLACK_BOT_TOKEN = 'XXXX-XXXXXX' SLACK_BOT_ID = 'XXXXXXXXX' SLACK_BOT_TAG = "<@" + SLACK_BOT_ID + ">" HEROKU_API_KEY = 'XXXXXX-XXXXXXXXXXX-XXXXXXX-XXXXXXXX' slack_client = SlackClient(SLACK_BOT_TOKEN) heroku_conn = heroku3.from_key(HEROKU_API_KEY) def create_app(app_name): try: heroku_conn.create_app(app_name) return True except TypeError as te: return False def rename_app(old_app_name, new_app_name): try: heroku_conn.app(old_app_name).rename(new_app_name) return True except requests.exceptions.HTTPError as he: return False def delete_app(app_name):
import os import asyncio from bot import bot import logging import random import sys from heroku3 import from_key from telethon import TelegramClient, events, custom from telethon.sessions import StringSession from telethon.errors.rpcerrorlist import SessionPasswordNeededError, PhoneCodeInvalidError logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) API_ID = int(os.environ.get("API_ID", 0)) API_HASH = os.environ.get("API_HASH", None) BOT_TOKEN = os.environ.get("BOT_TOKEN", None) APP_NAME = os.environ.get("APP_NAME", None) API_KEY = os.environ.get("API_KEY", None) HU_APP = from_key(API_KEY).apps()[APP_NAME] bot = Client(":memory:", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
async def upstream(ups): global UPSTREAM_REPO_URL check = ups.message.sender_id OK = int(OWNER_ID) if int(check) != OK: return lol = await ups.reply("`Checking for updates, please wait....`") conf = ups.pattern_match.group(1) off_repo = UPSTREAM_REPO_URL force_update = False try: txt = "`Oops.. Updater cannot continue " txt += "please add heroku apikey, name`\n\n**LOGTRACE:**\n" repo = Repo() except NoSuchPathError as error: await lol.edit(f"{txt}\n`directory {error} is not found`") repo.__del__() return except GitCommandError as error: await lol.edit(f"{txt}\n`Early failure! {error}`") repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await lol.edit( f"**Unfortunately, the directory {error} does not seem to be a git repository.\ \nBut we can fix that by force updating the bot using** `/update now`" ) return repo = Repo.init() origin = repo.create_remote("upstream", off_repo) origin.fetch() force_update = True 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 ac_br != "main": await lol.edit( f"**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). " "in that case, Updater is unable to identify " "which branch is to be merged. " "please checkout to any official branch`") repo.__del__() return try: repo.create_remote("upstream", off_repo) except BaseException: pass ups_rem = repo.remote("upstream") ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f"HEAD..upstream/{ac_br}") if not changelog and not force_update: await lol.edit("\nYour DaisyX >> **up-to-date** \n") repo.__del__() return if conf != "now" and not force_update: changelog_str = ( f"**New UPDATE available for {ac_br}\n\nCHANGELOG:**\n`{changelog}`" ) if len(changelog_str) > 4096: await lol.edit("`Changelog is too big, view the file to see it.`") file = open("output.txt", "w+") file.write(changelog_str) file.close() await update.send_file( ups.chat_id, "output.txt", reply_to=ups.id, ) remove("output.txt") else: await lol.edit(changelog_str) await ups.respond("**do** `/update now` **to update**") return if force_update: await lol.edit( "`Force-Syncing to latest main bot code, please wait...`") else: await lol.edit("`Still Running ....`") if conf == 'deploy': if HEROKU_API_KEY is not None: heroku = heroku3.from_key(HEROKU_API_KEY) heroku_app = None heroku_applications = heroku.apps() if not HEROKU_APP_NAME: await lol.edit( "`Please set up the HEROKU_APP_NAME variable to be able to update your bot.`" ) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APP_NAME: heroku_app = app break if heroku_app is None: await lol.edit( f"{txt}\n`Invalid Heroku credentials for updating bot dyno.`" ) repo.__del__() return await lol.edit("`[Updater]\ Your bot is being deployed, please wait for it to complete.\nIt may take upto 5 minutes `" ) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/main", force=True) except GitCommandError as error: await lol.edit(f"{txt}\n`Here is the error log:\n{error}`") repo.__del__() return await lol.edit("Successfully Updated!\n" "Restarting.......") else: try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") reqs_upgrade = await updateme_requirements() await lol.edit("`Successfully Updated!\n" "restarting......`") args = [sys.executable, "-m", "DaisyX"] execle(sys.executable, *args, environ) return
async def update_button(client, query): await client.send_message(Owner, "Updating, please wait...") try: repo = Repo() except NoSuchPathError as error: log.warning(f"Check update failed!\nDirectory {error} is not found!") return except InvalidGitRepositoryError as error: log.warning( f"Check update failed!\nDirectory {error} does not seems to be a git repository" ) return except GitCommandError as error: log.warning(f"Check update failed!\n{error}") return brname = repo.active_branch.name if brname not in OFFICIAL_BRANCH: return try: repo.create_remote("upstream", REPOSITORY) except BaseException: pass upstream = repo.remote("upstream") upstream.fetch(brname) changelog = await gen_chlog(repo, f"HEAD..upstream/{brname}") if HEROKU_API is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API) heroku_applications = heroku.apps() if len(heroku_applications) >= 1: heroku_app = heroku_applications[0] heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) remote.push(refspec="HEAD:refs/heads/master") else: await client.send_message( Owner, "no heroku application found, but a key given? 😕 ") await client.send_message( Owner, "Build Unsuccess, Check heroku build log for more detail") return else: try: os.system('git reset --hard') os.system('git pull') os.system('pip install -U -r requirements.txt') await client.send_message( Owner, "Built Successfully, Please Restart Manually in /settings") return except Exception as e: await client.send_message(Owner, f"Build Unsuccess,\nLog:{e}") return try: upstream.pull(brname) await client.send_message( Owner, "Successfully Updated!\nBot is restarting...") except GitCommandError: repo.git.reset("--hard") repo.git.clean("-fd", "nana/modules/") repo.git.clean("-fd", "nana/assistant/") repo.git.clean("-fd", "nana/helpers/") await client.send_message( Owner, "Successfully Force Updated!\nBot is restarting...") await update_changelog(changelog) await restart_all()
""" Kullanıcı botunuz için Heroku yöneticisi """ import os import math import heroku3 import asyncio import urllib3 import requests from .. import CMD_HELP from ..utils import admin_cmd, sudo_cmd, edit_or_reply urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # ================= Heroku = heroku3.from_key(Config.HEROKU_API_KEY) heroku_api = "https://api.heroku.com" HEROKU_APP_NAME = Config.HEROKU_APP_NAME HEROKU_API_KEY = Config.HEROKU_API_KEY @borg.on( admin_cmd( pattern=r"(set|get|del) var(?: |$)(.*)(?: |$)([\s\S]*)", outgoing=True)) @borg.on( sudo_cmd( pattern=r"(set|get|del) var(?: |$)(.*)(?: |$)([\s\S]*)", allow_sudo=True)) async def variable(var): """
def __init__(self, token, app_name, dry_run, logger): self._api = heroku3.from_key(token) self._api_app = self._api.app(app_name) self._dry_run = dry_run self._logger = logger
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=DEBUG, ) else: basicConfig( format="[%(asctime)s]- %(name)s- %(levelname)s- %(message)s", level=INFO, datefmt="%m-%d %H:%M:%S", ) LOGS = getLogger(__name__) try: if Config.HEROKU_API_KEY is not None or Config.HEROKU_APP_NAME is not None: HEROKU_APP = heroku3.from_key(Config.HEROKU_API_KEY).apps()[ Config.HEROKU_APP_NAME ] else: HEROKU_APP = None except Exception: HEROKU_APP = None # Global Configiables COUNT_MSG = 0 USERS = {} COUNT_PM = {} LASTMSG = {} CMD_HELP = {} ISAFK = False AFKREASON = None CMD_LIST = {}
def get_heroku_conn(): assert settings.HEROKU_API_KEY assert settings.HEROKU_APPNAME heroku_conn = heroku3.from_key(settings.HEROKU_API_KEY) return heroku_conn, heroku_conn.app(settings.HEROKU_APPNAME)
import heroku3 import psutil import requests from git import Repo from telethon import __version__ from . import * HEROKU_API = None HEROKU_APP_NAME = None try: if Var.HEROKU_API and Var.HEROKU_APP_NAME: HEROKU_API = Var.HEROKU_API HEROKU_APP_NAME = Var.HEROKU_APP_NAME Heroku = heroku3.from_key(Var.HEROKU_API) heroku_api = "https://api.heroku.com" app = Heroku.app(Var.HEROKU_APP_NAME) except BaseException: HEROKU_API = None HEROKU_APP_NAME = None @ultroid_cmd( pattern="alive$", ) async def lol(ult): pic = udB.get("ALIVE_PIC") uptime = grt((time.time() - start_time)) header = udB.get("ALIVE_TEXT") if udB.get("ALIVE_TEXT") else "Hey, I am alive." als = """
async def updater(event: NewMessage.Event) -> None: """Pull newest changes from the official repo and update the script/app.""" arg = event.matches[0].group(1) await event.answer("`Checking for updates!`") try: repo = git.Repo(basedir) fetched_items = repo.remotes.origin.fetch() except git.exc.NoSuchPathError as path: await event.answer(f"`Couldn't find {path}!`") repo.__del__() return except git.exc.GitCommandError as command: await event.answer( f"`An error occured trying to get the Git Repo.`\n`{command}`") repo.__del__() return except git.exc.InvalidGitRepositoryError: repo = git.Repo.init(basedir) origin = repo.create_remote('origin', main_repo) if not origin.exists(): await event.answer( "`The main repository does not exist. Remote is invalid!`") repo.__del__() return fetched_items = origin.fetch() repo.create_head('master', origin.refs.master).set_tracking_branch( origin.refs.master).checkout() fetched_commits = repo.iter_commits(f"HEAD..{fetched_items[0].ref.name}") untracked_files = repo.untracked_files old_commit = repo.head.commit for diff_added in old_commit.diff('FETCH_HEAD').iter_change_type('M'): if "requirements.txt" in diff_added.b_path: await event.answer("`Updating the pip requirements!`") updated = await update_requirements() if updated == 0: await event.answer("`Successfully updated the requirements.`") else: if isinstance(updated, int): await event.answer( "`Failed trying to install requirements." " Install them manually and run the command again.`") else: await event.answer(f'```{updated}```') return break if arg == "add": repo.index.add(untracked_files, force=True) repo.index.commit("[TG-UserBot] Updater: Untracked files") elif arg == "reset": repo.head.reset('--hard') try: repo.remotes.origin.pull() except git.exc.GitCommandError as command: text = ("`An error occured trying to Git pull:`\n`{0}`\n\n" "`You may use` **{1}update reset** `or` **{1}update add** " "`to reset your repo or add and commit your changes as well.`") prefix = client.prefix if client.prefix is not None else '.' await event.answer(text.format(command, prefix)) repo.__del__() return new_commit = repo.head.commit if old_commit == new_commit: await event.answer("`Already up-to-date!`") repo.__del__() return remote_url = repo.remote().url.replace(".git", '/') if remote_url[-1] != '/': remote_url = remote_url + '/' now = datetime.datetime.now(datetime.timezone.utc) def_changelog = changelog = "**TG-UserBot changelog:**" for commit in fetched_commits: changelog += summary.format(rev=repo.git.rev_parse(commit.hexsha, short=7), summary=commit.summary, url=remote_url, sha=commit.hexsha) ago = (now - commit.committed_datetime).total_seconds() elspased = (await _humanfriendly_seconds(ago)).split(',')[0] committers_link = author_link.format(author=commit.committer, url=remote_url) authors_link = author_link.format(author=commit.author, url=remote_url) if commit.author == commit.committer: committed = commited.format(committer=committers_link, elapsed=elspased) else: committed = authored.format(author=authors_link, committer=committers_link, elapsed=elspased) changelog += f"{committed:>{len(committed) + 8}}" if changelog == def_changelog: changelog = "`No changelog for you! IDK what happened.`" toast = await event.answer( "`Successfully pulled the new commits. Updating the bot!`", log=("update", changelog.strip())) if not client.logger: await event.answer(changelog.strip(), reply_to=toast.id, link_preview=False) os.environ['userbot_update'] = "True" heroku_api_key = client.config['api_keys'].get('api_key_heroku', False) if os.getenv("DYNO", False) and heroku_api_key: heroku_conn = heroku3.from_key(heroku_api_key) app = None for heroku_app in heroku_conn.apps(): if "api_key_heroku" in heroku_app.config(): app = heroku_app break if app is None: await event.answer( "`You seem to be running on Heroku " "with an invalid environment. Couldn't update the app.`\n" "`The changes will be reverted upon dyno restart.`") await asyncio.sleep(2) repo.__del__() await restart(event) else: for build in app.builds(): if build.status == "pending": await event.answer( "`There seems to be an ongoing build in your app.`" " `Try again after it's finished.`") return # Don't update the telethon environment varaibles userbot_config = client.config['userbot'] app.config().update(dict(userbot_config)) app.config().update( userbot_restarted=f"{event.chat_id}/{event.message.id}", userbot_update="True") if event.client.disabled_commands: disabled_list = ", ".join(client.disabled_commands.keys()) app.config().update(userbot_disabled_commands=disabled_list) url = f"https://*****:*****@git.heroku.com/{app.name}.git" if "heroku" in repo.remotes: repo.remotes['heroku'].set_url(url) else: repo.create_remote('heroku', url) if repo.untracked_files: repo.index.add(untracked_files, force=True) repo.index.commit("[TG-UserBot] Updater: Untracked files") app.enable_feature('runtime-dyno-metadata') await event.answer( "`Pushing all the changes to Heroku. Might take a while.`") remote = repo.remotes['heroku'] try: remote.push(refspec=f'{repo.active_branch.name}:master', force=True) await event.answer("`There was nothing to push to Heroku?`") except git.exc.GitCommandError as command: await event.answer( "`An error occured trying to pull and push to Heorku`" f"\n`{command}`") LOGGER.exception(command) repo.__del__() else: repo.__del__() await restart(event)
import heroku3 from functools import wraps from bot import HEROKU_API_KEY, HEROKU_APP_NAME # Preparing For Setting Config # Implement by https://github.com/jusidama18 and Based on this https://github.com/DevsExpo/FridayUserbot/blob/master/plugins/heroku_helpers.py heroku_client = None if HEROKU_API_KEY: heroku_client = heroku3.from_key(HEROKU_API_KEY) def check_heroku(func): @wraps(func) async def heroku_cli(client, message): heroku_app = None if not heroku_client: await message.reply_text("`Please Add HEROKU_API_KEY Key For This To Function To Work!`", parse_mode="markdown") elif not HEROKU_APP_NAME: await message.reply_text("`Please Add HEROKU_APP_NAME For This To Function To Work!`", parse_mode="markdown") if HEROKU_APP_NAME and heroku_client: try: heroku_app = heroku_client.app(HEROKU_APP_NAME) except: await message.reply_text(message, "`Heroku Api Key And App Name Doesn't Match!`", parse_mode="markdown") if heroku_app: await func(client, message, heroku_app) return heroku_cli
async def deploy(event, repo, ups_rem, ac_br, txt): if HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API_KEY) heroku_app = None heroku_applications = heroku.apps() if HEROKU_APP_NAME is None: await event.edit( '`[HEROKU]: Please set up the` **HEROKU_APP_NAME** `variable' ' to be able to deploy newest changes of userbot.`' ) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APP_NAME: heroku_app = app break if heroku_app is None: await event.edit( f'{txt}\n`Invalid Heroku credentials for deploying userbot dyno.`' ) return repo.__del__() await event.edit('`[HEROKU]:' '\nUserbot dyno build in progress, please wait it can take 7-8 mins`' ) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except GitCommandError as error: await event.edit(f'{txt}\n`Here is the error log:\n{error}`') return repo.__del__() build = app.builds(order_by="created_at", sort="desc")[0] if build.status == "failed": await event.edit( "`Build failed!\n" "Cancelled or there were some errors...`" ) await asyncio.sleep(5) return await event.delete() else: await event.edit("`Successfully deployed!\n" "Restarting, please wait...`") await asyncio.sleep(15) await event.delete() if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#NOTE \n" "Bot Yama Berhasil Di Update") else: await event.edit('`[HEROKU]:' '\nPlease set up` **HEROKU_API_KEY** `variable.`' ) await asyncio.sleep(10) await event.delete() return
class Config: """ Configs to setup Userge """ API_ID = int(os.environ.get("API_ID")) API_HASH = os.environ.get("API_HASH") WORKERS = int(os.environ.get("WORKERS")) or os.cpu_count() + 4 BOT_TOKEN = os.environ.get("BOT_TOKEN") HU_STRING_SESSION = os.environ.get("HU_STRING_SESSION") OWNER_ID = tuple( filter(lambda x: x, map(int, os.environ.get("OWNER_ID", "0").split()))) LOG_CHANNEL_ID = int(os.environ.get("LOG_CHANNEL_ID")) AUTH_CHATS = (OWNER_ID[0], LOG_CHANNEL_ID) if OWNER_ID else (LOG_CHANNEL_ID, ) DB_URI = os.environ.get("DATABASE_URL") LANG = os.environ.get("PREFERRED_LANGUAGE") DOWN_PATH = os.environ.get("DOWN_PATH") CMD_TRIGGER = os.environ.get("CMD_TRIGGER") SUDO_TRIGGER = os.environ.get("SUDO_TRIGGER") FINISHED_PROGRESS_STR = os.environ.get("FINISHED_PROGRESS_STR") UNFINISHED_PROGRESS_STR = os.environ.get("UNFINISHED_PROGRESS_STR") ALIVE_MEDIA = os.environ.get("ALIVE_MEDIA") CUSTOM_PACK_NAME = os.environ.get("CUSTOM_PACK_NAME") INSTA_ID = os.environ.get("INSTA_ID") INSTA_PASS = os.environ.get("INSTA_PASS") UPSTREAM_REPO = os.environ.get("UPSTREAM_REPO") UPSTREAM_REMOTE = os.environ.get("UPSTREAM_REMOTE") SPAM_WATCH_API = os.environ.get("SPAM_WATCH_API") CURRENCY_API = os.environ.get("CURRENCY_API") OCR_SPACE_API_KEY = os.environ.get("OCR_SPACE_API_KEY") OPEN_WEATHER_MAP = os.environ.get("OPEN_WEATHER_MAP") REMOVE_BG_API_KEY = os.environ.get("REMOVE_BG_API_KEY") WEATHER_DEFCITY = os.environ.get("WEATHER_DEFCITY") TZ_NUMBER = os.environ.get("TZ_NUMBER", 1) G_DRIVE_CLIENT_ID = os.environ.get("G_DRIVE_CLIENT_ID") G_DRIVE_CLIENT_SECRET = os.environ.get("G_DRIVE_CLIENT_SECRET") G_DRIVE_PARENT_ID = os.environ.get("G_DRIVE_PARENT_ID") G_DRIVE_INDEX_LINK = os.environ.get("G_DRIVE_INDEX_LINK") GOOGLE_CHROME_DRIVER = os.environ.get("GOOGLE_CHROME_DRIVER") GOOGLE_CHROME_BIN = os.environ.get("GOOGLE_CHROME_BIN") HEROKU_API_KEY = os.environ.get("HEROKU_API_KEY") HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME") G_DRIVE_IS_TD = os.environ.get("G_DRIVE_IS_TD") == "true" LOAD_UNOFFICIAL_PLUGINS = os.environ.get( "LOAD_UNOFFICIAL_PLUGINS") == "true" THUMB_PATH = DOWN_PATH + "thumb_image.jpg" TMP_PATH = "userge/plugins/temp/" MAX_MESSAGE_LENGTH = 4096 MSG_DELETE_TIMEOUT = 120 WELCOME_DELETE_TIMEOUT = 120 EDIT_SLEEP_TIMEOUT = 10 AUTOPIC_TIMEOUT = 300 ALLOWED_CHATS = filters.chat([]) ALLOW_ALL_PMS = True USE_USER_FOR_CLIENT_CHECKS = False SUDO_ENABLED = False SUDO_USERS: Set[int] = set() DISABLED_ALL = False DISABLED_CHATS: Set[int] = set() ALLOWED_COMMANDS: Set[str] = set() ANTISPAM_SENTRY = False SPAM_PROTECTION = False RUN_DYNO_SAVER = False HEROKU_ENV = bool(int(os.environ.get("HEROKU_ENV", "0"))) HEROKU_APP = heroku3.from_key(HEROKU_API_KEY).apps()[HEROKU_APP_NAME] \ if HEROKU_ENV and HEROKU_API_KEY and HEROKU_APP_NAME else None STATUS = None BOT_FORWARDS = False BOT_MEDIA = os.environ.get("BOT_MEDIA") SPOTIFY_CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID') SPOTIFY_CLIENT_SECRET = os.environ.get('SPOTIFY_CLIENT_SECRET') SPOTIFY_MODE = False IMGFLIP_ID = os.environ.get('IMGFLIP_ID') IMGFLIP_PASS = os.environ.get('IMGFLIP_PASS') ALLOW_NSFW = os.environ.get("ALLOW_NSFW", "False") PM_LOG_GROUP_ID = int(os.environ.get("PM_LOG_GROUP_ID", 0)) PM_LOGGING = False DEEP_AI = os.environ.get("DEEP_AI") LASTFM_USERNAME = os.environ.get("LASTFM_USERNAME") LASTFM_API_KEY = os.environ.get("LASTFM_API_KEY") TG_IDS = [777000, 1087968824, 454000] INLINE_NOTES = False BOT_ANTIFLOOD = False
async def upstream(ups): "For .update command, check if the bot is up to date, update if specified" conf = ups.pattern_match.group(1) await ups.edit("Checking for updates, please wait....") off_repo = UPSTREAM_REPO_URL force_update = False try: txt = "Oops.. Updater cannot continue due to " txt += "some problems occured`\n\n**LOGTRACE:**\n" repo = Repo() except NoSuchPathError as error: await ups.edit(f'{txt}\ndirectory {error} is not found') repo.__del__() return except GitCommandError as error: await ups.edit(f'{txt}\nEarly failure! {error}') repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await ups.edit( f"Hey, did you type update🤔.....Okie..My dear sweet master..🤗\ \nPlease do type |.update now| to update your Raganork😎.") return repo = Repo.init() origin = repo.create_remote('upstream', off_repo) origin.fetch() force_update = True repo.create_head('master', origin.refs.master) repo.heads.master.set_tracking_branch(origin.refs.master) repo.heads.master.checkout(True) ac_br = repo.active_branch.name if ac_br != 'master': await ups.edit( f'**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). ' 'in that case, Updater is unable to identify ' 'which branch is to be merged. ' 'please checkout to any official branch`') repo.__del__() return try: repo.create_remote('upstream', off_repo) except BaseException: pass ups_rem = repo.remote('upstream') ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}') if not changelog and not force_update: await ups.edit( f'\n`Your BOT is` **up-to-date** `with` **{ac_br}**\n') repo.__del__() return if conf != "now" and not force_update: changelog_str = f'**New UPDATE available for [{ac_br}]:\n\nCHANGELOG:**\n`{changelog}`' if len(changelog_str) > 4096: await ups.edit("`Changelog is too big, view the file to see it.`") file = open("output.txt", "w+") file.write(changelog_str) file.close() await ups.client.send_file( ups.chat_id, "output.txt", reply_to=ups.id, ) remove("output.txt") else: await ups.edit(changelog_str) await ups.respond("do `.update now` to update") return if force_update: await ups.edit( 'Force-Syncing to latest stable userbot code, please wait master...😅😅' ) else: await ups.edit( 'Updating userbot, please wait....you are my best boss🤗😇') if HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API_KEY) heroku_app = None heroku_applications = heroku.apps() if not HEROKU_APP_NAME: await ups.edit( 'Please set up the `HEROKU_APP_NAME` variable to be able to update userbot.' ) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APP_NAME: heroku_app = app break if heroku_app is None: await ups.edit( f'{txt}\n`Invalid Heroku credentials for updating userbot dyno.`' ) repo.__del__() return ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) await ups.edit( "Updating and Deploying New Update. Please wait for 5 minutes then use `.on` to check if i'm working or not, you are my best boss...🤗🤗😎.. Just after this update a restart will take place.." ) remote.push(refspec="HEAD:refs/heads/master", force=True) else: try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") reqs_upgrade = await update_requirements() await ups.edit('`Successfully Updated!\n' 'Bot is restarting... Wait for some mins!`') # Spin a new instance of bot args = [sys.executable, "-m", "userbot"] execle(sys.executable, *args, environ) return
#import socket #import httplib #import logging #httplib.HTTPConnection.debuglevel = 1 #logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests #logging.getLogger().setLevel(logging.INFO) #requests_log = logging.getLogger("requests.packages.urllib3") #requests_log.setLevel(logging.INFO) #requests_log.propagate = True HEROKU_API_KEY = os.environ.get('HEROKU_API_KEY', False) HEROKU_APPNAME = os.environ.get('HEROKU_APPNAME', False) TEST_EMAIL = os.environ.get('TEST_EMAIL', False) heroku_conn = heroku3.from_key(HEROKU_API_KEY) #app = heroku_conn.create_app(name='testy2124app', stack_id_or_name='cedar', region_id_or_name='us') #print app.addons() #print heroku_conn.addons('testy123app') #for addon in app.addons(): #addon.delete() #del config['TEST1'] #del config['TEST2'] #del config['TEST3'] #del config['Z01'] #del config['Z02'] #print config #config['TEST1'] = u'MM1' #config['TEST2'] = u'MM2'
async def upstream(ups): ".update komutu ile botunun güncel olup olmadığını denetleyebilirsin." await ups.edit(LANG['DETECTING']) conf = ups.pattern_match.group(1) off_repo = UPSTREAM_REPO_URL force_update = False try: txt = "`Güncelleme başarısız oldu! Bazı sorunlarla karşılaştık.`\n\n**LOG:**\n" repo = Repo() except NoSuchPathError as error: await ups.edit(f'{txt}\n`{error} {LANG["NOT_FOUND"]}.`') repo.__del__() return except GitCommandError as error: await ups.edit(f'{txt}\n`{LANG["GIT_ERROR"]} {error}`') repo.__del__() return except InvalidGitRepositoryError as error: if conf != "now": await ups.edit(f"`{error} {LANG['NOT_GIT']}`") return repo = Repo.init() origin = repo.create_remote('upstream', off_repo) origin.fetch() force_update = True repo.create_head('master', origin.refs.seden) repo.heads.seden.set_tracking_branch(origin.refs.sql) repo.heads.seden.checkout(True) ac_br = repo.active_branch.name if ac_br != 'master': await ups.edit(LANG['INVALID_BRANCH']) repo.__del__() return try: repo.create_remote('upstream', off_repo) except BaseException: pass ups_rem = repo.remote('upstream') ups_rem.fetch(ac_br) changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}') if not changelog and not force_update: await ups.edit(LANG['UPDATE'].format(ac_br)) repo.__del__() return if conf != "now" and not force_update: changelog_str = LANG['WAS_UPDATE'].format(ac_br, changelog) if len(changelog_str) > 4096: await ups.edit(LANG['BIG']) file = open("degisiklikler.txt", "w+") file.write(changelog_str) file.close() await ups.client.send_file( ups.chat_id, "degisiklikler.txt", reply_to=ups.id, ) remove("degisiklikler.txt") else: await ups.edit(changelog_str) await ups.respond(LANG['DO_UPDATE']) return if force_update: await ups.edit(LANG['FORCE_UPDATE']) else: await ups.edit(LANG['UPDATING']) # Bot bir Heroku dynosunda çalışıyor, bu da bazı sıkıntıları beraberinde getiriyor. if HEROKU_APIKEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_APIKEY) heroku_app = None heroku_applications = heroku.apps() if not HEROKU_APPNAME: await ups.edit(LANG['INVALID_APPNAME']) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APPNAME: heroku_app = app break if heroku_app is None: await ups.edit(LANG['INVALID_HEROKU'].format(txt)) repo.__del__() return await ups.edit(LANG['HEROKU_UPDATING']) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except GitCommandError as error: await ups.edit(f'{txt}\n`{LANG["ERRORS"]}:\n{error}`') repo.__del__() return await ups.edit(LANG['SUCCESSFULLY']) else: # Klasik güncelleyici, oldukça basit. try: ups_rem.pull(ac_br) except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") await update_requirements() await ups.edit(LANG['SUCCESSFULLY']) # Bot için Heroku üzerinde yeni bir instance oluşturalım. args = [sys.executable, "main.py"] execle(sys.executable, *args, environ) return
def restart_heroku(): cloud = heroku3.from_key(HEROKU_TOKEN) app = cloud.apps()[APP_NAME] for dyno in app.dynos(): dyno.kill()
async def deploy(event, repo, ups_rem, ac_br, txt): if HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API_KEY) heroku_app = None heroku_applications = heroku.apps() if HEROKU_APP_NAME is None: await event.edit( '`[HEROKU]: Harap Siapkan Variabel` **HEROKU_APP_NAME** `' ' untuk dapat deploy perubahan terbaru dari Petercord Userbot.`' ) repo.__del__() return for app in heroku_applications: if app.name == HEROKU_APP_NAME: heroku_app = app break if heroku_app is None: await event.edit( f'{txt}\n`Kredensial Heroku tidak valid untuk deploy Petercord Userbot dyno.`' ) return repo.__del__() await event.edit( '`[HEROKU]:' '\nDyno Petercord Userbot Sedang Dalam Proses, Mohon Menunggu 7-8 Menit`' ) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec="HEAD:refs/heads/master", force=True) except GitCommandError as error: await event.edit(f'{txt}\n`Terjadi Kesalahan Di Log:\n{error}`') return repo.__del__() build = app.builds(order_by="created_at", sort="desc")[0] if build.status == "failed": await event.edit("`Build Gagal!\n" "Dibatalkan atau ada beberapa kesalahan...`") await asyncio.sleep(5) return await event.delete() else: await event.edit("`Petercord-Userbot Berhasil Di Deploy!\n" "Restarting, Mohon Menunggu Petercord.....`") await asyncio.sleep(15) await event.delete() if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#BOT \n" "`Petercord Userbot Berhasil Di Update`") else: await event.edit('`[HEROKU]:' '\nHarap Siapkan Variabel` **HEROKU_API_KEY** `.`') await asyncio.sleep(10) await event.delete() return