Ejemplo n.º 1
0
def interests_process(bot, update):
    query = update.callback_query
    interest_id = query.data.split("_")[1]
    user_object = get_or_register_user(query.from_user)
    user = query.from_user
    target_interest = Interest.get(id=interest_id)
    keyboard = []

    if not User.select().join(UserInterests).join(Interest).where(User.tlg_id == user.id,
                                                                  Interest.name == target_interest.name).exists():
        UserInterests.create(user=user_object, interest=target_interest)
    else:
        ui = UserInterests.get(UserInterests.user == user_object, UserInterests.interest == target_interest)
        ui.delete_instance()

    for interest in Interest.select():
        if User.select().join(UserInterests).join(Interest).where(User.tlg_id == user.id,
                                                                  Interest.name == interest.name).exists():
            prefix = "✅ "
        else:
            prefix = ""
        keyboard.append([InlineKeyboardButton(prefix + interest.name, callback_data="interest_{}".format(interest.id))])
    keyboard.append([InlineKeyboardButton("Готово", callback_data="interests_finish")])
    reply_markup = InlineKeyboardMarkup(keyboard)
    query.edit_message_reply_markup(reply_markup=reply_markup)
    query.answer("Интерес обновлен ✅")
Ejemplo n.º 2
0
def get_or_register_user(user, ref_id=None):
    ref_user = None
    if ref_id:
        query = User.select().where(User.unique_id == ref_id)
        if query.exists():
            ref_user = query.get()
    # logger.info("In register user, ref_id is {} and user found is {}".format(ref_id, ref_user))

    # Register in DB if not exist, putting the referrer id if provided
    if not User.select().where(User.tlg_id == user.id).exists():
        # logger.info("Putting ref_user id {} to user {}".format(ref_user, user.first_name))
        user_object = User.create(tlg_id=user.id,
                                  tlg_username=user.username,
                                  first_name=user.first_name,
                                  last_name=user.last_name,
                                  referer=ref_user)
    else:
        user_object = User.select().where(User.tlg_id == user.id).get()
    return user_object
Ejemplo n.º 3
0
def create_menu_message(bot, update, is_callback=False):
    if is_callback:
        user = update.from_user
    else:
        user = update.message.from_user
    user_object = get_or_register_user(user)
    keyboard = []
    # Check, if the user have not calculate scale - display only one option
    if get_user_scale(user).amount <= 0:
        keyboard.append([InlineKeyboardButton("Рассчитать масштаб личности", callback_data="scale_processing_start")])
        reply_markup = InlineKeyboardMarkup(keyboard)
        message = "Хочешь узнать на сколько ты масштабная личность и получить доступ к самым интересным для тебя " \
                  "событиям? "
        update.message.reply_text(message, reply_markup=reply_markup)
        return
    # Adding the ability to recalculate scale at any time
    query = Scale.select().join(User).where(User.tlg_id == user.id)
    message = "{}, ваши данные по нетворкинг сети:\n" \
              "Масштаб вашей личности: {}\n".format(user.first_name if user.first_name else user.username,
                                                    query.get().amount)
    keyboard.append([InlineKeyboardButton("Пересчитать масштаб личности", callback_data="scale_processing_start")])
    # Referral system data to message append
    Referrer = User.alias()
    query = User.select().join(Referrer, on=(Referrer.referer == User.id)).where(User.tlg_id == user.id)
    ref_link = "https://t.me/{bot_name}?start={lnk}".format(bot_name=BOT_NAME, lnk=user_object.unique_id)
    message = "{}\nПриглашено человек по реферальной системе: {}" \
              "\nВаша реферальная ссылка: {}\n".format(message, query.count(), ref_link)

    # If the user does not have selected interests, show him the invitation to fill them
    if Interest.select().join(UserInterests).join(User).where(User.tlg_id == user.id).count() < 1:
        message = "{}\nЧтобы получать наиболее интересные для вас новости, укажите ваши интересы".format(message)
        keyboard.append([InlineKeyboardButton("Указать интересы", callback_data="interests_set")])
        keyboard = appendSocialButtons(keyboard, ref_link)
        reply_markup = InlineKeyboardMarkup(keyboard)
        update.message.reply_text(message, reply_markup=reply_markup)
        return
    query = User.select().join(UserInterests).join(Interest).where(User.tlg_id == user.id)
    message = "{}\nУказано {} интересов для уточнения новостей".format(message, query.count())
    keyboard.append([InlineKeyboardButton("Уточнить интересы", callback_data="interests_set")])
    keyboard = appendSocialButtons(keyboard, ref_link)
    # Final reply
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text(message, reply_markup=reply_markup)
Ejemplo n.º 4
0
def interests_show(bot, update):
    query = update.callback_query
    user = query.from_user
    keyboard = []
    for interest in Interest.select():
        if User.select().join(UserInterests).join(Interest).where(User.tlg_id == user.id,
                                                                  Interest.name == interest.name).exists():
            prefix = "✅ "
        else:
            prefix = ""
        keyboard.append([InlineKeyboardButton(prefix + interest.name, callback_data="interest_{}".format(interest.id))])
    keyboard.append([InlineKeyboardButton("Готово", callback_data="interests_finish")])
    reply_markup = InlineKeyboardMarkup(keyboard)
    query.edit_message_text("Отметьте ваши интересы.\nДля заверешения нажмите \"Готово\"", reply_markup=reply_markup)
Ejemplo n.º 5
0
    def __call__(self):
        while True:
            now = datetime.now()
            now = now.replace(microsecond=0)
            hour_ago = now - timedelta(hours=1)

            # проверка на запланированное действие в расписании
            actions = Schedule.select().where((Schedule.timestamp >= now) & (
                Schedule.timestamp < now + timedelta(seconds=1)))
            for action in actions:
                eval(action.action)(**json.loads(action.arguments))

            # проверка на last_activity
            users = User.select().where(
                (User.last_activity >= hour_ago)
                & (User.last_activity < hour_ago + timedelta(seconds=1))
                & (User.state != s.canceled) & (User.state != s.pause)
                & (User.state != s.stop))
            for user in users:
                bot.send_message(user.user_id, s.one_hour_reminder)
            sleep(1)
Ejemplo n.º 6
0
def publish_news(novelty_object, my_bot):
    # Match the user by interest and scale
    query = User.select().join(UserInterests).join(Interest).join(NoveltyInterests).join(Novelty).switch(User).join(Scale) \
        .where(Novelty.id == novelty_object.id,
               ((Scale.amount >= novelty_object.scale_from) & (Scale.amount < novelty_object.scale_to)))

    logger.info("Publish the news to {} users".format(query.count()))
    for user in query:
        try:
            my_bot.send_message(chat_id=user.tlg_id, text=novelty_object.text)
        except Unauthorized as u:
            user_msg = "{}:{} {}".format(user.username, user.first_name,
                                         user.last_name)
            logger.info(
                "Exception occurred while sending message to user {}\n Message: {}"
                .format(user_msg, u.message))
            continue
        except TelegramError as te:
            user_msg = "{}:{} {}".format(user.username, user.first_name,
                                         user.last_name)
            logger.info(
                "Telegram Error occurred while sending message to user {}\n Message: {}"
                .format(user_msg, te.message))
            continue