def chosen_owns(update): user_id = update.effective_user.id try: user = Own.select().where(Own.user == user_id)[Show.get(user_id=user_id).owns or 0] except IndexError: user, created = Own.get_or_create(user=user_id) return user
def save_user_data(update, context): """callbackQuery from reject. save user data""" log.info(log_msg(update)) user = chosen_owns(update) if not user.updated: text = 'В базу ДОБАВЛЕН:\n' else: text = 'В базе ОБНОВЛЕН:\n' if update.callback_query.data == '_apart_reject': user_mode = Show.get(user_id=update.effective_user.id) user_mode.msg_apart_mode = False user.apartment = None user_mode.save() update.callback_query.message.reply_text( text='Квартиру не сохраняем пока что.') user.updated = datetime.now().strftime('%y.%m.%d %H:%M:%S.%f')[:-4] user.save() # TODO: properly do user_created_report # user_created_report(update, context, created_user=user, text=text) new_neighbor_report(update, context, created_user=user) reply_markup = InlineKeyboardMarkup( [[InlineKeyboardButton('Меню', callback_data='_menu')]]) update.callback_query.message.reply_text(text="Данные сохранены.", parse_mode=ParseMode.HTML, reply_markup=reply_markup)
def section_kbd(update, _): user_query = Show.get(user_id=update.effective_user.id) user_query.house = int(update.callback_query.data[-2:]) user_query.save() keyboard = [[ InlineKeyboardButton('Подъезд №1', callback_data='p_s1'), InlineKeyboardButton('Подъезд №2', callback_data='p_s2') ], [ InlineKeyboardButton('Подъезд №3', callback_data='p_s3'), InlineKeyboardButton('Подъезд №4', callback_data='p_s4') ], [ InlineKeyboardButton('Показать всех в доме?', callback_data='show_this_house') ]] if user_query.house == 87: del keyboard[1:3] reply_markup = InlineKeyboardMarkup(keyboard) update.callback_query.message.reply_text('Какой подъезд показать?', reply_markup=reply_markup) update.callback_query.answer()
def save_user_data(bot, update): """callbackQuery handler. pattern: ^_apart_reject$|^_section_reject$ AND integer text handler""" log.info(log_msg(update)) if update.callback_query: update.callback_query.answer() user = chosen_owns(update) user_mode = Show.get(user_id=update.effective_user.id) text = f'В базе {"ОБНОВЛЕН" if user.updated else "СОЗДАН"} пользователь:\n' if user_mode.msg_apart_mode and update.message: apartment = int(update.message.text) user.apartment = apartment else: if update.callback_query.data == '_apart_reject': user.apartment = None user.updated = datetime.now().strftime('%y.%m.%d %H:%M:%S.%f')[:-4] user.save() user_mode.msg_apart_mode = False user_mode.save() user_created_report(bot, update, created_user=user, text=text) new_neighbor_report(bot, update, created_user=user) text_success = '<b>Дякую, Ваші дані збережені</b>. Бажаєте подивитись сусідів?' bot.sendMessage(text=text_success, chat_id=update.effective_user.id, parse_mode=ParseMode.HTML) menu_kbd(bot, update) prepared_data = prepare_data() make_pie(prepared_data) make_bars(prepared_data)
def show_house(bot, update): """ """ log.info(log_msg(update)) update.callback_query.answer() reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('Меню', callback_data='_menu')]]) if update.callback_query.data == 'show_this_house': # if user want see selected house user_query = Show.get(user_id=update.effective_user.id) else: # if user want see own house and have one user_query = chosen_owns(update) neighbors = [] sections = Own.select(Own.section).where(Own.house == user_query.house, Own.section).distinct().order_by( Own.section) query = Own.select().where(Own.house == user_query.house, Own.section).order_by(Own.floor) for i in sections: neighbors.append(f'\n{"📭 <b>Секція".rjust(30, " ")} {i.section}</b>\n') for user in query.where(Own.section == i.section): neighbors.append(f'{user.user} {user}\n') show_list = (f'<b>Мешканці будинку № {user_query.house}</b>:\n' + '{}' * len(neighbors)).format(*neighbors) if len(show_list) < 6200: bot.sendMessage(chat_id=update.effective_user.id, parse_mode=ParseMode.HTML, text=show_list, reply_markup=reply_markup) else: part_1, part_2, part_3 = show_list.partition('📭 <b>Секція 4'.rjust(30, ' ') + '</b>' + '\n') bot.sendMessage(chat_id=update.effective_user.id, parse_mode=ParseMode.HTML, text=part_1[:-2]) # to do: remove "." from 2nd msg. Without that dot, rjust not works bot.sendMessage(chat_id=update.effective_user.id, parse_mode=ParseMode.HTML, text='.' + part_2 + part_3, reply_markup=reply_markup)
def show_section(update, _, some_section=False): """Here need some documentation""" # TODO: rework that func completely log.info(log_msg(update)) reply_markup = InlineKeyboardMarkup( [[InlineKeyboardButton('Меню', callback_data='_menu')]]) if not some_section: user_query = chosen_owns(update) else: user_query = Show.get(user_id=update.effective_user.id) query = User.select().where(User.house == user_query.house, User.section == user_query.section).order_by( User.floor) neighbors = [str(user) + '\n' for user in query] show_list = ('<b>Жители подъезда № ' + str(user_query.section) + ' Дома № ' + str(user_query.house) + '</b>:\n' + '{}' * len(neighbors)).format(*neighbors) update.message.reply_text(parse_mode=ParseMode.HTML, disable_web_page_preview=True, text=show_list, reply_markup=reply_markup) update.callback_query.answer()
def notifications_kbd(update, _): """callbackQuery handler. pattern:^notifications$. Show notifications keyboard settings""" log.info(log_msg(update)) keyboard = [[ InlineKeyboardButton('В моем доме 🏠', callback_data='_notify_house') ], [ InlineKeyboardButton('В моем подъезде 🔢', callback_data='_notify_section') ], [ InlineKeyboardButton('Выключить оповещения 🔕', callback_data='_notify_OFF') ], [InlineKeyboardButton('Меню', callback_data='_menu')]] reply_markup = InlineKeyboardMarkup(keyboard) user = Show.get(user_id=update.effective_user.id) _dict = { None: 'Выключено', '_notify_OFF': 'Выключено', '_notify_section': 'В моем подъезде 🔢', '_notify_house': 'В моєм доме 🏠' } text = f'Сейчас оповещения установлены в режим\n' \ f'<b>{_dict[user.notification_mode]}</b>\nПолучать оповещения ' \ f'когда появится новый сосед:' update.message.reply_text(parse_mode=ParseMode.HTML, text=text, reply_markup=reply_markup, message_id=update.effective_message.message_id) update.callback_query.answer()
def notifications_kbd(bot, update): """callbackQuery handler. pattern:^notifications$. Show notifications keyboard settings""" log.info(log_msg(update)) keyboard = [[ InlineKeyboardButton('В моєму будинку 🏠', callback_data='_notify_house') ], [ InlineKeyboardButton('В моєму під\'їзді 🔢', callback_data='_notify_section') ], [ InlineKeyboardButton('Вимкнути сповіщення 🔕', callback_data='_notify_OFF') ], [InlineKeyboardButton('Меню', callback_data='_menu')]] reply_markup = InlineKeyboardMarkup(keyboard) user = Show.get(user_id=update.effective_user.id) _dict = { None: 'Вимкнено', '_notify_OFF': 'Вимкнено', '_notify_section': 'В моєму під\'їзді 🔢', '_notify_house': 'В моєму будинку 🏠' } text = f'Зараз сповіщення встановленні в режим\n' \ f'<b>{_dict[user.notification_mode]}</b>\nОтримувати сповіщення коли з\'явиться новий сусід:' bot.editMessageText(chat_id=update.effective_user.id, parse_mode=ParseMode.HTML, text=text, reply_markup=reply_markup, message_id=update.effective_message.message_id) update.callback_query.answer()
def show_section(bot, update, some_section=False): """Here need some documentation""" log.info(log_msg(update)) reply_markup = InlineKeyboardMarkup( [[InlineKeyboardButton('Меню', callback_data='_menu')]]) if not some_section: user_query = chosen_owns(update) else: user_query = Show.get(user_id=update.effective_user.id) query = User.select().where(User.house == user_query.house, User.section == user_query.section).order_by( User.floor) neighbors = [str(user) + '\n' for user in query] show_list = ('<b>Мешканці під\'їзду № ' + str(user_query.section) + ' Будинку № ' + str(user_query.house) + '</b>:\n' + '{}' * len(neighbors)).format(*neighbors) bot.sendMessage(chat_id=update.effective_user.id, parse_mode=ParseMode.HTML, disable_web_page_preview=True, text=show_list, reply_markup=reply_markup) update.callback_query.answer()
def save_user_data(bot, update): """callbackQuery from reject. save user data""" log.info(log_msg(update)) user = chosen_owns(update) if not user.updated: text = 'В базу ДОДАНО сусіда:\n' else: text = 'В базі ОНОВЛЕНО сусіда:\n' if update.callback_query.data == '_apart_reject': user_mode = Show.get(user_id=update.effective_user.id) user_mode.msg_apart_mode = False user_mode.save() user.apartment = None user.updated = datetime.now().strftime('%y.%m.%d %H:%M:%S.%f')[:-4] user.save() update.callback_query.answer() user_created_report(bot, update, created_user=user, text=text) new_neighbor_report(bot, update, created_user=user) bot.sendMessage( chat_id=update.effective_user.id, parse_mode=ParseMode.HTML, text='<b>Дякую, Ваші дані збережені</b>. Бажаєте подивитись сусідів?') start_command(bot, update)
def section_kbd(bot, update): user_query = Show.get(user_id=update.effective_user.id) user_query.house = int(update.callback_query.data[-2:]) user_query.save() keyboard = [[ InlineKeyboardButton('П-зд №1', callback_data='p_s1'), InlineKeyboardButton('П-зд №2', callback_data='p_s2') ], [ InlineKeyboardButton('П-зд №3', callback_data='p_s3'), InlineKeyboardButton('П-зд №4', callback_data='p_s4') ], [ InlineKeyboardButton('П-зд №5', callback_data='p_s5'), InlineKeyboardButton('П-зд №6', callback_data='p_s6') ], [ InlineKeyboardButton('Показати всіх в цьому будинку? ', callback_data='show_this_house') ]] if user_query.house == 87: del keyboard[1:3] reply_markup = InlineKeyboardMarkup(keyboard) update.callback_query.message.reply_text('Який під\'їзд показати? ', reply_markup=reply_markup) update.callback_query.answer()
def chosen_owns(update): user_id = update.effective_user.id try: user = User.select().where( User.user_id == user_id)[Show.get(user_id=user_id).owns or 0] except IndexError: user = User.select().where(User.user_id == user_id)[0] return user
def save_params(update, context): """callbackQuery from section_kbd(). save params to db table""" log.info(log_msg(update)) user_query = Show.get(user_id=update.effective_user.id) user_query.section = int(update.callback_query.data[3]) user_query.save() some_section = True show_section(update, context, some_section) update.callback_query.answer()
def get_show_settings(show_id): s = Show.get(id=show_id) c = {'show': s, 'settings': settings, 'choice': 'saved_show'} if request.method == 'POST': s.folder = request.form['folder'] s.filters = request.form['filters'] s.use_season_folders = 'use_season_folders' in request.form s.save() msg = 'Successfully saved settings' return redirect('/show/{id}/?msg={msg}'.format(id=show_id, msg=msg)) return render_template('show_add.html', **c)
def notifications_save(bot, update): """callbackQuery handler. pattern: from notifications_kbd func. Save notifications settings to db""" log.info(log_msg(update)) update.callback_query.answer() reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('Меню', callback_data='_menu')]]) user = Show.get(user_id=update.effective_user.id) user.notification_mode = update.callback_query.data user.save() bot.editMessageText('<b>Ок!</b> Налаштування збережено', reply_markup=reply_markup, parse_mode=ParseMode.HTML, message_id=update.effective_message.message_id, chat_id=update.effective_chat.id, )
def api(**kwargs): args = [] action = request.args.get('action', '') def scan_show(show): return show.check_download_status() def delete_show(show): show.delete_instance(recursive=True) def update_show(show): return utils.save_show(tvdb_id=show.tvdb_id) def episode_mark_skipped(episode): episode.status = models.SKIPPED episode.save() def episode_mark_wanted(episode): episode.status = models.WANTED episode.save() def episode_mark_downloaded(episode, location): episode.status = models.DOWNLOADED episode.location = location episode.save() actions = { 'scan': scan_show, 'delete': delete_show, 'update': update_show, 'episode_mark_wanted': episode_mark_wanted, 'episode_mark_skipped': episode_mark_skipped, 'episode_mark_downloaded': episode_mark_downloaded, 'background_search': utils.process_search_torrent, 'background_download': utils.process_download_torrent, 'background_update': utils.process_check_new_episodes, 'background_status': utils.process_check_downloaded } if not action in actions: msg = 'No action named {}'.format(action) return jsonify(stat='fail', msg=msg, result=[]) if 'show_id' in request.args: args.append(Show.get(id=request.args['show_id'])) if 'episode_id' in request.args: args.append(Episode.get(id=request.args['episode_id'])) if 'location' in request.args: args.append(request.args['location']) res = actions[action](*args) return jsonify(stat='ok', result=res)
def get_show_settings(show_id): s = Show.get(id=show_id) c = { 'show': s, 'settings': settings, 'choice': 'saved_show' } if request.method == 'POST': s.folder = request.form['folder'] s.filters = request.form['filters'] s.use_season_folders = 'use_season_folders' in request.form s.save() msg = 'Successfully saved settings' return redirect('/show/{id}/?msg={msg}'.format(id=show_id, msg=msg)) return render_template('show_add.html', **c)
def notifications_save(update, _): """callbackQuery handler. pattern: from notifications_kbd func. Save notifications settings to db""" log.info(log_msg(update)) reply_markup = InlineKeyboardMarkup( [[InlineKeyboardButton('Меню', callback_data='_menu')]]) user = Show.get(user_id=update.effective_user.id) user.notification_mode = update.callback_query.data user.save() update.message.reply_text(text='Ок! Настройки сохранены', chat_id=update.effective_chat.id, parse_mode=ParseMode.HTML, message_id=update.effective_message.message_id, reply_markup=reply_markup) update.callback_query.answer()
def set_apartment_kbd(bot, update): """func show message with ask to tell its own appartment""" log.info(log_msg(update)) update.callback_query.answer() floor = [s for s in list(update.callback_query.data) if s.isdigit()] floor = int(''.join(floor)) user = chosen_owns(update) user.floor = floor user.save() user_mode = Show.get(user_id=update.effective_user.id) user_mode.msg_apart_mode = True user_mode.save() text = 'В якій ви квартирі? 🚪 \nНапишіть в повідомленні номер квартири, або нажміть кнопку відмови:' keyboard = [[InlineKeyboardButton('Не хочу вказувати квартиру', callback_data='_apart_reject')]] reply_markup = InlineKeyboardMarkup(keyboard) update.callback_query.message.reply_text(text=text, reply_markup=reply_markup)
def owns_selected(bot, update): """save params to db""" log.info(log_msg(update)) update.callback_query.answer() view_edit = update.callback_query.data[-13:] owns = [s for s in list(update.callback_query.data) if s.isdigit()] owns = int(''.join(owns)) user = Show.get(user_id=update.effective_user.id) user.owns = owns user.save() if view_edit == 'view_my_house': show_house(bot, update) elif view_edit == 'view_my_secti': show_section(bot, update) else: user = Own.select().where(Own.user == update.effective_user.id)[owns] text = f'Змінюємо Ваші дані:\n{user.setting_str}\nВ якому Ви будинку ? 🏠 :' set_houses_kbd(bot, update, text)
def owns_selected(update, context): """save params to db""" log.info(log_msg(update)) view_edit = update.callback_query.data[-13:] owns = [s for s in list(update.callback_query.data) if s.isdigit()] owns = int(''.join(owns)) user = Show.get(user_id=update.effective_user.id) user.owns = owns user.save() if view_edit == 'view_my_house': show_house(update, context) elif view_edit == 'view_my_secti': show_section(update, context) else: user = User.select().where( User.user_id == update.effective_user.id)[owns] text = 'Изменяем ваши данные:\n' + user.setting_str( ) + '\nВ каком вы доме?' set_houses_kbd(update, context, text) update.callback_query.answer()
def show_house(update, _): """callbackQuery handler """ # TODO: rework that func completely log.info(log_msg(update)) reply_markup = InlineKeyboardMarkup( [[InlineKeyboardButton('Меню', callback_data='_menu')]]) if update.callback_query.data == 'show_this_house': # if user want see selected house user_query = Show.get(user_id=update.effective_user.id) else: # if user want see own house and have one user_query = chosen_owns(update) neighbors = [] sections = User.select(User.section).where( User.house == user_query.house).distinct().order_by(User.section) for i in sections: neighbors.append('\n' + '📭 <b>Подъезд '.rjust(30, ' ') + str(i.section) + '</b>' + '\n') for user in User.select().where(User.house == user_query.house, User.section == i.section).order_by( User.floor): neighbors.append(str(user) + '\n') show_list = ('<b>Жители дома №' + str(user_query.house) + '</b>:\n' + '{}' * len(neighbors)).format(*neighbors) if len(show_list) < 6200: update.message.reply_text(parse_mode=ParseMode.HTML, text=show_list, reply_markup=reply_markup) else: part_1, part_2, part_3 = \ show_list.partition('📭 <b>Подъезд №4'.rjust(30, ' ') + '</b>' + '\n') update.message.reply_text(parse_mode=ParseMode.HTML, text=part_1[:-2]) # to do: remove "." from 2nd msg. Without that dot doesn't work update.message.reply_text(parse_mode=ParseMode.HTML, text='.' + part_2 + part_3, reply_markup=reply_markup) update.callback_query.answer()
def apartment_save(update, context): """integer text handler""" log.info(log_msg(update)) user_mode = Show.get(user_id=update.effective_user.id) if user_mode.msg_apart_mode: apartment = int(update.message.text) user = chosen_owns(update) user.apartment = apartment if not user.updated: text = 'В базу ДОБАВЛЕН:\n' else: text = 'В базе ОБНОВЛЕН:\n' user.updated = datetime.now().strftime('%y.%m.%d %H:%M:%S.%f')[:-4] user.save() user_mode.save() user_mode.msg_apart_mode = False new_neighbor_report(update, context, created_user=user) reply_markup = InlineKeyboardMarkup( [[InlineKeyboardButton('Меню', callback_data='_menu')]]) update.callback_query.message.reply_text(text="Данные сохранены.", parse_mode=ParseMode.HTML, reply_markup=reply_markup)
def section_kbd(bot, update): """callbackQuery from houses_kbd(). show keyboard to chose section to show""" log.info(log_msg(update)) update.callback_query.answer() user_query = Show.get(user_id=update.effective_user.id) user_query.house = int(update.callback_query.data[3]) user_query.save() keyboard = [[InlineKeyboardButton('Секція 1', callback_data='p_s1'), InlineKeyboardButton('Секція 2', callback_data='p_s2')], [InlineKeyboardButton('Секція 3', callback_data='p_s3'), InlineKeyboardButton('Секція 4', callback_data='p_s4')], [InlineKeyboardButton('Секція 5', callback_data='p_s5'), InlineKeyboardButton('Секція 6', callback_data='p_s6')], [InlineKeyboardButton('Показати всіх в цьому будинку 🏠', callback_data='show_this_house')]] # if selected house 3 or 4, so no 6s section there. delete it from keyboard if user_query.house in [3, 4]: del keyboard[-2][1] reply_markup = InlineKeyboardMarkup(keyboard) bot.editMessageText('Яку секцію показати ? 🔢 :', reply_markup=reply_markup, message_id=update.effective_message.message_id, chat_id=update.effective_user.id)
def apartment_save(bot, update): """integer text handler""" log.info(log_msg(update)) user_mode = Show.get(user_id=update.effective_user.id) text_success = '<b>Дякую, Ваші дані збережені</b>. Бажаєте подивитись сусідів?' if user_mode.msg_apart_mode: apartment = int(update.message.text) user = chosen_owns(update) user.apartment = apartment if not user.updated: text = 'В базу ДОДАНО сусіда:\n' else: text = 'В базі ОНОВЛЕНО сусіда:\n' user.updated = datetime.now().strftime('%y.%m.%d %H:%M:%S.%f')[:-4] user.save() bot.sendMessage(text=text_success, chat_id=update.effective_user.id, parse_mode=ParseMode.HTML) user_mode.msg_apart_mode = False user_mode.save() user_created_report(bot, update, created_user=user, text=text) new_neighbor_report(bot, update, created_user=user) menu_kbd(bot, update)
def set_apartment_kbd(update, _): """func show message with ask to tell its own apartment""" log.info(log_msg(update)) update.callback_query.answer() floor = [s for s in list(update.callback_query.data) if s.isdigit()] floor = int(''.join(floor)) user = chosen_owns(update) user.floor = floor user.save() user_mode = Show.get(user_id=update.effective_user.id) user_mode.msg_apart_mode = True user_mode.save() text = 'В какой квартире? \nНапишите номер в сообщении или нажмите кнопку ниже.' keyboard = [[ InlineKeyboardButton('Не хочу указывать квартиру', callback_data='_apart_reject') ]] reply_markup = InlineKeyboardMarkup(keyboard) # TODO: add proper return after flat was added update.callback_query.message.reply_text(text=text, reply_markup=reply_markup)
def get_show(show_id): c = { 'show': Show.get(id=show_id), 'episodes': Episode.select().join(Show).where(Show.id == show_id) } return render_template('show.html', **c)