示例#1
0
 def add_bot(self, channel, name):
     channel = channel.lower()
     name = name.lower()
     try:
         Bot.get(Bot.name == name)
     except peewee.DoesNotExist:
         pass  # this seems really unpythonic somehow
     else:
         raise KeyError('Bot already exists')
     try:
         chan_o = Channel.get(Channel.name == channel)
     except peewee.DoesNotExist:
         chan_o = Channel.create(name=channel)
     Bot.create(name=name,
                channel=chan_o)
示例#2
0
 def shutdown_and_redeploy(self):
     live_bots = self.fetch_live_bots()
     for bot in live_bots:
         allocation = bot.allocation
         name = Bot.get(id=bot.id).name
         self.shutdown_bot(name)
         self.start_bot(name, allocation)
示例#3
0
def lookup_entity(query, exact=True):
    """
    Searches for a Bot or User contained in the query
    """
    if exact:
        try:
            return Bot.by_username(query, include_disabled=True)
        except Bot.DoesNotExist:
            pass

        try:
            return Bot.get(chat_id=int(query))
        except ValueError:
            pass
        except Bot.DoesNotExist:
            pass

        try:
            return User.by_username(query)
        except User.DoesNotExist:
            pass

        try:
            return User.get(chat_id=query)
        except User.DoesNotExist:
            pass
        return None
示例#4
0
文件: tasks.py 项目: xorduna/telemock
def send_message(chat, message):
    bot, user = Bot.get(chat['botname']), User.get(chat['username'])
    response = create_fake_message(user, bot, chat, message)
    logger.info('send message to bot response: %s' % (response))
    print(response)
    r = requests.post(bot['callback'], json=response)
    print(r.text)
示例#5
0
文件: tasks.py 项目: xorduna/telemock
def random_replay(keyboard, chat, type='chat'):
    """
        when type=chat take create_message_response
        when type=callback_query take create_callback_query_response
    """
    # select random answer
    print(keyboard[0])
    #options = keyboard
    answer = random.choice(keyboard[0])
    if 'text' in answer:
        answer = answer['text']

    bot = Bot.get(chat['botname'])
    user = User.get(chat['username'])

    if type == 'chat':
        response = create_fake_message(user, bot, chat, answer)
    elif type == 'callback_query':
        text, data = answer['text'], answer['callback_data']
        response = create_callback_query_response(user, bot, text, data)
    else:
        raise ValueError("type must be chat or callback_query")

    logger.info('random_replay[type=%s] response: %s' % (type, response))
    # send random answer to the callback_url
    print(response)
    r = requests.post(bot['callback'], json=response)
    print(r.text)
示例#6
0
 def shutdown_bot(self, name):
     b = Bot.get(name=name)
     settings = BotSettings.get(id=b.id)
     subprocess.Popen(["kill", "-9", str(settings.pid)])
     settings.bot_live = False
     settings.save()
     print("Killed bot: {}".format(name))
示例#7
0
 def get(self):
     key = self.request.get('key')
     bot = Bot.get(key)
     template_values = {
         'bot': bot,
         'logout_url': users.create_logout_url("/"),
         }
     path = template_path("edit")
     self.response.out.write(template.render(path, template_values))
示例#8
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)
示例#9
0
文件: tasks.py 项目: xorduna/telemock
def start_chat(chat):
    bot, user = Bot.get(chat['botname']), User.get(chat['username'])
    print(bot)
    #response = create_message_response(user, bot, "/start")
    response = create_fake_message(user, bot, chat, "/start")

    logger.info('send START message to bot response: %s' % (response))
    print(response)
    r = requests.post(bot['callback'], json=response)
    print(r.text)
示例#10
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,
    )
示例#11
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
def test_new(client: BotIntegrationClient):
    uname = '@test__bot'
    try:
        try:
            b = Bot.get(username=uname)
            b.delete_instance()
        except Bot.DoesNotExist:
            pass

        res = client.send_command_await("new", [uname])
        if client.get_me().id in settings.MODERATORS:
            assert 'is currently pending' in res.full_text.lower()
            assert res.inline_keyboards[0].find_button(r'.*Accept.*')
        else:
            assert re.search('you submitted.*for approval', res.full_text, re.IGNORECASE)
    finally:
        Bot.delete().where(Bot.username == uname)
示例#13
0
def callback_router(bot, update, chat_data, user_data, job_queue):
    obj = json.loads(str(update.callback_query.data))
    user = User.from_update(update)

    try:
        if "a" in obj:
            action = obj["a"]

            # BOTLISTCHAT
            if action == CallbackActions.DELETE_CONVERSATION:
                botlistchat.delete_conversation(bot, update, chat_data)
            # HELP
            elif action == CallbackActions.HELP:
                help.help(bot, update)
            elif action == CallbackActions.CONTRIBUTING:
                help.contributing(bot, update)
            elif action == CallbackActions.EXAMPLES:
                help.examples(bot, update)
            # BASIC QUERYING
            elif action == CallbackActions.SELECT_CATEGORY:
                select_category(bot, update, chat_data)
            elif action == CallbackActions.SELECT_BOT_FROM_CATEGORY:
                category = Category.get(id=obj["id"])
                send_category(bot, update, chat_data, category)
            elif action == CallbackActions.SEND_BOT_DETAILS:
                item = Bot.get(id=obj["id"])
                send_bot_details(bot, update, chat_data, item)
            # FAVORITES
            elif action == CallbackActions.TOGGLE_FAVORITES_LAYOUT:
                value = obj["v"]
                favorites.toggle_favorites_layout(bot, update, value)
            elif action == CallbackActions.ADD_FAVORITE:
                favorites.add_favorite_handler(bot, update)
            elif action == CallbackActions.REMOVE_FAVORITE_MENU:
                favorites.remove_favorite_menu(bot, update)
            elif action == CallbackActions.REMOVE_FAVORITE:
                to_remove = Favorite.get(id=obj["id"])
                bot_details = to_remove.bot
                to_remove.delete_instance()
                if obj.get("details"):
                    send_bot_details(bot, update, chat_data, bot_details)
                else:
                    favorites.remove_favorite_menu(bot, update)
            elif action == CallbackActions.SEND_FAVORITES_LIST:
                favorites.send_favorites_list(bot, update)
            elif action == CallbackActions.ADD_ANYWAY:
                favorites.add_custom(bot, update, obj["u"])
            elif action == CallbackActions.ADD_TO_FAVORITES:
                details = obj.get("details")
                discreet = obj.get("discreet", False) or details
                item = Bot.get(id=obj["id"])
                favorites.add_favorite(bot,
                                       update,
                                       item,
                                       callback_alert=discreet)
                if details:
                    send_bot_details(bot, update, chat_data, item)
            # ACCEPT/REJECT BOT SUBMISSIONS
            elif action == CallbackActions.APPROVE_REJECT_BOTS:
                custom_approve_list = [Bot.get(id=obj["id"])]
                admin.approve_bots(bot,
                                   update,
                                   override_list=custom_approve_list)
            elif action == CallbackActions.ACCEPT_BOT:
                to_accept = Bot.get(id=obj["id"])
                admin.edit_bot_category(bot, update, to_accept,
                                        CallbackActions.BOT_ACCEPTED)
                # Run in x minutes, giving the moderator enough time to edit bot details
                job_queue.run_once(
                    lambda b, job: botlistchat.
                    notify_group_submission_accepted(b, job, to_accept),
                    settings.BOT_ACCEPTED_IDLE_TIME * 60,
                )
            elif action == CallbackActions.RECOMMEND_MODERATOR:
                bot_in_question = Bot.get(id=obj["id"])
                admin.recommend_moderator(bot, update, bot_in_question,
                                          obj["page"])
            elif action == CallbackActions.SELECT_MODERATOR:
                bot_in_question = Bot.get(id=obj["bot_id"])
                moderator = User.get(id=obj["uid"])
                admin.share_with_moderator(bot, update, bot_in_question,
                                           moderator)
                admin.approve_bots(bot, update, obj["page"])
            elif action == CallbackActions.REJECT_BOT:
                to_reject = Bot.get(id=obj["id"])
                notification = obj.get("ntfc", True)
                admin.reject_bot_submission(
                    bot,
                    update,
                    None,
                    to_reject,
                    verbose=False,
                    notify_submittant=notification,
                )
                admin.approve_bots(bot, update, obj["page"])
            elif action == CallbackActions.BOT_ACCEPTED:
                to_accept = Bot.get(id=obj["bid"])
                category = Category.get(id=obj["cid"])
                admin.accept_bot_submission(bot, update, to_accept, category)
            elif action == CallbackActions.COUNT_THANK_YOU:
                new_count = obj.get("count", 1)
                basic.count_thank_you(bot, update, new_count)
            # ADD BOT
            # elif action == CallbackActions.ADD_BOT_SELECT_CAT:
            #     category = Category.get(id=obj['id'])
            #     admin.add_bot(bot, update, chat_data, category)
            # EDIT BOT
            elif action == CallbackActions.EDIT_BOT:
                to_edit = Bot.get(id=obj["id"])
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_SELECT_CAT:
                to_edit = Bot.get(id=obj["id"])
                admin.edit_bot_category(bot, update, to_edit)
            elif action == CallbackActions.EDIT_BOT_CAT_SELECTED:
                to_edit = Bot.get(id=obj["bid"])
                cat = Category.get(id=obj["cid"])
                botproperties.change_category(bot, update, to_edit, cat)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_COUNTRY:
                to_edit = Bot.get(id=obj["id"])
                botproperties.set_country_menu(bot, update, to_edit)
            elif action == CallbackActions.SET_COUNTRY:
                to_edit = Bot.get(id=obj["bid"])
                if obj["cid"] == "None":
                    country = None
                else:
                    country = Country.get(id=obj["cid"])
                botproperties.set_country(bot, update, to_edit, country)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_DESCRIPTION:
                to_edit = Bot.get(id=obj["id"])
                botproperties.set_text_property(bot, update, chat_data,
                                                "description", to_edit)
            elif action == CallbackActions.EDIT_BOT_EXTRA:
                to_edit = Bot.get(id=obj["id"])
                # SAME IS DONE HERE, but manually
                botproperties.set_text_property(bot, update, chat_data,
                                                "extra", to_edit)
            elif action == CallbackActions.EDIT_BOT_NAME:
                to_edit = Bot.get(id=obj["id"])
                botproperties.set_text_property(bot, update, chat_data, "name",
                                                to_edit)
            elif action == CallbackActions.EDIT_BOT_USERNAME:
                to_edit = Bot.get(id=obj["id"])
                botproperties.set_text_property(bot, update, chat_data,
                                                "username", to_edit)
            # elif action == CallbackActions.EDIT_BOT_KEYWORDS:
            #     to_edit = Bot.get(id=obj['id'])
            #     botproperties.set_keywords_init(bot, update, chat_data, to_edit)
            elif action == CallbackActions.APPLY_ALL_CHANGES:
                to_edit = Bot.get(id=obj["id"])
                admin.apply_all_changes(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_INLINEQUERIES:
                to_edit = Bot.get(id=obj["id"])
                value = bool(obj["value"])
                botproperties.toggle_value(bot, update, "inlinequeries",
                                           to_edit, value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_OFFICIAL:
                to_edit = Bot.get(id=obj["id"])
                value = bool(obj["value"])
                botproperties.toggle_value(bot, update, "official", to_edit,
                                           value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_OFFLINE:
                to_edit = Bot.get(id=obj["id"])
                value = bool(obj["value"])
                botproperties.toggle_value(bot, update, "offline", to_edit,
                                           value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_SPAM:
                to_edit = Bot.get(id=obj["id"])
                value = bool(obj["value"])
                botproperties.toggle_value(bot, update, "spam", to_edit, value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.CONFIRM_DELETE_BOT:
                to_delete = Bot.get(id=obj["id"])
                botproperties.delete_bot_confirm(bot, update, to_delete)
            elif action == CallbackActions.DELETE_BOT:
                to_edit = Bot.get(id=obj["id"])
                botproperties.delete_bot(bot, update, to_edit)
                # send_category(bot, update, chat_data, to_edit.category)
            elif action == CallbackActions.ACCEPT_SUGGESTION:
                suggestion = Suggestion.get(id=obj["id"])
                components.botproperties.accept_suggestion(
                    bot, update, suggestion)
                admin.approve_suggestions(bot, update, page=obj["page"])
            elif action == CallbackActions.REJECT_SUGGESTION:
                suggestion = Suggestion.get(id=obj["id"])
                suggestion.delete_instance()
                admin.approve_suggestions(bot, update, page=obj["page"])
            elif action == CallbackActions.CHANGE_SUGGESTION:
                suggestion = Suggestion.get(id=obj["id"])
                botproperties.change_suggestion(bot,
                                                update,
                                                suggestion,
                                                page_handover=obj["page"])
            elif action == CallbackActions.SWITCH_SUGGESTIONS_PAGE:
                page = obj["page"]
                admin.approve_suggestions(bot, update, page)
            elif action == CallbackActions.SWITCH_APPROVALS_PAGE:
                admin.approve_bots(bot, update, page=obj["page"])
            elif action == CallbackActions.SET_NOTIFICATIONS:
                set_notifications(bot, update, obj["value"])
            elif action == CallbackActions.NEW_BOTS_SELECTED:
                show_new_bots(bot, update, chat_data, back_button=True)
            elif action == CallbackActions.ABORT_SETTING_KEYWORDS:
                to_edit = Bot.get(id=obj["id"])
                admin.edit_bot(bot, update, chat_data, to_edit)
            # SENDING BOTLIST
            elif action == CallbackActions.SEND_BOTLIST:
                silent = obj.get("silent", False)
                re_send = obj.get("re", False)
                botlist.send_botlist(bot,
                                     update,
                                     resend=re_send,
                                     silent=silent)
            elif action == CallbackActions.RESEND_BOTLIST:
                botlist.send_botlist(bot, update, resend=True)
            # BROADCASTING
            elif action == "send_broadcast":
                broadcasts.send_broadcast(bot, update, user_data)
            elif action == "pin_message":
                broadcasts.pin_message(bot, update, obj["mid"])
            elif action == "add_thank_you":
                basic.add_thank_you_button(bot, update, obj["cid"], obj["mid"])
            # EXPLORING
            elif action == CallbackActions.EXPLORE_NEXT:
                explore.explore(bot, update, chat_data)
    except Exception as e:
        traceback.print_exc()

        # get the callback action in plaintext
        actions = dict(CallbackActions.__dict__)
        a = next(k for k, v in actions.items() if v == obj.get("a"))
        util.send_md_message(
            bot,
            settings.DEVELOPER_ID,
            "Exception in callback query for {}:\n{}\n\nWith CallbackAction {}\n\nWith data:\n{}"
            .format(
                user.markdown_short,
                util.escape_markdown(e),
                util.escape_markdown(a),
                util.escape_markdown(str(obj)),
            ),
        )
    finally:
        bot.answerCallbackQuery(update.callback_query.id)
        return ConversationHandler.END
示例#14
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)
def submit():
    if not request.is_json:
        res = _error('MimeType must be application/json.')
        res.status_code = 400
        return res

    content = request.get_json()
    try:
        access = APIAccess.get(APIAccess.token == content.get('token'))
    except APIAccess.DoesNotExist:
        res = _error('The access token is invalid.')
        res.status_code = 401
        return res

    username = content.get('username')
    if username is None or not isinstance(username, str):
        res = _error('You must supply a username.')
        res.status_code = 400
        return res

    # insert `@` if omitted
    username = '******' + username if username[0] != '@' else username

    try:
        Bot.get(Bot.username == username)
        res = _error('The bot {} is already in the BotList.'.format(username))
        res.status_code = 409
        return res
    except Bot.DoesNotExist:
        b = Bot(username=username)

    name = content.get('name')
    description = content.get('description')
    inlinequeries = content.get('inlinequeries')

    try:
        if name:
            if isinstance(name, str):
                b.name = name
            else:
                raise AttributeError('The name field must be a string.')
        if description:
            if isinstance(description, str):
                b.description = description
            else:
                raise AttributeError('The description field must be a string.')
        if inlinequeries:
            if isinstance(inlinequeries, bool):
                b.inlinequeries = inlinequeries
            else:
                raise AttributeError(
                    'The inlinequeries field must be a boolean.')
    except Exception as e:
        res = _error(str(e))
        res.status_code = 400
        return res

    b.date_added = datetime.date.today()
    b.submitted_by = access.user
    b.approved = False

    b.save()
    res = jsonify({'success': '{} was submitted for approval.'.format(b)})
    res.status_code = 201
    return res
示例#16
0
def notify_bot_offline(bot, update, args=None):
    tg_user = update.message.from_user
    user = User.from_telegram_object(tg_user)
    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() == "/offline@botlistbot")
        if command_no_args:
            update.message.reply_text(
                util.action_hint(
                    "Please use this command with an argument. For example:\n/offline @mybot"
                ),
                reply_to_message_id=reply_to,
            )
            return

    # `#offline` 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:
        offline_bot = Bot.get(
            fn.lower(Bot.username)**username.lower(), Bot.approved == True)
        try:
            Suggestion.get(action="offline", subject=offline_bot)
        except Suggestion.DoesNotExist:
            suggestion = Suggestion(
                user=user,
                action="offline",
                date=datetime.date.today(),
                subject=offline_bot,
            )
            suggestion.save()
        update.message.reply_text(
            util.success(
                "Thank you! We will review your suggestion and set the bot offline."
            ),
            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
示例#17
0
 def set_allocation(self, bot_name, dollar_amount):
     b_id = Bot.get(name=bot_name).id
     settings = BotSettings.get(id=b_id)
     settings.allocation = dollar_amount
     settings.save()
     print("Allocation set to {}".format(settings.allocation))
示例#18
0
 def shutdown_all_bots(self):
     live_bots = BotSettings.select().where(BotSettings.bot_live == True)
     for bot in live_bots:
         name = Bot.get(id=bot.id).name
         self.shutdown_bot(name)
         print("Killed bot {}".format(name))