예제 #1
0
def update_handler(bot, update):
    try:
        infos = Infos.Infos(bot, update)
        if infos.error:
            return Log.d("Errore owo!")

        if infos.user.uid in json.loads(open("Files/jsons/blacklist.json").read()) or infos.skip:
            return

        if "message" in update:
            if "new_chat_members" not in update["message"]:
                return

            if update["message"]["new_chat_members"] or "left_chat_member" in update["message"]:
                if bot["id"] == Manager.get_main_bot_id():
                    return Foos.status(bot, update)
                return BotsFoos.status(bot, update)

        if infos.user.message.what != "command":
            return Elaborator.reader(infos)

        if infos.user.message.command == "report":
            return Foos.report(infos)

        ok = Elaborator.command_reader(infos)
        if ok != "procedi":
            return

        if infos.user.message.pers_command:
            return Elaborator.pers_commands(infos)

    except Exception as err:
        Log.e("Ho trovato un errore: riga %s %s %s" % (sys.exc_info()[-1].tb_lineno, type(err).__name__, err))
예제 #2
0
def command_reader(infos):
    try:
        command = infos.user.message.command

        if infos.is_kitsu:
            Log.d("I'm Kitsu.")
            for com in kitsu_commands:
                if command == com:
                    return kitsu_commands[com](infos)

            if infos.user.is_master:
                Log.d("You're master.")
                for com in master_commands:
                    if command == com:
                        return master_commands[com](infos)

        if command == "start":
            return BotsFoos.startb(infos)

        if infos.user.is_owner:
            for com in bot_master_comm:
                if command == com:
                    return bot_master_comm[com](infos)

        infos.admins.append(Manager.get_owner_id())

        if infos.user.uid in infos.admins:
            for com in bot_commands:
                if command == com:
                    return bot_commands[com](infos)

        for com in general_commands:
            if command == com:
                return general_commands[com](infos)

        return "procedi"
    except Exception as err:
        Log.e("Ho trovato un errore: riga %s %s %s (%s)" %
              (sys.exc_info()[-1].tb_lineno, type(err).__name__, err,
               infos.text))
        infos.reply(
            "C-c'è stato un errore...\nInoltra a @Kaikyu il tuo ultimo messaggio!"
        )
예제 #3
0
def send(infos,
         sezione,
         antispam=True,
         to_id=None,
         special_name=None,
         special_group_name=None,
         special_user_name=None,
         no_log=False,
         special_token=None,
         special_bid=None,
         special_text=None,
         ignore_specials=False,
         recorsivity=None,
         add=None,
         parse="markdown"):
    text = "<vuoto>"
    try:
        quote = False
        inter_bot_id = None
        sezione_inter = None
        quitta = False
        no_prew = False

        if sezione:
            infos.trigger = sezione
        else:
            infos.trigger = ""

        if recorsivity:
            if recorsivity > 3:
                return
            else:
                recorsivity += 1
        else:
            recorsivity = 1

        if not to_id:
            to_id = infos.cid

        if special_group_name:
            infos.name = special_group_name
        if special_user_name:
            infos.user.name = special_user_name

        if special_token:
            infos.token = special_token

        if special_bid:
            infos.bid = special_bid

        if not special_text:

            text = Dialogs.get_text(infos, sezione)
            if add:
                try:
                    text += add
                except Exception:
                    pass
            if not text:
                return False

            if text.lower() == "skip" or text.lower() == "+skip+":
                return True

            if antispam:
                if Unreloaded.antispam(infos):
                    return True

        else:
            text = special_text

        text = Dialogs.section_replacer(infos, text)

        if infos.api:
            return text

        if "[warn]" in text:
            return BotsFoos.warn(infos)

        if "[unwarn]" in text:
            return BotsFoos.unwarn(infos)

        if "+exe+" in text:
            infos.master_message("Master, +exe+ is deprecated:\n`" + text +
                                 "`\nIn `" + sezione + "`",
                                 parse_mode="markdown")
            Log.a("[%s] U: %s %s" %
                  (infos.bot_name, infos.user.username, sezione))
            return

        if not ignore_specials:
            text = Utils.replacer(infos, text)
            text = Actions.action(infos, text, sezione)
            if not text:
                return

        if type(text) is bool:
            return

        if "[noprew]" in text:
            text = text.replace("[noprew]", "")
            no_prew = True

        if "[quote]" in text:
            text = text.replace("[quote]", "")
            quote = infos.user.message.id

        if "[quote2]" in text:
            text = text.replace("[quote2]", "")
            if infos.to_user:
                quote = infos.to_user.message.id

        if "[quit]" in text:
            text = text.replace("[quit]", "")
            quitta = True

        match = re.search("\[(\d+)\]", text)
        if match:
            if int(match.group(1)) not in Manager.get_bots_id():
                return HTTPLL.sendMessage(
                    infos.token, Manager.get_prop_id(infos.token),
                    "%s non è un ID valido." % match.group(1))

            result = text.split("[" + match.group(1) + "]")

            trigs = json.loads(
                open("Files/bot_files/%s/%s" %
                     (match.group(1), "triggers.json")).read())

            if "autorizzati" not in trigs:
                HTTPLL.sendMessage(
                    infos.token, infos.prop_id,
                    "%s non ti ha autorizzato." % match.group(1))

            elif infos.bid not in trigs["autorizzati"]:
                HTTPLL.sendMessage(
                    infos.token, infos.prop_id,
                    "%s non ti ha autorizzato." % match.group(1))
                # infos.reply("Autorizzati: %s" % )
            else:
                inter_bot_id = int(match.group(1))
                sezione_inter = result[1]

            text = result[0]

        if special_name:
            text = text.replace("+newuser+", special_name)

        if not text:
            return

        text, kb = Utils.get_keyboard(text)
        if text == "":
            return

        try:
            caption = None
            if "+stk+" in text:
                stk = text.split("()")[1]
                HTTPLL.sendSticker(infos.token, chat_id=to_id, sticker=stk)
                return True

            if "+pht+" in text:
                elems = text.split("()")
                pht = elems[1]
                if len(elems) == 3:
                    caption = elems[2]
                HTTPLL.sendChatAction(infos.token, to_id, 'upload_photo')
                time.sleep(0.3)
                HTTPLL.sendPhoto(infos.token,
                                 chat_id=to_id,
                                 photo=pht,
                                 caption=caption,
                                 reply_to_message_id=quote)
                return True

            if "+doc+" in text:
                elems = text.split("()")
                doc = elems[1]
                if len(elems) == 3:
                    caption = elems[2]
                HTTPLL.sendDocument(infos.token,
                                    to_id,
                                    doc,
                                    caption=caption,
                                    reply_to_message_id=quote)
                return True

            if "+aud+" in text or "+voi+" in text:
                aud = text.split("()")[1]
                HTTPLL.sendVoice(infos.token,
                                 to_id,
                                 aud,
                                 reply_to_message_id=quote)
                return True

            if "+vid+" in text:
                elems = text.split("()")
                vid = elems[1]
                if len(elems) == 3:
                    caption = elems[2]
                HTTPLL.sendVideo(infos.token,
                                 to_id,
                                 vid,
                                 caption=caption,
                                 reply_to_message_id=quote)
                return True
        except Exception as err:
            Log.w("Errore nell'invio del media: %s" % err)
            return False

        text = Utils.escape_markdown(text)

        text = text.replace("<b>", "*").replace("</b>", "*")
        text = text.replace("<c>", "`").replace("</c>", "`")
        text = text.replace("<i>", "_").replace("</i>", "_")

        text = Utils.link_elab(text, infos)

        text = re.sub("\/\w+\\_\w+", "$&", text).replace("\\\\_", "\\_")

        match = re.search("\B<q>.+</q>\B", text)
        if match:
            iquote = "[%s](tg://user?id=%s)" % (str(match.group(0)).replace(
                "<q>", "").replace("</q>", ""), infos.user.uid)
            text = re.sub("\B<q>.+</q>\B", iquote, text)

        result = re.finditer(re.compile(r"\*.+?\*"), text)
        if result:
            for res in result:
                text = text.replace(res.group(),
                                    res.group(0).replace("\_", "_"))

        HTTPLL.sendChatAction(infos.token, to_id, 'typing')
        HTTPLL.sendMessage(infos.token,
                           chat_id=to_id,
                           text=text,
                           parse_mode=parse,
                           disable_web_page_preview=no_prew,
                           reply_to_message_id=quote,
                           reply_markup=kb)

        if not no_log:
            Log.a("%s <- %s -> [%s]" % (infos.bid, infos.user.uid, sezione))

        if infos.chat_private:
            return
        if quitta:
            HTTPLL.leaveChat(infos.token, infos.cid)
        if inter_bot_id and sezione_inter:
            try:
                send(infos,
                     sezione_inter,
                     special_token=Manager.get_token_from_bot_id(inter_bot_id),
                     antispam=False,
                     special_bid=inter_bot_id,
                     recorsivity=recorsivity)
            except Exception:
                pass
        return True

    except Error.Unauthorized:
        if not to_id:
            Log.e("Qualcosa non va, l'ID era None...")
            return "ERR"
        DBs.remove_id(infos.entity, to_id)
        return "ERR"

    except Error.BadRequest as err:
        if "chat not found" in str(err):
            return

        if "group chat was migrated" in str(err):
            DBs.remove_id(infos.entity, to_id)
            return "ERR"

        Log.e("Bot %s -> BadRequest (%s)" % (infos.bot_name, err))

        if infos.user.is_owner:
            infos.reply(
                "Master non sono riuscita ad inviare questo messaggio:\n"
                "`%s`\nSegnalalo a @Kaikyu o controlla la formattazione." %
                text,
                markdown=True)
        return "ERR"

    except Error.NotEnoughtRights:
        DBs.remove_id(infos.entity, to_id)
        return "ERR"

    except Exception as err:
        msg = "Ho trovato un errore: riga {} {} {}".format(
            sys.exc_info()[-1].tb_lineno,
            type(err).__name__, err)
        HTTPLL.sendMessage(infos.token, infos.prop_id, msg)
        Log.e(msg)
        if "can't parse" in str(err).lower():
            # noinspection PyTypeChecker
            send(infos,
                 "",
                 to_id=Manager.get_prop_id(infos.token),
                 special_text=
                 "C'è un problema con la formattazione del messaggio:\n\n%s" %
                 text,
                 parse=None,
                 antispam=False)
        return "ERR"
예제 #4
0
def reader(i):
    try:

        kl = i.text.lower()
        inter = False

        if i.chat_private:
            if i.user.message.what != "text":
                return BotsFoos.extractor(i)

            wait_list = json.loads(open("Files/jsons/wait_for.json").read())
            if str(i.user.uid) in wait_list:
                try:
                    if i.text.lower() == "annulla":
                        del wait_list[str(i.user.uid)]
                        with open("Files/jsons/wait_for.json", "w") as fl:
                            fl.write(json.dumps(wait_list))
                        Dialoger.send(i, None, special_text="Annullato!")
                        return

                    x = wait_list[str(i.user.uid)]
                    obj = x["thing"]
                    cosa = "???"
                    prefix = None
                    if obj == "photo":
                        cosa = "la foto"
                        prefix = "+pht+"

                    if obj == "sticker":
                        cosa = "lo sticker"
                        prefix = "+stk+"

                    if obj == "document":
                        cosa = "il documento"
                        prefix = "+doc+"

                    if obj == "voice":
                        cosa = "la registrazione"
                        prefix = "+voi+"

                    if obj == "audio":
                        cosa = "l'audio"
                        prefix = "+aud+"

                    if obj == "video":
                        cosa = "il video"
                        prefix = "+vid+"

                    if not prefix:
                        return
                    obj_id = x["id"]
                    trigger = i.text.lower()
                    Dialoger.send(i,
                                  None,
                                  special_text="Aggiungo %s alla sezione %s" %
                                  (cosa, trigger))

                    reply = "%s()%s" % (prefix, obj_id)

                    if x["text"]:
                        reply += "()%s" % x["text"]

                    if LowLevel.add_risposta(i.bid, reply, trigger,
                                             i.user.lang_n):
                        risp = "Aggiunto!"
                        del wait_list[str(i.user.uid)]
                        with open("Files/jsons/wait_for.json", "w") as fl:
                            fl.write(json.dumps(wait_list))
                    else:
                        risp = "C'è qualche problema..."
                    Dialoger.send(i, None, special_text=risp)
                    return
                except Exception as err:
                    Log.e(err)
            else:
                pass

        DBs.add_group(i)
        DBs.add_user(i)

        if re.search("^" + i.regex + "\W*$", kl):
            return Dialoger.send(i, "chiamata")

        if (re.search(i.regex + "$", kl)
                or re.search("^" + i.regex, kl)) or i.chat_private:
            sezione = interaction(i)
            inter = True
            if sezione:
                return Dialoger.send(i, sezione)

        if i.is_reply:
            if i.to_user.uid != i.bid:
                sezione = risposta(i)
                if sezione:
                    return Dialoger.send(i, sezione)
            else:
                sezione = interaction(i)
                inter = True
                if sezione:
                    return Dialoger.send(i, sezione)

        sezione = checking(i)

        if sezione:
            return Dialoger.send(i, sezione)

        if inter:
            Dialoger.send(i, "gen_answ")
            t = "a"
            if not os.path.isfile("Files/bot_files/%s/gen_answ.txt" % i.bid):
                t = "w"
            with open("Files/bot_files/%s/gen_answ.txt" % i.bid, t) as fl:
                fl.write("@%s: %s \n\n" % (i.user.username, i.text))

        if random.randint(0, 750) == 500:
            return Dialoger.send(i, ("autom_" + timemoment()[0]).lower())
    except Exception as err:
        Log.e(err)
예제 #5
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