예제 #1
0
def send_message(infos):
    try:
        args = infos.text.split(" ")
        HTTPLL.sendMessage(infos.token, args[0],
                           infos.text.replace(args[0], ""))
    except Exception as err:
        HTTPLL.sendMessage(infos.token, Manager.get_owner_id(), str(err))
예제 #2
0
def get_empty_bot(infos):
    try:
        infos.reply("Ok, master.")
        d = 0
        w = 0
        wb = 0
        u_bots = "Zero-Trigger bots:"
        bids = Manager.get_bots_id()
        for bid in bids:
            tot = Manager.trigger_count(bid)
            toke = Manager.get_token_from_bot_id(bid)
            if tot < 5:
                if toke not in BotCache.bots:
                    BotCache.bots[toke] = HTTPLL.getMe(toke)

                bot = BotCache.bots[toke]
                u_bots += "\n%s - %s" % (bid, bot["username"])
                Manager.delete_bot(bid)
                d += 1
            elif tot < 20:
                try:
                    HTTPLL.sendMessage(toke, Manager.get_prop_id(toke), "Master, t-ti sei dimenticato di me...?")
                except Exception:
                    wb += 1
                    Manager.delete_bot(bid)
                w += 1
        u_bots += "\n\n%s unactive bots detached.\n%s warns sent to the bot masters but %s of them had blocked their bot." % (d, w, wb)
        infos.reply(u_bots)
    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("M-master... Controlla il log... k-kitsu! ><")
예제 #3
0
def backup(infos):
    say = infos.reply
    try:
        if infos.user.lang_n != 0:
            dialogs = "dialogs_eng.json"
            triggers = "triggers_eng.json"
        else:
            dialogs = "dialogs.json"
            triggers = "triggers.json"

        name = "Files/bot_files/%s/backup - %s.kb" % (
            infos.bid, time.strftime("%A - %H:%M:%S"))
        d = json.loads(
            open("Files/bot_files/%s/%s" % (infos.bid, dialogs)).read())
        t = json.loads(
            open("Files/bot_files/%s/%s" % (infos.bid, triggers)).read())
        f = json.dumps({"dialogs": d, "triggers": t})
        with open(name, "w") as fl:
            fl.write(encode("kitsu", f))

        HTTPLL.sendFileDocument(infos.token,
                                infos.cid,
                                name,
                                caption="Ecco il backup.")
    except Exception as err:
        say("S-si è verificato un errore...")
        say(str(err))
        Log.e(err)
예제 #4
0
def rnd_elab(infos, text):
    try:
        x = 0
        while "rnd[" in text:
            if x > 10:
                x = 0 / 0
            minmax = text.split("rnd[")[1]
            minn = int(minmax.split(",")[0])
            maxx = int(minmax.split(",")[1].split("]")[0])
            if minn > maxx:
                x = 0 / 0
            num = random.randint(minn, maxx)
            if "rnd[%s,%s]" % (minn, maxx) in text:
                text = text.replace("rnd[%s,%s]" % (minn, maxx), str(num), 1)
            elif "rnd[%s, %s]" % (minn, maxx) in text:
                text = text.replace("rnd[%s, %s]" % (minn, maxx), str(num), 1)
            x += 1
        return text
    except Exception:
        warn = get_phrase("rnd[ err")
        HTTPLL.sendMessage(infos.token,
                           chat_id=Manager.get_prop_id(infos.token),
                           text=warn)
        Log.d("[Bot: @%s | %s] rnd error" % (infos.bid, infos.username))
        return None
예제 #5
0
def callback(token, data):
    try:
        update = json.loads(data)
    except Exception as err:
        return Log.w("Not JSON data (%s) (%s)" % (err, data))

    if token not in BotCache.bots:
        Log.w("This token is not in the cache!")
        if token not in token_black_list:
            if len(token) == 45:
                HTTPLL.deleteWebhook(token)
            else:
                Log.w("Invalid token!! (%s) blacklist." % token)
            token_black_list.append(token)
            return

    if token not in offsets:
        offsets[token] = 0

    last_id = offsets[token]
    bot = BotCache.bots[token]
    if update["update_id"] > last_id:
        offsets[token] = update["update_id"]
        try:
            update_handler(bot, update)
        except Exception as err:
            Log.e("UNHANDLED EXCEPTION IN THE UPDATE HANDLER: %s" % str(err))
예제 #6
0
def clean_updates(token):
    # Puliamo gli update!
    updates = HTTPLL.getUpdates(token)
    if not updates:
        offsets[token] = 0
    while updates:
        offsets[token] = updates[-1]["update_id"] + 1
        updates = HTTPLL.getUpdates(token, offset=updates[-1]["update_id"] + 1)
예제 #7
0
def temp_mute(infos, minutes):
    try:
        time.sleep(minutes * 60)
        HTTPLL.restrictChatMember(infos.token, infos.cid, infos.to_user.uid)
        send(infos, "user_unmuted")
    except Exception as err:
        HTTPLL.sendMessage(infos.token, infos.cid, "Non ho potuto unmutare l'utente con ID %s..." % infos.to_user.uid)
        Log.d("Errore nel unmute: %s" % err)
예제 #8
0
def help(infos):
    try:
        if infos.user.uid not in auth:
            return

        string = "%s [@%s] (%s) ha detto:\n%s" % (infos.user.name, infos.user.username, infos.user.uid, infos.text)
        HTTPLL.sendMessage(infos.token, Manager.get_owner_id(), string)
    except Exception as err:
        HTTPLL.sendMessage(infos.token, Manager.get_owner_id(), str(err))
예제 #9
0
def get_gen_answ(infos):
    if not os.path.isfile("Files/bot_files/%s/gen_answ.txt" % infos.bid):
        return infos.reply("File ancora non creato, master.")

    HTTPLL.sendFileDocument(infos.token, infos.cid, "Files/bot_files/%s/gen_answ.txt" % infos.bid,
                            caption="Ecco master.")
    with open("Files/bot_files/%s/gen_answ.txt" % infos.bid, "w") as fl:
        fl.write((">> Log iniziato il %s\n\n" % time.strftime("%A - %H:%M:%S")))
    return
예제 #10
0
def run():
    httpd = ThreadedHTTPServer(('', port), S)
    httpd.socket = ssl.wrap_socket(httpd.socket, certfile=certfile, keyfile=ckey, server_side=True)
    Log.i("Starting server, use <Ctrl-C> to stop")
    HTTPLL.sendMessage(Manager.get_main_bot_token(), Manager.get_owner_id(), "Avvio concluso.")
    try:
        httpd.serve_forever()
    except Exception as err:
        print(err)
    Log.e("Server has stopped, warning.")
예제 #11
0
def getter(token):
    if token not in offsets:
        offsets[token] = 0

    while token in BotCache.bots:
        for update in HTTPLL.getUpdates(token, offsets[token], timeout=120):
            offsets[token] = update["update_id"] + 1
            update_handler(BotCache.bots[token], update)

    HTTPLL.sendMessage(token, Manager.get_owner_id(),
                       "Bot {} stopped.".format(token))
예제 #12
0
def warn_token(key):
    ids = Manager.get_bot_from_token(key)
    pid = ids["user_id"]
    bid = ids["bot_id"]

    try:
        HTTPLL.sendMessage(
            Manager.get_main_bot_token(), pid,
            "Il tuo bot è stato scollegato per token revokata o invalida,"
            " registra la sua nuova token per tornare ad utilizzarlo!")
    except Exception:
        pass

    if Manager.delete_bot(bid):
        Log.a("Master, ho scollegato il bot di %s per token revocata." % pid)
예제 #13
0
def detach_bot(token, bid=None):
    if bid:
        token = Manager.get_token_from_bot_id(bid)

    if not token:
        return Log.w("Empty token.")

    if token not in BotCache.bots:
        return Log.w("This token is not running.")

    HTTPLL.deleteWebhook(token)
    del BotCache.bots[token]

    Log.i("Bot with %s token stopped." % token)
    return True
예제 #14
0
def get_keyboard(text):
    kb = None
    pattern = re.compile(r'(<btn>)(.*?)(->)(.*?)(</btn>)')
    res = re.finditer(pattern, text)
    if res:
        kb = []
        for btn in res:
            btn_text = btn.group(2)
            btn_link = btn.group(4)
            kb.append(HTTPLL.keyboard_btn(btn_text, btn_link))
            text = text.replace(btn.group(0), "")

        kb = HTTPLL.inline_keyboard(kb)

    return text, kb
예제 #15
0
def extractor(infos):
    if not infos.chat_private:
        return

    uid = infos.user.uid
    if infos.user.uid != Manager.get_owner_id():
        if Manager.get_prop_id(infos.token) != uid:
            return

    stkid = infos.user.message.item_id
    thing = infos.user.message.what

    if thing == "document":
        try:
            f_name = HTTPLL.getFileName(infos.token, stkid)
            if f_name.endswith(".kb"):
                content = HTTPLL.getFile(infos.token, None, file_path="documents/" + f_name).read().decode("utf-8")
                success, message = Commands.restore(content, infos.bid, infos.user.lang_n)
                if success:
                    repl = "Restore riuscito!"
                else:
                    repl = "Restore fallito: %s" % message
                return infos.reply(repl)
        except Exception as err:
            Log.e("Errore: %s" % err)
            return

    msg = "Vuoi aggiungere [%s], master? ~\nInviami il trigger a cui aggiungerlo!\n...*aspetta*" % thing
    wait_list = json.loads(open("Files/jsons/wait_for.json").read())
    if str(uid) in wait_list:
        x = wait_list[str(uid)]
        obj = x["thing"]
        obj_id = x["id"]
        msg = "Sto ancora aspettando il trigger per:\n%s con ID: %s~" % (obj, obj_id)
    else:
        wait_list[str(uid)] = {}
        wait_list[str(uid)]["thing"] = thing
        wait_list[str(uid)]["id"] = stkid

        if infos.user.message.text != "":
            wait_list[str(uid)]["text"] = infos.user.message.text
        else:
            wait_list[str(uid)]["text"] = None

        with open("Files/jsons/wait_for.json", "w") as fl:
            fl.write(json.dumps(wait_list))

    Dialoger.send(infos, None, special_text=msg)
예제 #16
0
def unjoin(infos):
    infos.admins.remove(infos.prop_id)
    if not infos.admins:
        return infos.reply("Ma non hai autorizzato nessuno!")

    if infos.text == "":
        return infos.reply("Devi specificare il numero dell'admin da rimuovere!\nGuarda /admin_list")

    if not infos.text.isdecimal():
        return infos.reply("Devi dirmi un numero!")

    num = int(infos.text)
    if num < 1:
        return infos.reply("Mi prendi in giro...?")

    if len(infos.admins) > num:
        return infos.reply("Ma ci sono %s admin..." % len(infos.admins))

    admin = infos.admins[num - 1]
    try:
        name = HTTPLL.getChat(infos.token, admin)["result"]["first_name"]
    except:
        name = "???"

    reply = "Rimuovo %s - %s dagli admin..." % (admin, name)
    admins = DBs.read_obj(infos.bid, infos.bid, "users")["ext3"]
    admins = admins.replace(str(admin), "")
    DBs.set_obj(infos.bid, admins, "ext3", infos.bid, where="users")
    infos.reply(reply)
예제 #17
0
def mcast(infos):
    unsend = 0
    send = 0
    bids = Manager.get_bots_id()
    tot = len(bids)
    msg = infos.text
    for bid in bids:
        btoken = Manager.get_token_from_bot_id(bid)
        pid = Manager.get_prop_id(btoken)
        try:
            HTTPLL.sendMessage(btoken, pid, msg)
            send += 1
        except Exception:
            Manager.delete_bot(bid)
            unsend += 1

    infos.reply("Inviato a %s su %s (%s avevano bloccato il proprio bot e sono stati eliminati)" % (send, tot, unsend))
예제 #18
0
def bot_init(token, clean):
    ok = False
    try:
        BotCache.bots[token] = HTTPLL.getMe(token)
        ok = True
        LowLevel.check_files(Manager.get_botid_from_token(token))
        if clean:
            HTTPLL.deleteWebhook(token)
            clean_updates(token)
        HTTPLL.setWebhook(token, certfile)
    except Unauthorized:
        if ok:
            Log.w("getMe ok but unauth.")
        Log.w("Bot with token '%s' unauthorized." % token)
        Utils.warn_token(token)
    except Exception as error:
        Log.e(error)
예제 #19
0
 def reply(self, text, quote=None, markdown=None, **kwargs):
     return HTTPLL.sendMessage(
         self.token,
         self.cid,
         text,
         reply_to_message_id=self.user.message.id if quote else None,
         parse_mode="markdown" if markdown else None,
         **kwargs)
예제 #20
0
def status(bot, update):
    try:
        g_name = update["message"]["chat"]["title"]
        by = update["message"]["from"]["username"]
        byid = update["message"]["from"]["id"]
        gid = update["message"]["chat"]["id"]

        if update["message"]["new_chat_members"]:
            join_user_name = update["message"]["new_chat_members"][0]['first_name']
            if "username" in update["message"]["new_chat_members"][0]:
                join_user_username = update["message"]["new_chat_members"][0]['username']
            else:
                join_user_username = join_user_name
            join_user_id = update["message"]["new_chat_members"][0]['id']

            if join_user_id == bot["id"]:
                text = "Aggiunta a: %s\nUtente: @%s" % (g_name, by)
                bpht = None  # ToDo Get Propic Method
                if bpht:
                    HTTPLL.sendPhoto(Manager.get_main_bot_token(), Manager.get_owner_id(), bpht, caption=text)
                else:
                    HTTPLL.sendMessage(Manager.get_main_bot_token(), Manager.get_owner_id(), text)

        elif update["message"]["left_chat_member"]:
            left_user_name = update["message"]["left_chat_member"]['first_name']
            left_user_id = update["message"]["left_chat_member"]['id']

            if left_user_id == bot["id"]:
                HTTPLL.sendMessage(Manager.get_main_bot_token(), Manager.get_owner_id(), text="Rimossa da: %s\nUtente @%s" % (g_name, by))
                Log.a("[%s] Rimossa da un gruppo da %s" % (bot["first_name"], by))

    except Exception as err:
        Log.e(err)
        pprint.pprint(update)
예제 #21
0
def bcast(infos, who):
    if not infos.user.is_owner:
        return
    dialogs = LowLevel.jfile("d", infos.bid, infos.user.lang_n)
    if "broadcast" not in dialogs:
        infos.reply("Crea la sezione con \"/add_sezione broadcast\" prima...")
        return

    if not dialogs["broadcast"]:
        infos.reply("Aggiungi le risposte alla sezione \"broadcast\" con \"/add_risposte broadcast | Risposta\" prima!")
        return

    Log.d("Broadcast utenti avviato da %s ID %s" % (infos.user.username, infos.user.uid))
    try:
        itms = DBs.get_data(infos.entity, who)
        n_itms = len(itms)
        msg_id = infos.reply("Invio 0/%s..." % n_itms)["message_id"]

        uns = 0
        s = 0

        for itm in itms:
            res = Dialoger.send(infos, "broadcast", special_user_name=itm[2], to_id=itm[0], antispam=False, no_log=True)

            if res == "ERR":
                uns += 1
            else:
                s += 1
                time.sleep(0.05)

            if (s + uns) % 10 == 0:
                HTTPLL.editMessageText(infos.token, chat_id=infos.cid,
                                       message_id=msg_id, text="Invio %s/%s..." % (s + uns, n_itms))

        Dialoger.send(infos, None, special_text="Fatto!\nInviato a %s su %s!" % (s, n_itms))

    except Exception as err:
        Log.w(str(err))
        Dialoger.send(infos, "general_error", antispam=False)
예제 #22
0
def link_elab(text, infos):
    links = 0
    while "<link>" in text:
        if links > 10:
            HTTPLL.sendMessage(
                infos.token,
                chat_id=infos.prop_id,
                text="Problema nella formattazione del messagio:\n\n\"%s\"" %
                text)
            break

        if "<link>" in text and "</link>" in text:
            if ":>" not in text:
                return
            desc = text.split(":>")[1]
            desc = desc.split("</link>")[0]
            link = text.split("<link>")[1]
            link = link.split(":>")[0]
            text = text.replace("<link>%s:>%s</link>" % (link, desc),
                                "[%s](%s)" % (desc, link))
        links += 1
    return text
예제 #23
0
def base_send(infos, sezione, special_text=None, to_id=None):
    try:
        infos.trigger = sezione
        if special_text:
            text = special_text
        elif sezione:
            text = get_text(infos, sezione)
        else:
            return

        text = Utils.replacer(infos, text)
        if not text:
            return

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

        text = Utils.escape_markdown(text)

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

        if to_id:
            infos.cid = to_id

        HTTPLL.sendChatAction(infos.token, infos.cid, 'typing')
        time.sleep(0.2)
        HTTPLL.sendMessage(infos.token, chat_id=infos.cid, text=text)

        return None

    except Error.Unauthorized:
        return "ERR"

    except Exception:
        return "ERR"
예제 #24
0
def bot_init(token, clean):
    try:
        BotCache.bots[token] = HTTPLL.getMe(token)
        LowLevel.check_files(Manager.get_botid_from_token(token))

        if clean:
            clean_updates(token)

        threading.Thread(target=getter, args=(token, )).start()

    except Unauthorized:
        Log.w("Bot with token '%s' unauthorized." % token)
        Utils.warn_token(token)
    except Exception as error:
        Log.e(error)
예제 #25
0
def admin_list(infos):
    infos.admins.remove(infos.prop_id)
    if not infos.admins:
        return infos.reply("Non hai autorizzato nessuno!")

    msg = "I miei admin sono:\n"
    n = 1
    for admin in infos.admins:
        try:
            name = HTTPLL.getChat(infos.token, admin)["result"]["first_name"]
        except:
            name = "???"
        msg += "%s) %s - %s\n" % (n, admin, name)
        n += 1

    infos.reply(msg)
예제 #26
0
def status(bot, update):
    try:
        g_name = update["message"]["chat"]["title"]
        gid = update["message"]["chat"]["id"]
        if "username" in update["message"]["from"]:
            by = update["message"]["from"]["username"]
        else:
            by = "[no username]"
        byid = update["message"]["from"]["id"]
        # gid = update["message"]["chat"]["id"]
        propid = Manager.get_prop_id(bot["token"])

        if update["message"]["new_chat_members"]:
            join_user_name = update["message"]["new_chat_members"][0]['first_name']
            # join_user_username = update["message"]["new_chat_members"][0]['username']
            join_user_id = update["message"]["new_chat_members"][0]['id']

            if join_user_id == bot["id"]:
                text = "Aggiunta a: %s\nUtente: @%s" % (g_name, by)

                bpht = HTTPLL.getChatPhoto(bot["token"], gid)
                if bpht:
                    HTTPLL.sendPhoto(bot["token"], propid, bpht, caption=text)
                else:
                    HTTPLL.sendMessage(bot["token"], propid, text)

                Log.a("[Bot: %s | @%s] Aggiunto a %s da %s" % (bot["username"], bot["id"], g_name, byid))
                Dialoger.send(Infos(bot, update), "newgroup", special_token=bot["token"])
            else:
                state = DBs.read_obj(gid, bot["id"], "groups")["ext"]
                if not state or state == "0":
                    Dialoger.send(Infos(bot, update), "welcome", special_name=join_user_name,
                                  special_token=bot["token"])

        elif update["message"]["left_chat_member"]:
            left_user_id = update["message"]["left_chat_member"]['id']

            if left_user_id == bot["id"]:
                Log.i("bot quitt")
                Unreloaded.gbots[str(update["message"]["chat"]["id"])].remove(bot["id"])
                HTTPLL.sendMessage(bot["token"], propid, "Rimossa da: %s\nUtente @%s" % (g_name, by))
                Log.a("[%s] Rimosso da un gruppo da %s" % (bot["first_name"], by))

    except Exception as err:
        Log.e(err)
예제 #27
0
def change_token(infos):
    token = infos.text
    try:
        bot = HTTPLL.getMe(token)

    except NotFound404:
        infos.reply("Token non valida.")
        return

    except Exception as err:
        infos.reply("Eccezione: %s" % err)
        return

    nbid = bot["id"]
    obids = Manager.get_botid_from_prop_id(infos.user.uid)

    if len(obids) == 0:
        infos.reply("Non hai un bot!")
        return

    if len(obids) == 1:
        if obids[0] != nbid:
            infos.reply("Devi darmi la chiave dello stesso tuo bot!")
            return

    elif nbid not in obids:
        infos.reply(
            "Non riconsco questo bot.\nPuoi cambiare token, non bot...")
        return

    bots = json.loads(open("Files/jsons/bots.json").read())
    bots.pop(Manager.get_token_from_bot_id(nbid))
    bots[token] = {"bot_id": nbid, "user_id": infos.user.uid}

    with open("Files/jsons/bots.json", "w") as fl:
        fl.write(json.dumps(bots))

    infos.reply("Token sostituita!")

    Core.attach_bot(token)

    infos.reply("Ora il bot dovrebbe essere on!")
예제 #28
0
def get_rankings():
    bot_scores, bot_scores, bot_usages = get_ordered_bots()
    rankings = []
    n = 1
    for bid in bot_scores:
        token = Manager.get_token_from_bot_id(bid)
        if token not in bots_cache:
            bot = HTTPLL.getMe(token)
            del bot["token"]
            del bot["is_bot"]
            del bot["id"]
            bots_cache[token] = bot

        bots_cache[token]["score"] = int(bot_scores[str(bid)])
        bots_cache[token]["usages"] = bot_usages[str(bid)]
        bots_cache[token]["position"] = n

        rankings.append(bots_cache[token])
        n += 1
        if n >= 101:
            return rankings

    return rankings
예제 #29
0
def notice(infos):
    if infos.text == "":
        return infos.reply("Cosa dovrei dire...?")

    infos.text = infos.text.replace("[_]", "\n")

    HTTPLL.sendMessage(infos.token, Manager.get_owner_id(), infos.text)

    bids = Manager.get_bots_id()
    for bid in bids:
        token = Manager.get_token_from_bot_id(bid)
        uid = Manager.get_prop_id(token)
        try:
            HTTPLL.sendMessage(infos.token, uid, infos.text)
        except Exception:
            Log.w("%s notice unauth" % uid)

    HTTPLL.sendMessage(infos.token, Manager.get_owner_id(), "Avviso importante inviato.")
예제 #30
0
def get_rankings():
    bot_scores, bot_scores, bot_usages = get_ordered_bots()
    rankings = []
    n = 1
    for bid in bot_scores:
        token = Manager.get_token_from_bot_id(bid)
        if token not in BotCache.bots:
            try:
                bot = HTTPLL.getMe(token)
            except Unauthorized:
                continue
            del bot["token"]
            del bot["is_bot"]
            del bot["id"]
            BotCache.bots[token] = bot

        BotCache.bots[token]["score"] = int(bot_scores[str(bid)])
        BotCache.bots[token]["usages"] = bot_usages[str(bid)]
        BotCache.bots[token]["position"] = n

        rankings.append(BotCache.bots[token])
        n += 1

    return rankings