def del_trigger_vuoti(infos): say = infos.reply try: if infos.user.lang_n != 0: triggers = "triggers_eng.json" dialogs = "dialogs_eng.json" else: triggers = "triggers.json" dialogs = "dialogs.json" dials = json.loads( open("Files/bot_files/%s/%s" % (infos.bid, dialogs)).read()) trigs = json.loads( open("Files/bot_files/%s/%s" % (infos.bid, triggers)).read()) sections = [ "contents", "interactions", "equals", "eteractions", "admin_actions", "bot_commands" ] msg = "Sezioni rimosse:\n" msg2 = "Trigger rimossi:\n" to_remove = [] for sezione in dials.keys(): if not dials[sezione]: to_remove.append(sezione) # dials.pop(sezione) msg += "- `%s`\n" % sezione for section in sections: if sezione in trigs[section]: trigs[section].remove(sezione) msg += "- `%s`\n" % sezione for element in to_remove: dials.pop(element) msg = msg + msg2 with open("Files/bot_files/%s/%s" % (infos.bid, dialogs), "w") as file_d: file_d.write(json.dumps(dials)) with open("Files/bot_files/%s/%s" % (infos.bid, triggers), "w") as file_d: file_d.write(json.dumps(trigs)) msg += "\nEseguito con successo!" say(msg, markdown=True) except Exception as err: say("S-si è verificato un errore...") Log.e(err)
def default_list(infos): say = infos.reply try: text = "Le sezioni default al momento sono:\n\n" text += "complimenti\nbene\ninsulti\ngiorno\nscuse\nringraziamenti\nnotte\nsaluti\namare\n" text += "\nVedendo il contenuto di essi puoi facilmente kitsucapire a cosa servono ~" say(text) Log.a("[Bot: @%s | %s] user: %s ID: %s 'list_risposte riuscito'" % (infos.username, infos.bid, infos.user.username, infos.user.uid)) except Exception as err: say(Utils.get_phrase("error")) Log.e(err)
def del_risp(infos): say = infos.reply try: if infos.user.lang_n != 0: dialogs = "dialogs_eng.json" else: dialogs = "dialogs.json" if infos.text == "": return say( "Devi specificare la sezione da cui eliminare e il numero della frase da eliminare:\n" "/del_risposta sezione (n)") trigger = infos.text.lower() matches = re.search("\(\d+\)", trigger) if matches: n = matches.group(0) trigger = trigger.replace(" " + n, "").replace(n, "") n = int(re.search("\d+", n).group(0)) if n < 1: return say("(n) non valida \"(%s)\"" % n) else: return say( "Non hai specificato il numero della risposta da eliminare \"(n)\"" ) dials = json.loads( open("Files/bot_files/%s/%s" % (infos.bid, dialogs)).read()) if trigger not in dials: return say("non ho trovato il trigger %s." % trigger) if not dials[trigger]: return say("Non ci sono gia' frasi in questa sezione kitsu!") if len(dials[trigger]) < n: return say( "Ci sono %s risposte, impossibile trovare la risposta n°%s..." % (len(dials[trigger]), n)) phrase = dials[trigger].pop(n - 1) with open("Files/bot_files/%s/%s" % (infos.bid, dialogs), "w") as file_d: file_d.write(json.dumps(dials)) say("Frase:\n`%s`\nEliminata con successo." % phrase, markdown=True) except Exception as err: say("S-si è verificato un errore...") Log.e(err)
def get_owner_id(): global _owner_id if _owner_id == 0: try: _owner_id = int(json.loads(open("Files/jsons/config.json").read())["owner_id"]) if _owner_id == 0: Log.e("Errore critico, imposta il tuo ID in Files/jsons/config.json (owner_id)") exit() except: Log.e("Errore critico, l'ID proprietario non è valido.") exit() return _owner_id
def add_bot(user_id, bot_id, bot_token): try: new = {"user_id": user_id, "bot_id": bot_id} bots = json.loads(open("Files/jsons/bots.json").read()) if bot_token in bots: return False bots[bot_token] = new with open("Files/jsons/bots.json", "w") as fl: fl.write(json.dumps(bots)) Log.d("Nuovo bot (%s) aggiunto al file bots" % bot_id) return True except Exception as err: Log.e(err) return False
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 make_post(method, toke, chat_id, photo=None, voice=None, document=None, certificate=None, caption=None, reply_to_message_id=None): url = base_url + toke + "/" + method if chat_id: url += "?chat_id=" + str(chat_id) files = None if photo: files = {"photo": photo} if voice: files = {"voice": voice} if document: files = {"document": document} if certificate: files = {"certificate": certificate} if not files: return if reply_to_message_id: url += get_symbol(url) + "reply_to_message_id=%s" % reply_to_message_id if caption: url += get_symbol(url) + "caption=%s" % caption try: r = requests.post(url, files=files) if r.status_code != 200: if "rights" in r.json()["description"]: raise NotEnoughtRights if r.status_code == 403: raise Unauthorized else: raise UnkownError(r.json()["description"]) return r.json()["result"] except Exception as err: Log.e(url) Log.e(err)
def risposta(infos): try: cont = LowLevel.jfile("t", infos.bid, infos.user.lang_n) eteractions = cont["eteractions"] kl = infos.text.lower() if re.search(infos.regex + "$", kl) or re.search( "^" + infos.regex, kl): for inter in eteractions: x = cicler(inter, kl) if x: return x return None 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 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 write_stats(obj, value, obj2=None): try: sts = json.loads(open("Files/jsons/stats.json").read()) if not obj2: sts[obj] = value else: try: sts[obj][obj2] = value except: sts[obj] = {} sts[obj][obj2] = value with open("Files/jsons/stats.json", "w") as fl: fl.write(json.dumps(sts)) return True except Exception as err: Log.e(err) return False
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"] 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 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 triggers_stats_inv(infos): try: stats = LowLevel.get_stats_file(infos.bid) sorted_stats = OrderedDict(sorted(stats.items(), key=operator.itemgetter(1))) msg = "Ecco la lista dei trigger meno utilizzati!\n\n" tot = 0 for trigger in sorted_stats: if tot == 25: break msg += "*%s* -> *%s* utilizzi,\n" % (trigger, sorted_stats[trigger]) tot += 1 msg += "\nCon un totale di %s utilizzi!" % sum(stats.values()) infos.reply(msg, markdown=True) except Exception as err: Log.e(err) infos.reply("Errore: %s" % err)
def unwarn(infos): try: try: warns = json.loads(open("Files/bot_files/%s/warns.json" % infos.bid).read()) except Exception: warns = {} if not infos.admin: return send(infos, "non_admin", antispam=False, recorsivity=1) if infos.is_auto: return send(infos, "auto_unwarn", antispam=False, recorsivity=1) if not infos.user.is_admin: return send(infos, "ut_non_admin", antispam=False, recorsivity=1) if infos.to_user.is_owner: return send(infos, "user_is_owner", antispam=False, recorsivity=1) if infos.to_user.is_admin: return send(infos, "ut_admin", antispam=False, recorsivity=1) gid = str(infos.cid) ut_to_unwarn = str(infos.to_user.uid) if gid not in warns: warns[gid] = {} if ut_to_unwarn not in warns[gid]: warns[gid][ut_to_unwarn] = 0 warns[gid][ut_to_unwarn] -= 1 nwarns = warns[gid][ut_to_unwarn] if nwarns == -1: return send(infos, "unwarn_-1", antispam=False, recorsivity=1) if nwarns == 0: send(infos, "unwarn_0", antispam=False, recorsivity=1) if nwarns == 1: send(infos, "unwarn_1", antispam=False, recorsivity=1) with open("Files/bot_files/%s/warns.json" % infos.bid, "w") as fl: fl.write(json.dumps(warns)) except Exception as err: send(infos, "general_error", antispam=False, recorsivity=1) Log.e(err)
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!" )
def list_risps(infos): say = infos.reply try: if infos.user.lang_n != 0: dialogs = "dialogs_eng.json" else: dialogs = "dialogs.json" lang_itm = "IT" if infos.user.lang_n == 0 else "EN" if infos.text == "": say("Devi specificare il trigger da cui eliminare le risposte.") return trigger = infos.text.lower() dials = json.loads( open("Files/bot_files/%s/%s" % (infos.bid, dialogs)).read()) if trigger not in dials: say("Non ho trovato questa sezione.. kitsu...") return if not dials[trigger]: say("Non ci sono gia' frasi in questa sezione kitsu!") return msg = "Ecco le frasi (%s) per `%s`:\n\n" % (lang_itm, trigger) frasi = dials[trigger] x = 1 for frase in frasi: msg += "`%s`) `%s`\n\n" % (x, frase) x += 1 msg += "\nTotale di %s frasi!" % len(frasi) say(msg, markdown=True) Log.a("%s <- %s -> [list_risposte]" % (infos.bid, infos.user.uid)) except Exception as err: say("S-si è verificato un errore...") Log.e(err)
def list_sezioni(infos): say = infos.reply try: if infos.user.lang_n != 0: dialogs = "dialogs_eng.json" else: dialogs = "dialogs.json" dials = json.loads( open("Files/bot_files/%s/%s" % (infos.bid, dialogs)).read()) msg = "Ecco le mie sezioni dei dialoghi:\nSezione [numero risposte]\n\n" for section in dials: msg += "%s [%s]\n" % (section, len(dials[section])) msg += "\nTotale di %s sezioni." % len(dials) say(msg) except Exception as err: say("S-si è verificato un errore...") Log.e(err)
def class_text(): try: wait = False bot_scores, bot_scores, bot_usages = get_ordered_bots() n = 1 msg = "Classifica dei *25* bot più *utilizzati*!\n\n" for bid in bot_scores: try: bot = BotCache.bots[Manager.get_token_from_bot_id(bid)] simbol = "" if n == 1: simbol = "🥇" elif n == 2: simbol = "🥈" elif n == 3: simbol = "🥉" msg += "#*%s* - *%s* %s\n • @%s\n *%s punti - %s utilizzi*\n\n" % ( n, bot["first_name"], simbol, escape_markdown(bot["username"]), int( bot_scores[str(bid)]), bot_usages[str(bid)]) except Exception: wait = True msg += "#*%s* - *%s* %s\n • @%s\n *%s punti - %s utilizzi*\n\n" % ( n, "???", "???", "???", "???", "???") n += 1 if n == 26: break if wait: time.sleep(2) return msg except Exception as err: msg = "Ho trovato un errore: riga {} {} {}".format( sys.exc_info()[-1].tb_lineno, type(err).__name__, err) Log.e(msg) return None
def list_default(token, text, lang_n): try: bid = token.split(":")[0] default = text.lower() if lang_n != 0: triggers = "triggers_eng.json" else: triggers = "triggers.json" lang_itm = "IT" if lang_n == 0 else "EN" if text == "": return "Devi dirmi il default del quale elencare i trigger", False triggers = json.loads( open("Files/bot_files/%s/%s" % (bid, triggers)).read()) if default not in [ "complimenti", "bene", "insulti", "scuse", "ringraziamenti", "saluti", "amare" ]: return "Non ho trovato questa sezione.. kitsu...", False if default not in triggers: return "Non ho trovato questa sezione.. kitsu...", False if not triggers[default]: return "ma... Questo default e'... kitsuvuoto!", False msg = "Ecco i trigger (%s) default per %s:\n\n" % (lang_itm, default) trigs = triggers[default] msg += trigs msg += "\n\nTotale di %s triggers!" % len(trigs.split()) return msg, True except Exception as err: Log.e(err) return "Qualcosa e' andato storto...", False
def update_handler(bot, update): try: infos = Infos.Infos(bot, update) if infos.error: return Log.e("Errore nell'update: " + str(update)) 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" in update["message"]: if not update["message"][ "new_chat_members"] or "left_chat_member" not in update[ "message"]: return 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: Elaborator.pers_commands(infos) except Exception as error: Log.e("Ho trovato un errore: riga %s %s %s" % (sys.exc_info()[-1].tb_lineno, type(error).__name__, error))
def controlla(infos): try: frase = infos.text.lower() sezioni = [ "insulti", "ringraziamenti", "scuse", "complimenti", "saluti", "amare", "bene" ] cont = LowLevel.jfile("t", infos.bid, infos.user.lang_n) for sezione in sezioni: tmp = cont[sezione] tmp = tmp.split(" ") for trigger in tmp: if re.search( boundary(regexa(escape(trigger.replace("_", " ")))), frase): return sezione return None except Exception as err: Log.e(err) return None
def interaction(infos): try: cont = LowLevel.jfile("t", infos.bid, infos.user.lang_n) moment = LowLevel.get_moment().lower() day_parts = cont["day_parts"] interactions = cont["interactions"] kl = infos.text.lower() if infos.user.is_owner: for inter in cont["admin_actions"]: x = cicler(inter, kl, interact=True) if x: return x x = controlla(infos) if x: return x for inter in interactions: x = cicler(inter, kl, interact=True) if x: return x for day_part in day_parts: if "|" in day_part: day_part = day_part.split("|") for segment in day_part: if segment in kl: return day_part[0] + " " + moment else: if day_part in kl: return day_part + " " + moment return None except Exception as err: Log.e(err)
def add_interazione(infos): say = infos.reply try: if infos.user.lang_n != 0: dialogs = "dialogs_eng.json" else: dialogs = "dialogs.json" lang_itm = "IT" if infos.user.lang_n == 0 else "EN" user = infos.user.username uid = infos.user.uid if infos.text == "": say("Devi specificare il nome della sezione da creare.") return Log.a("[Bot: @%s | %s] user: %s ID: %s 'senza trigger'" % (infos.username, infos.user.uid, user, uid)) trigger = infos.text.lower() dials = json.loads( open("Files/bot_files/%s/%s" % (infos.bid, dialogs)).read()) if trigger in dials: return say("Questa sezione e' gia' presente ~") else: dials[trigger] = [] with open("Files/bot_files/%s/%s" % (infos.bid, dialogs), "w") as file_d: file_d.write(json.dumps(dials)) say("Sezione aggiunta! (%s)\nAggiungici cio' che vuoi ~" % lang_itm) Log.a("[Bot: @%s | %s] user: %s ID: %s 'add_frase riuscito'" % (infos.username, infos.user.uid, user, uid)) except Exception as err: Log.e(err) say("S-si è verificato un errore...")
def list_risps_form(infos): say = infos.reply try: if infos.user.lang_n != 0: dialogs = "dialogs_eng.json" else: dialogs = "dialogs.json" if infos.text == "": say("Devi specificare il trigger per cui listare le risposte.") return trigger = infos.text.lower() dials = json.loads( open("Files/bot_files/%s/%s" % (infos.bid, dialogs)).read()) if trigger not in dials: say("Non ho trovato questa sezione.. kitsu...") return if not dials[trigger]: say("Non ci sono gia' frasi in questa sezione kitsu!") return com = "Ecco a te:\n`%s" % trigger for frase in dials[trigger]: com += " | %s" % frase com += "`" say(com, markdown=True) Log.a("%s <- %s -> [list_risposte_form]" % (infos.bid, infos.user.uid)) except Exception as err: say("S-si è verificato un errore...") Log.e(err)
def get_chat_photo(toke, chat_id): x = io.BytesIO() res = make_request("getChat", toke, chat_id=chat_id)["result"] try: if "photo" not in res: Log.d("Chat %s probably has no photo" % chat_id) return None file_id = res["photo"]["big_file_id"] if not file_id: Log.d("Non è stato possibile recuperare la propic") return None x = getFile(toke, file_id, out=x) x.seek(0) return x except Exception as err: Log.e( "Non è stato possibile recuperare l'immagine di profilo di %s: %s" % (chat_id, err)) file_id = None return file_id
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 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 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"