Ejemplo n.º 1
0
def _new_bots_text():
    new_bots = Bot.select_new_bots()
    if len(new_bots) > 0:
        txt = "Fresh new bots since the last update 💙:\n\n{}".format(
            Bot.get_new_bots_markdown())
    else:
        txt = 'No new bots available.'
    return txt
Ejemplo n.º 2
0
 def add_bot(self):
     """Добавляем/обновляем существующего бота"""
     start_time = int(time.time())
     bot = Bot(start_time, 0, 0)
     self.session.add(bot)
     self.session.commit()
     return bot.id
Ejemplo n.º 3
0
    def send_footer(self):
        num_bots = Bot.select_approved().count()
        self.notify_admin('Sending footer...')

        # add footer as notification
        footer = '\n```'
        footer += '\n' + mdformat.centered("• @BotList •\n{}\n{} bots".format(
            datetime.date.today().strftime("%d-%m-%Y"), num_bots))
        footer += '```'

        if self.resend or not self.silent:
            try:
                self._delete_message(self.channel.footer_mid)
            except BadRequest as e:
                pass
            footer_to_edit = None
        else:
            footer_to_edit = self.channel.footer_mid

        footer_msg = self.bot.formatter.send_or_edit(
            self.channel.chat_id,
            footer,
            to_edit=footer_to_edit,
            timeout=120,
            disable_notifications=self.silent,
            reply_markup=self.portal_markup)
        if footer_msg:
            self.channel.footer_mid = footer_msg.message_id
            self.sent['footer'] = "Footer sent"
        self._save_channel()
Ejemplo n.º 4
0
def notify_bot_spam(bot, update, args=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'^/spam\s*$',
                       text)) > 0 or text.lower().strip() == '/spam@botlistbot'
        if command_no_args:
            update.message.reply_text(util.action_hint(
                "Please use this command with an argument. For example:\n/spam @mybot"
            ),
                                      reply_to_message_id=reply_to)
            return

    # `#spam` is already checked by handler
    try:
        username = re.match(settings.REGEX_BOT_IN_TEXT, text).groups()[0]
        if username == '@' + settings.SELF_BOT_NAME:
            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)
        else:
            log.info("Ignoring {}".format(text))
            # no bot username, ignore update
            pass
        return

    try:
        spam_bot = Bot.get(
            fn.lower(Bot.username)**username.lower(), Bot.approved == True)
        try:
            Suggestion.get(action="spam", subject=spam_bot)
        except Suggestion.DoesNotExist:
            suggestion = Suggestion(user=user,
                                    action="spam",
                                    date=datetime.date.today(),
                                    subject=spam_bot)
            suggestion.save()
        update.message.reply_text(util.success(
            "Thank you! We will review your suggestion and mark the bot as spammy."
        ),
                                  reply_to_message_id=reply_to)
    except Bot.DoesNotExist:
        update.message.reply_text(
            util.action_hint("The bot you sent me is not in the @BotList."),
            reply_to_message_id=reply_to)
    return ConversationHandler.END
Ejemplo n.º 5
0
def add_bots():
    """Add bots from a seed file. Data is stored in this format:

    creator_id|content_id|bot_name|bot_icon|bot_description
    """

    print("Bots")

    # Deletes any existing data in the bots table
    Bot.query.delete()

    for line in open("seed_files/bots.txt"):
        line = line.rstrip()

        creator_id, source_id, bot_name, bot_icon, bot_description = line.split(
            "|")

        bot = Bot(creator_id=creator_id,
                  source_id=source_id,
                  bot_name=bot_name,
                  bot_icon=bot_icon,
                  bot_description=bot_description)

        db.session.add(bot)

    db.session.commit()
Ejemplo n.º 6
0
def ban_user(bot, update, user: User, ban_state: bool):
    if user.banned and ban_state is True:
        update.message.reply_text(mdformat.none_action(
            "User {} is already banned.".format(user)),
                                  parse_mode='markdown')
        return
    if not user.banned and ban_state is False:
        update.message.reply_text(mdformat.none_action(
            "User {} is not banned.".format(user)),
                                  parse_mode='markdown')
        return
    user.banned = ban_state
    if ban_state is True:
        with db.atomic():
            users_bots = Bot.select().where((Bot.approved == False)
                                            & (Bot.submitted_by == user))
            for b in users_bots:
                b.delete_instance()

            users_suggestions = Suggestion.select().where(
                (Suggestion.executed == False) & (Suggestion.user == user))
            for s in users_suggestions:
                s.delete_instance()
        update.message.reply_text(mdformat.success(
            "User {} banned, all bot submissions and suggestions removed.".
            format(user)),
                                  parse_mode='markdown')
        Statistic.of(update, 'ban', user.markdown_short)
    else:
        update.message.reply_text(mdformat.success(
            "User {} unbanned.".format(user)),
                                  parse_mode='markdown')
        Statistic.of(update, 'unban', user.markdown_short)
    user.save()
Ejemplo n.º 7
0
def job_callback(bot, job):
    bot_checker = job.context.get('checker')
    bot_checker.reset()

    start = datetime.datetime.now()

    total_bot_count = BotModel.select().where(
        BotModel.userbot == False).count()
    batch_size = 5

    for i in range(1, int(total_bot_count / batch_size) + 1):
        try:
            bots_page = list(
                BotModel.select().where(BotModel.userbot == False).join(
                    Ping, JOIN.LEFT_OUTER).order_by(fn.Random()).paginate(
                        i, batch_size))
            log.info("Checking {}...".format(', '.join(x.username
                                                       for x in bots_page)))
            for b in bots_page:
                if job.context.get('stop').is_set():
                    raise StopAsyncIteration()
                try:
                    check_bot(bot, bot_checker, b)
                except NotABotError:
                    b.userbot = True
                    b.save()
        except FloodWaitError as e:
            bot.formatter.send_failure(
                settings.ADMINS[0],
                "Userbot received a Flood Wait timeout: {} seconds".format(
                    e.seconds))
            traceback.print_exc()
            log.error(
                "Userbot received a Flood Wait timeout: {} seconds".format(
                    e.seconds))
            return
        except StopAsyncIteration:
            break
        except:
            traceback.print_exc()
            log.debug("Continuing...")
            time.sleep(5)
            continue

    duration = datetime.datetime.now() - start
    bot.send_message(settings.ADMINS[0],
                     "Botchecker completed in {}.".format(duration))
Ejemplo n.º 8
0
def random_bot():
    """
    Returns a random bot from the BotList. By default, only "interesting" bots with description and tags are shown.
    Use the parameter `?all=True` to receive _all_ possible choices.
    """
    show_all = bool(request.args.get("all", False))

    if show_all:
        random_bot = Bot.select().order_by(fn.Random()).limit(1)[0]
    else:
        random_bot = random.choice(Bot.explorable_bots())
    data = random_bot.serialize

    if data:
        res = jsonify({'search_result': data, 'meta': {'url': request.url}})
        res.status_code = 200
    else:
        res = _error("No bot found.")
    return res
Ejemplo n.º 9
0
def _admin_buttons(send_botlist_button=False, logs_button=False):
    n_unapproved = len(Bot.select().where(Bot.approved == False))
    n_suggestions = len(Suggestion.select_all())
    n_pending = len(Bot.select_pending_update())

    second_row = list()
    if n_unapproved > 0:
        second_row.append(
            KeyboardButton(
                captions.APPROVE_BOTS +
                ' {}🆕'.format(mdformat.number_as_emoji(n_unapproved))))
    if n_suggestions > 0:
        second_row.append(
            KeyboardButton(
                captions.APPROVE_SUGGESTIONS +
                ' {}⁉️'.format(mdformat.number_as_emoji(n_suggestions))))

    buttons = [[
        KeyboardButton(captions.EXIT),
        KeyboardButton(captions.REFRESH),
    ],
               [
                   KeyboardButton(captions.FIND_OFFLINE),
                   KeyboardButton(captions.SEND_CONFIG_FILES)
               ]]

    update_row = list()
    if n_pending > 0:
        update_row.append(
            KeyboardButton(captions.PENDING_UPDATE +
                           ' {}{}'.format(mdformat.number_as_emoji(n_pending),
                                          captions.SUGGESTION_PENDING_EMOJI)))
    if send_botlist_button:
        update_row.append(KeyboardButton(captions.SEND_BOTLIST))
    if logs_button:
        update_row.append(KeyboardButton(captions.SEND_ACTIVITY_LOGS))

    if len(update_row) > 0:
        buttons.insert(1, update_row)
    if len(second_row) > 0:
        buttons.insert(1, second_row)

    return buttons
Ejemplo n.º 10
0
def apply_all_changes(bot, update, chat_data, to_edit):
    user = User.from_update(update)

    user_suggestions = Suggestion.select_all_of_user(user)
    for suggestion in user_suggestions:
        suggestion.apply()

    refreshed_bot = Bot.get(id=to_edit.id)
    edit_bot(bot, update, chat_data, refreshed_bot)
    Statistic.of(update, 'apply', refreshed_bot.username)
Ejemplo n.º 11
0
def make_bots():
    """Create bots with names for the database."""

    bot_name_list = ['jerry_bot', 'george_bot', 'elaine_bot', 'kramer_bot']

    for i in range(len(bot_name_list)):

        bot_to_make = bot_name_list[i]
        bot_creation = Bot(bot_name=bot_to_make)
        db.session.add(bot_creation)

    db.session.commit()
Ejemplo n.º 12
0
def t3chnostats(bot, update):
    days = 30
    txt = 'Bots approved by other people *in the last {} days*:\n\n'.format(
        days)
    bots = Bot.select().where(
        (Bot.approved_by != User.get(User.chat_id == 918962))
        & (Bot.date_added.between(
            datetime.date.today() -
            datetime.timedelta(days=days), datetime.date.today())))
    txt += '\n'.join(
        ['{} by @{}'.format(str(b), b.approved_by.username) for b in bots])
    update.message.reply_text(txt, parse_mode=ParseMode.MARKDOWN)
Ejemplo n.º 13
0
    def update_new_bots_list(self):
        text = self._read_file(self.NEW_BOTS_FILE)

        # insert spaces and the name of the bot
        new_bots_joined = Bot.get_new_bots_markdown()
        text = text.format(new_bots_joined)

        msg = self.send_or_edit(text, self.channel.new_bots_mid)
        self.sent['new_bots_list'] = "List of new bots sent"
        if msg:
            self.channel.new_bots_mid = msg.message_id
        self._save_channel()
Ejemplo n.º 14
0
def send_category(bot, update, chat_data, category=None):
    uid = util.uid_from_update(update)
    cid = update.effective_chat.id
    bots = Bot.of_category_without_new(
        category)[:settings.MAX_BOTS_PER_MESSAGE]
    bots_with_description = [b for b in bots if b.description is not None]
    detailed_buttons_enabled = len(
        bots_with_description) > 0 and util.is_private_message(update)

    callback = CallbackActions.SEND_BOT_DETAILS

    if detailed_buttons_enabled:
        buttons = [
            InlineKeyboardButton(x.username,
                                 callback_data=util.callback_for_action(
                                     callback, {'id': x.id}))
            for x in bots_with_description
        ]
    else:
        buttons = []
    menu = util.build_menu(buttons, 2)
    menu.insert(0, [
        InlineKeyboardButton(captions.BACK,
                             callback_data=util.callback_for_action(
                                 CallbackActions.SELECT_CATEGORY)),
        InlineKeyboardButton("Show in BotList",
                             url='http://t.me/botlist/{}'.format(
                                 category.current_message_id)),
        InlineKeyboardButton("Share", switch_inline_query=category.name)
    ])
    txt = "There are *{}* bots in the category *{}*:\n\n".format(
        len(bots), str(category))

    if uid in settings.MODERATORS and util.is_private_message(update):
        # append admin edit buttons
        txt += '\n'.join(["{} — /edit{} 🛃".format(b, b.id) for b in bots])
    else:
        txt += '\n'.join([str(b) for b in bots])

    if detailed_buttons_enabled:
        txt += "\n\n" + util.action_hint(
            "Press a button below to get a detailed description.")

    reply_markup = InlineKeyboardMarkup(menu)
    reply_markup, callback = botlistchat.append_delete_button(
        update, chat_data, reply_markup)
    msg = bot.formatter.send_or_edit(cid,
                                     txt,
                                     to_edit=util.mid_from_update(update),
                                     reply_markup=reply_markup)
    callback(msg)
    Statistic.of(update, 'menu', 'of category {}'.format(str(category)),
                 Statistic.ANALYSIS)
Ejemplo n.º 15
0
    def finish(self):
        # set last update
        self.channel.last_update = datetime.date.today()
        self._save_channel()

        new_bots = Bot.select_new_bots()
        if not self.silent and len(new_bots) > 0:
            self.notify_admin("Sending notifications to subscribers...")
            subscribers = Notifications.select().where(
                Notifications.enabled == True)
            notification_count = 0
            for sub in subscribers:
                try:
                    util.send_md_message(
                        self.bot, sub.chat_id,
                        messages.BOTLIST_UPDATE_NOTIFICATION.format(
                            n_bots=len(new_bots),
                            new_bots=Bot.get_new_bots_markdown()))
                    notification_count += 1
                    sub.last_notification = datetime.date.today()
                    sub.save()
                except TelegramError:
                    pass
            self.sent[
                'notifications'] = "Notifications sent to {} users.".format(
                    notification_count)

        changes_made = len(self.sent) > 1 or len(self.sent['category']) > 0
        if changes_made:
            text = util.success('{}{}'.format(
                'BotList updated successfully:\n\n',
                mdformat.results_list(self.sent)))
        else:
            text = mdformat.none_action("No changes were necessary.")

        log.info(self.sent)
        self.bot.formatter.send_or_edit(self.chat_id,
                                        text,
                                        to_edit=self.message_id)
Ejemplo n.º 16
0
def manybots(bot, update):
    uid = update.effective_chat.id
    bots = Bot.select().where(Bot.approved == True & Bot.botbuilder == True)

    txt = 'Manybots in the BotList:\n\n'

    # if uid in settings.MODERATORS and util.is_private_message(update):
    #     # append admin edit buttons
    #     txt += '\n'.join(["{} — /approve{}".format(b, b.id) for b in bots])
    # else:
    txt += '\n'.join([str(b) for b in bots])

    bot.formatter.send_message(uid, txt)
    async def on_list_bot(self, user: User):
        self.log.info(f'user requested for listing bots available for setting')
        user = await self._update_user_record_in_db(user)
        messenger = self._messenger_for_user(user)

        if await self._validate_user_state(user, self.UserState.WAITING_FOR_BOT_TOKEN):
            bots = Bot.objects(banned=False)
            bot_names = [bot.bot_name for bot in bots]
            bot_tokens = [bot.token for bot in bots]
            await messenger.list_bots(user, bot_names, bot_tokens)
        else:
            await messenger.send_message_to_user(user, self.messages('bot_setting_not_in_set_bot'), False)

        return
Ejemplo n.º 18
0
def category_article(cat):
    cat_bots = Bot.of_category_without_new(cat)
    txt = messages.PROMOTION_MESSAGE + '\n\n'
    txt += "There are *{}* bots in the category *{}*:\n\n".format(
        len(cat_bots), str(cat))
    txt += '\n'.join([str(b) for b in cat_bots])
    return InlineQueryResultArticle(
        id=uuid4(),
        title=emoji.emojize(cat.emojis, use_aliases=True) + cat.name,
        input_message_content=InputTextMessageContent(
            message_text=txt, parse_mode=ParseMode.MARKDOWN),
        description=cat.extra,
        # thumb_url='https://pichoster.net/images/2017/03/13/cfa5e29e29e772373242bc177a9e5479.jpg'
    )
Ejemplo n.º 19
0
def forward_router(bot, update, chat_data):
    text = update.effective_message.text

    # match first username in forwarded message
    try:
        username = re.match(settings.REGEX_BOT_IN_TEXT, text).groups()[0]
        if username == '@' + settings.SELF_BOT_NAME:
            return  # ignore

        item = Bot.get(Bot.username == username)

        send_bot_details(bot, update, chat_data, item)

    except (AttributeError, TypeError, Bot.DoesNotExist):
        pass  # no valid username in forwarded message
Ejemplo n.º 20
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)
    )
    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)
    )
    results.update(keyword_results)

    # many @usernames
    usernames = re.findall(settings.REGEX_BOT_ONLY, query)
    if usernames:
        try:
            bots = Bot.many_by_usernames(usernames)
            results.update(bots)
        except Bot.DoesNotExist:
            pass

    return list(results)
Ejemplo n.º 21
0
def thumbnail(username):
    if username[0] != '@':
        username = '******' + username
    try:
        item = Bot.by_username(username)
    except Bot.DoesNotExist:
        item = None
    if not item:
        return _error(
            "There is no bot in the BotList with the username {}.".format(
                username))
    if not os.path.exists(item.thumbnail_file):
        return _error("Sorry, we don't have a thumbnail for this bot.")

    return send_file(item.thumbnail_file, mimetype='image/jpeg')
Ejemplo n.º 22
0
def explore(bot, update, chat_data):
    cid = update.effective_chat.id
    uid = update.effective_user.id
    mid = util.mid_from_update(update)
    explorable_bots = Bot.explorable_bots()

    chat_data['explored'] = chat_data.get('explored', list())

    # don't explore twice
    for explored in chat_data['explored']:
        explorable_bots.remove(explored)

    if len(explorable_bots) == 0:
        util.send_md_message(
            bot, cid,
            mdformat.none_action(
                "You have explored all the bots. Congratulations, you might be the first 😜"
            ))
        return

    random_bot = random.choice(explorable_bots)

    buttons = [[
        InlineKeyboardButton(captions.ADD_TO_FAVORITES,
                             callback_data=util.callback_for_action(
                                 CallbackActions.ADD_TO_FAVORITES,
                                 {'id': random_bot.id})),
        InlineKeyboardButton(captions.SHARE,
                             switch_inline_query=random_bot.username)
    ],
               [
                   InlineKeyboardButton(random_explore_text(),
                                        callback_data=util.callback_for_action(
                                            CallbackActions.EXPLORE_NEXT)),
               ]]

    markup = InlineKeyboardMarkup(buttons)

    text = random_bot.detail_text

    if uid in settings.MODERATORS and util.is_private_message(update):
        text += '\n\n🛃 /edit{}'.format(random_bot.id)

    msg = bot.formatter.send_or_edit(cid,
                                     text,
                                     to_edit=mid,
                                     reply_markup=markup)
    chat_data['explored'].append(random_bot)
Ejemplo n.º 23
0
 def select_all(user):
     user_favs = list(Favorite.select().where(Favorite.user == user))
     for n, f in enumerate(user_favs):
         try:
             if not fn.exists(f.bot):
                 bot = Bot(category=Favorite.CUSTOM_CATEGORY,
                           username=f.custom_bot,
                           approved=True,
                           date_added=datetime.date.today())
                 f.bot = bot
                 user_favs[n] = f
             if not fn.exists(f.bot.category):
                 f.bot.category = Favorite.CUSTOM_CATEGORY
         except (Bot.DoesNotExist, AttributeError):
             f.delete_instance()
     return user_favs
Ejemplo n.º 24
0
def edit_bot(bot, update, chat_data, to_edit=None):
    uid = util.uid_from_update(update)
    message_id = util.mid_from_update(update)
    user = User.from_update(update)

    if not to_edit:
        if update.message:
            command = update.message.text

            if 'edit' in command:
                b_id = re.match(r'^/edit(\d+)$', command).groups()[0]
            elif 'approve' in command:
                b_id = re.match(r'^/approve(\d+)$', command).groups()[0]
            else:
                raise ValueError("No 'edit' or 'approve' in command.")

            try:
                to_edit = Bot.get(id=b_id)
            except Bot.DoesNotExist:
                update.message.reply_text(
                    util.failure('No bot exists with this id.'))
                return
        else:
            bot.formatter.send_failure(uid, "An unexpected error occured.")
            return

    if not to_edit.approved:
        return approve_bots(bot, update, override_list=[to_edit])

    pending_suggestions = Suggestion.pending_for_bot(to_edit, user)
    reply_markup = InlineKeyboardMarkup(
        _edit_bot_buttons(to_edit, pending_suggestions, uid
                          in settings.MODERATORS))
    pending_text = '\n\n{} Some changes are pending approval{}.'.format(
        captions.SUGGESTION_PENDING_EMOJI,
        '' if user.chat_id in settings.MODERATORS else
        ' by a moderator') if pending_suggestions else ''
    meta_text = '\n\nDate added: {}\nMember since revision {}\n' \
                'Submitted by {}\nApproved by {}'.format(
        to_edit.date_added, to_edit.revision, to_edit.submitted_by, to_edit.approved_by)
    bot.formatter.send_or_edit(
        uid,
        "🛃 Edit {}{}{}".format(
            to_edit.detail_text,
            meta_text if user.id in settings.MODERATORS else '', pending_text),
        to_edit=message_id,
        reply_markup=reply_markup)
Ejemplo n.º 25
0
def pending_update(bot, update):
    uid = update.effective_chat.id
    bots = Bot.select_pending_update()

    if len(bots) == 0:
        update.message.reply_text("No bots pending for update.")
        return

    txt = 'Bots pending for next Update:\n\n'

    if uid in settings.MODERATORS and util.is_private_message(update):
        # append admin edit buttons
        txt += '\n'.join(["{} — /edit{}".format(b, b.id) for b in bots])
    else:
        txt += '\n'.join([str(b) for b in bots])

    bot.formatter.send_message(uid, txt)
Ejemplo n.º 26
0
def short_approve_list(bot, update):
    uid = update.effective_chat.id
    bots = Bot.select_unapproved()

    if len(bots) == 0:
        update.message.reply_text("No bots to be approved.")
        return

    txt = 'Bots pending approval:\n\n'

    if uid in settings.MODERATORS and util.is_private_message(update):
        # append admin edit buttons
        txt += '\n'.join(["{} — /approve{}".format(b, b.id) for b in bots])
    else:
        txt += '\n'.join([str(b) for b in bots])

    bot.formatter.send_message(uid, txt)
Ejemplo n.º 27
0
def create_bot():
    """Adds bot to DB."""

    name = request.form.get('name')
    desc = request.form.get('description')
    data_source = request.form.get('source')
    content_type = request.form.get('type')
    icon = request.form.get('icon')

    if content_type == "text_file":
        data_source = []
        file_list = request.files.getlist("text_file")
        for file in file_list:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            data_source.append("uploads/" + filename)

    content = process_source(content_type, data_source)

    if content == False:
        flash('error in bot creation! make sure your sources are correct?')
        return redirect("/")

    else:
        source = Source(content_type=content_type,
                        content_source=data_source,
                        content=content)

        db.session.add(source)
        db.session.commit()

        bot = Bot(bot_name=name,
                    creator_id = session['user_id'],
                    bot_description=desc,
                    bot_icon=icon,
                    source_id=source.source_id)

        db.session.add(bot)
        db.session.commit()

        flash('bot planted!')


        return redirect("/bot/" + str(bot.bot_id))
Ejemplo n.º 28
0
def send_offline(bot, update):
    chat_id = util.uid_from_update(update)
    offline = Bot.select(Bot, Ping).join(Ping, JOIN.LEFT_OUTER).where(
        Bot.offline == True).order_by(Ping.last_response.asc())

    def offline_since(b):
        if not b.ping.last_response:
            return 'a long time'
        slanged_time = helpers.slang_datetime(b.ping.last_response)
        return slanged_time.replace(' ago', '')

    if len(offline) > 0:
        text = "Offline Bots:\n\n"
        text += '\n'.join([
            "{}{} — /edit{}".format(str(b),
                                    " (for {})".format(offline_since(b)), b.id)
            for b in offline
        ])
    else:
        text = "No bots are offline."
    bot.formatter.send_message(chat_id, text)
Ejemplo n.º 29
0
def add_favorite_handler(bot, update, args=None):
    uid = util.uid_from_update(update)
    from components.basic import main_menu_buttons
    main_menu_markup = ReplyKeyboardMarkup(main_menu_buttons(uid in settings.MODERATORS))

    if args:
        query = ' '.join(args) if isinstance(args, list) else args
        try:
            # TODO: add multiple
            username = re.match(settings.REGEX_BOT_IN_TEXT, query).groups()[0]
            try:
                # TODO: get exact database matches for input without `@`
                item = Bot.by_username(username)

                return add_favorite(bot, update, item)
            except Bot.DoesNotExist:
                buttons = [
                    InlineKeyboardButton(
                        "Yai!", callback_data=util.callback_for_action(CallbackActions.ADD_ANYWAY, {'u': username})),
                    InlineKeyboardButton("Nay...", callback_data=util.callback_for_action(CallbackActions.ADD_FAVORITE))
                ]
                reply_markup = InlineKeyboardMarkup([buttons])
                util.send_md_message(bot, uid,
                                     "{} is not in the @BotList. Do you want to add it to your {} anyway?".format(
                                         username, captions.FAVORITES),
                                     reply_markup=reply_markup)
        except AttributeError:
            # invalid bot username
            # TODO when does this happen?
            update.message.reply_text(
                util.failure("Sorry, but that is not a valid username. Please try again. /addfav"))
    else:
        buttons = [
            InlineKeyboardButton("Search inline", switch_inline_query_current_chat='')
        ]
        reply_markup = InlineKeyboardMarkup([buttons])

        bot.sendMessage(uid, messages.ADD_FAVORITE, reply_markup=ForceReply(selective=True))
    return ConversationHandler.END
Ejemplo n.º 30
0
def accept_bot_submission(bot, update, of_bot: Bot, category):
    uid = util.uid_from_update(update)
    message_id = util.mid_from_update(update)
    user = User.from_update(update)

    try:
        of_bot.category = category
        of_bot.date_added = datetime.date.today()
        of_bot.approved = True
        of_bot.approved_by = user
        of_bot.save()

        buttons = [[
            InlineKeyboardButton("Edit {} details".format(of_bot.username),
                                 callback_data=util.callback_for_action(
                                     CallbackActions.EDIT_BOT,
                                     {'id': of_bot.id}))
        ]]
        reply_markup = InlineKeyboardMarkup(buttons)

        bot.formatter.send_or_edit(
            uid,
            "{} has been accepted to the Botlist. ".format(
                of_bot, settings.BOT_ACCEPTED_IDLE_TIME),
            to_edit=message_id,
            reply_markup=reply_markup)

        log_msg = "{} accepted by {}.".format(of_bot.username, uid)

        # notify submittant
        if of_bot.submitted_by != user:
            try:
                bot.sendMessage(
                    of_bot.submitted_by.chat_id,
                    util.success(
                        messages.ACCEPTANCE_PRIVATE_MESSAGE.format(
                            of_bot.username, of_bot.category)))
                log_msg += "\nUser {} was notified.".format(
                    str(of_bot.submitted_by))
            except TelegramError:
                log_msg += "\nUser {} could NOT be contacted/notified in private.".format(
                    str(of_bot.submitted_by))

        log.info(log_msg)
    except:
        bot.formatter.send_failure(uid, "An error has occured. Bot not added.")