Beispiel #1
0
def add_favorite(bot, update, item: Bot, callback_alert=None):
    user = User.from_update(update)
    uid = util.uid_from_update(update)
    mid = util.mid_from_update(update)
    from botlistbot.components.basic import main_menu_buttons
    main_menu_markup = ReplyKeyboardMarkup(
        main_menu_buttons(uid in settings.MODERATORS))

    fav, created = Favorite.add(user=user, item=item)
    if created:
        Statistic.of(user, 'add-favorite', item.username)
        text = mdformat.love("{} added to your {}favorites.".format(
            fav.bot, '' if callback_alert else '/'))
        if callback_alert:
            update.callback_query.answer(text=text, show_alert=False)
        else:
            msg = util.send_md_message(bot,
                                       uid,
                                       text,
                                       to_edit=mid,
                                       reply_markup=main_menu_markup)
            mid = msg.message_id
            util.wait(bot, update)
            send_favorites_list(bot, update, to_edit=mid)
    else:
        text = mdformat.none_action(
            "{} is already a favorite of yours.{}".format(
                fav.bot, '' if callback_alert else ' /favorites'))
        if callback_alert:
            update.callback_query.answer(text=text, show_alert=False)
        else:
            util.send_md_message(bot, uid, text, reply_markup=main_menu_markup)
    return ConversationHandler.END
Beispiel #2
0
def edit_bot_category(bot, update, for_bot, callback_action=None):
    if callback_action is None:
        callback_action = CallbackActions.EDIT_BOT_CAT_SELECTED
    uid = util.uid_from_update(update)
    categories = Category.select().order_by(Category.name.asc()).execute()

    buttons = util.build_menu(
        [
            InlineKeyboardButton(
                "{}{}".format(emoji.emojize(c.emojis, use_aliases=True), c.name),
                callback_data=util.callback_for_action(
                    callback_action, {"cid": c.id, "bid": for_bot.id}
                ),
            )
            for c in categories
        ],
        2,
    )
    return bot.formatter.send_or_edit(
        uid,
        util.action_hint(
            "Please select a category" + (" for {}".format(for_bot) if for_bot else "")
        ),
        to_edit=util.mid_from_update(update),
        reply_markup=InlineKeyboardMarkup(buttons),
    )
Beispiel #3
0
def add_custom(bot, update, username):
    uid = util.uid_from_update(update)
    user = User.from_update(update)
    mid = util.mid_from_update(update)
    from botlistbot.components.basic import main_menu_buttons
    main_menu_markup = ReplyKeyboardMarkup(
        main_menu_buttons(uid in settings.MODERATORS))

    try:
        fav = Favorite.get(custom_bot=username)
        util.send_or_edit_md_message(
            bot,
            uid,
            mdformat.none_action(
                "{} is already a favorite of yours. /favorites".format(
                    fav.custom_bot)),
            to_edit=mid,
            reply_markup=main_menu_markup)
    except Favorite.DoesNotExist:
        fav = Favorite(user=user,
                       custom_bot=username,
                       date_added=datetime.date.today())
        fav.save()
        msg = bot.formatter.send_or_edit(
            uid,
            mdformat.love("{} added to your /favorites.".format(
                fav.custom_bot)),
            to_edit=mid)
        mid = msg.message_id
        util.wait(bot, update)
        send_favorites_list(bot, update, to_edit=mid)
    return ConversationHandler.END
Beispiel #4
0
def recommend_moderator(bot, update, bot_in_question, page):
    uid = update.effective_user.id
    mid = util.mid_from_update(update)
    moderators = User.select().where(
        (User.chat_id << settings.MODERATORS) & (User.chat_id != uid)
    )
    buttons = [
        InlineKeyboardButton(
            u.first_name,
            callback_data=util.callback_for_action(
                CallbackActions.SELECT_MODERATOR,
                {"bot_id": bot_in_question.id, "uid": u.id, "page": page},
            ),
        )
        for u in moderators
    ]
    buttons.insert(
        0,
        InlineKeyboardButton(
            captions.BACK,
            callback_data=util.callback_for_action(
                CallbackActions.SWITCH_APPROVALS_PAGE, {"page": page}
            ),
        ),
    )
    reply_markup = InlineKeyboardMarkup(util.build_menu(buttons, 1))
    text = mdformat.action_hint(
        "Select a moderator you think is better suited to evaluate the submission of {}.".format(
            str(bot_in_question)
        )
    )
    bot.formatter.send_or_edit(uid, text, to_edit=mid, reply_markup=reply_markup)
Beispiel #5
0
def show_new_bots(bot, update, chat_data, back_button=False):
    chat_id = update.effective_chat.id
    channel = helpers.get_channel()

    buttons = []

    if channel:
        buttons.append(
            [
                InlineKeyboardButton(
                    "Show in BotList",
                    url="http://t.me/{}/{}".format(
                        channel.username, channel.new_bots_mid
                    ),
                )
            ]
        )

    buttons.append(
        [
            InlineKeyboardButton(
                "Share", switch_inline_query=messages.NEW_BOTS_INLINEQUERY
            )
        ]
    )

    if back_button:
        buttons[0].insert(
            0,
            InlineKeyboardButton(
                captions.BACK,
                callback_data=util.callback_for_action(CallbackActions.SELECT_CATEGORY),
            ),
        )
    reply_markup = InlineKeyboardMarkup(buttons)
    reply_markup, callback = botlistchat.append_restricted_delete_button(
        update, chat_data, reply_markup
    )
    msg = bot.formatter.send_or_edit(
        chat_id,
        _new_bots_text(),
        to_edit=util.mid_from_update(update),
        reply_markup=reply_markup,
        reply_to_message_id=util.mid_from_update(update),
    )
    callback(msg)
    return ConversationHandler.END
Beispiel #6
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,
    )
Beispiel #7
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
            ),
            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.")
Beispiel #8
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)
Beispiel #9
0
def select_category(bot, update, chat_data, callback_action=None):
    chat_id = update.effective_chat.id
    reply_markup = InlineKeyboardMarkup(_select_category_buttons(callback_action))
    reply_markup, callback = botlistchat.append_restricted_delete_button(
        update, chat_data, reply_markup
    )
    msg = bot.formatter.send_or_edit(
        chat_id,
        util.action_hint(messages.SELECT_CATEGORY),
        to_edit=util.mid_from_update(update),
        reply_markup=reply_markup,
    )
    callback(msg)
    return ConversationHandler.END
Beispiel #10
0
def delete_conversation(bot, update, chat_data):
    cid = update.effective_chat.id
    uid = update.effective_user.id
    mid = util.mid_from_update(update)

    deletions_pending = chat_data.get("deletions_pending", dict())
    context: Optional[dict] = deletions_pending.get(mid)

    if context and uid != context.get("user_id"):
        if uid not in settings.MODERATORS:
            bot.answerCallbackQuery(update.callback_query.id,
                                    text="✋️ You didn't prompt this message.")
            return

    bot.delete_message(cid, mid, safe=True)
    bot.delete_message(cid, context["command_id"], safe=True)
Beispiel #11
0
def set_notifications(bot, update, value: bool):
    cid = update.effective_chat.id
    try:
        notifications = Notifications.get(Notifications.chat_id == cid)
    except Notifications.DoesNotExist:
        notifications = Notifications(chat_id=cid)
    notifications.enabled = value
    notifications.save()

    Statistic.of(update, ('enabled' if value else 'disabled') +
                 ' notifications for their group {}'.format(cid))

    msg = util.success("Nice! Notifications enabled."
                       ) if value else "Ok, notifications disabled."
    msg += '\nYou can always adjust this setting with the /subscribe command.'
    bot.formatter.send_or_edit(cid, msg, to_edit=util.mid_from_update(update))
    return ConversationHandler.END
Beispiel #12
0
    def __init__(self, bot, update, channel, resend, silent):
        if not channel:
            self.notify_admin_err(
                "I don't know the channel `{}`. Please make sure I am an admin there, "
                "and send a random message so that I can remember the channel meta data."
                .format(self.channel.username))
            return

        self.bot = bot
        self.update = update
        self.channel = channel
        self.resend = resend
        self.silent = silent
        self.sent = {}
        self.sent['category'] = list()
        self.chat_id = update.effective_chat.id
        self.message_id = util.mid_from_update(update)
Beispiel #13
0
def send_broadcast(bot, update, user_data):
    uid = update.effective_user.id

    try:
        bc = user_data['broadcast']
        text = bc['text']
        recipient = bc['target_chat_id']
        mode = bc.get('mode', 'just_send')
    except AttributeError:
        bot.formatter.send_failure(
            uid, "Missing attributes for broadcast. Aborting...")
        return ConversationHandler.END

    mid = bc.get('reply_to_message_id')

    if mode == 'replying':
        msg = util.send_md_message(bot,
                                   recipient,
                                   text,
                                   reply_to_message_id=mid)
    elif mode == 'editing':
        msg = bot.formatter.send_or_edit(recipient, text, to_edit=mid)
    else:
        msg = util.send_md_message(bot, recipient, text)

    # Post actions
    buttons = [
        InlineKeyboardButton(captions.PIN,
                             callback_data=util.callback_for_action(
                                 'pin_message', {'mid': msg.message_id})),
        InlineKeyboardButton('Add "Thank You" counter',
                             callback_data=util.callback_for_action(
                                 'add_thank_you', {
                                     'cid': recipient,
                                     'mid': msg.message_id
                                 })),
    ]
    reply_markup = InlineKeyboardMarkup(util.build_menu(buttons, 1))
    mid = util.mid_from_update(update)
    action_taken = "edited" if mode == 'editing' else "broadcasted"
    bot.formatter.send_or_edit(uid,
                               mdformat.success(
                                   "Message {}.".format(action_taken)),
                               mid,
                               reply_markup=reply_markup)
Beispiel #14
0
def send_favorites_list(bot, update, to_edit=None):
    uid = util.uid_from_update(update)
    user = User.from_update(update)

    t = threading.Thread(target=_too_many_favorites_handler,
                         args=(bot, update, user))
    t.start()

    favorites = Favorite.select_all(user)

    buttons = [[
        InlineKeyboardButton(captions.ADD_FAVORITE,
                             callback_data=util.callback_for_action(
                                 CallbackActions.ADD_FAVORITE)),
        InlineKeyboardButton(captions.REMOVE_FAVORITE,
                             callback_data=util.callback_for_action(
                                 CallbackActions.REMOVE_FAVORITE_MENU))
    ],
               [
                   InlineKeyboardButton(
                       'Layout: ' + Layouts.get_caption(user.favorites_layout),
                       callback_data=util.callback_for_action(
                           CallbackActions.TOGGLE_FAVORITES_LAYOUT,
                           {'v': Layouts.get_next(user.favorites_layout)})),
               ],
               [
                   InlineKeyboardButton(
                       captions.SHARE,
                       switch_inline_query=DeepLinkingActions.FAVORITES),
               ]]
    reply_markup = InlineKeyboardMarkup(buttons)

    if to_edit is None:
        to_edit = util.mid_from_update(update)

    if len(favorites) == 0:
        text = "You have no favorites yet."
    else:
        text = _favorites_categories_md(favorites, user.favorites_layout)

    bot.formatter.send_or_edit(uid,
                               text,
                               to_edit=to_edit,
                               reply_markup=reply_markup)
Beispiel #15
0
def broadcast(bot, update, user_data):
    cid = update.effective_chat.id
    uid = update.effective_user.id
    mid = util.mid_from_update(update)
    user = User.from_update(update)
    text = ''

    if cid == settings.BOTLISTCHAT_ID:
        replied_to = update.message.reply_to_message
        if replied_to:
            user_data['broadcast'] = dict(
                user_data.get('broadcast', dict()),
                reply_to_message_id=replied_to.message_id)
            if replied_to.from_user.username.lower() == settings.SELF_BOT_NAME:
                # editing
                text += '*You are editing one of my messages*\n\n'
                user_data['broadcast']['mode'] = 'editing'
            else:
                # replying
                text += '*You are replying to a message of {}.*\n\n'.format(
                    update.message.reply_to_message.from_user.first_name)
                user_data['broadcast']['mode'] = 'replying'
        # answer and clean
        msg = bot.send_message(cid, "k")
        _delete_multiple_delayed(bot,
                                 cid,
                                 delayed=[msg.message_id],
                                 immediately=[update.message.message_id])

    to_text = "  _to_  "
    text += "Send me the text to broadcast to @BotListChat.\n"
    text += "_You can use the following words and they will replaced:_\n\n"

    text += '\n'.join([
        '"{}"{}{}'.format(k, to_text, v)
        for k, v in BROADCAST_REPLACEMENTS.items()
    ])

    # TODO Build text mentioning replacements
    # text += '\n@' + str(update.effective_user.username) + to_text + user.markdown_short

    bot.formatter.send_or_edit(uid, mdformat.action_hint(text), mid)
    return BotStates.BROADCASTING
Beispiel #16
0
def reroute_private_chat(
    bot, update, quote, action, message, redirect_message=None, reply_markup=None
):
    cid = update.effective_chat.id
    mid = util.mid_from_update(update)
    if redirect_message is None:
        redirect_message = messages.REROUTE_PRIVATE_CHAT

    if util.is_group_message(update):
        update.message.reply_text(
            redirect_message,
            quote=quote,
            parse_mode=ParseMode.MARKDOWN,
            reply_markup=InlineKeyboardMarkup(
                [
                    [
                        InlineKeyboardButton(
                            captions.SWITCH_PRIVATE,
                            url="https://t.me/{}?start={}".format(
                                settings.SELF_BOT_NAME, action
                            ),
                        ),
                        InlineKeyboardButton(
                            "🔎 Switch to inline", switch_inline_query=action
                        ),
                    ]
                ]
            ),
        )
    else:
        if mid:
            bot.formatter.send_or_edit(cid, message, mid, reply_markup=reply_markup)
        else:
            update.message.reply_text(
                message,
                quote=quote,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=reply_markup,
            )
Beispiel #17
0
def remove_favorite_menu(bot, update):
    uid = util.uid_from_update(update)
    user = User.from_update(update)
    favorites = Favorite.select_all(user)

    fav_remove_buttons = [
        InlineKeyboardButton('✖️ {}'.format(str(f.bot.username)),
                             callback_data=util.callback_for_action(
                                 CallbackActions.REMOVE_FAVORITE,
                                 {'id': f.id})) for f in favorites
    ]
    buttons = util.build_menu(fav_remove_buttons,
                              2,
                              header_buttons=[
                                  InlineKeyboardButton(
                                      captions.DONE,
                                      callback_data=util.callback_for_action(
                                          CallbackActions.SEND_FAVORITES_LIST))
                              ])
    reply_markup = InlineKeyboardMarkup(buttons)
    bot.formatter.send_or_edit(uid,
                               util.action_hint("Select favorites to remove"),
                               to_edit=util.mid_from_update(update),
                               reply_markup=reply_markup)
Beispiel #18
0
def send_bot_details(
    bot, update, chat_data, item=None, header_msg: Optional[str] = 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 = f"{header_msg}\n\n{item.detail_text}" if header_msg else item.detail_text

        if (
            item.description is None
            and not Keyword.select().where(Keyword.entity == item).exists()
        ):
            txt += " is in the @BotList, but has no description or keywords yet."
        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_restricted_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
Beispiel #19
0
def examples(bot, update, quote=True):
    mid = util.mid_from_update(update)
    cid = update.effective_chat.id
    bot.formatter.send_or_edit(cid, messages.EXAMPLES, to_edit=mid, reply_markup=_help_markup())
    return ConversationHandler.END
Beispiel #20
0
def contributing(bot, update, quote=True):
    mid = util.mid_from_update(update)
    cid = update.effective_chat.id
    bot.formatter.send_or_edit(cid, messages.CONTRIBUTING, to_edit=mid, reply_markup=_help_markup())
    return ConversationHandler.END
Beispiel #21
0
def help(bot, update):
    mid = util.mid_from_update(update)
    cid = update.effective_chat.id
    bot.formatter.send_or_edit(cid, messages.HELP_MESSAGE_ENGLISH, to_edit=mid, reply_markup=_help_markup())
    return ConversationHandler.END
Beispiel #22
0
def send_category(bot, update, chat_data, category):
    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_restricted_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
    )
Beispiel #23
0
def approve_suggestions(bot, update, page=0):
    uid = util.uid_from_update(update)
    suggestions = Suggestion.select_all()
    if page * settings.PAGE_SIZE_SUGGESTIONS_LIST >= len(suggestions):
        # old item deleted, list now too small
        page = page - 1 if page > 0 else 0
    start = page * settings.PAGE_SIZE_SUGGESTIONS_LIST
    end = start + settings.PAGE_SIZE_SUGGESTIONS_LIST

    has_prev_page = page > 0
    has_next_page = (page + 1) * settings.PAGE_SIZE_SUGGESTIONS_LIST < len(suggestions)

    suggestions = suggestions[start:end]

    if len(suggestions) == 0:
        bot.formatter.send_or_edit(
            uid, "No more suggestions available.", to_edit=util.mid_from_update(update)
        )
        return

    buttons = []
    count = 1
    text = "Please choose suggestions to accept.\n"
    for x in suggestions:
        number = str(count) + "."
        text += "\n{} {}".format(number, str(x))
        row = []

        # Should the suggestion be editable and is it too long?
        if x.action in Suggestion.TEXTUAL_ACTIONS:
            row.append(
                InlineKeyboardButton(
                    "{} {}📝".format(number, Emoji.WHITE_HEAVY_CHECK_MARK),
                    callback_data=util.callback_for_action(
                        CallbackActions.CHANGE_SUGGESTION, {"id": x.id, "page": page}
                    ),
                )
            )
        else:
            row.append(
                InlineKeyboardButton(
                    "{} {}".format(number, Emoji.WHITE_HEAVY_CHECK_MARK),
                    callback_data=util.callback_for_action(
                        CallbackActions.ACCEPT_SUGGESTION, {"id": x.id, "page": page}
                    ),
                )
            )

        row.append(
            InlineKeyboardButton(
                "{} {}".format(number, Emoji.CROSS_MARK),
                callback_data=util.callback_for_action(
                    CallbackActions.REJECT_SUGGESTION, {"id": x.id, "page": page}
                ),
            )
        )
        buttons.append(row)
        count += 1

    page_arrows = list()
    if has_prev_page:
        page_arrows.append(
            InlineKeyboardButton(
                Emoji.LEFTWARDS_BLACK_ARROW,
                callback_data=util.callback_for_action(
                    CallbackActions.SWITCH_SUGGESTIONS_PAGE, {"page": page - 1}
                ),
            )
        )
    if has_next_page:
        page_arrows.append(
            InlineKeyboardButton(
                Emoji.BLACK_RIGHTWARDS_ARROW,
                callback_data=util.callback_for_action(
                    CallbackActions.SWITCH_SUGGESTIONS_PAGE, {"page": page + 1}
                ),
            )
        )
    buttons.append(page_arrows)

    reply_markup = InlineKeyboardMarkup(buttons)

    bot.formatter.send_or_edit(
        uid,
        util.action_hint(text),
        reply_markup=reply_markup,
        to_edit=util.mid_from_update(update),
        disable_web_page_preview=True,
    )
    return CallbackStates.APPROVING_BOTS
Beispiel #24
0
def approve_bots(bot, update, page=0, override_list=None):
    chat_id = util.uid_from_update(update)

    if override_list:
        unapproved = override_list
    else:
        unapproved = (
            Bot.select()
            .where(Bot.approved == False, Bot.disabled == False)
            .order_by(Bot.date_added)
        )

    if page < 0:
        page = 0

    last_page = int((len(unapproved) - 1) / settings.PAGE_SIZE_BOT_APPROVAL)

    if page * settings.PAGE_SIZE_BOT_APPROVAL >= len(unapproved):
        # old item deleted, list now too small
        page = last_page
    start = page * settings.PAGE_SIZE_BOT_APPROVAL
    end = start + settings.PAGE_SIZE_BOT_APPROVAL

    has_prev_page = page > 0
    has_next_page = (page + 1) * settings.PAGE_SIZE_BOT_APPROVAL < len(unapproved)
    unapproved = unapproved[start:end]

    if len(unapproved) == 0:
        bot.formatter.send_or_edit(
            chat_id,
            "No more unapproved bots available. "
            "Good job! (Is this the first time? 😂)",
            to_edit=util.mid_from_update(update),
        )
        return

    buttons = list()
    for x in unapproved:
        first_row = [
            InlineKeyboardButton(
                x.username, url="http://t.me/{}".format(x.username[1:])
            )
        ]
        second_row = [
            InlineKeyboardButton(
                "👍",
                callback_data=util.callback_for_action(
                    CallbackActions.ACCEPT_BOT, {"id": x.id}
                ),
            ),
            InlineKeyboardButton(
                "👎",
                callback_data=util.callback_for_action(
                    CallbackActions.REJECT_BOT, {"id": x.id, "page": page, "ntfc": True}
                ),
            ),
            InlineKeyboardButton(
                "🗑",
                callback_data=util.callback_for_action(
                    CallbackActions.REJECT_BOT,
                    {"id": x.id, "page": page, "ntfc": False},
                ),
            ),
            InlineKeyboardButton(
                emojis.RECOMMEND_MODERATOR,
                callback_data=util.callback_for_action(
                    CallbackActions.RECOMMEND_MODERATOR, {"id": x.id, "page": page}
                ),
            ),
        ]
        if len(unapproved) > 1:
            buttons.append(first_row)
        buttons.append(second_row)

    page_arrows = list()
    if has_prev_page:
        page_arrows.append(
            InlineKeyboardButton(
                "⏮",
                callback_data=util.callback_for_action(
                    CallbackActions.SWITCH_APPROVALS_PAGE, {"page": -1}
                ),
            )
        )
        page_arrows.append(
            InlineKeyboardButton(
                Emoji.LEFTWARDS_BLACK_ARROW,
                callback_data=util.callback_for_action(
                    CallbackActions.SWITCH_APPROVALS_PAGE, {"page": page - 1}
                ),
            )
        )

    if has_prev_page or has_next_page:
        page_arrows.append(
            InlineKeyboardButton(
                "·{}·".format(page + 1),
                callback_data=util.callback_for_action(
                    CallbackActions.SWITCH_APPROVALS_PAGE, {"page": page}
                ),
            )
        )

    if has_next_page:
        page_arrows.append(
            InlineKeyboardButton(
                Emoji.BLACK_RIGHTWARDS_ARROW,
                callback_data=util.callback_for_action(
                    CallbackActions.SWITCH_APPROVALS_PAGE, {"page": page + 1}
                ),
            )
        )
        page_arrows.append(
            InlineKeyboardButton(
                "⏭",
                callback_data=util.callback_for_action(
                    CallbackActions.SWITCH_APPROVALS_PAGE, {"page": last_page}
                ),
            )
        )
    buttons.append(page_arrows)

    reply_markup = InlineKeyboardMarkup(buttons)
    text = (
        "What to do with {}?".format(util.escape_markdown(unapproved[0].username))
        if len(unapproved) == 1
        else messages.SELECT_BOT_TO_ACCEPT
    )
    bot.formatter.send_or_edit(
        chat_id,
        util.action_hint(text),
        reply_markup=reply_markup,
        to_edit=util.mid_from_update(update),
    )
    return CallbackStates.APPROVING_BOTS