예제 #1
0
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
예제 #2
0
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)
예제 #3
0
def jubilee(bot, update, created_user):
    """Check if new added user is 'hero of the day' i.e some round number in db"""
    log.info(log_msg(update))
    celebration_count = [i for i in range(0, 2000, 50)]
    query = Own.select().where(Own.house, Own.section)

    check_list = [query.where(Own.house == i).count() for i in range(1, 5)]
    total = query.count()
    text = f'сусідів 🎇 🎈 🎉 🎆 🍹\nВітаємо\n{created_user.joined_str}'

    for count, house in enumerate(check_list, start=1):
        if house in celebration_count:
            x, created = Jubilee.get_or_create(house=count, count=house)
            if created:
                text = f'В будинку № {count} Вже зареєстровано {house} ' + text
                try:
                    bot.sendMessage(chat_id=-1001076439601, text=text, parse_mode=ParseMode.HTML)  # test chat
                except BadRequest:
                    bot.sendMessage(chat_id=-1001307649156, text=text, parse_mode=ParseMode.HTML)
                return

    if total in celebration_count:
        text = f'Вже зареэстровано {total} сусідів 🎇 🎈 🎉 🎆 🍹\nВітаємо\n{created_user.joined_str}'
        x, created = Jubilee.get_or_create(house=0, count=total)
        if created:
            try:
                bot.sendMessage(chat_id=-1001076439601, text=text, parse_mode=ParseMode.HTML)  # test chat
            except BadRequest:
                bot.sendMessage(chat_id=-1001307649156, text=text, parse_mode=ParseMode.HTML)
예제 #4
0
 def command_func(*args, **kwargs):
     bot, update = args
     if not Own.get_or_none(Own.house, Own.section, user=update.effective_user.id):
         if update.callback_query:
             update.callback_query.answer()
         return
     return func(bot, update, **kwargs)
예제 #5
0
def new_neighbor_report(bot, update, created_user):
    """Send message for users who enabled notifications"""
    log.info(log_msg(update))

    # query for users who set notifications as _notify_house
    query_params = Show.select(Show.user_id).where(Show.notification_mode == '_notify_house')
    query_users = Own.select(Own.user).where(Own.house == created_user.house)
    query = query_params & query_users
    # prevent telegram blocking spam
    for i, user in enumerate(query):
        if i % 29 == 0:
            time.sleep(1)
        try:
            bot.sendMessage(chat_id=user.user_id, parse_mode=ParseMode.HTML,
                            text=f'Новий сусід\n{created_user.joined_str}')
        except BadRequest as err:
            bot.sendMessage(chat_id=ADMIN_ID, text=f'failed to send notification for user {user.user_id} {err}',
                            parse_mode=ParseMode.HTML)

    # query for users who set notifications as _notify_section
    query_params = Show.select(Show.user_id).where(Show.notification_mode == '_notify_section')
    query_users = query_users.where(Own.section == created_user.section)
    query = query_params & query_users
    for i, user in enumerate(query):
        if i % 29 == 0:
            time.sleep(1)
        try:
            bot.sendMessage(chat_id=user.user_id, parse_mode=ParseMode.HTML,
                            text=f'Новий сусід\n{created_user.joined_str}')
        except BadRequest as err:
            bot.sendMessage(chat_id=ADMIN_ID, text=f'failed to send notification for user {user.user_id} {err}',
                            parse_mode=ParseMode.HTML)
예제 #6
0
def check_owns(bot, update):
    """check how many records for user in db"""
    log.info(log_msg(update))
    if not len(Own.select().where(Own.user == update.effective_user.id)) > 1:
        if update.callback_query.data == 'house_neighbors':
            show_house(bot, update)
            return
        elif update.callback_query.data == 'section_neighbors':
            show_section(bot, update)
            return
        else:
            if not Own.get_or_none(Own.user == update.effective_user.id, Own.house):
                text = 'В якому Ви будинку ? 🏠 :'
                set_houses_kbd(bot, update, text)
            else:
                text = f'Змінюємо Ваші дані:\n{Own.get(user=update.effective_user.id).setting_str}\nВ якому Ви будинку ? 🏠 :'
                set_houses_kbd(bot, update, text)
    # if more than 1 records for user, call func for select
    else:
        select_owns(bot, update)
예제 #7
0
    def answer(self, bot, update, show_list):
        if not Own.get_or_none(
                Own.house, Own.section, user=update.effective_user.id):
            for i in range(1, 6):
                show_list = show_list.replace(show_list.split('\n')[-i], '')
            show_list = show_list[:-5]

        bot.editMessageText(chat_id=update.effective_user.id,
                            parse_mode=ParseMode.HTML,
                            text=show_list,
                            message_id=update.effective_message.message_id,
                            reply_markup=self.reply_markup)
예제 #8
0
def prepare_data():
    """Create show_list (string) for statistic message, and pie_values (list) for chart"""
    log.info('this func has no update')

    query = Own.select().where(Own.house, Own.section)
    houses = query.select(Own.house).distinct().order_by(Own.house)
    total_users = UserName.select().count()

    # did users indicate their info
    intro_yes = Own.select(Own.user).where(Own.house, Own.section).distinct().count()
    intro_not = total_users - intro_yes
    introduced = {'Yes': intro_yes, 'No': intro_not}

    # last 3 joined users
    last_3_users = list(reversed(query.order_by(Own.id)[-3:]))

    neighbors = []
    pie_values = []
    bars_values = {}
    for house_ in houses:
        count = query.where(Own.house == house_.house).count()
        pie_values.append(count)
        neighbors.append(f'\n{"🏠 <b>Будинок".rjust(30, " ")} {house_.house}</b> <code>({count})</code>\n')
        sections = query.select(Own.section).where(Own.house == house_.house).distinct().order_by(Own.section)
        section_dict = {}
        for section_ in sections:
            count = query.where(Own.house == house_.house, Own.section == section_.section).count()
            neighbors.append(f'Секція{section_.section} <code>({count})</code>\n')
            section_dict[section_.section] = count
        bars_values[house_.house] = section_dict

    show_list = (f'<b>Всього користувачів: {total_users}</b>\n'
                 f'<i>Дані вказані {intro_yes}</i>\n'
                 f'<i>Дані не вказані {intro_not}</i>\n'
                 + '{}' * len(neighbors)).format(*neighbors) + '\n<b>Нові користувачі</b>'

    for i in last_3_users:
        show_list += f'\n{i.joined_str}'

    return {'show_list': show_list, 'pie_values': pie_values, 'bars_values': bars_values, 'introduced': introduced}
예제 #9
0
def show_section(bot, update, *args, some_section=False):
    """Here need some documentation"""
    log.info(log_msg(update))
    update.callback_query.answer()
    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 = Own.select().where(Own.house == user_query.house, Own.section == user_query.section).order_by(Own.floor)
    neighbors = [f'{user.user}   {user}\n' for user in query]
    show_list = (f'<b>Мешканці секції № {user_query.section} Будинку № {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)
예제 #10
0
def menu_kbd(bot, update):
    """show keyboard to chose: show neighbors or edit own info"""
    log.info(log_msg(update))
    text = '<b>Меню:</b>\n<i>Додайте свої дані, щоб мати доступ до перегляду сусідів, та інших функцій</i>'
    keyboard = [[InlineKeyboardButton('Додати свої дані 📝', callback_data='edit')],
                [InlineKeyboardButton('Хід будівництва 🏗️', callback_data='building')],
                [InlineKeyboardButton('Статистика 📊️', callback_data='statistics')], ]

    if Own.get_or_none(Own.house, Own.section, user=update.effective_user.id):
        text = text.split('\n')[0]
        keyboard[0] = [InlineKeyboardButton('Змінити свої дані ✏', callback_data='edit')]
        keyboard += [[InlineKeyboardButton('Дивитись сусідів 👫', callback_data='show')],
                     [InlineKeyboardButton('Мій будинок 🏠', callback_data='house_neighbors'),
                      InlineKeyboardButton('Моя секція 🔢', callback_data='section_neighbors')],
                     [InlineKeyboardButton('Паркомісця 🅿️', callback_data='parking')],
                     [InlineKeyboardButton('Сповіщення 🔔', callback_data='notifications')], ]

    reply_markup = InlineKeyboardMarkup(keyboard)
    bot.sendMessage(chat_id=update.effective_user.id, text=text, reply_markup=reply_markup,
                    parse_mode=ParseMode.HTML)
예제 #11
0
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)
예제 #12
0
def select_owns(bot, update):
    """if user have more than 1 records in db, select which one to show/edit"""
    log.info(log_msg(update))
    update.callback_query.answer()

    if update.callback_query.data == 'house_neighbors':
        text = 'Сусіди по якому будинку ? :'
        view_edit = 'view_my_house'
    elif update.callback_query.data == 'section_neighbors':
        text = 'Секція якої з Ваших квартир ? :'
        view_edit = 'view_my_secti'
    else:
        text = 'Яку адресу змінити? :'
        view_edit = 'edit'

    keyboard = []
    user_owns = Own.select().where(Own.user == update.effective_user.id)
    for i, j in enumerate(user_owns):
        keyboard.append([InlineKeyboardButton(f'{j.edit_btn_str}', callback_data=f'set_owns{i}{view_edit}')])
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.callback_query.message.reply_text(text=text, reply_markup=reply_markup, parse_mode=ParseMode.HTML)