Exemplo n.º 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
Exemplo n.º 2
0
def newbot(infos):
    user = infos.user.username
    uid = infos.user.uid
    say = infos.reply

    if uid not in auth:
        say("Per potermi utilizzare devi effettuare una donazione a PayPal.me/KaikyuDev di 5 euro,"
            "includendo come messaggio il tuo ID, se non sai il tuo ID esegui il comando /myid.\n\n"
            "I server, così come il tempo, hanno un valore.")
        return

    if uid in limits:
        limit = limits[uid]
    else:
        limit = 1

    if infos.text == "token":
        say("Non devi scrivere \"token\", devi darmi la **token** del tuo **bot**.",
            markdown=True)
        HTTPLL.sendMessage(
            infos.token, Manager.get_owner_id(),
            "@%s ha usato /newbot \"token\" lol" % infos.user.username)
        return

    if Manager.get_bot_count() >= max_bots and "!!" not in infos.text:
        say("Tutti i posti sono stati occupati.\nSegui @KitsuneCode per sapere quando ce ne saranno altri ~"
            )
        return

    msg = "Nuovo bot da %s (ID: %s)" % (user, uid)

    if infos.text == "":
        say("La sintassi del comando è semplice:\n/newbot token\nRiprova...")
        return Log.a("[Bot: @%s | %s] user: %s ID: %s 'newbot senza chiave'" %
                     (infos.username, infos.bid, user, uid))

    key = infos.text.replace("!!", "")
    if Manager.is_token_used(key):
        Log.a("[Bot: @%s | %s] user: %s ID: %s 'newbot chiave usata'" %
              (infos.username, infos.bid, user, uid))
        return say("Questa chiave è già usata...")

    if Manager.count_bots(uid) >= limit:
        Log.a("[Bot: @%s | %s] user: %s ID: %s 'newbot utente ha già un bot'" %
              (infos.username, infos.bid, user, uid))
        return say(
            "A quanto pare non puoi fare altri bot ne hai già %s su %s..." %
            (Manager.count_bots(uid), limit))

    if ":" not in key or len(key) != 45:
        say("%s non credo che questa sia una chiave valida." % user)
        return Log.a("[Bot: @%s | %s] user: %s ID: %s 'newbot chiave errata'" %
                     (infos.username, infos.bid, user, uid))

    try:
        tbot = HTTPLL.getMe(key)
        txt = "Eccomi master.\nQuesta è una [guida](%s) sul miofunzionamento.\nUnisciti al [gruppo ufficiale](%s) per avere " \
              "le novità in tempo reale." % ("telegra.ph/Come-creare-un-KitsuBot-08-20", "t.me/KitsuBotsGroup")
        HTTPLL.sendMessage(key, uid, text=txt, parse_mode="markdown")
        msg += "\nHa usato la token %s\n" % key
    except Exception as err:
        Log.d(
            "L'utente non ha avviato il proprio bot, o c'è qualche problema (%s)"
            % err)
        return say("Sicuro di aver avviato il tuo bot in privato?")

    if Manager.add_bot(uid, tbot["id"], tbot["token"]):
        say("Registrato con successo!\nTutti i prossimi comandi dovrai eseguirli dal tuo bot: @%s\n"
            "Il tuo bot è il %sesimo su %s!" %
            (tbot["username"], Manager.get_bot_count(), max_bots))
    else:
        Log.d("Qualcosa è andato storto...")
        return say("Qualcosa è andato storto!")

    msg += "Nome %s\nUsername @%s\nID: %s" % (tbot["first_name"],
                                              tbot["username"], tbot["id"])

    HTTPLL.sendMessage(infos.token, Manager.get_owner_id(), msg)
    Core.attach_bot(key)