class WorkerBot: def __init__(self): self.whatsapp = None self.bot = Bot() self.log_web = [] self.log_info = {} self.init() def init(self): self.whatsapp = WhatsappApi() self.bot.restart() self.log_web = [] self.log_info = {} clear_log() def run(self): set_forever() while get_keep_running(): for message in self.whatsapp.get_messages(restart_index=True): chat_id = message["chatId"] name = message["senderName"] text = message["body"] tt = text if "media/" in tt: tt = f'<a href="{tt}">{tt}</a>' self.add_log_web(f'Answer "{tt}" received from {name}') self.add_log_info(chat_id, name, text, is_question=False) question = self.bot.receive_message(chat_id, name, text) response = self.whatsapp.send_message(chat_id, question) self.add_log_web(f'Question "{question}" sent to {name}') self.add_log_info(chat_id, name, question) self.bot.export_results() self.restart() def add_log_web(self, text): print(text) self.log_web.append(text) file = open(FILE_LOG_WEB, 'w') json.dump(self.log_web, file) def add_log_info(self, chat_id, name, text, is_question=True): if chat_id in self.log_info: if is_question: self.log_info[chat_id]["questions"].append(text) else: self.log_info[chat_id]["answers"].append(text) else: self.log_info[chat_id] = { "name": name, "text": text, "questions": [], "answers": [] } file = open(FILE_LOG_INFO, 'w') json.dump(self.log_info, file) def restart(self): f = open(FILE_FOREVER, "w") f.write("0") f.close() self.init() set_forever() self.run()
def export(): bot = Bot() bot.export_results() return 'exported'