Ejemplo n.º 1
0
    def get_action(self, bot, update, args):
        msg = f"{emo.WAIT} Restarting bot..."
        m = update.message.reply_text(msg)

        user_id = update.effective_user.id
        cls_name = type(self).__name__.lower()

        Cfg.set(user_id, "plugins", cls_name, "user_id")
        Cfg.set(m.message_id, "plugins", cls_name, "message")

        m_name = __spec__.name
        m_name = m_name[:m_name.index(".")]

        time.sleep(0.2)
        os.execl(sys.executable, sys.executable, '-m', m_name, *sys.argv[1:])
Ejemplo n.º 2
0
    def get_action(self, bot, update, args):
        restart = False
        force = False
        check = False

        if "force" in args:
            force = True
        if "check" in args:
            check = True
        if "restart" in args:
            restart = True

        if force and check:
            msg = f"{emo.ERROR} Combination of 'force' " \
                  f"and 'check' arguments not allowed"
            update.message.reply_text(msg)
            return

        kw = utl.get_kw(args)
        branch = kw.get("branch", None)
        release = kw.get("release", None)

        if branch and release:
            msg = f"{emo.ERROR} Combination of 'branch' " \
                  f"and 'release' arguments not allowed"
            update.message.reply_text(msg)
            return

        msg = f"{emo.WAIT} Check for update..."
        m = update.message.reply_text(msg)

        user = Cfg.get('update', 'github_user')
        repo = Cfg.get('update', 'github_repo')
        gh = GitHub(github_user=user, github_repo=repo)

        uid = update.message.from_user.id
        download_url = str()

        try:
            # Clean old update data if present
            shutil.rmtree(os.path.join(os.getcwd(), con.UPD_DIR))
        except:
            pass

        # ---------- BRANCH ----------
        if branch:
            try:
                # Get latest commit info for branch
                response = gh.get_latest_branch(branch)
            except Exception as e:
                return self.handle_error(e, update)

            cfg_hash = Cfg.get("update", "update_hash")
            new_hash = response["commit"]["sha"]

            msg = f"{emo.CHECK} Check for update..."
            bot.edit_message_text(msg, chat_id=uid, message_id=m.message_id)

            if cfg_hash == new_hash and not force:
                msg = f"{emo.CHECK} You are already running the latest version"
                update.message.reply_text(msg)
                return

            if check:
                msg = f"{emo.CHECK} New branch commits available!"
                update.message.reply_text(msg)
                return

            # Get latest version of branch as zip
            download_url = f"https://github.com/{user}/{repo}/archive/{branch}.zip"

        # ---------- RELEASE ----------
        else:
            try:
                if release:
                    # Get specific release
                    response = gh.get_releases()
                else:
                    # Get latest release
                    response = gh.get_latest_release()
            except Exception as e:
                return self.handle_error(e, update)

            if release:
                tag = response[0]["tag_name"]
                release_notes = response[0]["body"]
            else:
                tag = response["tag_name"]
                release_notes = response["body"]

            try:
                response = gh.get_tags()
            except Exception as e:
                return self.handle_error(e, update)

            new_hash = str()
            for t in response:
                if t["name"] == tag:
                    new_hash = t["commit"]["sha"]
                    download_url = t["zipball_url"]
                    break

            if not new_hash:
                msg = f"{emo.ERROR} Tag '{tag}' unknown"
                update.message.reply_text(msg)
                return

            cfg_hash = Cfg.get("update", "update_hash")

            msg = f"{emo.CHECK} Check for update..."
            bot.edit_message_text(msg, chat_id=uid, message_id=m.message_id)

            if cfg_hash == new_hash and not force:
                msg = f"{emo.CHECK} You are already running this release"
                update.message.reply_text(msg)
                return

            if check:
                msg = f"{emo.CHECK} New release *{tag}* available!\n\n" \
                      f"*Release Notes*\n{release_notes}"
                update.message.reply_text(msg, parse_mode=ParseMode.MARKDOWN)
                return

        # ---------- DOWNLOAD & UPDATE ----------

        msg = f"{emo.WAIT} Downloading update..."
        m = update.message.reply_text(msg)

        try:
            response = requests.get(download_url)
            response.raise_for_status()
        except Exception as e:
            return self.handle_error(e, update)

        msg = f"{emo.CHECK} Downloading update..."
        bot.edit_message_text(msg, chat_id=uid, message_id=m.message_id)

        msg = f"{emo.WAIT} Updating bot..."
        m = update.message.reply_text(msg)

        zip_file = zipfile.ZipFile(io.BytesIO(response.content))
        zip_file.extractall(con.UPD_DIR)

        done = False
        unzip_dir = str()
        for _, dirs, _ in os.walk(con.UPD_DIR):
            for d in dirs:
                unzip_dir = d
                done = True
                break
            if done:
                break

        self._update_bot(os.path.join(con.UPD_DIR, unzip_dir))

        Cfg.set(new_hash, "update", "update_hash")

        msg = f"{emo.CHECK} Updating bot..."
        bot.edit_message_text(msg, chat_id=uid, message_id=m.message_id)

        if restart:
            msg = f"{emo.WAIT} Restarting bot..."
            update.message.reply_text(msg)

            time.sleep(0.2)
            os.execl(sys.executable, sys.executable, *sys.argv)
        else:
            msg = "Bot /restart needed"
            update.message.reply_text(msg)
Ejemplo n.º 3
0
    def get_action(self, bot, update, args):
        if args:
            command = args[0].lower()

            # Execute raw SQL
            if command == "sql":
                if Cfg.get("database", "use_db"):
                    args.pop(0)

                    sql = " ".join(args)
                    data = self.tgb.db.execute_sql(sql)

                    if data["error"]:
                        msg = data["error"]
                    elif data["result"]:
                        msg = '\n'.join(str(s) for s in data["result"])
                    else:
                        msg = f"{emo.INFO} No data returned"

                    update.message.reply_text(msg)
                else:
                    update.message.reply_text(
                        f"{emo.INFO} Database not enabled")

            # Change configuration
            elif command == "cfg":
                args.pop(0)
                v = args[-1]
                v = v.lower()
                args.pop(-1)

                # Convert to boolean
                if v == "true" or v == "false":
                    v = utl.str2bool(v)

                # Convert to integer
                elif v.isnumeric():
                    v = int(v)

                # Convert to null
                elif v == "null" or v == "none":
                    v = None

                try:
                    Cfg.set(v, *args)
                except Exception as e:
                    return self.handle_error(e, update)

                update.message.reply_text("Config changed")

            # Send global message
            elif command == "msg":
                if Cfg.get("database", "use_db"):
                    args.pop(0)

                    sql = self.get_sql("global_msg")
                    data = self.tgb.db.execute_sql(sql)

                    title = "This is a global message to " \
                            "every user of @OpenCryptoBot:\n\n"

                    msg = " ".join(args)

                    for user_id in data or []:
                        try:
                            bot.send_message(chat_id=user_id[0],
                                             text=f"{title}{msg}")
                        except Exception as e:
                            self.handle_error(e, update, send_error=False)
                else:
                    update.message.reply_text(
                        f"{emo.INFO} Database not enabled")

            # Manage plugins
            elif command == "plg":
                args.pop(0)

                # LOAD plugin
                if args[0].lower() == "load":
                    self.tgb.reload_plugin(args[1])
                    update.message.reply_text("Plugin loaded")

                # UNLOAD plugin
                elif args[0].lower() == "unload":
                    self.tgb.remove_plugin(args[1])
                    update.message.reply_text("Plugin unloaded")

        else:
            usr = update.effective_user.first_name

            update.message.reply_text(
                text=f"Welcome {usr}.\nChoose a statistic",
                reply_markup=self._keyboard_stats())