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 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 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 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 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 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 __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 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"
def __init__(self, bot, update): try: self.api = False self.time = time.time() message, tipe, what = get_message(update) self.error = False if not message: self.skip = True return self.skip = False self.prop_id = Manager.get_prop_id(bot["token"]) self.what = what self.token = bot["token"] self.update_id = update["update_id"] self.bid = int(bot["id"]) self.cid = int(message["chat"]["id"]) tmp = DBs.read_obj(self.bid, self.bid, "users")["ext3"] if not tmp: self.admins = [] else: self.admins = [int(uid) for uid in tmp.split()] self.admins.append(self.prop_id) self.entity = self.bid self.symbol = Utils.get_com_symbol(self.entity) bot["symb"] = self.symbol self.bot_name = bot["first_name"] self.username = bot["username"] if " " in bot["first_name"]: self.regex = Utils.regexa(bot["first_name"].lower().split()[0]) else: self.regex = Utils.regexa(bot["first_name"].lower()) self.regex = Utils.boundary(self.regex) self.text = "" self.group_username = None self.is_reply = False self.chat_private = False self.error = False self.edited = False self.admin = False self.to_user = None self.is_auto = False self.is_kitsu = False if Manager.get_main_bot_id( ) != self.bid else True if "from" in message: self.user = User(bot, message["from"], message) else: if what == "channel_post": name = None if "author_signature" in update["channel_post"]: name = update["channel_post"]["author_signature"] self.user = DummyUser(bot, message, name=name) else: self.error = True return self.name = message["chat"]["title"] if "title" in message[ "chat"] else message["chat"]["first_name"] self.lang = "ita" if "it" in self.user.lang else "eng" self.langn = 0 if "it" in self.user.lang else 1 if "username" in message["chat"]: self.group_username = message["chat"]["username"] if "text" in message: self.text = message["text"] if what != "channel post": if "reply_to_message" in message: self.to_user = User(bot, message["reply_to_message"]["from"], message["reply_to_message"]) self.is_auto = True if self.bid == self.to_user.uid else False self.is_reply = True if self.to_user.uid == self.bid: self.to_user.is_to_bot = True if message["chat"]["type"] == 'private': self.chat_private = True self.admin = True else: self.perms = Permissions(bot["token"], message["chat"]["id"], self.bid) self.admin = self.perms.is_admin self.bot_count = 0 if tipe: self.edited = True self.time_diff = int( abs((datetime.strptime(self.user.message.my_time, "%H:%M:%S") - datetime.strptime(self.user.message.time, "%H:%M:%S")).seconds)) self.timed_out = True if self.time_diff > 7 else False self.text = self.user.message.text self.args = None if ": " in self.text: tmp_args = self.text.split(": ") if len(tmp_args) > 1: self.args = self.text.split(": ")[1] except Exception as err: Log.w("Qualcosa è andato storto: %s" % err) # pprint.pprint(update) self.error = True
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
def proprietary(infos): prop_id = Manager.get_prop_id(infos.token) user = HTTPLL.getChat(infos.token, prop_id)["result"] msg = "Il mio padrone è [%s](tg://user?id=%s)" % (escape_markdown(user["first_name"]), prop_id) infos.reply(msg, markdown=True)
def get_text(infos, sezione): try: sezione = sezione.lower() dialogs = LowLevel.jfile("d", infos.bid, infos.user.lang_n) if not dialogs: return Log.w( "Mi è stato impossibile leggere i dialoghi di %s lang_n %s" % (infos.bid, infos.user.lang_n)) if sezione not in dialogs: if sezione == "start": dialogs = {"start": ["Nessuno start impostato."]} else: warning = "sezione dei dialoghi %s in lingua %s non trovata..." % ( sezione, "IT" if infos.user.lang_n == 0 else "EN") HTTPLL.sendMessage(infos.token, chat_id=Manager.get_prop_id(infos.token), text=warning) return None if not dialogs[sezione]: if sezione == "start": dialogs = {"start": ["Nessuno start impostato."]} else: warning = "%s in lingua %s non ha frasi!" % ( sezione, "IT" if infos.user.lang_n == 0 else "EN") HTTPLL.sendMessage(infos.token, chat_id=Manager.get_prop_id(infos.token), text=warning) return None frisp = None risposte = dialogs[sezione] while risposte: try: risp = random.choice(risposte) except: break match = re.search("^\[\d{1,2}>\d{1,2}]", risp) if match: ore = match.group(0).split(">") mi = int(str(ore[0]).replace("[", "")) ma = int(str(ore[1]).replace("]", "")) if ma == 0: ma = 24 at = int(time.strftime("%H")) if at == 0: at = 24 if mi <= at <= ma: frisp = risp.replace(match.group(0), "") # infos.reply("Trovato: %s > %s : %s" % (mi, ma, at)) break if not frisp: frisp = "skip" risposte.remove(risp) else: frisp = risp risposte.remove(risp) if frisp: risp = frisp # risp = random.choice(dialogs[sezione]) if risp.startswith("[private]") and not risp.endswith("[private]"): if not infos.chat_private: while dialogs[sezione]: risp = random.choice(dialogs[sezione]) dialogs[sezione].remove(risp) if risp.startswith("[private]") or risp.endswith( "[private]"): risp = risp.replace("[private]", "") break elif "[private]" in risp: risp = risp.split("[private]")[1] break return None else: risp = risp.replace("[private]", "") elif "[private]" in risp and not risp.endswith( "[private]") and not risp.startswith("[private]"): if infos.chat_private: risp = risp.split("[private]")[0] else: risp = risp.split("[private]")[1] if risp.lower() in ["skip", "+skip+"]: return None stats = LowLevel.get_stats_file(infos.bid) if sezione not in stats: stats[sezione] = 0 stats[sezione] += 1 LowLevel.write_stats_file(infos.bid, stats) return risp except Exception as err: msg = "Ho trovato l'errore: riga {} {} {}\nSegnalalo a @Kaikyu fast!".format( sys.exc_info()[-1].tb_lineno, type(err).__name__, err) print(msg) return None