Beispiel #1
0
def replacer(infos, text):
    try:

        if "[fm]" in text:
            if DBs.get_groups_number(
                    infos.bid) < 100 and Manager.trigger_count(
                        infos.bid) < 120:
                HTTPLL.sendMessage(
                    infos.token, Manager.get_prop_id(infos.token),
                    "Master, non posso ancora usare la funzionalità last.fm..."
                )
                return
            text = text.replace("[fm]", "")
            username = infos.user.uid
            if infos.args:
                username = infos.args

            try:
                fm = LastFM(username)
            except UnregistredUser:
                return Dialogs.base_send(infos, "fmnick_missing")
            except UnvalidUsername:
                return Dialogs.base_send(infos, "fmnick_invalid")
            except EmptyTracks:
                return Dialogs.base_send(infos, "fm_no_result")

            text = text.replace("+fmnick+", fm.nickname)
            text = text.replace("+title+", fm.title())
            text = text.replace("+artist+", fm.artist())
            text = text.replace("+album+", fm.album())
            text = text.replace("[img]", "<link>+img_link+:>+zwnj+</link>")
            text = text.replace("+img_link+", fm.image())
            text = text.replace("+action+", fm.np())

        lett = "a" if infos.user.sesso == "1" else "o"

        if infos.name:
            text = text.replace("+gnome+", infos.name)

        text = text.replace(
            "+sesso+",
            "una ragazza" if infos.user.sesso == "1" else "un ragazzo")

        if "+anni+" in text or "+giorni+" in text or "+anni_reali+" in text:
            date_strig = LowLevel.jfile("d", infos.bid,
                                        infos.user.lang_n)["data_nascita"]
            try:
                d, m, y = map(int, date_strig.split("/"))

                Log.d("Quindi %s/%s/%s" % (d, m, y))
                days = str(timedelta(days=(date.today() -
                                           date(y, m, d)).days)).split(" ")[0]
                years = str(int(int(days) / 365))
                age = str(int(int(days) / 30))

                text = text.replace("+anni+", age)
                text = text.replace("+giorni+", days)
                text = text.replace("+anni_reali+", years)
            except Exception:
                HTTPLL.sendMessage(
                    infos.token, infos.prop_id,
                    "master, reimposta la mia data di nascita con /set_nascita GG/MM/AAA..."
                )
                Log.w("%s non è una data di nascita valida..." % date_strig)
                return None

        text = text.replace("+zwnj+", zwnj)
        text = text.replace("+snome+", infos.user.sname)
        text = text.replace("+username+", infos.user.username)
        text = text.replace("{?}", lett)
        text = text.replace("[_]", "\n")
        text = text.replace("+bcount+", str(infos.bot_count))
        text = text.replace("+tcount+", str(Manager.trigger_count(infos.bid)))
        text = text.replace("+ore+", time.strftime("%H"))
        text = text.replace("+minuti+", time.strftime("%M"))
        text = text.replace("+secondi+", time.strftime("%S"))
        text = text.replace("+nome+", infos.user.name)
        text = text.replace("+moment+", timemoment()[infos.langn])
        text = text.replace("+bnome+", infos.bot_name)
        text = text.replace("+busername+", infos.username)
        text = text.replace("+uid+", str(infos.user.uid))
        text = text.replace("+gid+", str(infos.cid))
        text = text.replace("+bid+", str(infos.bid))
        text = text.replace("+kcu+", str(Unreloaded.get_cpu()) + "%")
        text = text.replace("+kmb+", str(Unreloaded.get_memory()))
        text = text.replace("+csymb+", infos.symbol)
        text = text.replace("+is_admin+",
                            "sì" if infos.user.perms.is_admin else "no")
        text = text.replace("+kbcount+", str(Manager.get_bot_count()))
        text = text.replace("+trigger_count+",
                            str(Manager.trigger_count(infos.bid)))

        if "+glink+" in text:
            if infos.chat_private:
                text = text.replace("+glink+", "t.me/%s" % infos.user.username)
            else:
                try:
                    text = text.replace("+glink+", HTTPLL.getInviteLink(infos))
                except Exception:
                    text = text.replace("+glink+", "<non autorizzata>")

        if infos.user.perms.is_admin:
            text = text.replace(
                "+can_mute+",
                "sì" if infos.user.perms.can_restrict_members else "no")
        else:
            text = text.replace("+can_mute+", "no")

        if "+is_muted+" in text:
            usr = HTTPLL.getChatMember(infos.token, infos.cid,
                                       infos.user.uid)["result"]
            muted = "no"
            if "can_send_messages" in usr:
                if not usr["can_send_messages"]:
                    muted = "si"
            text = text.replace("+is_muted+", muted)

        if "+benvenuto+" in text:
            state = DBs.read_obj(infos.cid, infos.entity, "groups")["ext"]
            if not state or state == "0":
                state = "sì"
            else:
                state = "no"
            text = text.replace("+benvenuto+", state)

        if "cpu%" in text:
            text = text.replace("cpu", str(psutil.cpu_percent()))
        if "ram%" in text:
            text = text.replace("ram", str(psutil.virtual_memory()[2]))
        if "disk%" in text:
            text = text.replace("disk", str(psutil.disk_usage('/')[3]))

        if "+upt+" in text:
            t = datetime.fromtimestamp(
                Unreloaded.get_time()).strftime("%d alle %H:%M:%S")
            text = text.replace("+upt+", t)

        if infos.to_user and infos.to_user.uid != infos.bid:
            text = text.replace("+is_admin2+",
                                "sì" if infos.to_user.perms.is_admin else "no")

            if infos.to_user.perms.is_admin:
                text = text.replace(
                    "+can_mute2+",
                    "sì" if infos.to_user.perms.can_restrict_members else "no")
            else:
                text = text.replace("+can_mute2+", "no")

            if "+is_muted2+" in text:
                usr = HTTPLL.getChatMember(infos.token, infos.cid,
                                           infos.to_user.uid)["result"]
                muted = "no"
                if "can_send_messages" in usr:
                    if not usr["can_send_messages"]:
                        muted = "si"
                text = text.replace("+is_muted2+", muted)

            text = text.replace("+snome2+", infos.to_user.sname)
            text = text.replace("+username2+", infos.to_user.username)
            text = text.replace("+nome2+", infos.to_user.name)
            text = text.replace("+uid2+", str(infos.to_user.uid))

            lett2 = "a" if infos.to_user.sesso == "1" else "o"
            text = text.replace("{??}", lett2)
            if "+nwarns+" in text:
                try:
                    warns = json.loads(
                        open("Files/bot_files/%s/warns.json" %
                             infos.bid).read())[str(infos.cid)][str(
                                 infos.to_user.uid)]
                except Exception:
                    warns = 0
                text = text.replace("+nwarns+", str(warns))
        else:
            if "+nwarns+" in text:
                try:
                    warns = json.loads(
                        open("Files/bot_files/%s/warns.json" %
                             infos.bid).read())[str(infos.cid)][str(
                                 infos.user.uid)]
                except Exception:
                    warns = 0
                text = text.replace("+nwarns+", str(warns))

        text = text.replace("+pingt+", LowLevel.get_time(infos.time))
        text = text.replace("pingt", LowLevel.get_time(infos.time))

        if infos.is_reply:
            try:
                if "|" in infos.trigger:
                    for trigger in infos.trigger.split("|"):
                        text = text.replace(
                            "+msg2+",
                            infos.to_user.message.text.replace(
                                str(trigger), ""))
                elif "&" in infos.trigger:
                    for trigger in infos.trigger.split("&"):
                        text = text.replace(
                            "+msg2+",
                            infos.to_user.message.text.replace(
                                str(trigger), ""))
                else:
                    msg = re.sub(re.escape(infos.trigger),
                                 "",
                                 infos.to_user.message.text,
                                 flags=re.IGNORECASE)
                    text = text.replace("+msg2+", msg)
            except:
                pass

        try:
            msg = re.sub(infos.regex, "", infos.text, flags=re.IGNORECASE)
            if "|" in infos.trigger:
                for trigger in infos.trigger.split("|"):
                    msg = re.sub(trigger, "", msg, flags=re.IGNORECASE)
            elif "&" in infos.trigger:
                for trigger in infos.trigger.split("&"):
                    msg = re.sub(trigger, "", msg, flags=re.IGNORECASE)
            else:
                msg = re.sub(re.escape(infos.trigger),
                             "",
                             msg,
                             flags=re.IGNORECASE)

            msg = msg.strip()
            text = text.replace("+msg+", msg)
            text = re.sub(" +", " ", text)
            text = text.strip()

        except Exception as err:
            Log.e("Errore: %s" % err)

        text = rnd_elab(infos, text)

        return text
    except Exception as err:
        msg = "riga {} {} {}".format(sys.exc_info()[-1].tb_lineno,
                                     type(err).__name__, err)
        Log.e(msg)
        Dialogs.base_send(infos, "general_error")
        return None
Beispiel #2
0
def action(infos, text, sezione):
    try:
        acts = []

        if "[reg_fm]" in text:
            acts.append("[reg_fm]")
            if not infos.args:
                Dialogs.base_send(infos, "no_args")
                return None
            try:
                LastFM(infos.args)
            except UnvalidUsername:
                Dialogs.base_send(infos, "fmnick_unexistent")
                return None
            DBs.set_data(infos.entity, infos.user.uid, "ext0", infos.args)

        if "[ban_usr]" in text or "ban_usr]" in text:
            acts.append("[ban_usr]")
            acts.append("ban_usr]")
            if not infos.admin:
                return Dialogs.base_send(infos, "bot_non_admin")
            if infos.user.is_admin:
                return Dialogs.base_send(infos, "ban_self_admin")
            HTTPLL.kickChatMember(infos.token,
                                  infos.cid,
                                  infos.user.uid,
                                  until="h0")

        if "[ban]" in text or "ban]" in text:
            acts.append("[ban]")
            acts.append("ban]")
            if infos.is_reply:
                if not infos.admin:
                    return Dialogs.base_send(infos, "bot_non_admin")
                if not infos.user.is_admin:
                    return Dialogs.base_send(infos, "ut_non_admin")
                if infos.to_user.is_admin:
                    return Dialogs.base_send(infos, "ut_admin")
                if infos.user.is_admin:
                    HTTPLL.kickChatMember(infos.token, infos.cid,
                                          infos.to_user.uid)

        if "[meteo]" in text:
            if not sezione:
                HTTPLL.sendMessage(
                    infos.token, infos.prop_id,
                    "Errore: meteo_text non può contenere [meteo]!")
                Log.w("Utente avvisato per errore [meteo]")
                return

            if not infos.args:
                Dialogs.base_send(infos, "no_args")
                return None

            res, sugg = Meteo.exists(infos.args)
            if not res:
                if sugg:
                    text = Dialogs.get_text(infos, "meteo_sugg")
                    if not text:
                        return None
                    text = text.replace("+sugg+", sugg.capitalize())
                    Dialogs.base_send(infos, None, special_text=text)
                    return None
                else:
                    text = Dialogs.get_text(infos, "citta_inesist")
                    if not text:
                        return None
                    Dialogs.base_send(infos, None, special_text=text)
                    return None

            text = Dialogs.get_text(infos, "meteo_text")
            if not text:
                return None

            datas = Meteo.get_datas(infos.args)
            for data_name in sorted(datas.keys()):
                text = text.replace("+" + data_name + "+", datas[data_name])
            # Dialogs.base_send(infos, None, special_text=text)

            # return None

        if "[pin]" in text:
            if infos.user.is_admin:
                HTTPLL.pinMessage(infos)
                acts.append("[pin]")
            else:
                Dialogs.base_send(infos, "ut_non_admin")
                return None

        if "[unpin]" in text:
            if infos.user.is_admin:
                HTTPLL.unpinMessage(infos)
                acts.append("[unpin]")
            else:
                return Dialogs.base_send(infos, "ut_non_admin")

        if "[settitle]" in text:
            if infos.user.is_admin:
                HTTPLL.setChatTitle(infos)
                acts.append("[settitle]")
            else:
                return Dialogs.base_send(infos, "ut_non_admin")

        if "[setdesc]" in text:
            if infos.user.is_admin:
                HTTPLL.setChatDescription(infos)
                acts.append("[setdesc]")
            else:
                return Dialogs.base_send(infos, "ut_non_admin")

        if "[setphoto]" in text:
            if infos.user.is_admin:
                if infos.to_user.message.what != "photo":
                    return None
                HTTPLL.setChatPhoto(infos)
                acts.append("[setphoto]")
            else:
                return Dialogs.base_send(infos, "ut_non_admin")

        if "[disable welcome]" in text:
            if infos.chat_private:
                return Dialogs.get_text(infos, "disable welcome privato")

            if infos.user.is_admin:
                state = DBs.read_obj(infos.cid, infos.entity, "groups")["ext"]

                if state == "1":
                    return Dialogs.get_text(infos,
                                            "benvenuto gia disabilitato")

                DBs.set_obj(infos.cid, "1", "ext", infos.entity)
                acts.append("[disable welcome]")
            else:
                return Dialogs.base_send(infos, "ut_non_admin")

        if "[enable welcome]" in text:
            if infos.chat_private:
                return Dialogs.get_text(infos, "enable welcome privato")

            if infos.user.is_admin:
                state = DBs.read_obj(infos.cid, infos.entity, "groups")["ext"]

                if not state or state == "0":
                    return Dialogs.get_text(infos, "benvenuto gia abilitato")

                DBs.set_obj(infos.cid, "0", "ext", infos.entity)
                acts.append("[enable welcome]")
            else:
                return Dialogs.base_send(infos, "ut_non_admin")

        if "[warn_usr]" in text:
            if infos.chat_private:
                return

            BotsFoos.warn(infos, self=True)
            acts.append("[warn_usr]")

        if "[mute2]" in text:
            if infos.chat_private:
                return Dialogs.get_text(infos, "mute privato")

            if not infos.user.is_admin:
                return Dialogs.get_text(infos, "ut_non_admin")

            if infos.to_user.is_admin:
                return Dialogs.get_text(infos, "ut_admin")

            if not infos.user.perms.can_restrict_members:
                return Dialogs.get_text(infos, "no_permessi")

            usr = HTTPLL.getChatMember(infos.token, infos.cid,
                                       infos.to_user.uid)["result"]
            if "can_send_messages" in usr:
                if not usr["can_send_messages"]:
                    return Dialogs.section_replacer(infos, "{already muted}")

            HTTPLL.restrictChatMember(infos.token,
                                      infos.cid,
                                      infos.to_user.uid,
                                      can_send_messages=False,
                                      can_add_web_page_previews=False,
                                      can_send_other_messages=False,
                                      can_send_media_messages=False)
            acts.append("[mute2]")

        if infos.is_reply:
            pattern = re.compile(r"\[mute:(\d+)]")
            res = re.search(pattern, text)
            if res:
                if not Utils.check_admin_action(infos):
                    return
                minutes = int(res.group(1))
                text = re.sub(pattern, "", text)
                if minutes > 60:
                    Dialogs.base_send(
                        infos,
                        None,
                        special_text=
                        "Il massimo del tempo di mute temporaneo è 60 minuti!",
                        to_id=infos.prop_id)
                    return
                if minutes < 1:
                    Dialogs.base_send(
                        infos,
                        None,
                        special_text=
                        "Il minimo del tempo di mute temporaneo è 1 minuto!",
                        to_id=infos.prop_id)
                    return

                HTTPLL.restrictChatMember(infos.token,
                                          infos.cid,
                                          infos.to_user.uid,
                                          can_send_messages=False,
                                          can_add_web_page_previews=False,
                                          can_send_other_messages=False,
                                          can_send_media_messages=False)
                threading.Thread(target=BotsFoos.temp_mute,
                                 args=(infos, minutes)).start()

        if "[unmute2]" in text:
            if infos.chat_private:
                return Dialogs.get_text(infos, "unmute privato")

            if not infos.user.is_admin:
                return Dialogs.get_text(infos, "ut_non_admin")

            if not infos.user.perms.can_restrict_members:
                return Dialogs.get_text(infos, "no_permessi")

            HTTPLL.restrictChatMember(infos.token, infos.cid,
                                      infos.to_user.uid)
            acts.append("[unmute2]")

        if "[to_en]" in text:
            if not infos.chat_private:
                if not infos.user.is_admin:
                    Dialogs.base_send(infos, "ut_non_admin")
                    return None

            if infos.chat_private:
                to_read = "users"
            else:
                to_read = "groups"
            lang = DBs.read_obj(infos.cid, infos.entity, to_read)["ext2"]
            if lang == "1":
                return Dialogs.get_text(infos, "already english")
            DBs.set_obj(infos.cid, 1, "ext2", infos.entity, where=to_read)
            acts.append("[to_en]")

        if "[to_it]" in text:
            if not infos.chat_private:
                if not infos.user.is_admin:
                    Dialogs.base_send(infos, "ut_non_admin")
                    return None

            if infos.chat_private:
                to_read = "users"
            else:
                to_read = "groups"
            lang = DBs.read_obj(infos.cid, infos.entity, to_read)["ext2"]
            if lang == "0":
                return Dialogs.get_text(infos, "già italiano")
            DBs.set_obj(infos.cid, 0, "ext2", infos.entity, where=to_read)
            acts.append("[to_it]")

        if text.startswith("kick:") and "]" in text:
            if not infos.is_reply:
                return

            if not infos.admin:
                return Dialogs.base_send(infos, "bot_non_admin")

            if not infos.user.is_admin:
                return Dialogs.base_send(infos, "ut_non_admin")

            if infos.to_user.is_admin:
                return Dialogs.base_send(infos, "ut_admin")
            t = text.split(":")[1].split("]")[0]
            acts.append("kick:%s]" % t)
            try:
                HTTPLL.kickChatMember(infos.token,
                                      infos.cid,
                                      infos.to_user.uid,
                                      until="h" + t)
            except Error.InvalidKickTime:
                HTTPLL.sendMessage(infos.token, infos.prop_id,
                                   "%s non è un valido kicktime!" % t)
                return None

    except Error.NotEnoughtRights:
        Dialogs.base_send(infos, "bot_non_admin")
        return None

    except Error.GeneralError:
        Dialogs.base_send(infos, "general_error")
        return None

    except Error.UnkownError:
        Dialogs.base_send(infos, "general_error")
        return None

    except Exception as err:
        Log.e(err)
        return None

    for act in acts:
        text = text.replace(act, "")

    return text