Пример #1
0
def search_bots(query):
    query = query.lower().strip()
    split = query.split(' ')

    # easter egg
    if query in ('awesome bot', 'great bot', 'superb bot', 'best bot',
                 'best bot ever'):
        return [Bot.by_username('@botlistbot')]

    # exact results
    where_query = ((fn.lower(Bot.username).contains(query)
                    | fn.lower(Bot.name) << split | fn.lower(Bot.extra)**query)
                   & (Bot.revision <= Revision.get_instance().nr & Bot.approved
                      == True & Bot.disabled == False))
    results = set(Bot.select().distinct().where(where_query))

    # keyword results
    keyword_results = Bot.select(Bot).join(
        Keyword).where((fn.lower(Keyword.name) << split)
                       & (Bot.revision <= Revision.get_instance().nr)
                       & (Bot.approved == True & Bot.disabled == False))
    results.update(keyword_results)

    # many @usernames
    usernames = re.findall(settings.REGEX_BOT_ONLY, query)
    if usernames:
        try:
            bots = Bot.many_by_usernames(usernames)
            print([b.username for b in bots])
            results.update(bots)
        except Bot.DoesNotExist:
            pass

    return list(results)
Пример #2
0
 def is_new(self):
     # today = datetime.date.today()
     # delta = datetime.timedelta(days=settings.BOT_CONSIDERED_NEW)
     # result = today - self.date_added <= delta
     # return result
     return self.revision >= Revision.get_instance(
     ).nr - settings.BOT_CONSIDERED_NEW + 1
Пример #3
0
 def many_by_usernames(names: List):
     results = Bot.select().where(
         (fn.lower(Bot.username) << [n.lower() for n in names])
         & (Bot.revision <= Revision.get_instance().nr)
         & (Bot.approved == True) & (Bot.disabled == False))
     if results:
         return results
     raise Bot.DoesNotExist
Пример #4
0
    def update_categories(self, categories: List[Category]):
        self.notify_admin(
            "Updating BotList categories to Revision {}...".format(
                Revision.get_instance().nr))

        for cat in categories:
            text = _format_category_bots(cat)

            log.info(f"Updating category {cat.name}...")
            msg = self.send_or_edit(text, cat.current_message_id)
            if msg:
                cat.current_message_id = msg.message_id
                self.sent['category'].append("{} {}".format(
                    'Resent' if self.resend else 'Updated', cat))
            cat.save()

        self._save_channel()

        # Add "share", "up", and "down" buttons
        for i in range(0, len(categories)):
            buttons = list()
            if i > 0:
                # Not first category
                # Add "Up" button
                buttons.append(
                    InlineKeyboardButton(
                        "🔺",
                        url=BotList.create_hyperlink(
                            categories[i - 1].current_message_id)))

            buttons.append(
                InlineKeyboardButton("Share",
                                     url="https://t.me/{}?start={}".format(
                                         settings.SELF_BOT_NAME,
                                         categories[i].id)))

            if i < len(categories) - 1:
                # Not last category
                buttons.append(
                    InlineKeyboardButton(
                        "🔻",
                        url=BotList.create_hyperlink(
                            categories[i + 1].current_message_id)))

            reply_markup = InlineKeyboardMarkup([buttons])

            log.info(
                f"Adding buttons to message with category {categories[i].name}..."
            )
            self.bot.edit_message_reply_markup(
                self.channel.chat_id,
                categories[i].current_message_id,
                reply_markup=reply_markup,
                timeout=60)
Пример #5
0
def send_botlist(bot, update, resend=False, silent=False):
    log.info("Re-sending BotList..." if resend else "Updating BotList...")

    channel = helpers.get_channel()
    revision = Revision.get_instance()
    revision.nr += 1
    revision.save()

    all_categories = Category.select_all()

    botlist = BotList(bot, update, channel, resend, silent)
    if resend:
        botlist.delete_full_botlist()
    botlist.update_intro()
    botlist.update_categories(all_categories)
    botlist.update_new_bots_list()
    botlist.update_category_list()
    botlist.send_footer()
    botlist.finish()
    channel.save()
    Statistic.of(update, 'send', 'botlist (resend: {})'.format(str(resend)),
                 Statistic.IMPORTANT)
Пример #6
0
 def select_pending_update():
     return Bot.select().where(Bot.approved == True,
                               Bot.revision == Revision.get_instance().next,
                               Bot.disabled == False)
Пример #7
0
 def select_approved():
     return Bot.select().where(Bot.approved == True,
                               Bot.revision <= Revision.get_instance().nr,
                               Bot.disabled == False)
Пример #8
0
 def select_new_bots():
     return Bot.select().where(Bot.is_new == True,
                               Bot.revision < Revision.get_instance().next,
                               Bot.approved == True, Bot.disabled == False)
Пример #9
0
 def of_category_without_new(category):
     return Bot.select().where(
         (Bot.category == category), (Bot.approved == True),
         (Bot.revision <= Revision.get_instance().nr),
         (Bot.disabled == False)).order_by(fn.Lower(Bot.username))
Пример #10
0
 def explorable_bots():
     results = Bot.select().where(
         ~(Bot.description.is_null()), (Bot.approved == True),
         (Bot.revision <= Revision.get_instance().nr),
         (Bot.offline == False), (Bot.disabled == False))
     return list(results)
Пример #11
0
import os

from decouple import config
from playhouse.migrate import SqliteMigrator, IntegerField, migrate
from playhouse.sqlite_ext import SqliteExtDatabase

from botlistbot.models.revision import Revision

db_path = config('DATABASE_URL',
                 default=os.path.expanduser('~/botlistbot.sqlite3'))
db = SqliteExtDatabase(db_path)

migrator = SqliteMigrator(db)

revision = IntegerField(default=100)

with db.transaction():
    migrate(migrator.add_column('bot', 'revision', revision), )

Revision.create_table(fail_silently=True)
Revision.insert({'nr': 101}).execute()
Пример #12
0
def new_bot_submission(bot, update, chat_data, args=None, bot_checker=None):
    tg_user = update.message.from_user
    user = User.from_telegram_object(tg_user)
    if util.stop_banned(update, user):
        return
    reply_to = util.original_reply_id(update)

    if args:
        text = " ".join(args)
    else:
        text = update.message.text
        command_no_args = (
            len(re.findall(r"^/new\s*$", text)) > 0
            or text.lower().strip() == "/new@botlistbot"
        )
        if command_no_args:
            update.message.reply_text(
                util.action_hint(
                    "Please use this command with an argument. For example:\n/new @mybot 🔎"
                ),
                reply_to_message_id=reply_to,
            )
            return

    # `#new` is already checked by handler
    try:
        username = re.match(settings.REGEX_BOT_IN_TEXT, text).groups()[0]
        if username.lower() == "@" + settings.SELF_BOT_NAME.lower():
            log.info("Ignoring {}".format(text))
            return
    except AttributeError:
        if args:
            update.message.reply_text(
                util.failure("Sorry, but you didn't send me a bot `@username`."),
                quote=True,
                parse_mode=ParseMode.MARKDOWN,
                reply_to_message_id=reply_to,
            )
        log.info("Ignoring {}".format(text))
        # no bot username, ignore update
        return

    try:
        new_bot = Bot.by_username(username, include_disabled=True)
        if new_bot.disabled:
            update.message.reply_text(
                util.failure(
                    "{} is banned from the @BotList.".format(new_bot.username)
                ),
                reply_to_message_id=reply_to,
            )
        elif new_bot.approved:
            update.message.reply_text(
                util.action_hint(
                    "Sorry fool, but {} is already in the @BotList 😉".format(
                        new_bot.username
                    )
                ),
                reply_to_message_id=reply_to,
            )
        else:
            update.message.reply_text(
                util.action_hint(
                    "{} has already been submitted. Please have patience...".format(
                        new_bot.username
                    )
                ),
                reply_to_message_id=reply_to,
            )
        return
    except Bot.DoesNotExist:
        new_bot = Bot(
            revision=Revision.get_instance().next,
            approved=False,
            username=username,
            submitted_by=user,
        )

    new_bot.inlinequeries = "🔎" in text
    new_bot.official = "🔹" in text

    # find language
    languages = Country.select().execute()
    for lang in languages:
        if lang.emoji in text:
            new_bot.country = lang

    new_bot.date_added = datetime.date.today()

    description_reg = re.match(settings.REGEX_BOT_IN_TEXT + " -\s?(.*)", text)
    description_notify = ""
    if description_reg:
        description = description_reg.group(2)
        new_bot.description = description
        description_notify = " Your description was included."

    new_bot.save()

    if (
        util.is_private_message(update)
        and util.uid_from_update(update) in settings.MODERATORS
    ):
        from botlistbot.components.explore import send_bot_details

        send_bot_details(bot, update, chat_data, new_bot)
    else:
        update.message.reply_text(
            util.success(
                "You submitted {} for approval.{}".format(new_bot, description_notify)
            ),
            parse_mode=ParseMode.MARKDOWN,
            reply_to_message_id=reply_to,
        )

        # Ask the user to fill in the bot details
        util.send_md_message(
            bot,
            update.effective_user.id,
            "Congratulations, you just submitted a bot to the @BotList. Please help us fill in the details below:",
        )
        edit_bot(bot, update, chat_data, to_edit=new_bot)

    try:
        check_submission(bot, bot_checker, new_bot)
    except Exception as e:
        log.exception(e)

    return ConversationHandler.END