Esempio n. 1
0
async def info(call: CallbackQuery, state: FSMContext):
    await call.answer()

    settings = database.get_settings(call.from_user.id) or {}

    msg = 'Отправка оповещений через Telegram '
    if settings.get('active'):
        msg += '<b>активирована</b>.'
    else:
        msg += '<b>отключена</b>.'

    msg += '\nТекущий e-mail: '
    if settings.get('email'):
        msg += f'<b>{settings["email"]}</b>.'
    else:
        msg += '<b>не задан</b>.'

    msg += '\nОтправка оповещений на e-mail '
    if settings.get('email_active'):
        msg += '<b>активирована</b>.'
    else:
        msg += '<b>отключена</b>.'

    for host in fl_parser.HOSTS:
        msg += '\n\n\n<b>Настройки фильтров для сайта '
        msg += f'{fl_parser.host_to_hashtag(host)}</b>.'

        job_filters = database.get_filters(
            user_id=call.from_user.id, host=host, query='keywords') or []
        msg += f'\n\n{EMO_KEY} Поиск по ключевым словам:\n'
        if len(job_filters) > 0:
            msg += ('<b>' + ', '.join(job_filters[0]['keywords'].split(',')) +
                    '</b>.')
        else:
            msg += '<b>не настроен</b>.'

        job_filters = database.get_filters(
            user_id=call.from_user.id, host=host, query='categories') or []
        msg += f'\n\n{EMO_CLIPBOARD} Поиск по категориям:\n'
        if len(job_filters) > 0:
            titles = fl_parser.get_all_titles(host)
            cat_ids = (job_filters[0]['categories'] +
                       job_filters[0]['subcategories'])
            msg += '<b>'
            msg += ', '.join([f'"{titles[cat_id]}"' for cat_id in cat_ids])
            msg += '</b>.'
        else:
            msg += '<b>не настроен</b>.'

    await Menu.info.set()
    await call.message.edit_text(text=msg,
                                 reply_markup=menu.get_back(),
                                 parse_mode=ParseMode.HTML)
def get_root(user_id: str) -> InlineKeyboardMarkup:
    settings = database.get_settings(user_id) or {}

    markup = InlineKeyboardMarkup()

    if settings.get('active'):
        markup.row(
            InlineKeyboardButton(
                text=f'{EMO_BELL} Отключить отправку оповещений',
                callback_data='disable'))
    else:
        markup.row(
            InlineKeyboardButton(
                text=f'{EMO_NO_BELL} Активировать отправку оповещений',
                callback_data='enable'))

    markup.row(
        InlineKeyboardButton(text=f'{EMO_MEMO} Добавить фильтры оповещений',
                             callback_data='select_host'))

    if settings.get('email'):
        markup.row(
            InlineKeyboardButton(
                text=f'{EMO_EMAIL} Изменить e-mail для оповещений',
                callback_data='input_email'))
    else:
        markup.row(
            InlineKeyboardButton(
                text=f'{EMO_EMAIL} Ввести e-mail для оповещений',
                callback_data='input_email'))

    if settings.get('email_active'):
        markup.row(
            InlineKeyboardButton(
                text=f'{EMO_BELL} Отключить оповещения по e-mail',
                callback_data='email_disable'))
    else:
        markup.row(
            InlineKeyboardButton(
                text=f'{EMO_NO_BELL} Активировать оповещения по e-mail',
                callback_data='email_enable'))

    markup.row(
        InlineKeyboardButton(
            text=f'{EMO_CROSS_MARK} Удалить все фильтры оповещений',
            callback_data='confirm_delete'))

    markup.row(
        InlineKeyboardButton(text=f'{EMO_INFORMATION} Информация о настройках',
                             callback_data='info'))

    return markup
Esempio n. 3
0
def handle_settings(bot, message):
    member_status = bot.get_chat_member(
        chat_id=message.chat.id,
        user_id=message.from_user.id,
    ).status

    if not (message.chat.type == "supergroup"):
        return False

    if not (member_status == "creator" or member_status == "administrator"):
        return False

    try:
        settings_from_message = json.loads(message.text[9:].strip())
    except json.decoder.JSONDecodeError:
        settings_from_message = None

    if not (settings_from_message
            and validate_settings(settings_schema, settings_from_message)):
        bot.send_message(
            chat_id=message.chat.id,
            text=settings_message_error,
            parse_mode="markdown",
        )
        return False

    settings = database.get_settings(chat_id=message.chat.id, )

    if not settings:
        database.create_settings(
            chat_id=message.chat.id,
            votes_for_decision=settings_from_message["votes_for_decision"],
            punishment=settings_from_message["punishment"],
            days=settings_from_message["days"],
        )
    else:
        database.update_settings(
            id=settings.id,
            votes_for_decision=settings_from_message["votes_for_decision"],
            punishment=settings_from_message["punishment"],
            days=settings_from_message["days"],
        )

    bot.send_message(
        chat_id=message.chat.id,
        text=settings_message_success,
        parse_mode="markdown",
    )

    return True
Esempio n. 4
0
async def menu_input_email(call: CallbackQuery, state: FSMContext):
    await call.answer()

    settings = database.get_settings(call.from_user.id) or {}
    if settings.get('email'):
        msg = f'Текущий e-mail: <b>{settings["email"]}</b>.'
    else:
        msg = 'Текущий e-mail <b>не задан</b>.'

    msg += '\n\nВведите <b>e-mail</b> для оповещений о новых проектах:'

    await Menu.input_email.set()
    await call.message.edit_text(text=msg,
                                 reply_markup=menu.get_back(),
                                 parse_mode=ParseMode.HTML)
Esempio n. 5
0
async def settings(self, message, args):
    if args:
        return await error_message(message)

    settings = db.get_settings(message.author.id)
    embed = discord.Embed(title=f"Your current settings", colour=BOT_COLOR)

    settings = [('prefix', f'``{settings[1]}``'),
                ('group', f'``{settings[2]}``')]

    for set in settings:
        embed.add_field(name=set[0], value=set[1], inline=True)

    msg = await message.channel.send(embed=embed)
    await msg.add_reaction(emoji='❌')
Esempio n. 6
0
def handle_callback_vote(bot, call):
    # Получение голосовалки
    poll = database.get_poll(
        chat_id=call.message.chat.id,
        message_id=call.message.message_id,
    )

    if not poll:
        bot.answer_callback_query(
            callback_query_id=call.id,
            text=callback_error_no_poll,
            show_alert=True,
        )
        return False

    # Получение голоса
    vote = database.get_vote(
        poll_id=poll.id,
        voted_id=call.from_user.id,
    )

    # Создание/обновление/игнорирование голоса
    if not vote:
        database.create_vote(
            poll_id=poll.id,
            voted_id=call.from_user.id,
            to_ban=(call.data == "vote_for"),
        )
    elif ((vote.to_ban and call.data == "vote_for")
          or (not vote.to_ban and call.data == "vote_against")):
        bot.answer_callback_query(
            callback_query_id=call.id,
            text=callback_error_vote_counted,
            show_alert=False,
        )
        return True
    else:
        database.update_vote(
            id=vote.id,
            to_ban=(call.data == "vote_for"),
        )

    # Получение результатов голосования
    poll_results = database.get_poll_results(poll_id=poll.id, )

    # Подстановка результатов в клавиатуру
    bot.edit_message_reply_markup(
        chat_id=call.message.chat.id,
        message_id=call.message.message_id,
        reply_markup=create_poll_keyboard(
            votes_for_amount=poll_results["votes_for_amount"],
            votes_against_amount=poll_results["votes_against_amount"],
        ),
    )

    # Нотификейшн о выбранном варианте ответа
    bot.answer_callback_query(
        callback_query_id=call.id,
        text=callback_message.format("Да" if call.data ==
                                     "vote_for" else "Нет"),
        show_alert=False,
    )

    # Получение настроек бота
    settings = database.get_settings(chat_id=call.message.chat.id)

    # Если голосов не достаточно для принятия решения - выход
    if ((poll_results["votes_for_amount"] < settings.votes_for_decision) and
        (poll_results["votes_against_amount"] < settings.votes_for_decision)):
        return True

    # Получение инфы об обвиняемом
    accused = bot.get_chat_member(
        chat_id=call.message.chat.id,
        user_id=poll.accused_id,
    )
    accused_full_name = "{} {}".format(
        accused.user.first_name,
        accused.user.last_name,
    )

    # Большинство проголосовало против - выход
    if (poll_results["votes_against_amount"] >= settings.votes_for_decision):
        bot.send_message(
            chat_id=call.message.chat.id,
            text=result_message_innocent.format(
                accused_full_name,
                poll.accused_id,
                poll.accused_message,
            ),
            parse_mode="markdown",
        )
        bot.delete_message(
            chat_id=call.message.chat.id,
            message_id=poll.message_id,
        )
        database.delete_poll(poll.id)
        return True

    # Определяем тип наказания
    punishment = "ban" if poll.reason == "spam" else settings.punishment

    # Применение наказания
    if (punishment == "ban"):
        bot.kick_chat_member(
            chat_id=call.message.chat.id,
            user_id=poll.accused_id,
            until_date=time.time(),
        )
    elif (punishment == "kick"):
        bot.kick_chat_member(
            chat_id=call.message.chat.id,
            user_id=poll.accused_id,
            until_date=time.time() + 60,
        )
    else:
        bot.restrict_chat_member(
            chat_id=call.message.chat.id,
            user_id=poll.accused_id,
            until_date=time.time() + settings.days * 86400,
        )

    # Сообщение о наказании
    bot.send_message(
        chat_id=call.message.chat.id,
        text=result_message_guilty.format(
            accused_full_name,
            poll.accused_id,
            "Спам" if poll.reason == "spam" else poll.accused_message,
            punishment,
        ),
        parse_mode="markdown",
    )

    # Удаление сообщения с голосовалкой
    bot.delete_message(
        chat_id=call.message.chat.id,
        message_id=poll.message_id,
    )

    # Удаление сообщения со спамом
    if poll.reason == "spam":
        bot.delete_message(
            chat_id=call.message.chat.id,
            message_id=poll.accused_message_id,
        )

    # Удаление голосовалки
    database.delete_poll(poll.id)

    return True
Esempio n. 7
0
def get_settings():
    return {"settings": database.get_settings()}
Esempio n. 8
0
    def openSettings(self):
        self.in_settings = True

        self.setBoxesVisibility(False)
        self.openSettingsButton.setVisible(False)
        self.allInstallButton.setVisible(False)
        self.packageSelector.setVisible(False)
        self.fileDrop.setVisible(False)

        applySettingsButton = getButton("Применить")
        self.mainLayout.addWidget(applySettingsButton, 0, 4, 1, 1)
        applySettingsButton.clicked.connect(
            lambda state: saveSettings(packageEdit, oneDeviceCheckBox))

        closeSettingsButton = getButton("Назад")
        self.mainLayout.addWidget(closeSettingsButton, 0, 3, 1, 1)
        closeSettingsButton.clicked.connect(lambda state: closeSettings())

        settings = get_settings()

        settingsBox = Box(self.scrollWidget)

        packageLabel = getLabel("Имя пакета приложения")
        packageInfoLabel = getLabel("Можно ввести несколько через запятую")

        packageEdit = QtWidgets.QLineEdit(settings.get('package'))

        settingsBox.boxLayout.addWidget(packageLabel)
        settingsBox.boxLayout.addWidget(packageInfoLabel)
        settingsBox.boxLayout.addWidget(packageEdit)

        oneDeviceCheckBox = QtWidgets.QCheckBox('Режим одного устройства')
        if isOneDevice():
            self.OneDevice.setVisible(False)
            #self.OneDevice.deleteLater()
            oneDeviceCheckBox.setChecked(True)
        else:
            oneDeviceCheckBox.setChecked(False)
        settingsBox.boxLayout.addWidget(oneDeviceCheckBox)

        self.scrollLayout.addWidget(settingsBox)

        def saveSettings(url, checkbox):
            text = url.text().strip()
            is_checked = checkbox.isChecked()
            if not text.isspace():
                Timer(0, set_settings, args=[text, is_checked]).start()

            closeSettings()

        def closeSettings():
            applySettingsButton.deleteLater()
            closeSettingsButton.deleteLater()
            settingsBox.deleteLater()
            self.in_settings = False

            self.allInstallButton.setVisible(True)
            self.openSettingsButton.setVisible(True)
            self.packageSelector.setVisible(True)
            self.fileDrop.setVisible(True)
            self.setBoxesVisibility(True)

            self.fillPackageSelector()
async def notify_users(bot: Bot, user_id=None) -> bool:
    """Возвращаемое значение:
    True, если сообщения фактически были кому-то отправлены;
    False, если никаких отправок не было (к обработке ошибок это не относится).
    """
    result = False

    if user_id:
        user = database.get_settings(user_id)
        if user:
            users = [user]
        else:
            users = []
    else:
        users = database.get_settings_all() or []

    for user in users:
        if not (user['active'] or user['email_active']):
            continue

        for host in fl_parser.HOSTS:
            jobs_complete_list = []
            for query in ['keywords', 'categories']:
                job_filters = database.get_filters(
                    user_id=user['user_id'], host=host, query=query) or []

                if not job_filters:
                    continue

                jobs = fl_parser.get_jobs(
                    host=host,
                    category_ids=job_filters[0]['categories'],
                    subcategory_ids=job_filters[0]['subcategories'],
                    keywords=job_filters[0]['keywords'])

                jobs = fl_parser.get_recent_jobs(
                    jobs=jobs, last_job_url=job_filters[0]['last_job_url'])

                if not jobs:
                    continue

                database.save_filter(
                    user_id=user['user_id'],
                    host=host,
                    categories=job_filters[0]['categories'],
                    subcategories=job_filters[0]['subcategories'],
                    keywords=job_filters[0]['keywords'],
                    last_job_url=jobs[0]['url'])

                if len(jobs) > MAX_JOB_COUNT:
                    jobs = jobs[:MAX_JOB_COUNT]

                i = 0
                while i <= len(jobs) - 1:
                    append = True
                    for job in jobs_complete_list:
                        if job['url'] == jobs[i]['url']:
                            append = False
                            break
                    if append:
                        jobs_complete_list.append(jobs[i])
                        i += 1
                    else:
                        del jobs[i]

                if user['active'] and jobs:
                    msg = ''
                    for index, job in enumerate(jobs):
                        msg += (
                            f'<b><a href="{job["url"]}">{job["title"]}</a></b>'
                            + f'\n{EMO_MONEY} <b>{job["price"]}</b>' +
                            f' {EMO_POINT_RIGHT} ' +
                            f'<b>{fl_parser.host_to_hashtag(host)}</b>' +
                            f'\n{job["description"]}')

                        if index < len(jobs) - 1:
                            msg += '\n\n\n'

                    try:
                        await bot.send_message(user['user_id'],
                                               msg,
                                               parse_mode=ParseMode.HTML,
                                               disable_web_page_preview=True)
                        result = True
                    except Exception as e:
                        logging.error(e)

                if user['email_active'] and jobs:
                    text = ''
                    html = HTML_BEGIN

                    for index, job in enumerate(jobs):
                        html += (
                            f'<p>\n<b><a href="{job["url"]}">' +
                            f'{escape(job["title"])}</a></b>' +
                            f'<br><b>Бюджет проекта:</b> {job["price"]}<br>' +
                            f'{escape(job["description"])}\n</p>\n')

                        text += (
                            f'Заголовок проекта: {job["title"]}\n' +
                            f'Ссылка на страницу проекта: {job["url"]}\n' +
                            f'Бюджет: {job["price"]}\n' +
                            f'Описание:\n{job["description"]}')

                        if index < len(jobs) - 1:
                            html += (
                                '<p>--- + --- + --- + --- + --- + ---</p>' +
                                '\n')
                            text += '\n\n--- + --- + --- + --- + --- + ---\n\n'

                    html += HTML_END

                    send_email(email_receiver=user['email'],
                               email_subject=f'Новые проекты от {host}: ' +
                               f'{jobs[0]["title"]}',
                               text_content=text,
                               html_content=html)
                    result = True

                await asyncio.sleep(
                    randint(REQUEST_DELAY_MIN, REQUEST_DELAY_MAX))

    return result