def start(bot, update, salutation_text, current_subscriber_text):
    cursor = users.find_one({
        'chat_id': update.message.chat_id,
        'subscriber': True
    })
    if cursor == None:
        if users.find_one({'chat_id': update.message.chat_id}) == None:
            users.insert_one({
                'chat_id':
                update.message.chat_id,
                'first_interaction':
                datetime.datetime.now(tz=tz_msk),
                'subscriber':
                False
            })
        else:
            users.update_one({'chat_id': update.message.chat_id}, {
                '$set': {
                    'latest_start_interaction':
                    datetime.datetime.now(tz=tz_msk)
                }
            })
        keyboard = [["Подписаться", "Помощь"]]
        reply_markup = ReplyKeyboardMarkup(keyboard,
                                           one_time_keyboard=True,
                                           resize_keyboard=True)
        bot.send_message(chat_id=update.message.chat_id,
                         text=salutation_text,
                         reply_markup=reply_markup)
    else:
        bot.send_message(chat_id=update.message.chat_id,
                         text=current_subscriber_text)
        help_function(bot, update)
def change_settings_event_themes_add(bot, update):
    '''
    '''
    users.update_one({
        'chat_id': update.message.chat_id,
        'subscriber': True
    }, {
        '$set': {
            ('event_theme.' + event_themes_dict[update.message.text] + '.status'):
            True
        }
    })
    cursor_settings = users.find_one({
        'chat_id': update.message.chat_id,
        'subscriber': True
    })
    subscriptions = ''
    count_unsubscribed = 0
    count_subscribed = 0
    count = 0
    for theme in cursor_settings['event_theme']:
        if cursor_settings['event_theme'][theme]['status'] == True:
            count_subscribed += 1
            if count == 0:
                subscriptions += cursor_settings['event_theme'][theme][
                    'RU'].lower()
                count += 1
            else:
                subscriptions += (
                    ', ' + cursor_settings['event_theme'][theme]['RU'].lower())
        else:
            count_unsubscribed += 1
    if cursor_settings['location'] == 'Москва':
        location = 'Москве'
    elif cursor_settings['location'] == 'Санкт-Петербург':
        location = 'Питере'

    if count_unsubscribed != 0:
        text = "Сейчас ты подписан на эти категории событий в " + location + ": " + subscriptions + '.' + '\n\n' + 'Ты можешь подписаться / отписаться от каких-то категорий или оставить как есть. Что сделать?)'
        keyboard = [['Добавить', 'Удалить'], ['Всё ок!']]
    elif count_subscribed == 0:
        text = "Сейчас ты не подписан ни на одну из категорий событий  в " + location + ".\n\n" + 'Ты можешь добавить подписку или оставить как есть. Что сделать?)'
        keyboard = [['Добавить'], ['Всё ок!']]
    else:
        text = "Сейчас ты подписан на все категории событий в " + location + ": " + subscriptions + '.' + '\n\n' + 'Ты можешь оставить подписки как есть или отписаться от чего-то. Что сделать?)'
        keyboard = [['Всё ок!'], ['Удалить']]

    reply_markup = ReplyKeyboardMarkup(keyboard,
                                       one_time_keyboard=True,
                                       resize_keyboard=True)
    bot.send_message(chat_id=update.message.chat_id,
                     text=text,
                     reply_markup=reply_markup)
    return 'change settings event themes'
def change_settings_organizations_delete(bot, update):
    '''
    '''
    users.update_one(
        {'chat_id': update.message.chat_id},
        {'$set': {
            ('organization.' + update.message.text + '.status'): False
        }})
    cursor_settings = users.find_one({
        'chat_id': update.message.chat_id,
        'subscriber': True
    })
    subscriptions = ''
    count_unsubscribed = 0
    count_subscribed = 0
    count = 0
    for unit in cursor_settings['organization']:
        if cursor_settings['organization'][unit]['status'] == True:
            count_subscribed += 1
            if count == 0:
                subscriptions += cursor_settings['organization'][unit]['name']
                count += 1
            else:
                subscriptions += (
                    ', ' + cursor_settings['organization'][unit]['name'])
        else:
            count_unsubscribed += 1
    if cursor_settings['location'] == 'Москва':
        location = 'Москве'
    elif cursor_settings['location'] == 'Санкт-Петербург':
        location = 'Питере'

    if count_unsubscribed == 0:
        text = "Сейчас ты подписан на эти организации в " + location + ": " + subscriptions + '.' + '\n\n' + 'Ты можешь подписаться / отписаться на организации или оставить как есть. Что сделать?)'
        keyboard = [['Добавить', 'Удалить'], ['Всё ок!']]
    elif count_unsubscribed != 0:
        text = "Сейчас ты не подписан ни на одну из оргазинацию в " + location + ".\n\n" + 'Ты можешь добавить подписку или оставить как есть. Что сделать?)'
        keyboard = [['Добавить'], ['Всё ок!']]
    else:
        text = "Сейчас ты подписан на все организации в " + location + ": " + subscriptions + '.' + '\n\n' + 'Ты можешь оставить подписки как есть или отписаться от чего-то. Что сделать?)'
        keyboard = [['Всё ок!'], ['Удалить']]

    reply_markup = ReplyKeyboardMarkup(keyboard,
                                       one_time_keyboard=True,
                                       resize_keyboard=True)
    bot.send_message(chat_id=update.message.chat_id,
                     text=text,
                     reply_markup=reply_markup)
    return 'change settings organizations'
def subscribe(bot, update):
    """
    """
    cursor = users.find_one({
        'chat_id': update.message.chat_id,
        'subscriber': True
    })
    if cursor == None:
        users.update_one({'chat_id': update.message.chat_id}, {
            "$set": {
                "start_subscription": datetime.datetime.now(tz=tz_msk),
                'subscriber': True
            }
        })
        for theme in event_themes:
            add = 'event_theme.' + theme
            users.update_one({'chat_id': update.message.chat_id}, {
                '$set': {
                    add: {
                        'status': True,
                        'RU': event_themes_dict_reverse[theme]
                    },
                    'last_modified': datetime.datetime.now(tz=tz_msk)
                }
            })
        analytics.update_one({"segment": "users"},
                             {'$inc': {
                                 'data.user_base': 1
                             }})
        text = 'В какой локации хочешь получать анонсы?'
        keyboard = [locations]
        reply_markup = ReplyKeyboardMarkup(keyboard,
                                           one_time_keyboard=True,
                                           resize_keyboard=True)
        bot.send_message(chat_id=update.message.chat_id,
                         text=text,
                         reply_markup=reply_markup)
        return 'set location'
    else:
        text = "Ты уже подписан:)"
        bot.send_message(chat_id=update.message.chat_id, text=text)
        help_function(bot, update)
def set_organizations_recurrent(bot, update):
    '''
    '''
    non_subscribed_organizations_list = []
    subscribed_organizations_list = []
    cursor_user = users.find_one({'chat_id': update.message.chat_id})
    for unit in organizations.find({'location': cursor_user['location']}):
        if cursor_user['organization'][unit['name']]['status'] == False:
            non_subscribed_organizations_list.append(unit['name'])
        else:
            subscribed_organizations_list.append(unit['name'])

    if update.message.text in non_subscribed_organizations_list:
        users.update_one({'chat_id': update.message.chat_id}, {
            '$set': {
                ('organization.' + update.message.text): {
                    'status': True,
                    'name': update.message.text
                }
            }
        })
        bot.send_message(chat_id=update.message.chat_id, text='Добавлено!')
        non_subscribed_organizations_list.remove(update.message.text)
        subscribed_organizations_list.append(update.message.text)

        cursor_organizations = organizations.find({})
        if len(non_subscribed_organizations_list) == 0:
            bot.send_message(
                chat_id=update.message.chat_id,
                text='Ты уже подписался на все доступные организации)')
            return set_preferences_logic(bot, update)
        elif len(subscribed_organizations_list) == 0:
            non_subscribed_organizations_list.append('Закончить')
            keyboard = [non_subscribed_organizations_list]
            reply_markup = ReplyKeyboardMarkup(keyboard,
                                               one_time_keyboard=True,
                                               resize_keyboard=True)
            bot.send_message(
                chat_id=update.message.chat_id,
                text='На какие организации ты хочешь подписаться?',
                reply_markup=reply_markup)
            return 'set organizations recurrent'
        else:
            non_subscribed_organizations_list.append('Закончить')
            keyboard = [non_subscribed_organizations_list]
            reply_markup = ReplyKeyboardMarkup(keyboard,
                                               one_time_keyboard=True,
                                               resize_keyboard=True)
            bot.send_message(
                chat_id=update.message.chat_id,
                text='На какие ещё организации ты хочешь подписаться?',
                reply_markup=reply_markup)
            return 'set organizations recurrent'
    elif update.message.text == 'Закончить':
        if len(subscribed_organizations_list) > 0:
            keyboard = ['ИЛИ', 'ТОЛЬКО']
            reply_markup = ReplyKeyboardMarkup([keyboard],
                                               one_time_keyboard=True,
                                               resize_keyboard=True)
            text = 'Выбери "ИЛИ", если хочешь получать анонсы событий выбранных категорий не только в организации, на которую ты подписался, но и в остальных в твоём городе.\n'
            text += 'Выбери "ТОЛЬКО", если хочешь получать анонсы только по выбранным категориям и только в организациях, на которые ты подписался)'
            bot.send_message(chat_id=update.message.chat_id,
                             text=text,
                             reply_markup=reply_markup)
            return 'set preferences logic'
        else:
            text = """
        А теперь получай анонсы событий в одном месте:). По мере появления, я буду отправлять их тебе.\n
По умолчанию, тебе будут приходить все анонсы. Для большей персонализации, жми /settings :)
        """
            bot.send_message(chat_id=update.message.chat_id, text=text)
            help_function(bot, update)
            return -1
    else:
        cursor_organizations = organizations.find({})
        organizations_list = []
        for unit in cursor_organizations:
            organizations_list.append(unit['name'])
        organizations_list.append('Закончить')
        keyboard = [organizations_list]
        reply_markup = ReplyKeyboardMarkup([keyboard],
                                           one_time_keyboard=True,
                                           resize_keyboard=True)
        bot.send_message(
            chat_id=update.message.chat_id,
            text=
            'Для выбора нажми на соответствующую кнопку. На какие организации ты хочешь подписаться? Выбирай по-очереди!',
            reply_markup=reply_markup)
        return 'set organizations recurrent'
def send_tomorrow(bot, update):
    cursor = users.find_one({'chat_id' : update.message.chat_id, 'subscriber' : True})

    if cursor != None:
        location = cursor['location']
        # iterate through subscriptions
        sent_objectID = []
        tomorrow = datetime.date.today() + datetime.timedelta(days=1)
        cursor_events = event_posts.find({'decision':'approved', 'location' : location,
                                          'year' : tomorrow.year,
                                          'month' : tomorrow.month,
                                          'day' : tomorrow.day})
        if cursor_events != None:
            if cursor['preferences_logic'] == 'ИЛИ':
                # iterating through categories
                for theme in cursor['event_theme']:
                    if cursor['event_theme'][theme]['status'] == True:
                        cursor_events = event_posts.find({'event_theme' : theme, 'location' : location,
                                                          'decision':'approved',
                                                          'year' : tomorrow.year,
                                                          'month' : tomorrow.month,
                                                          'day' : tomorrow.day})
                        if cursor_events != None:
                            for event in cursor_events:
                                if event['_id'] not in sent_objectID:
                                    sent_objectID.append(event['_id'])
                                    time = str(event['date_time_msk'].time())[:-3]
                                    if str(time) == '00:00':
                                        time = 'NA'
                                    try:
                                        event_name = event['event_name']
                                    except KeyError:
                                        event_name = 'NA'
                                    text = '#' + event['event_theme'].replace(" ", "_") + '\n\n'
                                    if event_name != 'NA':
                                        text += event_name + '\n'
                                    text += ('Время: ' + time + '. ' + event['organization'] +'\n' + event["link"])
                                    bot.send_message(chat_id = update.message.chat_id,
                                                     text = text)
                                    time.sleep(1)
                # iterating through organizers
                for unit in cursor['organization']:
                    if cursor['organization'][unit]['status'] == True:
                        cursor_events = event_posts.find({'organization' : unit, 'location' : location,
                                                          'decision':'approved',
                                                          'year' : tomorrow.year,
                                                          'month' : tomorrow.month,
                                                          'day' : tomorrow.day})
                        if cursor_events != None:
                            for event in cursor_events:
                                if event['_id'] not in sent_objectID:
                                    sent_objectID.append(event['_id'])
                                    time = str(event['date_time_msk'].time())[:-3]
                                    if str(time) == '00:00':
                                        time = 'NA'
                                    try:
                                        event_name = event['event_name']
                                    except KeyError:
                                        event_name = 'NA'
                                    text = '#' + event['event_theme'].replace(" ", "_") + '\n\n'
                                    if event_name != 'NA':
                                        text += event_name + '\n'
                                    text += ('Время: ' + time + '. ' + event['organization'] +'\n' + event["link"])
                                    bot.send_message(chat_id = update.message.chat_id,
                                                     text = text)
                                    time.sleep(1)
            elif cursor['preferences_logic'] == 'ТОЛЬКО':
                # iterating through categories
                for theme in cursor['event_theme']:
                    if cursor['event_theme'][theme]['status'] == True:
                        for unit in cursor['organization']:
                            if cursor['organization'][unit]['status'] == True:
                                cursor_events = event_posts.find({'event_theme' : theme, 'location' : location,
                                                                  'organization' : unit,
                                                                  'decision':'approved',
                                                                  'year' : tomorrow.year,
                                                                  'month' : tomorrow.month,
                                                                  'day' : tomorrow.day})
                                if cursor_events != None:
                                    for event in cursor_events:
                                        if event['_id'] not in sent_objectID:
                                            sent_objectID.append(event['_id'])
                                            time = str(event['date_time_msk'].time())[:-3]
                                            if str(time) == '00:00':
                                                time = 'NA'
                                            try:
                                                event_name = event['event_name']
                                            except KeyError:
                                                event_name = 'NA'
                                            text = '#' + event['event_theme'].replace(" ", "_") + '\n\n'
                                            if event_name != 'NA':
                                                text += event_name + '\n'
                                            text += ('Время: ' + time + '. ' + event['organization'] +'\n' + event["link"])
                                            bot.send_message(chat_id = update.message.chat_id,
                                                             text = text)
                                            time.sleep(1)
        else:
            bot.send_message(chat_id = update.message.chat_id,
                             text = 'Событий на завтра нет')
        if len(sent_objectID) == 0:
            bot.send_message(chat_id = update.message.chat_id,
                             text = 'Событий на завтра нет')
    else:
        users.update_one({'chat_id' : update.message.chat_id, 'subscriber' : False},
                         {'$set' : {'latest_send_tomorrow_interaction' : str(datetime.date.today())}})
        bot.send_message(chat_id = update.message.chat_id,
                         text = 'Ты не подписан, поэтому отправлю тебе все события на завтра без персонализации. Чтобы подписаться, жми /subscribe')
        sent_objectID = []
        tomorrow = datetime.date.today() + datetime.timedelta(days=1)
        cursor_events = event_posts.find({'decision' : 'approved',
                                          'year' : tomorrow.year,
                                          'month' : tomorrow.month,
                                          'day' : tomorrow.day})
        if cursor_events != None:
            for event in cursor_events:
                if event['_id'] not in sent_objectID:
                    sent_objectID.append(event['_id'])
                    time = str(event['date_time_msk'].time())[:-3]
                    if str(time) == '00:00':
                        time = 'NA'
                    try:
                        event_name = event['event_name']
                    except KeyError:
                        event_name = 'NA'
                    text = '#' + event['event_theme'].replace(" ", "_") + '\n\n'
                    if event_name != 'NA':
                        text += event_name + '\n'
                    text += ('Время: ' + time + '. ' + event['organization'] +'\n' + event["link"])
                    bot.send_message(chat_id = update.message.chat_id,
                                     text = text)
                    time.sleep(1)
        else:
            bot.send_message(chat_id = update.message.chat_id,
                             text = 'Событий на завтра нет')
def send_week(bot, update, num_days=7):
    cursor = users.find_one({
        'chat_id': update.message.chat_id,
        'subscriber': True
    })
    if cursor != None:  # iterate through subscriptions
        location = cursor['location']
        sent_objectID = []
        days = []
        today = datetime.date.today()
        iterate = 0
        for i in range(num_days + 1):
            days.append(today + datetime.timedelta(days=iterate))
            iterate += 1
        days_no_events = 0
        days_processed = 0

        if cursor['preferences_logic'] == 'ИЛИ':
            for day in days:
                for theme in cursor['event_theme']:
                    if cursor['event_theme'][theme]['status'] == True:

                        cursor_events = event_posts.find({
                            'event_theme': theme,
                            'location': location,
                            'decision': 'approved',
                            'year': day.year,
                            'month': day.month,
                            'day': day.day
                        })
                        if cursor_events != None:
                            for event in cursor_events:
                                if event['_id'] not in sent_objectID:
                                    date_time = event[
                                        'date_time_msk'].strftime(
                                            '%d.%m.%Y %H:%M')
                                    if date_time[-5:] == '00:00':
                                        date_time = date_time[:-5] + 'NA'
                                    try:
                                        event_name = event['event_name']
                                    except KeyError:
                                        event_name = 'NA'
                                    text = '#' + event['event_theme'].replace(
                                        " ", "_") + '\n\n'
                                    if event_name != 'NA':
                                        text += event_name + '\n'
                                    sent_objectID.append(event['_id'])
                                    text += ('Дата и время: ' + date_time +
                                             '. ' + event['organization'] +
                                             '\n' + event["link"])
                                    bot.send_message(
                                        chat_id=update.message.chat_id,
                                        text=text)
                                    time.sleep(1)
                for unit in cursor['organization']:
                    if cursor['organization'][unit]['status'] == True:
                        cursor_events = event_posts.find({
                            'organization': unit,
                            'location': location,
                            'decision': 'approved',
                            'year': day.year,
                            'month': day.month,
                            'day': day.day
                        })
                        if cursor_events != None:
                            for event in cursor_events:
                                if event['_id'] not in sent_objectID:
                                    date_time = event[
                                        'date_time_msk'].strftime(
                                            '%d.%m.%Y %H:%M')
                                    if date_time[-5:] == '00:00':
                                        date_time = date_time[:-5] + 'NA'
                                    sent_objectID.append(event['_id'])
                                    try:
                                        event_name = event['event_name']
                                    except KeyError:
                                        event_name = 'NA'
                                    text = '#' + event['event_theme'].replace(
                                        " ", "_") + '\n\n'
                                    if event_name != 'NA':
                                        text += event_name + '\n'
                                    text += ('Дата и время: ' + date_time +
                                             '. ' + event['organization'] +
                                             '\n' + event["link"])
                                    bot.send_message(
                                        chat_id=update.message.chat_id,
                                        text=text)
                                    time.sleep(1)
        elif cursor['preferences_logic'] == 'ТОЛЬКО':
            for day in days:
                for theme in cursor['event_theme']:
                    if cursor['event_theme'][theme]['status'] == True:
                        for unit in cursor['organization']:
                            if cursor['organization'][unit]['status'] == True:
                                cursor_events = event_posts.find({
                                    'event_theme':
                                    theme,
                                    'location':
                                    location,
                                    'organization':
                                    unit,
                                    'decision':
                                    'approved',
                                    'year':
                                    day.year,
                                    'month':
                                    day.month,
                                    'day':
                                    day.day
                                })
                                if cursor_events != None:
                                    for event in cursor_events:
                                        if event['_id'] not in sent_objectID:
                                            date_time = event[
                                                'date_time_msk'].strftime(
                                                    '%d.%m.%Y %H:%M')
                                            if date_time[-5:] == '00:00':
                                                date_time = date_time[:-5] + 'NA'
                                            sent_objectID.append(event['_id'])
                                            try:
                                                event_name = event[
                                                    'event_name']
                                            except KeyError:
                                                event_name = 'NA'
                                            text = '#' + event[
                                                'event_theme'].replace(
                                                    " ", "_") + '\n\n'
                                            if event_name != 'NA':
                                                text += event_name + '\n'
                                            text += ('Дата и время: ' +
                                                     date_time + '. ' +
                                                     event['organization'] +
                                                     '\n' + event["link"])
                                            bot.send_message(
                                                chat_id=update.message.chat_id,
                                                text=text)
                                            time.sleep(1)
        if len(sent_objectID) == 0:
            bot.send_message(chat_id=update.message.chat_id,
                             text='Событий на неделю нет')
    else:
        users.update_one(
            {
                'chat_id': update.message.chat_id,
                'subscriber': False
            }, {
                '$set': {
                    'latest_send_week_interaction': str(datetime.date.today())
                }
            })
        bot.send_message(
            chat_id=update.message.chat_id,
            text=
            'Ты не подписан, поэтому отправлю тебе все события на неделю без персонализации. Чтобы подписаться, жми /subscribe'
        )
        sent_objectID = []
        days = []
        today = datetime.date.today()
        iterate = 0
        for i in range(num_days + 1):
            days.append(today + datetime.timedelta(days=iterate))
            iterate += 1
        days_no_events = 0
        days_processed = 0
        for day in days:
            days_processed += 1
            cursor_events = event_posts.find({
                'decision': 'approved',
                'year': day.year,
                'month': day.month,
                'day': day.day
            })
            if cursor_events != None:
                for event in cursor_events:
                    if event['_id'] not in sent_objectID:
                        date_time = event['date_time_msk'].strftime(
                            '%d.%m.%Y %H:%M')
                        if date_time[-5:] == '00:00':
                            date_time = date_time[:-5] + 'NA'
                        sent_objectID.append(event['_id'])
                        try:
                            event_name = event['event_name']
                        except KeyError:
                            event_name = 'NA'
                        text = '#' + event['event_theme'].replace(" ",
                                                                  "_") + '\n\n'
                        if event_name != 'NA':
                            text += event_name + '\n'
                        text += ('Дата и время: ' + date_time + '. ' +
                                 event['organization'] + '\n' + event["link"])
                        bot.send_message(chat_id=update.message.chat_id,
                                         text=text)
                        time.sleep(1)
            else:
                days_no_events += 1
        if days_processed == days_no_events:
            bot.send_message(chat_id=update.message.chat_id,
                             dtext='Событий на неделю нет')
def change_settings(bot, update):
    """
    """
    cursor_settings = users.find_one({
        'chat_id': update.message.chat_id,
        'subscriber': True
    })
    if update.message.text == 'Изменить регион':
        text = 'В какой локации хочешь получать анонсы?'
        keyboard = [locations]
        reply_markup = ReplyKeyboardMarkup(keyboard,
                                           one_time_keyboard=True,
                                           resize_keyboard=True)
        bot.send_message(chat_id=update.message.chat_id,
                         text=text,
                         reply_markup=reply_markup)
        return 'change settings location'
    elif update.message.text == 'Изменить тематики':
        subscriptions_themes = ''
        count_themes_non_subscribed = 0
        count_themes_subscribed = 0
        count = 0
        for theme in cursor_settings['event_theme']:
            if cursor_settings['event_theme'][theme]['status'] == True:
                count_themes_subscribed += 1
                if count == 0:
                    subscriptions_themes += cursor_settings['event_theme'][
                        theme]['RU'].lower()
                    count += 1
                else:
                    subscriptions_themes += (
                        ', ' +
                        cursor_settings['event_theme'][theme]['RU'].lower())
            else:
                count_themes_non_subscribed += 1
        if cursor_settings['location'] == 'Москва':
            location = 'Москве'
        elif cursor_settings['location'] == 'Санкт-Петербург':
            location = 'Питере'
        if count_themes_non_subscribed != 0:
            text = "Сейчас ты подписан на эти категории событий в " + location + ": " + subscriptions_themes + '.\n'
            keyboard = [['Добавить'], ['Удалить'], ['Всё ок!']]
        elif count_themes_subscribed == 0:
            text = "Сейчас ты не подписан ни на одну из категорий событий  в " + location + ".\n"
            keyboard = [['Добавить'], ['Всё ок!']]
        else:
            text = "Сейчас ты подписан на все категории событий в " + location + ": " + subscriptions_themes + '.\n'
            keyboard = [['Всё ок!'], ['Удалить']]
        text += 'Что сделать?:)'
        reply_markup = ReplyKeyboardMarkup(keyboard,
                                           one_time_keyboard=True,
                                           resize_keyboard=True)
        bot.send_message(chat_id=update.message.chat_id,
                         text=text,
                         reply_markup=reply_markup)
        return 'change settings event themes'
    elif update.message.text == 'Изменить организации':
        subscriptions_organization = ''
        count_organizations_non_subscribed = 0
        count_organizations_subscribed = 0
        count = 0
        for organization in cursor_settings['organization']:
            if cursor_settings['organization'][organization]['status'] == True:
                count_organizations_subscribed += 1
                if count == 0:
                    subscriptions_organization += cursor_settings[
                        'organization'][organization]['name']
                    count += 1
                else:
                    subscriptions_organization += (
                        ', ' +
                        cursor_settings['organization'][organization]['name'])
            else:
                count_organizations_non_subscribed += 1
        if cursor_settings['location'] == 'Москва':
            location = 'Москве'
        elif cursor_settings['location'] == 'Санкт-Петербург':
            location = 'Питере'
        if count_organizations_non_subscribed == 0:
            text = 'Ты подписан на все организации в ' + location + ': ' + subscriptions_organization + '.\n'
            keyboard = [['Всё ок!'], ['Удалить']]
        elif count_organizations_subscribed == 0:
            text = 'Ты не подписан ни на одну из организаций в ' + location + '.\n'
            keyboard = [['Добавить'], ['Всё ок!']]
        else:
            text = 'Ты подписан на эти организации в ' + location + ': ' + subscriptions_organization + '.\n'
            keyboard = [['Добавить'], ['Удалить'], ['Всё ок!']]
        text += 'Что сделать?:)'
        reply_markup = ReplyKeyboardMarkup(keyboard,
                                           one_time_keyboard=True,
                                           resize_keyboard=True)
        bot.send_message(chat_id=update.message.chat_id,
                         text=text,
                         reply_markup=reply_markup)
        return 'change settings organizations'
    elif update.message.text == 'Всё ок!':
        bot.send_message(chat_id=update.message.chat_id, text='Adiós!)')
        return -1
    elif update.message.text == 'Изменить тип персонализации':
        keyboard = ['ИЛИ', 'ТОЛЬКО']
        reply_markup = ReplyKeyboardMarkup([keyboard],
                                           one_time_keyboard=True,
                                           resize_keyboard=True)
        text = 'Выбери "ИЛИ", если хочешь получать анонсы событий выбранных категорий не только в организации, на которую ты подписался, но и в остальных в твоём городе.\n'
        bot.send_message(
            chat_id=update.message.chat_id,
            text=text +
            'Выбери "ТОЛЬКО", если хочешь получать анонсы только по выбранным категориям и только в организациях, на которые ты подписался)',
            reply_markup=reply_markup)
        return 'change settings logic'
def change_settings_location(bot, update):
    '''
    '''
    users.update_one({
        'chat_id': update.message.chat_id,
        'subscriber': True
    }, {'$set': {
        'location': update.message.text
    }})

    cursor_settings = users.find_one({
        'chat_id': update.message.chat_id,
        'subscriber': True
    })
    cursor_organizations = organizations.find({})
    for unit in cursor_organizations:
        add = 'organization.' + unit['name']
        users.update_one(
            {'chat_id': update.message.chat_id},
            {'$set': {
                add: {
                    'status': False,
                    'name': unit['name']
                }
            }})
    subscriptions_themes = ''
    subscriptions_organization = ''
    count_themes_non_subscribed = 0
    count_themes_subscribed = 0
    count_organizations_non_subscribed = 0
    count_organizations_subscribed = 0

    # getting event themes followed
    count = 0
    for theme in cursor_settings['event_theme']:
        if cursor_settings['event_theme'][theme]['status'] == True:
            count_themes_subscribed += 1
            if count == 0:
                subscriptions_themes += cursor_settings['event_theme'][theme][
                    'RU'].lower()
                count += 1
            else:
                subscriptions_themes += (
                    ', ' + cursor_settings['event_theme'][theme]['RU'].lower())
        else:
            count_themes_non_subscribed += 1
    #getting organizations followed
    count = 0
    for organization in cursor_settings['organization']:
        if cursor_settings['organization'][organization]['status'] == True:
            count_organizations_subscribed += 1
            if count == 0:
                subscriptions_organization += cursor_settings['organization'][
                    organization]['name']
                count += 1
            else:
                subscriptions_organization += (
                    ', ' +
                    cursor_settings['organization'][organization]['name'])
        else:
            count_organizations_non_subscribed += 1
    # getting location name
    if cursor_settings['location'] == 'Москва':
        location = 'Москве'
    elif cursor_settings['location'] == 'Санкт-Петербург':
        location = 'Питере'
    # костыльно меняем текст))))
    count_organizations_subscribed = 0
    if count_themes_non_subscribed != 0:
        text = "Сейчас ты подписан на эти категории событий в " + location + ": " + subscriptions_themes + '.\n'
    elif count_themes_subscribed == 0:
        text = "Сейчас ты не подписан ни на одну из категорий событий  в " + location + ".\n"
    else:
        text = "Сейчас ты подписан на все категории событий в " + location + ": " + subscriptions_themes + '.\n'
    if count_organizations_non_subscribed == 0:
        text += 'Также ты подписан на все организации в ' + location + ': ' + subscriptions_organization + '.\n'
    elif count_organizations_subscribed == 0:
        text += 'Также ты не подписан ни на одну из организаций в ' + location + '.\n'
    else:
        text += 'Также ты подписан на эти организации в ' + location + ': ' + subscriptions_organization + '.\n'
    text += 'Что сделать?:)'
    keyboard = [['Изменить тематики'], ['Изменить организации'],
                ['Изменить регион'], ['Изменить тип персонализации'],
                ['Всё ок!']]
    reply_markup = ReplyKeyboardMarkup(keyboard,
                                       one_time_keyboard=True,
                                       resize_keyboard=True)
    bot.send_message(chat_id=update.message.chat_id,
                     text=text,
                     reply_markup=reply_markup)
    return 'change settings'
def change_settings_organizations(bot, update):
    '''
    '''
    cursor_settings = users.find_one({
        'chat_id': update.message.chat_id,
        'subscriber': True
    })
    if update.message.text == 'Добавить':
        non_subscriptions = []
        for unit in organizations.find(
            {'location': cursor_settings['location']}):
            if cursor_settings['organization'][unit['name']]['status'] != True:
                non_subscriptions.append(
                    cursor_settings['organization'][unit['name']]['name'])
        if len(non_subscriptions) > 0:
            text = 'Ты можешь подписаться на эти организации)'
            keyboard = [non_subscriptions]
            reply_markup = ReplyKeyboardMarkup(keyboard,
                                               one_time_keyboard=True,
                                               resize_keyboard=True)
            bot.send_message(chat_id=update.message.chat_id,
                             text=text,
                             reply_markup=reply_markup)
            return 'change settings organizations add'
        else:
            text = 'Ты уже подписан на все категории)'
            bot.send_message(chat_id=update.message.chat_id, text=text)
            return -1
    elif update.message.text == 'Удалить':
        subscriptions = []
        for unit in organizations.find(
            {'location': cursor_settings['location']}):
            if cursor_settings['organization'][
                    unit['name']]['status'] != False:
                subscriptions.append(
                    cursor_settings['organization'][unit['name']]['name'])
        if len(subscriptions) > 0:
            text = 'Что удалить из текущих подписок?'
            keyboard = [subscriptions]
            reply_markup = ReplyKeyboardMarkup(keyboard,
                                               one_time_keyboard=True,
                                               resize_keyboard=True)
            bot.send_message(chat_id=update.message.chat_id,
                             text=text,
                             reply_markup=reply_markup)
            return 'change settings organizations delete'
        else:
            text = "Хей, ты больше ни на что не подписан. Может стоит на что-то подписаться?"
            keyboard = [["Добавить", 'Всё ок!']]
            reply_markup = ReplyKeyboardMarkup(keyboard,
                                               one_time_keyboard=True,
                                               resize_keyboard=True)
            bot.send_message(chat_id=update.message.chat_id,
                             text=text,
                             reply_markup=reply_markup)
            return 'change settings'
    elif update.message.text == 'Всё ок!':
        subscriptions_themes = ''
        subscriptions_organization = ''
        count_themes_non_subscribed = 0
        count_themes_subscribed = 0
        count_organizations_non_subscribed = 0
        count_organizations_subscribed = 0

        # getting event themes followed
        count = 0
        for theme in cursor_settings['event_theme']:
            if cursor_settings['event_theme'][theme]['status'] == True:
                count_themes_subscribed += 1
                if count == 0:
                    subscriptions_themes += cursor_settings['event_theme'][
                        theme]['RU'].lower()
                    count += 1
                else:
                    subscriptions_themes += (
                        ', ' +
                        cursor_settings['event_theme'][theme]['RU'].lower())
            else:
                count_themes_non_subscribed += 1
        #getting organizations followed
        count = 0
        for organization in cursor_settings['organization']:
            if cursor_settings['organization'][organization]['status'] == True:
                count_organizations_subscribed += 1
                if count == 0:
                    subscriptions_organization += cursor_settings[
                        'organization'][organization]['name']
                    count += 1
                else:
                    subscriptions_organization += cursor_settings[
                        'organization'][organization]['name']
            else:
                count_organizations_non_subscribed += 1
        # getting location name
        if cursor_settings['location'] == 'Москва':
            location = 'Москве'
        elif cursor_settings['location'] == 'Санкт-Петербург':
            location = 'Питере'
        # figuring out the text to send
        if count_themes_non_subscribed != 0:
            text = "Сейчас ты подписан на эти категории событий в " + location + ": " + subscriptions_themes + '.\n'
        elif count_themes_subscribed == 0:
            text = "Сейчас ты не подписан ни на одну из категорий событий  в " + location + ".\n"
        else:
            text = "Сейчас ты подписан на все категории событий в " + location + ": " + subscriptions_themes + '.\n'
        if count_organizations_non_subscribed == 0:
            text += 'Также ты подписан на все организации в ' + location + ': ' + subscriptions_organization + '.\n'
        elif count_organizations_subscribed == 0:
            text += 'Также ты не подписан ни на одну из организаций в ' + location + '.\n'
        else:
            text += 'Также ты подписан на эти организации в ' + location + ': ' + subscriptions_organization + '.\n'
        text += 'Что сделать?:)'
        keyboard = [['Изменить тематики'], ['Изменить организации'],
                    ['Изменить регион'], ['Изменить тип персонализации'],
                    ['Всё ок!']]
        reply_markup = ReplyKeyboardMarkup(keyboard,
                                           one_time_keyboard=True,
                                           resize_keyboard=True)
        bot.send_message(chat_id=update.message.chat_id,
                         text=text,
                         reply_markup=reply_markup)
        return 'change settings'
def settings(bot, update):
    """
    """
    cursor = users.find_one({
        'chat_id': update.message.chat_id,
        'subscriber': True
    })
    if cursor == None:
        text = "Начни с подписки - /subscribe:)"
        bot.send_message(chat_id=update.message.chat_id, text=text)
    else:
        cursor_settings = users.find_one({
            'chat_id': update.message.chat_id,
            'subscriber': True
        })
        subscriptions_themes = ''
        subscriptions_organization = ''
        count_themes_non_subscribed = 0
        count_themes_subscribed = 0
        count_organizations_non_subscribed = 0
        count_organizations_subscribed = 0

        # getting event themes followed
        count = 0
        for theme in cursor_settings['event_theme']:
            if cursor_settings['event_theme'][theme]['status'] == True:
                count_themes_subscribed += 1
                if count == 0:
                    subscriptions_themes += cursor_settings['event_theme'][
                        theme]['RU'].lower()
                    count += 1
                else:
                    subscriptions_themes += (
                        ', ' +
                        cursor_settings['event_theme'][theme]['RU'].lower())
            else:
                count_themes_non_subscribed += 1
        #getting organizations followed
        count = 0
        for organization in cursor_settings['organization']:
            if cursor_settings['organization'][organization]['status'] == True:
                count_organizations_subscribed += 1
                if count == 0:
                    subscriptions_organization += cursor_settings[
                        'organization'][organization]['name']
                    count += 1
                else:
                    subscriptions_organization += (
                        ', ' +
                        cursor_settings['organization'][organization]['name'])
            else:
                count_organizations_non_subscribed += 1
        # getting location name
        if cursor_settings['location'] == 'Москва':
            location = 'Москве'
        elif cursor_settings['location'] == 'Санкт-Петербург':
            location = 'Питере'
        # figuring out the text to send
        if count_themes_non_subscribed != 0:
            text = "Сейчас ты подписан на эти категории событий в " + location + ": " + subscriptions_themes + '.\n'
        elif count_themes_subscribed == 0:
            text = "Сейчас ты не подписан ни на одну из категорий событий  в " + location + ".\n"
        else:
            text = "Сейчас ты подписан на все категории событий в " + location + ": " + subscriptions_themes + '.\n'
        if count_organizations_non_subscribed == 0:
            text += 'Также ты подписан на все организации в ' + location + ': ' + subscriptions_organization + '.\n'
        elif count_organizations_subscribed == 0:
            text += 'Также ты не подписан ни на одну из организаций в ' + location + '.\n'
        else:
            text += 'Также ты подписан на эти организации в ' + location + ': ' + subscriptions_organization + '.\n'
        text += 'Что сделать?:)'
        keyboard = [['Изменить тематики'], ['Изменить организации'],
                    ['Изменить регион'], ['Изменить тип персонализации'],
                    ['Всё ок!']]
        reply_markup = ReplyKeyboardMarkup(keyboard,
                                           one_time_keyboard=True,
                                           resize_keyboard=True)
        bot.send_message(chat_id=update.message.chat_id,
                         text=text,
                         reply_markup=reply_markup)
    return 'change settings'