def add_keyword(bot, update, chat_data):
    user = User.from_telegram_object(update.effective_user)
    if check_suggestion_limit(bot, update, user):
        return
    kw = update.message.text
    bot_to_edit = chat_data.get('edit_bot')
    kw = helpers.format_keyword(kw)

    # Sanity checks
    if kw in settings.FORBIDDEN_KEYWORDS:
        update.message.reply_text('The keyword {} is forbidden.'.format(kw))
        return
    if len(kw) <= 1:
        update.message.reply_text('Keywords must be longer than 1 character.')
        return
    if len(kw) >= 20:
        update.message.reply_text(
            'Keywords must not be longer than 20 characters.')

    # Ignore duplicates
    try:
        Keyword.get((Keyword.name == kw) & (Keyword.entity == bot_to_edit))
        return
    except Keyword.DoesNotExist:
        pass

    Suggestion.add_or_update(user=user,
                             action='add_keyword',
                             subject=bot_to_edit,
                             value=kw)
    set_keywords(bot, update, chat_data, bot_to_edit)
    Statistic.of(update, 'added keyword to'.format(kw), bot_to_edit.username)
示例#2
0
    def add_or_update(user, action, subject, value):
        from models import Statistic
        # value may be None
        already_exists = Suggestion.get_pending(action, subject, user, value)
        if already_exists:
            # Does the new suggestion reset the value?
            if action == 'remove_keyword':
                try:
                    kw = Keyword.get(entity=subject, name=value)
                    kw.delete_instance()
                except Keyword.DoesNotExist:
                    pass
            elif action == 'add_keyword':
                return  # TODO: is this right?
            elif value == getattr(already_exists.subject, action):
                already_exists.delete_instance()
                return None

            already_exists.value = value
            already_exists.save()

            Statistic.of(user, 'made changes to their suggestion: ',
                         str(already_exists))

            return already_exists
        else:
            new_suggestion = Suggestion(user=user,
                                        action=action,
                                        date=datetime.date.today(),
                                        subject=subject,
                                        value=value)
            new_suggestion.save()
            Statistic.of(user, 'suggestion', new_suggestion._md_plaintext())
            return new_suggestion
示例#3
0
def get_keyword(update: Update, context: CallbackContext):
    chat_id = update.message.from_user.id
    gif = Gif.get(Gif.id == context.user_data['gif'])
    text = update.message.text
    if text == 'DONE':
        context.bot.send_message(chat_id,
                                 'do you agree to show this gif to others?!',
                                 reply_markup=ReplyKeyboardMarkup([['YES'], ['NO']]))
        return PUBLIC

    try:
        keyword = Keyword.get(Keyword.text == text.lower())
        if keyword in gif.keywords:
            context.bot.send_message(chat_id, 'You have already added this keyword!')
        else:
            gif.keywords.add(keyword)
            context.bot.send_message(chat_id, 'keyword successfully added!')
    except:
        keyword = Keyword.insert({
            Keyword.text: text.lower()
        }).execute()
        gif.keywords.add(keyword)
        context.bot.send_message(chat_id, 'keyword successfully added!')

    return
示例#4
0
    def apply(self):
        try:
            if self.subject is None:
                self.delete_instance()
                return False
        except Bot.DoesNotExist:
            self.delete_instance()
            return False

        if self.action == 'category':
            from models import Category
            try:
                cat = Category.get(Category.id == self.value)
                self.subject.category = cat
            except Category.DoesNotExist:
                raise AttributeError("Category to change to does not exist.")
        elif self.action == 'name':
            self.subject.name = self.value
        elif self.action == 'username':
            self.subject.username = self.value
        elif self.action == 'description':
            self.subject.description = self.value
        elif self.action == 'extra':
            self.subject.extra = self.value
        elif self.action == 'country':
            if self._value == 'None' or self._value is None:
                self.subject.country = None
            else:
                from models import Country
                try:
                    con = Country.get(id=self._value)
                    self.subject.country = con
                except Country.DoesNotExist:
                    raise AttributeError(
                        "Country to change to does not exist.")
        elif self.action == 'inlinequeries':
            self.subject.inlinequeries = bool(self.value)
        elif self.action == 'official':
            self.subject.official = bool(self.value)
        elif self.action == 'offline':
            self.subject.offline = bool(self.value)
        elif self.action == 'spam':
            self.subject.spam = bool(self.value)
        elif self.action == 'add_keyword':
            kw_obj = Keyword(name=self.value, entity=self.subject)
            kw_obj.save()
        elif self.action == 'remove_keyword':
            try:
                kw_obj = Keyword.get(name=self.value, entity=self.subject)
                kw_obj.delete_instance()
            except Keyword.DoesNotExist:
                raise AttributeError(
                    "Keyword to disable does not exist anymore.")

        self.subject.save()

        self.executed = True
        self.save()
        return True
示例#5
0
def link_keyword_to_category():
    keyword = Keyword.get(keyword_id=request.values['keywordId'])
    category_id = request.values['categoryId']
    keyword.categories = [Category.get(
        category_id=category_id)] if category_id != '-1' else []
    db_session.commit()
    return HttpResponse('Keyword {0} assigned to category {1}'.format(
        keyword.keyword_id, category_id))
示例#6
0
def set_keywords():
    data = request.get_json(silent=True)
    for key, values in data['keywords'].items():
        keyword = Keyword.get(keyword_id=key)
        description = keyword.description
        for i in range(len(values)):
            keyword.value = values[i]
            db_session.commit()
            if i != len(values) - 1:
                # Creating new keyword for multiple values
                keyword = set_attributes(Keyword(), description=description)
                db_session.add(keyword)
    return HttpResponse('Keywords set!')
示例#7
0
    def by_name(cls, name):
        from sqlalchemy import func
        category = cls.get(func.lower(cls.name) == name.lower())

        if category is None:
            from models import Keyword
            keyword = Keyword.get(func.lower(Keyword.value) == name.lower())
            if keyword is not None:
                # TODO: Apply AI categorizer from keywords intelligence here
                category = keyword.categories[0] if len(
                    keyword.categories) > 0 else None
            else:
                cls.add_keyword(name)

        return category
示例#8
0
def register(dp: Dispatcher, bot_checker: "BotChecker"):
    def add(*args, **kwargs):
        dp.add_handler(*args, **kwargs)

    keywords_handler = ConversationHandler(
        entry_points=[
            InlineCallbackHandler(
                CallbackActions.EDIT_BOT_KEYWORDS,
                botproperties.set_keywords_init,
                serialize=lambda data: dict(to_edit=Bot.get(id=data["id"])),
                pass_chat_data=True,
            )
        ],
        states={
            BotStates.SENDING_KEYWORDS: [
                MessageHandler(Filters.text,
                               botproperties.add_keyword,
                               pass_chat_data=True),
                InlineCallbackHandler(
                    CallbackActions.REMOVE_KEYWORD,
                    botproperties.remove_keyword,
                    serialize=lambda data: dict(
                        to_edit=Bot.get(id=data["id"]),
                        keyword=Keyword.get(id=data["kwid"]),
                    ),
                    pass_chat_data=True,
                ),
                InlineCallbackHandler(
                    CallbackActions.DELETE_KEYWORD_SUGGESTION,
                    botproperties.delete_keyword_suggestion,
                    serialize=lambda data: dict(
                        to_edit=Bot.get(id=data["id"]),
                        suggestion=Suggestion.get(id=data["suggid"]),
                    ),
                    pass_chat_data=True,
                ),
            ]
        },
        fallbacks=[
            CallbackQueryHandler(
                callback_router,
                pass_chat_data=True,
                pass_user_data=True,
                pass_job_queue=True,
            )
        ],
        per_user=True,
        allow_reentry=False,
    )
    add(keywords_handler)

    broadcasting_handler = ConversationHandler(
        entry_points=[
            InlineCallbackHandler("broadcast",
                                  broadcasts.broadcast,
                                  pass_user_data=True),
            CommandHandler("broadcast",
                           broadcasts.broadcast,
                           pass_user_data=True),
            CommandHandler("bc", broadcasts.broadcast, pass_user_data=True),
        ],
        states={
            BotStates.BROADCASTING: [
                MessageHandler(Filters.text,
                               broadcasts.broadcast_preview,
                               pass_user_data=True)
            ]
        },
        fallbacks=[],
        per_user=True,
        per_chat=False,
        allow_reentry=True,
    )
    add(broadcasting_handler)

    add(
        CallbackQueryHandler(
            callback_router,
            pass_chat_data=True,
            pass_user_data=True,
            pass_job_queue=True,
        ))

    add(
        CommandHandler(("cat", "category", "categories"),
                       select_category,
                       pass_chat_data=True))
    add(
        CommandHandler(("s", "search"),
                       search_handler,
                       pass_args=True,
                       pass_chat_data=True))

    add(MessageHandler(Filters.reply, reply_router, pass_chat_data=True),
        group=-1)
    add(MessageHandler(Filters.forwarded, forward_router, pass_chat_data=True))

    add(CommandHandler("admin", admin.menu))
    add(CommandHandler("a", admin.menu))

    add(
        CommandHandler(("rej", "reject"),
                       admin.reject_bot_submission,
                       pass_args=True))
    add(
        CommandHandler(
            ("rejsil", "rejectsil", "rejsilent", "rejectsilent"),
            lambda bot, update: admin.reject_bot_submission(
                bot, update, None, notify_submittant=False),
        ))

    # admin menu
    add(RegexHandler(captions.APPROVE_BOTS + ".*", admin.approve_bots))
    add(
        RegexHandler(captions.APPROVE_SUGGESTIONS + ".*",
                     admin.approve_suggestions))
    add(RegexHandler(captions.PENDING_UPDATE + ".*", admin.pending_update))
    add(
        RegexHandler(captions.SEND_BOTLIST,
                     admin.prepare_transmission,
                     pass_chat_data=True))
    add(RegexHandler(captions.FIND_OFFLINE, admin.send_offline))
    add(RegexHandler(captions.SEND_CONFIG_FILES, admin.send_runtime_files))
    add(RegexHandler(captions.SEND_ACTIVITY_LOGS, admin.send_activity_logs))

    # main menu
    add(RegexHandler(captions.ADMIN_MENU, admin.menu))
    add(RegexHandler(captions.REFRESH, admin.menu))
    add(RegexHandler(captions.CATEGORIES, select_category,
                     pass_chat_data=True))
    add(RegexHandler(captions.EXPLORE, explore.explore, pass_chat_data=True))
    add(RegexHandler(captions.FAVORITES, favorites.send_favorites_list))
    add(RegexHandler(captions.NEW_BOTS, show_new_bots, pass_chat_data=True))
    add(RegexHandler(captions.SEARCH, search_handler, pass_chat_data=True))
    add(RegexHandler(captions.CONTRIBUTING, help.contributing))
    add(RegexHandler(captions.EXAMPLES, help.examples))
    add(RegexHandler(captions.HELP, help.help))

    add(RegexHandler("^/edit\d+$", admin.edit_bot, pass_chat_data=True),
        group=1)

    add(RegexHandler("^/approve\d+$", admin.edit_bot, pass_chat_data=True),
        group=1)
    add(CommandHandler("approve", admin.short_approve_list))

    add(CommandHandler(("manybot", "manybots"), admin.manybots))

    add(
        CommandHandler(
            "new",
            partial(contributions.new_bot_submission, bot_checker=bot_checker),
            pass_args=True,
            pass_chat_data=True,
        ))
    add(
        RegexHandler(
            ".*#new.*",
            lambda bot, update, chat_data: contributions.new_bot_submission(
                bot, update, chat_data, args=None, bot_checker=bot_checker),
            pass_chat_data=True,
        ),
        group=1,
    )
    add(
        CommandHandler("offline",
                       contributions.notify_bot_offline,
                       pass_args=True))
    add(RegexHandler(".*#offline.*", contributions.notify_bot_offline),
        group=1)
    add(CommandHandler("spam", contributions.notify_bot_spam, pass_args=True))
    add(RegexHandler(".*#spam.*", contributions.notify_bot_spam), group=1)

    add(CommandHandler("help", help.help))
    add(CommandHandler(("contribute", "contributing"), help.contributing))
    add(CommandHandler("examples", help.examples))
    add(CommandHandler("rules", help.rules))

    add(
        CommandHandler(("addfav", "addfavorite"),
                       favorites.add_favorite_handler,
                       pass_args=True))
    add(
        CommandHandler(("f", "fav", "favorites"),
                       favorites.send_favorites_list))

    add(CommandHandler(("e", "explore"), explore.explore, pass_chat_data=True))
    add(CommandHandler("official", explore.show_official))

    add(
        CommandHandler(
            "ban",
            partial(admin.ban_handler, ban_state=True),
            pass_args=True,
            pass_chat_data=True,
        ))
    add(
        CommandHandler(
            "unban",
            partial(admin.ban_handler, ban_state=False),
            pass_args=True,
            pass_chat_data=True,
        ))
    add(CommandHandler("t3chno", t3chnostats))
    add(CommandHandler("random", eastereggs.send_random_bot))
    add(
        CommandHandler("easteregg",
                       eastereggs.send_next,
                       pass_args=True,
                       pass_job_queue=True))

    add(CommandHandler("subscribe", manage_subscription))
    add(CommandHandler("newbots", show_new_bots, pass_chat_data=True))

    add(CommandHandler("accesstoken", access_token))

    add(
        CommandHandler(("stat", "stats", "statistic", "statistics"),
                       admin.send_statistic))

    add(
        CommandHandler(("log", "logs"),
                       admin.send_activity_logs,
                       pass_args=True))
    add(
        CommandHandler(
            ("debug", "analysis", "ana", "analyze"),
            lambda bot, update, args: admin.send_activity_logs(
                bot, update, args, Statistic.ANALYSIS),
            pass_args=True,
        ))
    add(
        CommandHandler(
            "info",
            lambda bot, update, args: admin.send_activity_logs(
                bot, update, args, Statistic.INFO),
            pass_args=True,
        ))
    add(
        CommandHandler(
            ("detail", "detailed"),
            lambda bot, update, args: admin.send_activity_logs(
                bot, update, args, Statistic.DETAILED),
            pass_args=True,
        ))
    add(
        CommandHandler(
            ("warn", "warning"),
            lambda bot, update, args: admin.send_activity_logs(
                bot, update, args, Statistic.WARN),
            pass_args=True,
        ))
    add(
        CommandHandler(
            "important",
            lambda bot, update, args: admin.send_activity_logs(
                bot, update, args, Statistic.IMPORTANT),
            pass_args=True,
        ))

    add(
        MessageHandler(
            Filters.text,
            lambda bot, update: botlistchat.text_message_logger(
                bot, update, log),
        ),
        group=99,
    )

    for hashtag in HINTS.keys():
        add(
            RegexHandler(r"{}.*".format(hashtag),
                         botlistchat.hint_handler,
                         pass_job_queue=True),
            group=1,
        )
    add(CommandHandler(("hint", "hints"), botlistchat.show_available_hints))

    add(
        RegexHandler(
            "^{}$".format(settings.REGEX_BOT_ONLY),
            send_bot_details,
            pass_chat_data=True,
        ))

    add(
        ChosenInlineResultHandler(inlinequeries.chosen_result,
                                  pass_chat_data=True))
    add(
        InlineQueryHandler(inlinequeries.inlinequery_handler,
                           pass_chat_data=True))
    add(MessageHandler(Filters.all, all_handler, pass_chat_data=True),
        group=98)