def detail_text(self):
     from models import Keyword
     keywords = Keyword.select().where(Keyword.entity == self)
     txt = '{}'.format(self.__str__())
     txt += '\n_{}_'.format(util.escape_markdown(
         self.name)) if self.name else ''
     txt += '\n\n{}'.format(self.description) if self.description else ''
     txt += util.escape_markdown('\n\nKeywords: {}'.format(', '.join(
         [str(k) for k in keywords])) if keywords else '')
     return txt
Beispiel #2
0
    def _get_keyword_id(self, word, type_):
        try:
            keyword = Keyword.select(word=word, type=type_).first()
        except Exception as e:
            print(f"Failed to search keyword {word} with error: {e}")
            return -1

        if keyword is None:
            try:
                keyword = Keyword(created=datetime.now(),
                                  word=word,
                                  type=type_)
                keyword.flush()
            except Exception as e:
                print(f"Failed to insert keyword {keyword} with error: {e}")
                return -1

        return keyword.id
 def keywords(self):
     from models.keywordmodel import Keyword
     return Keyword.select().where(Keyword.entity == self)
def set_keywords(bot, update, chat_data, to_edit):
    chat_id = util.uid_from_update(update)
    keywords = Keyword.select().where(Keyword.entity == to_edit)
    chat_data['edit_bot'] = to_edit
    set_keywords_msgid = chat_data.get('set_keywords_msg')

    pending = Suggestion.select().where(
        Suggestion.executed == False, Suggestion.subject == to_edit,
        Suggestion.action << ['add_keyword', 'remove_keyword'])
    pending_removal = [y for y in pending if y.action == 'remove_keyword']

    # Filter keywords by name to not include removal suggestions
    # We don't need to do this for add_keyword suggestions, because duplicates are not allowed.
    keywords = [
        k for k in keywords
        if k.name not in [s.value for s in pending_removal]
    ]

    kw_remove_buttons = [
        InlineCallbackButton('{} ✖️'.format(x),
                             callback_action=CallbackActions.REMOVE_KEYWORD,
                             params={
                                 'id': to_edit.id,
                                 'kwid': x.id
                             }) for x in keywords
    ]
    kw_remove_buttons.extend([
        InlineKeyboardButton('#{} 👓✖️'.format(x.value),
                             callback_data=util.callback_for_action(
                                 CallbackActions.DELETE_KEYWORD_SUGGESTION, {
                                     'id': to_edit.id,
                                     'suggid': x.id
                                 }))
        for x in [y for y in pending if y.action == 'add_keyword']
    ])
    kw_remove_buttons.extend([
        InlineKeyboardButton('#{} 👓❌'.format(x.value),
                             callback_data=util.callback_for_action(
                                 CallbackActions.DELETE_KEYWORD_SUGGESTION, {
                                     'id': to_edit.id,
                                     'suggid': x.id
                                 })) for x in pending_removal
    ])
    buttons = util.build_menu(
        kw_remove_buttons,
        2,
        header_buttons=[
            InlineKeyboardButton(captions.DONE,
                                 callback_data=util.callback_for_action(
                                     CallbackActions.ABORT_SETTING_KEYWORDS,
                                     {'id': to_edit.id}))
        ])
    reply_markup = InlineKeyboardMarkup(buttons)
    msg = util.send_or_edit_md_message(
        bot,
        chat_id,
        util.action_hint(
            'Send me the keywords for {} one by one...\n\n{}'.format(
                util.escape_markdown(to_edit.username),
                messages.KEYWORD_BEST_PRACTICES)),
        to_edit=set_keywords_msgid,
        reply_markup=reply_markup)

    if msg:
        # message might not have been edited if the user adds an already-existing keyword
        # TODO: should the user be notified about this?
        chat_data['set_keywords_msg'] = msg.message_id

    return BotStates.SENDING_KEYWORDS
Beispiel #5
0
def send_bot_details(bot, update, chat_data, item=None):
    is_group = util.is_group_message(update)
    cid = update.effective_chat.id
    user = User.from_update(update)

    if item is None:
        if is_group:
            return

        try:
            text = update.message.text
            bot_in_text = re.findall(settings.REGEX_BOT_IN_TEXT, text)[0]
            item = Bot.by_username(bot_in_text, include_disabled=True)

        except Bot.DoesNotExist:
            update.message.reply_text(
                util.failure(
                    "This bot is not in the @BotList. If you think this is a "
                    "mistake, see the /examples for /contributing."))
            return

    header_buttons = []
    buttons = []
    if item.disabled:
        txt = '{} {} and thus removed from the @BotList.'.format(
            item, Bot.DisabledReason.to_str(item.disabled_reason))
    elif item.approved:
        # bot is already in the botlist => show information
        txt = item.detail_text
        if item.description is None and not Keyword.select().where(
                Keyword.entity == item).exists():
            txt += ' is in the @BotList.'
        btn = InlineCallbackButton(captions.BACK_TO_CATEGORY,
                                   CallbackActions.SELECT_BOT_FROM_CATEGORY,
                                   {'id': item.category.id})
        header_buttons.insert(0, btn)
        header_buttons.append(
            InlineKeyboardButton(captions.SHARE,
                                 switch_inline_query=item.username))

        # if cid in settings.MODERATORS:
        header_buttons.append(
            InlineKeyboardButton("📝 Edit",
                                 callback_data=util.callback_for_action(
                                     CallbackActions.EDIT_BOT,
                                     {'id': item.id})))

        # Add favorite button
        favorite_found = Favorite.search_by_bot(user, item)
        if favorite_found:
            buttons.append(
                InlineKeyboardButton(captions.REMOVE_FAVORITE_VERBOSE,
                                     callback_data=util.callback_for_action(
                                         CallbackActions.REMOVE_FAVORITE, {
                                             'id': favorite_found.id,
                                             'details': True
                                         })))
        else:
            buttons.append(
                InlineKeyboardButton(captions.ADD_TO_FAVORITES,
                                     callback_data=util.callback_for_action(
                                         CallbackActions.ADD_TO_FAVORITES, {
                                             'id': item.id,
                                             'details': True
                                         })))
    else:
        txt = '{} is currently pending to be accepted for the @BotList.'.format(
            item)
        if cid in settings.MODERATORS:
            header_buttons.append(
                InlineKeyboardButton("🛃 Accept / Reject",
                                     callback_data=util.callback_for_action(
                                         CallbackActions.APPROVE_REJECT_BOTS,
                                         {'id': item.id})))

    if buttons or header_buttons:
        reply_markup = InlineKeyboardMarkup(
            util.build_menu(buttons, n_cols=3, header_buttons=header_buttons))
    else:
        reply_markup = None

    reply_markup, callback = botlistchat.append_delete_button(
        update, chat_data, reply_markup)

    # Should we ever decide to show thumbnails *shrug*
    # if os.path.exists(item.thumbnail_file):
    #     preview = True
    #     photo = '[\xad]({})'.format('{}/thumbnail/{}.jpeg'.format(
    #         settings.API_URL,
    #         item.username[1:]
    #     ))
    #     log.info(photo)
    #     txt = photo + txt
    # else:
    #     preview = False

    msg = bot.formatter.send_or_edit(cid,
                                     txt,
                                     to_edit=util.mid_from_update(update),
                                     reply_markup=reply_markup)
    callback(msg)
    Statistic.of(update, 'view-details', item.username, Statistic.ANALYSIS)
    return CallbackStates.SHOWING_BOT_DETAILS