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))
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.")
def report(infos): try: if not infos.user.is_master: return if infos.text == "": return Dialoger.send(infos, None, to_id=infos.prop_id, special_text="Questo bot è stato reportato da kfrahh per:\n%s" % infos.text) Dialoger.send(infos, None, to_id=Manager.get_owner_id(), special_text="Report inviato, master.", special_token=Manager.get_main_bot_token()) except Exception as err: print(err)
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! ><")
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)
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)
def reply_to_usermessage(self, msg, sendname, takename, chat_id, from_id, user_id): reply = None Log.d("Running RTU") if msg is not None: msg, branch = pars.ReadReply(msg) try: if branch == "admin_commands": reply = Manage.admin_commands(msg, chat_id, from_id, user_id, takename, branch) return reply if branch == "simple_interactions": if takename == "MayaChan": reply = pars.LoadDialog(msg, branch) pars.Usage(branch) return reply if branch == "user_interactions": reply = pars.LoadDialog(msg, branch) pars.Usage(branch) except: branch = None if reply is not None: if "{}" in reply: reply = reply.format(takename) return reply
def autorizza(infos): try: if infos.text == "": return infos.reply("Devi dirmi un ID!") if not infos.text.isdigit(): return infos.reply("L'ID e' un numero decimale!") auth_id = int(infos.text) if auth_id == infos.bid: return infos.reply("Non puoi autorizzare il tuo stesso bot!") if auth_id not in Manager.get_bots_id(): return infos.reply("Puoi autorizzare solo kitsubots!") trigs = json.loads( open("Files/bot_files/%s/%s" % (infos.bid, "triggers.json")).read()) if "autorizzati" not in trigs: trigs["autorizzati"] = [auth_id] else: if auth_id in trigs["autorizzati"]: return infos.reply("Hai gia' autorizzato questo ID!") else: trigs["autorizzati"].append(auth_id) with open("Files/bot_files/%s/%s" % (infos.bid, "triggers.json"), "w") as fl: fl.write(json.dumps(trigs)) return infos.reply("Fatto! ID %s autorizzato!" % auth_id) except Exception as err: infos.reply("Errore: %s" % err)
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))
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))
def get_trigger_list(token, lang_n=0): try: result = {} tot = 0 bid = Manager.get_botid_from_token(token) dic = LowLevel.get_triggers( bid, "triggers.json" if lang_n == 0 else "triggers_eng.json") sections = [ "contents", "equals", "interactions", "eteractions", "bot_commands", "admin_actions" ] for section in sections: tot += len(dic[section]) result[section] = [] for trig in dic[section]: result[section].append(trig) result["total"] = tot result["symbol"] = get_com_symbol(bid) return result except Exception as err: Log.e(err) return str(err)
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
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))
def stats(infos): t = time.time() if infos.user.uid != Manager.get_owner_id(): return text = "In questo momento sto mantenendo online %s bot.\n" % Core.count_bots() text += "Il tempo di elaborazione di questo messaggio è di %s ms, " % LowLevel.get_time(t) text += "quindi il carico di lavoro è leggero.\n\nFoos version: %s" % ver Dialoger.send(infos, None, special_text=text)
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.")
def start(infos): global max_bots if DBs.add_user(infos): txt = "Avviato da %s per la prima volta." % infos.user.username Dialoger.send(infos, "", special_text=txt, to_id=Manager.get_owner_id()) text = "Benvenuto *%s*, se vuoi utilizzarmi esegui il comando /newbot" % infos.user.name infos.reply(text, markdown=True, disable_web_page_preview=True)
def __init__(self, bot, x, message): self.message = Message(message, bot) self.name = x["first_name"] self.username = "" self.sname = "" self.lang = "it" self.uid = int(x["id"]) self.is_to_bot = False self.is_admin = False self.is_owner = True if Manager.get_prop_id( bot["token"]) == self.uid else False if self.uid == Manager.get_owner_id(): self.is_owner = True self.is_master = True if self.uid == Manager.get_owner_id() else False self.sesso = None self.lang_n = 0 if "username" in x: self.username = x["username"] if "last_name" in x: self.sname = x["last_name"] if "language_code" in x: self.lang = str(x["language_code"]).lower() if message["chat"]["type"] == 'private': to_read = "users" else: to_read = "groups" lang = DBs.read_obj(message["chat"]["id"], bot["id"], to_read)["ext2"] if lang: self.lang_n = int(lang) self.perms = Permissions(bot["token"], message["chat"]["id"], self.uid) if message["chat"]["type"] != 'private': self.is_admin = self.perms.is_admin if self.is_master: self.is_admin = True if not self.lang_n: self.lang_n = 0
def bot_list(infos): tokens = Manager.get_token_list() ls = "Ecco la lista dei miei bot!\n\n" for token in tokens: try: bot = BotCache.bots[token] ls += "• *%s*\n - @%s\n\n" % (bot["first_name"], bot["username"].replace("_", "\_")) except: pass infos.reply(ls, markdown=True)
def make_reply(self, msg, username, first_name): reply = None parse_mode = None if msg is not None: reply = None parse_mode = None msg, branch = pars.ReadTrigger(msg) reply, parse_mode = Manage.trigger(msg, branch, username) Log.d(str(reply) + " " + str(parse_mode)) return reply, parse_mode
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!")
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))
def riavvia(infos): if not Manager.has_a_bot(infos.user.uid): return if not Core.is_online(infos.token): return if not infos.user.is_owner and infos.user.uid not in infos.admins: return Core.detach_bot(infos.token) time.sleep(0.5) Core.attach_bot(infos.token) infos.reply("Riavviato.")
def __init__(self, user_id): self._key = "&api_key=" + Manager.get_lastfm_token() self._url = "http://ws.audioscrobbler.com/2.0/?" self._final = "&format=json&limit=1" self._method = "method=user.getrecenttracks" self.nickname = None self._data = None self._get_nickname(user_id) self._get_data() self._check_user() if not self._data['recenttracks']['track']: raise EmptyTracks()
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)
def elimina_bot(infos): try: if not infos.user.is_owner: return if not Core.is_online(infos.token): Dialoger.send(infos, None, special_text="M-ma io non sono online...") uid = str(infos.user.uid) bid = infos.bid if not infos.text: code = str(random.randint(1000, 9999)) Dialoger.send(infos, None, special_text="Se mi elimini perderai tutti i dati!\n" "Scrivi \"/elimina_bot %s\" se ne sei sicuro..." % code) Unreloaded.set_delete_code(uid, code) return if Unreloaded.get_delete_code(uid) == "": code = str(random.randint(1000, 9999)) Dialoger.send(infos, None, special_text="Non avevo ancora generato il codice, eccolo: %s." % code) Unreloaded.set_delete_code(uid, code) return if infos.text != Unreloaded.get_delete_code(uid): Dialoger.send(infos, None, special_text="Codice sbagliato, era: %s" % Unreloaded.get_delete_code(uid)) return Dialoger.send(infos, None, special_text="Procedo...") Log.d("Elimino il bot %s di %s" % (bid, uid)) Core.detach_bot(infos.token) Manager.delete_bot(bid) Dialoger.send(infos, None, special_text="Addio...") except Exception as err: Log.e(err)
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)
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
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)
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)
def attach_bot(token, bid=None, clean=True): if bid: token = Manager.get_token_from_bot_id(bid) if not token: return Log.w("Empty token.") if isinstance(token, list): Log.d("Passed a list, iterating...") for toke in token: attach_bot(toke, clean=clean) Log.d("Finished iterating tokens!") else: if token in BotCache.bots: if BotCache.bots[token]: return Log.w("This bot is already online...") threading.Thread(target=bot_init, args=(token, clean)).start() return True