def view_private_dialog(dialog=dict.fromkeys('dialog_id', 'members')): clear_console() dialog_history = api.get_dialog_history(peer=dialog['dialog_id'], peer_type='user')['items'] for message in reversed(dialog_history): message_author = dialog['members']['first_name'] if message[ 'from_id'] == dialog['members']['id'] else 'Me' print_message = message['body'] if message[ 'read_state'] else message['body'] + ' (unread)' print(message_author + ':' + '\n ' + print_message) if message['id'] == dialog_history[0]['id']: command = input("Answer: ") if command not in commands: if command: api.send_message(receiver=dialog['dialog_id'], message_text=command, receiver_type='user') view_private_dialog(dialog) else: list_dialogs() else: if command == '/refresh': view_private_dialog(dialog) elif command == '/back': list_dialogs() elif command == '/exit': app_exit()
def update(self, event, vk, spl): if len(spl) < 3: send_message(event, vk, message=self.full_help) return if len(spl) > 3: ScheduleData.homework[ScheduleData.get_lesson_number(spl[2])] = event.text.replace("/homework ", "", 1)\ .replace(spl[1], "", 1).replace(spl[2], "", 1) send_message(event, vk, message="Добавил") return if len(spl) == 3: if "reply_message" in event.message_data and "text" in event.message_data["reply_message"]\ and event.message_data["reply_message"]["text"] != "": ScheduleData.homework[ScheduleData.get_lesson_number(spl[2])] \ = event.message_data["reply_message"]["text"] send_message(event, vk, message="Добавил") elif "fwd_messages" in event.message_data and len(event.message_data["fwd_messages"]) != 0 \ and "text" in event.message_data["fwd_messages"][0] \ and event.message_data["fwd_messages"][0]["text"] != "": ScheduleData.homework[ScheduleData.get_lesson_number(spl[2])] \ = event.message_data["fwd_messages"][0]["text"] send_message(event, vk, message="Добавил") else: send_message(event, vk, message=self.full_help)
def delete(self, event, vk, spl): if len(spl) < 3: send_message(event, vk, message=self.full_help) return ScheduleData.homework[ScheduleData.get_lesson_number(spl[2])] = None send_message(event, vk, message="Не хочется делать, да?")
def on_msg_received(msg, matches): chat = msg["chat"]["id"] is_get = "get" in matches.group(1) content = matches.group(2) if not is_get: try: if content: item, value = content.split(", ") save_item(item.trim(), value) print(f"{item} = {value}") send_message(chat, f"ok sauvei aq q {item} = {value}", parse_mode="") else: send_message( chat, "a veloh vc precisiasa m e falala qqq vc ke grava.....") except Exception as e: print(f"{e}") send_message(chat, "pora n é assim q usa carai pora sifude") else: if content: text = get_item(content) send_message(chat, text, parse_mode="") else: for item in get_all_items(): send_message(chat, item, parse_mode="")
def on_msg_received(msg): """ Callback pra quando uma mensagem é recebida. """ if is_authorized(msg): log(msg) tipo = msg_type(msg) if tipo == "text": plugin_match, matches = msg_matches(msg["text"]) if plugin_match is not None and matches is not None: loaded = importlib.import_module("plugins." + plugin_match) try: loaded.on_msg_received(msg, matches) except: # Hardcodando aviso de erro. Não serve pra prevenir. exc_type, exc_value, exc_traceback = sys.exc_info() printable = repr(traceback.format_exception(exc_type, exc_value, exc_traceback)) for sudoer in config.config["sudoers"]: api.send_message(sudoer, "ME CAPOTARO AQUI PORRA \n\n" + printable) raise elif tipo != "text" and tipo != "outra coisa": # Garante as estatísticas para o que não for texto stt = importlib.import_module("plugins.stats") stt.do_statistics(msg) # Eu provavelmente deveria fazer um tratamento de erros aqui, mas o # plugin em questão é meio que parte do core, então tanto faz... else: log("Mensagem não autorizada de " + msg["from"]["first_name"] + " (" + str(msg["from"]["id"]) + ")")
def run(self): while True: sleep_to_hour(7) now = datetime.today() if now.isocalendar()[2] == 7: continue for i, value in enumerate(self.time_schedule): if now.hour < value[0] or now.hour == value[ 0] and now.minute < value[1]: sleep_to_hour(value[0]) sleep(value[1] * 60) now = datetime.today() lesson = ScheduleData.week.days[now.isocalendar()[2] - 1].lessons[i] if lesson.lesson_id != -1: lesson_name = list_of_lesson_names[lesson.lesson_id][0] ScheduleData.homework[lesson.lesson_id] = None send_message( self.event, self.vk, message=f"В {self.time_schedule[i][0]}:" f"{self.time_schedule[i][1] + 20} " f"будет {'лекция' if lesson.is_lecture else 'семинар'} по {lesson_name} " f"в кабинете {lesson.classroom}")
def on_msg_received(msg, matches): chat = msg["chat"]["id"] try: reddit = praw.Reddit(client_id="aEURITEt-YUgBQ", client_secret="Bd1cZ0OaS15znwNwKSCDtWH2-pg", user_agent="ed_reborn") entries = [] for submission in reddit.subreddit('FiftyFifty').hot(limit=1000): entries.append({"title": submission.title, "url": submission.url}) chosen = choice(entries) print(f"[{chosen['title']}]({chosen['url']})") title = chosen['title'].replace("(", "{").replace(")", "}").replace( "[", "{").replace("]", "}") url = chosen['url'] with open("/var/www/html/fiftyfifty", "w") as f: f.write(f"""<script language="JavaScript"> window.location="{url}"; </script>""") send_message(chat, f"[{title}](https://lucasberti.me/fiftyfifty", disable_web_page_preview="true") except: send_message(chat, "ops deu mreda....")
def on_msg_received(msg, matches): opt.chat_id = msg["chat"]["id"] # opt.log_msg_id = api.send_message(opt.chat_id, "esperando algo acontecer...")["result"]["message_id"] # opt.scoreboard_msg_id = api.send_message(opt.chat_id, "esperando scoreboard...")["result"]["message_id"] if re.match("(?:stop|parar?|cancelar?)", matches.group(1)): if opt.is_running: perform_exit() return if matches.group(2) is not None: if re.match("(?:simples?|clean|resumido)", matches.group(1)): opt.simple_mode = True thread = threading.Thread(name="hltvThread", target=get_infos_from_match, args=(matches.group(2), )) # get_infos_from_match(matches.group(2)) else: thread = threading.Thread(name="hltvThread", target=get_infos_from_match, args=(matches.group(1), )) # get_infos_from_match(matches.group(1)) opt.scoreboard_msg_id = api.send_message( opt.chat_id, "esperando scoreboard...")["result"]["message_id"] # Simple Mode só não vai ter log, mas scoreboard continua sendo atualizado. if not opt.simple_mode: opt.log_msg_id = api.send_message( opt.chat_id, "esperando algo acontecer...")["result"]["message_id"] thread.start()
def on_message(self, event, vk): message = Message(event) parse_text = message.text.replace("/echo ", "", 1) if message.is_empty("/echo"): send_message( event, vk, message="И как мне предлагаешь повторить пустое сообщение?") elif parse_text == "ping": send_message(event, vk, message="pong") elif parse_text == "жив?": send_message(event, vk, message="да, жив") elif parse_text == "": send_message(event, vk, attachment=message.attachments, forward_messages=message.forward_messages, reply_to=message.reply_to) else: send_message(event, vk, message=f'{parse_text}', attachment=message.attachments, forward_messages=message.forward_messages, reply_to=message.reply_to)
def on_msg_received(msg): """ Callback pra quando uma mensagem é recebida. """ if is_authorized(msg): log(msg) if msg_type(msg) == "text": plugin_match, matches = msg_matches(msg["text"]) if plugin_match is not None and matches is not None: loaded = importlib.import_module("plugins." + plugin_match) try: loaded.on_msg_received(msg, matches) except: # Hardcodando aviso de erro. Não serve pra prevenir. exc_type, exc_value, exc_traceback = sys.exc_info() printable = repr( traceback.format_exception(exc_type, exc_value, exc_traceback)) for sudoer in config.config["sudoers"]: api.send_message( sudoer, "ME CAPOTARO AQUI PORRA \n\n" + printable) raise else: log("Mensagem não autorizada de " + msg["from"]["first_name"] + " (" + str(msg["from"]["id"]) + ")")
def on_msg_received(msg, matches): chat = msg["chat"]["id"] user = msg["from"]["id"] send_message(chat, "perai vamo ve....") send_chat_action(chat, "typing") is_looking_for_operators = False player = None if matches.group(1): if matches.group(1) == "op": is_looking_for_operators = True if user in PLAYERS: player = PLAYERS[user] else: player = matches.group(1) else: if user in PLAYERS: player = PLAYERS[user] if player is not None: if is_looking_for_operators: stats = get_operator_stats(player) else: stats = get_stats(player) else: stats = "vc nem tem r6 kkkkk" print(stats) send_message(chat, stats)
def on_msg_received(msg, matches): url = "https://s.dicio.com.br/" + matches.group(1) + ".jpg" image = requests.get(url) if image: send_photo(msg["chat"]["id"], url, "taki qq e " + matches.group(1)) else: send_message(msg["chat"]["id"], "n sei qqe iso n")
def on_msg_received(msg, matches): with ts3.query.TS3Connection("localhost") as ts3conn: ts3conn.login(client_login_name="serveradmin", client_login_password=os.environ["TS3PASS"]) message = view(ts3conn, sid=1) send_message(msg["chat"]["id"], "```" + message + "```") send_message("14160874", "ts")
def command_settile(*args, player=None): if (len(args) != 4): api.send_message('Usage: /settile <x> <y> <tile_id>', color=api.RED, player=player) else: api.world.set_tile(int(args[1]), int(args[2]), args[3]) api.send_message(f'Tile placed at {args[1]} {args[2]}', player=player)
def on_message(self, event, vk): spl = event.text.split() if len(spl) < 2: send_message(event, vk, message=self.full_help) elif spl[1] == "сбросить": self.reset(event, vk, spl) else: super().on_message(event, vk)
def delete(self, event, vk, spl): if len(spl) < 4: send_message(event, vk, message=self.full_help) return ScheduleData.week.days[ScheduleData.get_day_number( spl[2])].lessons[int(spl[3]) - 1] = Lesson(-1, None, None) send_message(event, vk, message="Удалил, а зря!")
def run(self, args_list, auth_user, key): if len(args_list) != 1: raise WrongNumberArguments('Need to provide a target username ' + \ 'and no more.') to = args_list[0] body = input('Message body: ') api.send_message(to, body, self._hosts, auth_user, key) return 'Message probably sent'
def on_msg_received(msg, matches): img = getValidLink(matches.group(1)) send_message(msg["chat"]["id"], "AE pora ta aki a imag......") sent = send_photo(msg["chat"]["id"], img["link"], img["snippet"]) while sent["ok"] == "false": log("sendPhoto retornou false, rentando novamente...") img = getValidLink(matches.group(1)) sent = send_photo(msg["chat"]["id"], img["link"], img["snippet"])
def Network_error(self, data): if (self.game.connecting or self.game.connected): self.game.connecting = False if (type(data['error']) == ConnectionRefusedError): api.send_message('[{}] {}'.format(data['error'].errno, data['error'].strerror), color=(255, 50, 70)) else: api.send_message('[{}] {}'.format(*data['error']), color=(255, 50, 70)) connection.Close()
def update(self, event, vk, spl): if len(spl) < 6: send_message(event, vk, message=self.full_help) return ScheduleData.week.days[ScheduleData.get_day_number( spl[2])].lessons[int(spl[3]) - 1] = Lesson( ScheduleData.get_lesson_number(spl[5]), spl[4], len(spl) > 6 and spl[6] == "лекция") send_message(event, vk, message="Сделал")
def on_msg_received(msg, matches): chat = msg["chat"]["id"] print("O que chegou para mim: " + matches[1]) # Implementação crua if matches[1] == "stats": result = return_statistics(chat) send_message(chat, result) elif matches[1] == "fullstats": result = return_full_statistics(chat) send_message(chat, result)
def show_day(event, vk, spl): day_name = spl[2] message = f"Расписание на {day_name}\n" is_found = False for i, lesson in enumerate(ScheduleData.week.days[ ScheduleData.get_day_number(day_name)].lessons): if lesson.lesson_id != -1: message += f"Пара: {i + 1}, аудитория: {lesson.classroom}, предмет: " \ f"{list_of_lesson_names[lesson.lesson_id][0]}, {'не ' if not lesson.is_lecture else ''}лекция\n" is_found = True if is_found: send_message(event, vk, message=message)
def on_message(self, event, vk): spl = event.text.split() if len(spl) < 2: send_message(event, vk, message="И как я тебе должен сделать - ничего??") return send_message( event, vk, message=f"Я сделаю {spl[1]}, за {random.randint(100, 2000)} ))0)")
def on_message(self, event, vk): spl = event.text.split() if len(spl) < 2: send_message(event, vk, message=self.full_help) elif spl[1] == "добавить" or spl[1] == "изменить": self.update(event, vk, spl) elif spl[1] == "удалить": self.delete(event, vk, spl) elif spl[1] == "показать": self.show(event, vk, spl) else: send_message(event, vk, message=self.full_help)
def on_message(self, event, vk): message = Message(event) spl = message.text.split() if len(spl) < 3 and message.is_empty_except_text(): send_message( event, vk, message="И как мне предлагаешь запомнить пустое сообщение?") return dump = message.dump() try: if spl[1].find("/") != -1: send_message(event, vk, message="Иньекцию захотел сделать? А вот хрен!") return with open(f"save/{spl[1]}", "wb") as f: f.write(dump) send_message(event, vk, message="Я запомнил!") except IOError: send_message(event, vk, message="Невалидный ключ")
def run_ed(msg): chat = msg["chat"]["id"] msg_text = msg["text"] pattern = re.compile("^(?:[Ee]d,? (.*))|(?:(.*),? [Ee]d\??)$") match = pattern.search(msg_text) if match: if match.group(1) is not None: response = talk_to_ed(match.group(1)) elif match.group(2) is not None: response = talk_to_ed(match.group(2)) api.send_message(chat, response)
def on_message(self, event, vk): message = Message(event) if message.is_empty("/remind"): send_message( event, vk, message="И как мне предлагаешь вспомнить по пустому ключу?") return spl = message.text.split()[1] if spl.find("/") != -1: send_message(event, vk, message="Иньекцию захотел сделать? А вот хрен!") return if not isfile(f"save/{spl}"): send_message(event, vk, message=f"Сообщение по ключу {spl} не найдено") return with open(f"save/{spl}", "rb") as f: message = Message.load(f.read()) send_message(event, vk, message=message.text.replace("/remember", "", 1).replace(spl, "", 1), attachment=message.attachments, forward_messages=message.forward_messages, reply_to=message.reply_to)
def resend_messages(self): if self.log_msg_id != 0: api.delete_message(self.chat_id, self.log_msg_id) log("reenviando log...") self.log_msg_id = api.send_message( self.chat_id, self.log_msg, parse_mode="")["result"]["message_id"] if self.scoreboard_msg_id != 0: api.delete_message(self.chat_id, self.scoreboard_msg_id) log('reenviando score...') self.scoreboard_msg_id = api.send_message( self.chat_id, self.scoreboard_msg, parse_mode="")["result"]["message_id"]
def reset(self, event, vk, spl): if len(spl) < 3: send_message(event, vk, message=self.full_help) return target_day = ScheduleData.get_day_number(spl[2]) iso = datetime.today().isocalendar() is_even_week = ( iso[1] - 1) % 2 == 0 if target_day < iso[2] - 1 else iso[1] % 2 == 0 ScheduleData.week.days[target_day] = default_days_even[target_day] \ if is_even_week else default_days_odd[target_day] send_message(event, vk, message="Сбросил")
def check_time(): reminders = load_reminders() for chat in reminders: for date in reminders[chat]: if float(date) < time.time(): send_message(chat, "ESTÀ NA HORA DE " + reminders[chat][date]) # print(reminders[chat][date]) reminders[chat].pop(date) save_reminders(reminders) break scheduler.enter(1, 1, check_time)