コード例 #1
0
def __list_all_modules():
    from os.path import dirname, basename, isfile
    import glob
    # This generates a list of modules in this folder for the * in __main__ to work.
    mod_paths = glob.glob(dirname(__file__) + "/*.py")
    all_modules = [basename(f)[:-3] for f in mod_paths if isfile(f)
                   and f.endswith(".py")
                   and not f.endswith('__init__.py')]

    if LOAD or NO_LOAD:
        to_load = LOAD
        if to_load:
            if not all(any(mod == module_name for module_name in all_modules) for mod in to_load):
                LOGGER.error("Invalid loadorder names. Quitting.")
                quit(1)

        else:
            to_load = all_modules

        if NO_LOAD:
            LOGGER.info("Not loading: {}".format(NO_LOAD))
            return [item for item in to_load if item not in NO_LOAD]

        return to_load

    return all_modules
コード例 #2
0
ファイル: users.py プロジェクト: yupisky/Halubot
def get_user_id(username):
    # ensure valid userid
    if len(username) <= 5:
        return None

    if username.startswith('@'):
        username = username[1:]

    users = sql.get_userid_by_name(username)

    if not users:
        return None

    elif len(users) == 1:
        return users[0].user_id

    else:
        for user_obj in users:
            try:
                userdat = dispatcher.bot.get_chat(user_obj.user_id)
                if userdat.username == username:
                    return userdat.id

            except BadRequest as excp:
                if excp.message == 'Chat not found':
                    pass
                else:
                    LOGGER.exception("Error extracting user ID")

    return None
コード例 #3
0
ファイル: __main__.py プロジェクト: yupisky/Halubot
def help_button(bot: Bot, update: Update):
    query = update.callback_query
    mod_match = re.match(r"help_module\((.+?)\)", query.data)
    prev_match = re.match(r"help_prev\((.+?)\)", query.data)
    next_match = re.match(r"help_next\((.+?)\)", query.data)
    back_match = re.match(r"help_back", query.data)
    try:
        if mod_match:
            module = mod_match.group(1)
            text = tl(update.effective_message, "Ini bantuan untuk modul *{}*:\n").format(HELPABLE[module].__mod_name__) \
                   + tl(update.effective_message, HELPABLE[module].__help__)

            query.message.reply_text(text=text,
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup([[
                                         InlineKeyboardButton(
                                             text=tl(query.message, "Kembali"),
                                             callback_data="help_back")
                                     ]]))

        elif prev_match:
            curr_page = int(prev_match.group(1))
            query.message.reply_text(text=tl(query.message, HELP_STRINGS),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             curr_page - 1, HELPABLE, "help")))

        elif next_match:
            next_page = int(next_match.group(1))
            query.message.reply_text(text=tl(query.message, HELP_STRINGS),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             next_page + 1, HELPABLE, "help")))

        elif back_match:
            query.message.reply_text(text=tl(query.message, HELP_STRINGS),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(0, HELPABLE,
                                                          "help")))

        # ensure no spinny white circle
        query.message.delete()
        bot.answer_callback_query(query.id)
    except Exception as excp:
        if excp.message == "Message is not modified":
            pass
        elif excp.message == "Query_id_invalid":
            pass
        elif excp.message == "Message can't be deleted":
            pass
        else:
            query.message.edit_text(excp.message)
            LOGGER.exception("Exception in help buttons. %s", str(query.data))
コード例 #4
0
ファイル: cust_filters.py プロジェクト: yupisky/Halubot
def get_exception(excp, filt, chat):
    if excp.message == "Unsupported url protocol":
        return "Anda tampaknya mencoba menggunakan protokol url yang tidak didukung. Telegram tidak mendukung tombol untuk beberapa protokol, seperti tg://. Silakan coba lagi."
    elif excp.message == "Reply message not found":
        return "noreply"
    else:
        LOGGER.warning("Message %s could not be parsed", str(filt.reply))
        LOGGER.exception("Could not parse filter %s in chat %s",
                         str(filt.keyword), str(chat.id))
        return "Catatan ini tidak dapat dikirim karena formatnya salah."
コード例 #5
0
ファイル: languages.py プロジェクト: yupisky/Halubot
def tl(message, text):
    if type(message) == int or type(message) == str and message[1:].isdigit():
        getlang = sql.get_lang(message)
        if getlang == 'None' or not getlang:
            getlang = 'id'
    else:
        getlang = sql.get_lang(message.chat.id)
        if getlang == 'None' or not getlang:
            if message.from_user.language_code:
                if message.from_user.language_code in LOADED_LANGS_ID:
                    sql.set_lang(message.chat.id,
                                 message.from_user.language_code)
                    getlang = message.from_user.language_code
                else:
                    sql.set_lang(message.chat.id, 'en')
                    getlang = 'en'
            else:
                if message.chat.type == "private":
                    sql.set_lang(message.chat.id, 'en')
                    getlang = 'en'
                else:
                    sql.set_lang(message.chat.id, 'id')
                    getlang = 'id'

    getlangid = {}
    for x in LOADED_LANGS_ID:
        getlangid[x] = x

    if str(getlang) == 'id':
        get = getattr(FUNC_LANG['id'], 'id')
        if text in tuple(get):
            return get.get(text)
        if text in ("RUN_STRINGS", "SLAP_TEMPLATES", "ITEMS", "THROW", "HIT",
                    "RAMALAN_STRINGS", "RAMALAN_FIRST"):
            runstr = getattr(FUNC_LANG['id'], text)
            return runstr
        return text
    elif str(getlang) in LOADED_LANGS_ID:
        func = getattr(FUNC_LANG[getlang], getlang)
        if text in ("RUN_STRINGS", "SLAP_TEMPLATES", "ITEMS", "THROW", "HIT",
                    "RAMALAN_STRINGS", "RAMALAN_FIRST"):
            runstr = getattr(FUNC_LANG[getlang], text)
            return runstr
        langtxt = func.get(text)
        if not langtxt:
            LOGGER.warning(
                "Can't get translated string for lang '{}' ('{}')".format(
                    str(getlang), text))
            langtxt = text
        return langtxt
    else:
        return text
コード例 #6
0
ファイル: __main__.py プロジェクト: yupisky/Halubot
def main():
    test_handler = CommandHandler("test", test)
    start_handler = CommandHandler("start", start, pass_args=True)

    help_handler = CommandHandler("help", get_help)
    help_callback_handler = CallbackQueryHandler(help_button, pattern=r"help_")

    settings_handler = CommandHandler("settings", get_settings)
    settings_callback_handler = CallbackQueryHandler(settings_button,
                                                     pattern=r"stngs_")

    donate_handler = CommandHandler("donate", donate)
    M_CONNECT_BTN_HANDLER = CallbackQueryHandler(m_connect_button,
                                                 pattern=r"main_connect")
    M_SETLANG_BTN_HANDLER = CallbackQueryHandler(m_change_langs,
                                                 pattern=r"main_setlang")

    migrate_handler = MessageHandler(Filters.status_update.migrate,
                                     migrate_chats)

    # dispatcher.add_handler(test_handler)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(settings_handler)
    dispatcher.add_handler(help_callback_handler)
    dispatcher.add_handler(settings_callback_handler)
    dispatcher.add_handler(migrate_handler)
    dispatcher.add_handler(donate_handler)
    dispatcher.add_handler(M_CONNECT_BTN_HANDLER)
    dispatcher.add_handler(M_SETLANG_BTN_HANDLER)

    # dispatcher.add_error_handler(error_callback)

    # add antiflood processor
    Dispatcher.process_update = process_update

    if WEBHOOK:
        LOGGER.info("Using webhooks.")
        updater.start_webhook(listen="127.0.0.1", port=PORT, url_path=TOKEN)

        if CERT_PATH:
            updater.bot.set_webhook(url=URL + TOKEN,
                                    certificate=open(CERT_PATH, 'rb'))
        else:
            updater.bot.set_webhook(url=URL + TOKEN)

    else:
        LOGGER.info("Using long polling.")
        updater.start_polling(timeout=15, read_latency=4)

    updater.idle()
コード例 #7
0
ファイル: locks.py プロジェクト: yupisky/Halubot
def rest_handler(bot: Bot, update: Update):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    for restriction, filter in RESTRICTION_TYPES.items():
        if filter(msg) and sql.is_restr_locked(
                chat.id, restriction) and can_delete(chat, bot.id):
            try:
                msg.delete()
            except BadRequest as excp:
                if excp.message == "Message to delete not found":
                    pass
                else:
                    LOGGER.exception("ERROR in restrictions")
            break
コード例 #8
0
ファイル: __main__.py プロジェクト: yupisky/Halubot
def migrate_chats(bot: Bot, update: Update):
    msg = update.effective_message  # type: Optional[Message]
    if msg.migrate_to_chat_id:
        old_chat = update.effective_chat.id
        new_chat = msg.migrate_to_chat_id
    elif msg.migrate_from_chat_id:
        old_chat = msg.migrate_from_chat_id
        new_chat = update.effective_chat.id
    else:
        return

    LOGGER.info("Migrating from %s, to %s", str(old_chat), str(new_chat))
    for mod in MIGRATEABLE:
        mod.__migrate__(old_chat, new_chat)

    LOGGER.info("Successfully migrated!")
    raise DispatcherHandlerStop
コード例 #9
0
ファイル: users.py プロジェクト: yupisky/Halubot
def broadcast(bot: Bot, update: Update):
    to_send = update.effective_message.text.split(None, 1)
    if len(to_send) >= 2:
        chats = sql.get_all_chats() or []
        failed = 0
        for chat in chats:
            try:
                bot.sendMessage(int(chat.chat_id), to_send[1])
                sleep(0.1)
            except TelegramError:
                failed += 1
                LOGGER.warning("Couldn't send broadcast to %s, group name %s",
                               str(chat.chat_id), str(chat.chat_name))

        send_message(
            update.effective_message,
            "Siaran selesai. {} grup gagal menerima pesan, mungkin "
            "karena ditendang.".format(failed))
コード例 #10
0
ファイル: log_channel.py プロジェクト: yupisky/Halubot
        def log_action(bot: Bot, update: Update, *args, **kwargs):
            result = func(bot, update, *args, **kwargs)
            chat = update.effective_chat  # type: Optional[Chat]
            message = update.effective_message  # type: Optional[Message]
            if result:
                if chat.type == chat.SUPERGROUP and chat.username:
                    result += "\n<b>Link:</b> " \
                              "<a href=\"http://telegram.me/{}/{}\">klik disini</a>".format(chat.username,
                                                                                           message.message_id)
                log_chat = sql.get_chat_log_channel(chat.id)
                if log_chat:
                    try:
                        send_log(bot, log_chat, chat.id, result)
                    except Unauthorized:
                        sql.stop_chat_logging(chat.id)
            elif result == "":
                pass
            else:
                LOGGER.warning("%s was set as loggable, but had no return statement.", func)

            return result
コード例 #11
0
ファイル: log_channel.py プロジェクト: yupisky/Halubot
    def setlog(bot: Bot, update: Update):
        spam = spamfilters(update.effective_message.text, update.effective_message.from_user.id, update.effective_chat.id, update.effective_message)
        if spam == True:
            return
        message = update.effective_message  # type: Optional[Message]
        chat = update.effective_chat  # type: Optional[Chat]
        if chat.type == chat.CHANNEL:
            send_message(update.effective_message, tl(update.effective_message, "Sekarang, teruskan /setlog ke grup yang Anda ingin ikat saluran ini!"))

        elif message.forward_from_chat:
            sql.set_chat_log_channel(chat.id, message.forward_from_chat.id)
            try:
                message.delete()
            except BadRequest as excp:
                if excp.message == "Message to delete not found":
                    pass
                else:
                    LOGGER.exception("Error deleting message in log channel. Should work anyway though.")
                    
            try:
                bot.send_message(message.forward_from_chat.id,
                             tl(update.effective_message, "Saluran ini telah ditetapkan sebagai saluran log untuk {}.").format(
                                 chat.title or chat.first_name))
            except Unauthorized as excp:
                if excp.message == "Forbidden: bot is not a member of the channel chat":
                    bot.send_message(chat.id, tl(update.effective_message, "Gagal menyetel saluran log!\nSaya mungkin bukan admin di channel tersebut."))
                    sql.stop_chat_logging(chat.id)
                    return
                else:
                    LOGGER.exception("ERROR in setting the log channel.")
                    
            bot.send_message(chat.id, tl(update.effective_message, "Berhasil mengatur saluran log!"))

        else:
            send_message(update.effective_message, tl(update.effective_message, "Langkah-langkah untuk mengatur saluran log adalah:\n"
                               " - tambahkan bot ke saluran yang diinginkan\n"
                               " - Kirimkan /setlog ke saluran\n"
                               " - Teruskan /setlog ke grup\n"))
コード例 #12
0
ファイル: log_channel.py プロジェクト: yupisky/Halubot
    def send_log(bot: Bot, log_chat_id: str, orig_chat_id: str, result: str):
        try:
            bot.send_message(log_chat_id, result, parse_mode=ParseMode.HTML)
        except BadRequest as excp:
            if excp.message == "Chat not found":
                bot.send_message(orig_chat_id, tl(update.effective_message, "Saluran log ini telah dihapus - tidak bisa dibuka."))
                sql.stop_chat_logging(orig_chat_id)
            else:
                LOGGER.warning(excp.message)
                LOGGER.warning(result)
                LOGGER.exception("Could not parse")

                bot.send_message(log_chat_id, result + tl(update.effective_message, "\n\nMemformat telah dinonaktifkan karena kesalahan tak terduga."))
コード例 #13
0
def temp_mute(bot: Bot, update: Update, args: List[str]) -> str:
    spam = spamfilters(update.effective_message.text,
                       update.effective_message.from_user.id,
                       update.effective_chat.id, update.effective_message)
    if spam == True:
        return
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Anda sepertinya tidak mengacu pada pengguna."))
        return ""

    conn = connected(bot, update, chat, user.id, need_admin=True)
    if conn:
        chat = dispatcher.bot.getChat(conn)
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        if update.effective_message.chat.type == "private":
            update.effective_send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Anda bisa lakukan command ini pada grup, bukan pada PM"))
            return ""
        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Saya tidak dapat menemukan pengguna ini"))
            return ""
        else:
            raise

    if is_user_admin(chat, user_id, member):
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Saya benar-benar berharap dapat membisukan admin..."))
        return ""

    if user_id == bot.id:
        send_message(
            update.effective_message,
            tl(
                update.effective_message,
                "Saya tidak akan membisukan diri saya sendiri, apakah kamu gila?"
            ))
        return ""

    check = bot.getChatMember(chat.id, user.id)
    if check['can_restrict_members'] == False:
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Anda tidak punya hak untuk membatasi seseorang."))
        return ""

    if not reason:
        send_message(
            update.effective_message,
            tl(
                update.effective_message,
                "Anda belum menetapkan waktu untuk menonaktifkan pengguna ini!"
            ))
        return ""

    split_reason = reason.split(None, 1)

    time_val = split_reason[0].lower()
    if len(split_reason) > 1:
        reason = split_reason[1]
    else:
        reason = ""

    mutetime = extract_time(message, time_val)

    if not mutetime:
        return ""

    log = "<b>{}:</b>" \
          "\n#TMUTE" \
          "\n<b>Admin:</b> {}" \
          "\n<b>User:</b> {}" \
          "\n<b>Time:</b> {}".format(html.escape(chat.title), mention_html(user.id, user.first_name),
                                     mention_html(member.user.id, member.user.first_name), time_val)
    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        if member.can_send_messages is None or member.can_send_messages:
            bot.restrict_chat_member(chat.id,
                                     user_id,
                                     until_date=mutetime,
                                     can_send_messages=False)
            if conn:
                text = tl(update.effective_message,
                          "Dibisukan untuk *{}* pada *{}*!").format(
                              time_val, chat_name)
            else:
                text = tl(update.effective_message,
                          "Dibisukan untuk *{}*!").format(time_val)
            send_message(update.effective_message, text, parse_mode="markdown")
            return log
        else:
            send_message(
                update.effective_message,
                tl(update.effective_message, "Pengguna ini sudah dibungkam."))

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            send_message(update.effective_message,
                         tl(update.effective_message,
                            "Dibisukan untuk *{}*!").format(time_val),
                         quote=False)
            return log
        else:
            LOGGER.warning(update)
            LOGGER.exception("ERROR muting user %s in chat %s (%s) due to %s",
                             user_id, chat.title, chat.id, excp.message)
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Yah sial, aku tidak bisa membisukan pengguna itu."))

    return ""
コード例 #14
0
ファイル: cust_filters.py プロジェクト: yupisky/Halubot
def reply_filter(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]

    to_match = extract_text(message)
    if not to_match:
        return

    chat_filters = sql.get_chat_triggers(chat.id)
    for keyword in chat_filters:
        pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])"
        if re.search(pattern, to_match, flags=re.IGNORECASE):
            filt = sql.get_filter(chat.id, keyword)
            if filt.reply == "there is should be a new reply":
                buttons = sql.get_buttons(chat.id, filt.keyword)
                keyb = build_keyboard(buttons)
                keyboard = InlineKeyboardMarkup(keyb)
                if filt.file_type in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    try:
                        bot.send_message(
                            chat.id,
                            filt.reply_text,
                            reply_to_message_id=message.message_id,
                            parse_mode="markdown",
                            disable_web_page_preview=True,
                            reply_markup=keyboard)
                    except BadRequest as excp:
                        error_catch = get_exception(excp, filt, chat)
                        if error_catch == "noreply":
                            try:
                                bot.send_message(chat.id,
                                                 filt.reply_text,
                                                 parse_mode="markdown",
                                                 disable_web_page_preview=True,
                                                 reply_markup=keyboard)
                            except BadRequest as excp:
                                LOGGER.exception("Gagal mengirim pesan: " +
                                                 excp.message)
                                send_message(
                                    update.effective_message,
                                    tl(update.effective_message,
                                       get_exception(excp, filt, chat)))
                                pass
                        else:
                            try:
                                send_message(
                                    update.effective_message,
                                    tl(update.effective_message,
                                       get_exception(excp, filt, chat)))
                            except BadRequest as excp:
                                LOGGER.exception("Gagal mengirim pesan: " +
                                                 excp.message)
                                pass
                else:
                    ENUM_FUNC_MAP[filt.file_type](
                        chat.id,
                        filt.file_id,
                        caption=filt.reply_text,
                        reply_to_message_id=message.message_id,
                        parse_mode="markdown",
                        disable_web_page_preview=True,
                        reply_markup=keyboard)
                break
            else:
                if filt.is_sticker:
                    message.reply_sticker(filt.reply)
                elif filt.is_document:
                    message.reply_document(filt.reply)
                elif filt.is_image:
                    message.reply_photo(filt.reply)
                elif filt.is_audio:
                    message.reply_audio(filt.reply)
                elif filt.is_voice:
                    message.reply_voice(filt.reply)
                elif filt.is_video:
                    message.reply_video(filt.reply)
                elif filt.has_markdown:
                    buttons = sql.get_buttons(chat.id, filt.keyword)
                    keyb = build_keyboard(buttons)
                    keyboard = InlineKeyboardMarkup(keyb)

                    try:
                        send_message(update.effective_message,
                                     filt.reply,
                                     parse_mode=ParseMode.MARKDOWN,
                                     disable_web_page_preview=True,
                                     reply_markup=keyboard)
                    except BadRequest as excp:
                        if excp.message == "Unsupported url protocol":
                            try:
                                send_message(
                                    update.effective_message,
                                    tl(
                                        update.effective_message,
                                        "Anda tampaknya mencoba menggunakan protokol url yang tidak didukung. Telegram "
                                        "tidak mendukung tombol untuk beberapa protokol, seperti tg://. Silakan coba "
                                        "lagi."))
                            except BadRequest as excp:
                                LOGGER.exception("Gagal mengirim pesan: " +
                                                 excp.message)
                                pass
                        elif excp.message == "Reply message not found":
                            try:
                                bot.send_message(chat.id,
                                                 filt.reply,
                                                 parse_mode=ParseMode.MARKDOWN,
                                                 disable_web_page_preview=True,
                                                 reply_markup=keyboard)
                            except BadRequest as excp:
                                LOGGER.exception("Gagal mengirim pesan: " +
                                                 excp.message)
                                pass
                        else:
                            try:
                                send_message(
                                    update.effective_message,
                                    tl(
                                        update.effective_message,
                                        "Catatan ini tidak dapat dikirim karena formatnya salah."
                                    ))
                            except BadRequest as excp:
                                LOGGER.exception("Gagal mengirim pesan: " +
                                                 excp.message)
                                pass
                            LOGGER.warning("Message %s could not be parsed",
                                           str(filt.reply))
                            LOGGER.exception(
                                "Could not parse filter %s in chat %s",
                                str(filt.keyword), str(chat.id))

                else:
                    # LEGACY - all new filters will have has_markdown set to True.
                    try:
                        send_message(update.effective_message, filt.reply)
                    except BadRequest as excp:
                        LOGGER.exception("Gagal mengirim pesan: " +
                                         excp.message)
                        pass
                break
コード例 #15
0
def del_blackliststicker(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]
    user = update.effective_user
    to_match = message.sticker
    if not to_match:
        return

    getmode, value = sql.get_blacklist_setting(chat.id)

    chat_filters = sql.get_chat_stickers(chat.id)
    for trigger in chat_filters:
        if to_match.set_name.lower() == trigger.lower():
            try:
                if getmode == 0:
                    return
                elif getmode == 1:
                    message.delete()
                elif getmode == 2:
                    message.delete()
                    warn(
                        update.effective_user,
                        chat,
                        tl(
                            update.effective_message,
                            "Menggunakan stiker '{}' yang ada di daftar hitam stiker"
                        ).format(trigger),
                        message,
                        update.effective_user,
                        conn=False)
                    return
                elif getmode == 3:
                    message.delete()
                    bot.restrict_chat_member(chat.id,
                                             update.effective_user.id,
                                             can_send_messages=False)
                    bot.sendMessage(
                        chat.id,
                        tl(
                            update.effective_message,
                            "{} di bisukan karena menggunakan stiker '{}' yang ada di daftar hitam stiker"
                        ).format(mention_markdown(user.id, user.first_name),
                                 trigger),
                        parse_mode="markdown")
                    return
                elif getmode == 4:
                    message.delete()
                    res = chat.unban_member(update.effective_user.id)
                    if res:
                        bot.sendMessage(
                            chat.id,
                            tl(
                                update.effective_message,
                                "{} di tendang karena menggunakan stiker '{}' yang ada di daftar hitam stiker"
                            ).format(
                                mention_markdown(user.id, user.first_name),
                                trigger),
                            parse_mode="markdown")
                    return
                elif getmode == 5:
                    message.delete()
                    chat.kick_member(user.id)
                    bot.sendMessage(
                        chat.id,
                        tl(
                            update.effective_message,
                            "{} di blokir karena menggunakan stiker '{}' yang ada di daftar hitam stiker"
                        ).format(mention_markdown(user.id, user.first_name),
                                 trigger),
                        parse_mode="markdown")
                    return
                elif getmode == 6:
                    message.delete()
                    bantime = extract_time(message, value)
                    chat.kick_member(user.id, until_date=bantime)
                    bot.sendMessage(
                        chat.id,
                        tl(
                            update.effective_message,
                            "{} di blokir selama {} karena menggunakan stiker '{}' yang ada di daftar hitam stiker"
                        ).format(mention_markdown(user.id, user.first_name),
                                 value, trigger),
                        parse_mode="markdown")
                    return
                elif getmode == 7:
                    message.delete()
                    mutetime = extract_time(message, value)
                    bot.restrict_chat_member(chat.id,
                                             user.id,
                                             until_date=mutetime,
                                             can_send_messages=False)
                    bot.sendMessage(
                        chat.id,
                        tl(
                            update.effective_message,
                            "{} di bisukan selama {} karena menggunakan stiker '{}' yang ada di daftar hitam stiker"
                        ).format(mention_markdown(user.id, user.first_name),
                                 value, trigger),
                        parse_mode="markdown")
                    return
            except BadRequest as excp:
                if excp.message == "Message to delete not found":
                    pass
                else:
                    LOGGER.exception("Error while deleting blacklist message.")
                break
コード例 #16
0
ファイル: sed.py プロジェクト: yupisky/Halubot
def sed(bot: Bot, update: Update):
    start = time.time()
    spam = spamfilters(update.effective_message.text,
                       update.effective_message.from_user.id,
                       update.effective_chat.id, update.effective_message)
    if spam == True:
        return
    if update.effective_message.from_user.id != 388576209:
        return
    while elapsed_time() < max_time:
        sed_result = separate_sed(update.effective_message.text)
        if sed_result and update.effective_message.reply_to_message:
            if update.effective_message.reply_to_message.text:
                to_fix = update.effective_message.reply_to_message.text
            elif update.effective_message.reply_to_message.caption:
                to_fix = update.effective_message.reply_to_message.caption
            else:
                return

            repl, repl_with, flags = sed_result

            if not repl:
                update.effective_message.reply_to_message.reply_text(
                    "Anda mencoba untuk mengganti... "
                    "tidak ada apa-apa dengan sesuatu?")
                return

            try:
                check = re.match(repl, to_fix, flags=re.IGNORECASE)

                if check and check.group(0).lower() == to_fix.lower():
                    update.effective_message.reply_to_message.reply_text(
                        "Hai semuanya, {} sedang mencoba untuk membuat "
                        "saya mengatakan hal-hal yang saya tidak mau "
                        "katakan!".format(update.effective_user.first_name))
                    return

                if 'i' in flags and 'g' in flags:
                    text = re.sub(repl, repl_with, to_fix, flags=re.I).strip()
                elif 'i' in flags:
                    text = re.sub(repl, repl_with, to_fix, count=1,
                                  flags=re.I).strip()
                elif 'g' in flags:
                    text = re.sub(repl, repl_with, to_fix).strip()
                else:
                    text = re.sub(repl, repl_with, to_fix, count=1).strip()
            except sre_constants.error:
                LOGGER.warning(update.effective_message.text)
                LOGGER.exception("SRE constant error")
                update.effective_message.reply_text(
                    "Apakah itu sed? Sepertinya tidak.")
                return

            # empty string errors -_-
            if len(text) >= telegram.MAX_MESSAGE_LENGTH:
                return update.effective_message.reply_text(
                    "Hasil dari perintah sed terlalu lama untuk \
                                                     telegram!")
            elif text:
                return update.effective_message.reply_to_message.reply_text(
                    text)
    return update.effective_message.reply_to_message.reply_text(
        "Hasil terlalu lama untuk di proses!")
コード例 #17
0
def temp_ban(bot: Bot, update: Update, args: List[str]) -> str:
    currentchat = update.effective_chat  # type: Optional[Chat]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    spam = spamfilters(update.effective_message.text, update.effective_message.from_user.id, update.effective_chat.id, update.effective_message)
    if spam == True:
        return

    user_id, reason = extract_user_and_text(message, args)

    conn = connected(bot, update, chat, user.id, need_admin=True)
    if conn:
        chat = dispatcher.bot.getChat(conn)
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        if update.effective_message.chat.type == "private":
            send_message(update.effective_message, tl(update.effective_message, "Anda bisa lakukan command ini pada grup, bukan pada PM"))
            return ""
        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    check = bot.getChatMember(chat_id, bot.id)
    if check.status == 'member':
        if conn:
            text = tl(update.effective_message, "Saya tidak bisa membatasi orang di *{}*! Pastikan saya admin dan dapat menunjuk admin baru.").format(chat_name)
        else:
            text = tl(update.effective_message, "Saya tidak bisa membatasi orang di sini! Pastikan saya admin dan dapat menunjuk admin baru.")
        send_message(update.effective_message, text, parse_mode="markdown")
        return ""
    else:
        if check['can_restrict_members'] == False:
            if conn:
                text = tl(update.effective_message, "Saya tidak bisa membatasi orang di *{}*! Pastikan saya admin dan dapat menunjuk admin baru.").format(chat_name)
            else:
                text = tl(update.effective_message, "Saya tidak bisa membatasi orang di sini! Pastikan saya admin dan dapat menunjuk admin baru.")
            send_message(update.effective_message, text, parse_mode="markdown")
            return ""

    if not user_id:
        send_message(update.effective_message, tl(update.effective_message, "Anda sepertinya tidak mengacu pada pengguna."))
        return ""

    try:
        if conn:
            member = bot.getChatMember(chat_id, user_id)
        else:
            member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            send_message(update.effective_message, tl(update.effective_message, "Saya tidak dapat menemukan pengguna ini 😣"))
            return ""
        else:
            raise

    if user_id == bot.id:
        send_message(update.effective_message, tl(update.effective_message, "Saya tidak akan BAN diri saya sendiri, apakah kamu gila? 😠"))
        return ""

    if is_user_ban_protected(chat, user_id, member):
        send_message(update.effective_message, tl(update.effective_message, "Saya tidak bisa banned orang ini karena dia adalah admin 😒"))
        return ""

    if member['can_restrict_members'] == False:
        send_message(update.effective_message, tl(update.effective_message, "Anda tidak punya hak untuk membatasi seseorang."))
        return ""

    if not reason:
        send_message(update.effective_message, tl(update.effective_message, "Anda belum menetapkan waktu untuk banned pengguna ini!"))
        return ""
    
    split_reason = reason.split(None, 1)

    time_val = split_reason[0].lower()
    if len(split_reason) > 1:
        reason = split_reason[1]
    else:
        reason = ""
        
        bantime = extract_time(message, time_val)
        
        if not bantime:
            return ""

    log = "<b>{}:</b>" \
          "\n#TEMPBAN" \
          "\n<b>Admin:</b> {}" \
          "\n<b>User:</b> {} (<code>{}</code>)" \
          "\n<b>Time:</b> {}".format(html.escape(chat.title),
                                     mention_html(user.id, user.first_name),
                                     mention_html(member.user.id, member.user.first_name),
                                     member.user.id,
                                     time_val)
    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        if conn:
            bot.kickChatMember(chat_id, user_id, until_date=bantime)
            bot.send_sticker(currentchat.id, BAN_STICKER)  # banhammer marie sticker
            send_message(update.effective_message, tl(update.effective_message, "Banned! Pengguna diblokir untuk *{}* pada *{}*.").format(time_val, chat_name), parse_mode="markdown")
        else:
            chat.kick_member(user_id, until_date=bantime)
            bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
            send_message(update.effective_message, tl(update.effective_message, "Banned! Pengguna diblokir untuk {}.").format(time_val))
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            send_message(update.effective_message, tl(update.effective_message, "Banned! Pengguna diblokir untuk {}.").format(time_val), quote=False)
            return log
        else:
            LOGGER.warning(update)
            LOGGER.exception("ERROR banning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id,
                             excp.message)
            send_message(update.effective_message, tl(update.effective_message, "Yah sial, aku tidak bisa menendang pengguna itu 😒"))

    return ""
コード例 #18
0
ファイル: languages.py プロジェクト: yupisky/Halubot
from halubot.modules.helper_funcs.alternate import send_message

LOADED_LANGS_ID = []
LANGS_TEXT = {}
FUNC_LANG = {}

for x in os.listdir('halubot/modules/langs'):
    if os.path.isdir('halubot/modules/langs/' + x):
        continue
    x = x.replace('.py', '')
    LOADED_LANGS_ID.append(x)
    imported_langs = importlib.import_module("halubot.modules.langs." + x)
    FUNC_LANG[x] = imported_langs
    LANGS_TEXT[x] = imported_langs.__lang__

LOGGER.info("{} languages loaded: {}".format(len(LOADED_LANGS_ID),
                                             LOADED_LANGS_ID))


def tl(message, text):
    if type(message) == int or type(message) == str and message[1:].isdigit():
        getlang = sql.get_lang(message)
        if getlang == 'None' or not getlang:
            getlang = 'id'
    else:
        getlang = sql.get_lang(message.chat.id)
        if getlang == 'None' or not getlang:
            if message.from_user.language_code:
                if message.from_user.language_code in LOADED_LANGS_ID:
                    sql.set_lang(message.chat.id,
                                 message.from_user.language_code)
                    getlang = message.from_user.language_code
コード例 #19
0
def report(bot: Bot, update: Update) -> str:
	spam = spamfilters(update.effective_message.text, update.effective_message.from_user.id, update.effective_chat.id, update.effective_message)
	if spam == True:
		return
	message = update.effective_message  # type: Optional[Message]
	chat = update.effective_chat  # type: Optional[Chat]
	user = update.effective_user  # type: Optional[User]
	global CURRENT_REPORT

	if chat and message.reply_to_message and sql.chat_should_report(chat.id):
		reported_user = message.reply_to_message.from_user  # type: Optional[User]
		chat_name = chat.title or chat.first or chat.username

		a, b = user_protection_checker(bot, message.reply_to_message.from_user.id)
		if not a:
			return ""

		admin_list = chat.get_administrators()

		if chat.username and chat.type == Chat.SUPERGROUP:
			msg = tl(update.effective_message, "<b>{}:</b>" \
				  "\n<b>Pengguna yang dilaporkan:</b> {} (<code>{}</code>)" \
				  "\n<b>Dilaporkan oleh:</b> {} (<code>{}</code>)").format(html.escape(chat.title),
																	  mention_html(
																		  reported_user.id,
																		  reported_user.first_name),
																	  reported_user.id,
																	  mention_html(user.id,
																				   user.first_name),
																	  user.id)
			#link = "\n<b>Link:</b> " \
			#       "<a href=\"http://telegram.me/{}/{}\">klik disini</a>".format(chat.username, message.message_id)

		else:
			msg = tl(update.effective_message, "{} memanggil admin di \"{}\"!").format(mention_html(user.id, user.first_name),
															   html.escape(chat_name))
			#link = ""

		if chat.username:
			chatlink = "https://t.me/{}/{}".format(chat.username, str(message.reply_to_message.message_id))
		else:
			chatlink = "https://t.me/c/{}/{}".format(str(chat.id)[4:], str(message.reply_to_message.message_id))
		keyboard = [
			  [InlineKeyboardButton(tl(update.effective_message, "⚠️ Pesan yang dilaporkan"), url=chatlink)],
			  [InlineKeyboardButton(tl(update.effective_message, "⚠️ Tendang"), callback_data="rp_{}=1={}".format(chat.id, reported_user.id)),
			  InlineKeyboardButton(tl(update.effective_message, "⛔️ Banned"), callback_data="rp_{}=2={}".format(chat.id, reported_user.id))],
			  [InlineKeyboardButton(tl(update.effective_message, "Hapus pesan"), callback_data="rp_{}=3={}".format(chat.id, message.reply_to_message.message_id))],
			  [InlineKeyboardButton(tl(update.effective_message, "Tutup Tombol"), callback_data="rp_{}=4={}".format(chat.id, reported_user.id))]
			]
		reply_markup = InlineKeyboardMarkup(keyboard)

		should_forward = True
		bot.send_message(chat.id, tl(update.effective_message, "<i>⚠️ Pesan telah di laporkan ke semua admin!</i>"), parse_mode=ParseMode.HTML, reply_to_message_id=message.message_id)

		CURRENT_REPORT[str(chat.id)] = msg
		CURRENT_REPORT[str(chat.id)+"key"] = reply_markup
		CURRENT_REPORT[str(chat.id)+"user"] = {'name': reported_user.first_name, 'id': reported_user.id, 'rname': user.first_name, 'rid': user.id}
		for admin in admin_list:
			if admin.user.is_bot:  # can't message bots
				continue

			if sql.user_should_report(admin.user.id):
				try:
					#bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML)
					#bot.send_message(admin.user.id, msg, parse_mode=ParseMode.HTML, reply_markup=reply_markup)

					try:
						if should_forward:
							message.reply_to_message.forward(admin.user.id)

							if len(message.text.split()) > 1:  # If user is giving a reason, send his message too
								message.forward(admin.user.id)
					except:
						pass
					bot.send_message(admin.user.id, msg, parse_mode=ParseMode.HTML, reply_markup=reply_markup)

				except Unauthorized:
					pass
				except BadRequest as excp:  # TODO: cleanup exceptions
					LOGGER.exception("Exception while reporting user")
		return msg

	return ""
コード例 #20
0
ファイル: extraction.py プロジェクト: jagoanpilot/Halubot
def extract_unt_fedban(message: Message,
                       args: List[str]) -> (Optional[int], Optional[str]):
    prev_message = message.reply_to_message
    split_text = message.text.split(None, 1)

    if len(split_text) < 2:
        return id_from_reply(message)  # only option possible

    text_to_parse = split_text[1]

    text = ""

    entities = list(message.parse_entities([MessageEntity.TEXT_MENTION]))
    if len(entities) > 0:
        ent = entities[0]
    else:
        ent = None

    # if entity offset matches (command end/text start) then all good
    if entities and ent and ent.offset == len(
            message.text) - len(text_to_parse):
        ent = entities[0]
        user_id = ent.user.id
        text = message.text[ent.offset + ent.length:]

    elif len(args) >= 1 and args[0][0] == '@':
        user = args[0]
        user_id = get_user_id(user)
        if not user_id and not str(user_id).isdigit():
            message.reply_text(
                "Saya tidak memiliki pengguna di db saya. Anda akan dapat berinteraksi dengan mereka jika "
                "Anda membalas pesan orang itu, atau meneruskan salah satu dari pesan pengguna itu."
            )
            return None, None

        else:
            user_id = user_id
            res = message.text.split(None, 2)
            if len(res) >= 3:
                text = res[2]

    elif len(args) >= 1 and args[0].isdigit():
        user_id = int(args[0])
        res = message.text.split(None, 2)
        if len(res) >= 3:
            text = res[2]

    elif prev_message:
        user_id, text = id_from_reply(message)

    else:
        return None, None

    try:
        message.bot.get_chat(user_id)
    except BadRequest as excp:
        if excp.message in ("User_id_invalid",
                            "Chat not found") and not str(user_id).isdigit():
            message.reply_text(
                "Saya sepertinya tidak pernah berinteraksi dengan pengguna ini sebelumnya - silakan meneruskan pesan dari "
                "mereka untuk memberi saya kontrol! (Seperti boneka voodoo, saya butuh sepotong untuk bisa"
                "untuk menjalankan perintah tertentu...)")
            return None, None
        elif excp.message != "Chat not found":
            LOGGER.exception("Exception %s on user %s", excp.message, user_id)
            return None, None
        elif not str(user_id).isdigit():
            return None, None

    return user_id, text
コード例 #21
0
def ban(bot: Bot, update: Update, args: List[str]) -> str:
    currentchat = update.effective_chat  # type: Optional[Chat]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    spam = spamfilters(update.effective_message.text, update.effective_message.from_user.id, update.effective_chat.id, update.effective_message)
    if spam == True:
        return

    user_id, reason = extract_user_and_text(message, args)

    conn = connected(bot, update, chat, user.id, need_admin=True)
    if conn:
        chat = dispatcher.bot.getChat(conn)
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        if update.effective_message.chat.type == "private":
            send_message(update.effective_message, tl(update.effective_message, "Anda bisa lakukan command ini pada grup, bukan pada PM"))
            return ""
        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    check = bot.getChatMember(chat_id, bot.id)
    if check.status == 'member' or check['can_restrict_members'] == False:
        if conn:
            text = tl(update.effective_message, "Saya tidak bisa membatasi orang di {}! Pastikan saya admin dan dapat menunjuk admin baru.").format(chat_name)
        else:
            text = tl(update.effective_message, "Saya tidak bisa membatasi orang di sini! Pastikan saya admin dan dapat menunjuk admin baru.")
        send_message(update.effective_message, text, parse_mode="markdown")
        return ""

    if not user_id:
        send_message(update.effective_message, tl(update.effective_message, "Anda sepertinya tidak mengacu pada pengguna."))
        return ""

    try:
        if conn:
            member = bot.getChatMember(chat_id, user_id)
        else:
            member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            if conn:
                text = tl(update.effective_message, "Saya tidak dapat menemukan pengguna ini pada *{}* 😣").format(chat_name)
            else:
                text = tl(update.effective_message, "Saya tidak dapat menemukan pengguna ini 😣")
            send_message(update.effective_message, text, parse_mode="markdown")
            return ""
        else:
            raise

    if user_id == bot.id:
        send_message(update.effective_message, tl(update.effective_message, "Saya tidak akan BAN diri saya sendiri, apakah kamu gila? 😠"))
        return ""

    if is_user_ban_protected(chat, user_id, member):
        send_message(update.effective_message, tl(update.effective_message, "Saya tidak bisa banned orang ini karena dia adalah admin 😒"))
        return ""

    if member['can_restrict_members'] == False:
        if conn:
            text = tl(update.effective_message, "Anda tidak punya hak untuk membatasi seseorang pada *{}*.").format(chat_name)
        else:
            text = tl(update.effective_message, "Anda tidak punya hak untuk membatasi seseorang.")
        send_message(update.effective_message, text, parse_mode="markdown")
        return ""

    log = "<b>{}:</b>" \
          "\n#BANNED" \
          "\n<b>Admin:</b> {}" \
          "\n<b>User:</b> {} (<code>{}</code>)".format(html.escape(chat.title),
                                                       mention_html(user.id, user.first_name),
                                                       mention_html(member.user.id, member.user.first_name),
                                                       member.user.id)
    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        if conn:
            bot.kickChatMember(chat_id, user_id)
            bot.send_sticker(currentchat.id, BAN_STICKER)  # banhammer marie sticker
            send_message(update.effective_message, tl(update.effective_message, "Terbanned pada *{}*! 😝").format(chat_name), parse_mode="markdown")
        else:
            chat.kick_member(user_id)
            if message.text.split(None, 1)[0][1:] == "sban":
                update.effective_message.delete()
            else:
                bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
                send_message(update.effective_message, tl(update.effective_message, "Terbanned! 😝"))
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            send_message(update.effective_message, tl(update.effective_message, "Terbanned! 😝"), quote=False)
            return log
        elif excp.message == "Message can't be deleted":
            pass
        else:
            LOGGER.warning(update)
            LOGGER.exception("ERROR membanned pengguna %s di obrolan %s (%s) disebabkan oleh %s", user_id, chat.title, chat.id,
                             excp.message)
            send_message(update.effective_message, tl(update.effective_message, "Yah sial, aku tidak bisa banned pengguna itu 😒"))

    return ""
コード例 #22
0
    from os.path import dirname, basename, isfile
    import glob
    # This generates a list of modules in this folder for the * in __main__ to work.
    mod_paths = glob.glob(dirname(__file__) + "/*.py")
    all_modules = [basename(f)[:-3] for f in mod_paths if isfile(f)
                   and f.endswith(".py")
                   and not f.endswith('__init__.py')]

    if LOAD or NO_LOAD:
        to_load = LOAD
        if to_load:
            if not all(any(mod == module_name for module_name in all_modules) for mod in to_load):
                LOGGER.error("Invalid loadorder names. Quitting.")
                quit(1)

        else:
            to_load = all_modules

        if NO_LOAD:
            LOGGER.info("Not loading: {}".format(NO_LOAD))
            return [item for item in to_load if item not in NO_LOAD]

        return to_load

    return all_modules


ALL_MODULES = sorted(__list_all_modules())
LOGGER.info("Modules to load: %s", str(ALL_MODULES))
__all__ = ALL_MODULES + ["ALL_MODULES"]
コード例 #23
0
ファイル: locks.py プロジェクト: yupisky/Halubot
def del_lockables(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]

    for lockable, filter in LOCK_TYPES.items():
        if lockable == "rtl":
            if sql.is_locked(chat.id, lockable) and can_delete(chat, bot.id):
                if message.caption:
                    check = ad.detect_alphabet(u'{}'.format(message.caption))
                    if 'ARABIC' in check:
                        try:
                            message.delete()
                        except BadRequest as excp:
                            if excp.message == "Message to delete not found":
                                pass
                            else:
                                LOGGER.exception("ERROR in lockables")
                        getconf = sql.get_lockconf(chat.id)
                        if getconf:
                            warn(
                                update.effective_user,
                                chat,
                                tl(
                                    update.effective_message,
                                    "Mengirim 'Teks RTL' yang sedang di kunci saat ini"
                                ),
                                message,
                                update.effective_user,
                                conn=False)
                if message.text:
                    check = ad.detect_alphabet(u'{}'.format(message.text))
                    if 'ARABIC' in check:
                        try:
                            message.delete()
                        except BadRequest as excp:
                            if excp.message == "Message to delete not found":
                                pass
                            else:
                                LOGGER.exception("ERROR in lockables")
                        getconf = sql.get_lockconf(chat.id)
                        if getconf:
                            warn(
                                update.effective_user,
                                chat,
                                tl(
                                    update.effective_message,
                                    "Mengirim 'Teks RTL' yang sedang di kunci saat ini"
                                ),
                                message,
                                update.effective_user,
                                conn=False)
            break
        if filter(message) and sql.is_locked(chat.id, lockable) and can_delete(
                chat, bot.id):
            if lockable == "bots":
                new_members = update.effective_message.new_chat_members
                for new_mem in new_members:
                    if new_mem.is_bot:
                        if not is_bot_admin(chat, bot.id):
                            send_message(
                                update.effective_message,
                                tl(
                                    update.effective_message,
                                    "Saya melihat bot, dan saya diberitahu untuk menghentikan mereka bergabung... "
                                    "tapi saya bukan admin!"))
                            return

                        chat.kick_member(new_mem.id)
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Hanya admin yang diizinkan menambahkan bot ke obrolan ini! Keluar dari sini!"
                            ))
                        getconf = sql.get_lockconf(chat.id)
                        if getconf:
                            warn(
                                update.effective_user,
                                chat,
                                tl(
                                    update.effective_message,
                                    "Memasukan 'Bot' yang sedang di kunci saat ini"
                                ),
                                message,
                                update.effective_user,
                                conn=False)
            else:
                try:
                    message.delete()
                except BadRequest as excp:
                    if excp.message == "Message to delete not found":
                        pass
                    else:
                        LOGGER.exception("ERROR in lockables")
                getconf = sql.get_lockconf(chat.id)
                if getconf:
                    warn(update.effective_user,
                         chat,
                         tl(update.effective_message,
                            "Mengirim '{}' yang sedang di kunci saat ini").
                         format(lockable),
                         message,
                         update.effective_user,
                         conn=False)

            break
コード例 #24
0
ファイル: __main__.py プロジェクト: yupisky/Halubot
        # Stop processing with any other handler.
        except DispatcherHandlerStop:
            self.logger.debug(
                'Stopping further handlers due to DispatcherHandlerStop')
            break

        # Dispatch any error.
        except TelegramError as te:
            self.logger.warning(
                'A TelegramError was raised while processing the Update')

            try:
                self.dispatch_error(update, te)
            except DispatcherHandlerStop:
                self.logger.debug('Error handler stopped further handlers')
                break
            except Exception:
                self.logger.exception(
                    'An uncaught error was raised while handling the error')

        # Errors should not stop the thread.
        except Exception:
            self.logger.exception(
                'An uncaught error was raised while processing the update')


if __name__ == '__main__':
    LOGGER.info("Successfully loaded modules: " + str(ALL_MODULES))
    main()
コード例 #25
0
ファイル: __main__.py プロジェクト: yupisky/Halubot
def settings_button(bot: Bot, update: Update):
    query = update.callback_query
    user = update.effective_user
    mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data)
    prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data)
    next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data)
    back_match = re.match(r"stngs_back\((.+?)\)", query.data)
    try:
        if mod_match:
            chat_id = mod_match.group(1)
            module = mod_match.group(2)
            chat = bot.get_chat(chat_id)
            getstatusadmin = bot.get_chat_member(chat_id, user.id)
            isadmin = getstatusadmin.status in ('administrator', 'creator')
            if isadmin == False or user.id != OWNER_ID:
                query.message.edit_text("Status admin anda telah berubah")
                return
            text = tl(update.effective_message, "*{}* memiliki pengaturan berikut untuk modul *{}*:\n\n").format(escape_markdown(chat.title),
                                                                                     CHAT_SETTINGS[
                                                                                        module].__mod_name__) + \
                   CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id)
            try:
                set_button = CHAT_SETTINGS[module].__chat_settings_btn__(
                    chat_id, user.id)
            except AttributeError:
                set_button = []
            set_button.append([
                InlineKeyboardButton(
                    text=tl(query.message, "Kembali"),
                    callback_data="stngs_back({})".format(chat_id))
            ])
            query.message.reply_text(
                text=text,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(set_button))

        elif prev_match:
            chat_id = prev_match.group(1)
            curr_page = int(prev_match.group(2))
            chat = bot.get_chat(chat_id)
            query.message.reply_text(text=tl(
                update.effective_message,
                "Hai! Ada beberapa pengaturan untuk {} - lanjutkan dan pilih "
                "apa yang Anda minati.").format(chat.title),
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(curr_page - 1,
                                                          CHAT_SETTINGS,
                                                          "stngs",
                                                          chat=chat_id)))

        elif next_match:
            chat_id = next_match.group(1)
            next_page = int(next_match.group(2))
            chat = bot.get_chat(chat_id)
            query.message.reply_text(text=tl(
                update.effective_message,
                "Hai! Ada beberapa pengaturan untuk {} - lanjutkan dan pilih "
                "apa yang Anda minati.").format(chat.title),
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(next_page + 1,
                                                          CHAT_SETTINGS,
                                                          "stngs",
                                                          chat=chat_id)))

        elif back_match:
            chat_id = back_match.group(1)
            chat = bot.get_chat(chat_id)
            query.message.reply_text(text=tl(
                update.effective_message,
                "Hai! Ada beberapa pengaturan untuk {} - lanjutkan dan pilih "
                "apa yang Anda minati.").format(escape_markdown(chat.title)),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(0,
                                                          CHAT_SETTINGS,
                                                          "stngs",
                                                          chat=chat_id)))

        # ensure no spinny white circle
        query.message.delete()
        bot.answer_callback_query(query.id)
    except Exception as excp:
        if excp.message == "Message is not modified":
            pass
        elif excp.message == "Query_id_invalid":
            pass
        elif excp.message == "Message can't be deleted":
            pass
        else:
            query.message.edit_text(excp.message)
            LOGGER.exception("Exception in settings buttons. %s",
                             str(query.data))
コード例 #26
0
def purge(bot: Bot, update: Update, args: List[str]) -> str:
    spam = spamfilters(update.effective_message.text,
                       update.effective_message.from_user.id,
                       update.effective_chat.id, update.effective_message)
    if spam == True:
        return
    msg = update.effective_message  # type: Optional[Message]
    if msg.reply_to_message:
        user = update.effective_user  # type: Optional[User]
        chat = update.effective_chat  # type: Optional[Chat]
        if can_delete(chat, bot.id):
            message_id = msg.reply_to_message.message_id
            if args and args[0].isdigit():
                delete_to = message_id + int(args[0])
            else:
                delete_to = msg.message_id - 1
            for m_id in range(delete_to, message_id - 1,
                              -1):  # Reverse iteration over message ids
                try:
                    bot.deleteMessage(chat.id, m_id)
                except BadRequest as err:
                    if err.message == "Message can't be deleted":
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Tidak dapat menghapus semua pesan. Pesannya mungkin terlalu lama, saya mungkin "
                                "tidak memiliki hak menghapus, atau ini mungkin bukan supergrup."
                            ))

                    elif err.message != "Message to delete not found":
                        LOGGER.exception("Error while purging chat messages.")

            try:
                msg.delete()
            except BadRequest as err:
                if err.message == "Message can't be deleted":
                    send_message(
                        update.effective_message,
                        tl(
                            update.effective_message,
                            "Tidak dapat menghapus semua pesan. Pesannya mungkin terlalu lama, saya mungkin "
                            "tidak memiliki hak menghapus, atau ini mungkin bukan supergrup."
                        ))

                elif err.message != "Message to delete not found":
                    LOGGER.exception("Error while purging chat messages.")

            send_message(update.effective_message,
                         tl(update.effective_message, "Pembersihan selesai."))
            return "<b>{}:</b>" \
                   "\n#PURGE" \
                   "\n<b>Admin:</b> {}" \
                   "\nPurged <code>{}</code> messages.".format(html.escape(chat.title),
                                                               mention_html(user.id, user.first_name),
                                                               delete_to - message_id)

    else:
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Balas pesan untuk memilih tempat mulai membersihkan."))

    return ""
コード例 #27
0
ファイル: notes.py プロジェクト: yupisky/Halubot
def get(bot, update, notename, show_none=True, no_format=False):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if conn:
        chat_id = conn
        send_id = user.id
    else:
        chat_id = update.effective_chat.id
        send_id = chat_id

    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

    if note:
        # If we're replying to a message, reply to that message (unless it's an error)
        if message.reply_to_message:
            reply_id = message.reply_to_message.message_id
        else:
            reply_id = message.message_id

        if note.is_reply:
            if MESSAGE_DUMP:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=MESSAGE_DUMP,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Pesan ini tampaknya telah hilang - saya akan menghapusnya "
                                "dari daftar catatan Anda."))
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
            else:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=chat_id,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Sepertinya pengirim asli dari catatan ini telah dihapus "
                                "pesan mereka - maaf! Dapatkan admin bot Anda untuk mulai menggunakan "
                                "pesan dump untuk menghindari ini. Saya akan menghapus catatan ini dari "
                                "catatan tersimpan Anda."))
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            text = note.value
            keyb = []
            parseMode = ParseMode.MARKDOWN
            buttons = sql.get_buttons(chat_id, notename)
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                keyb = build_keyboard(buttons)

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                is_private, is_delete = sql.get_private_note(chat.id)
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    try:
                        if is_delete:
                            update.effective_message.delete()
                        if is_private:
                            bot.send_message(user.id,
                                             text,
                                             parse_mode=parseMode,
                                             disable_web_page_preview=True,
                                             reply_markup=keyboard)
                        else:
                            bot.send_message(send_id,
                                             text,
                                             reply_to_message_id=reply_id,
                                             parse_mode=parseMode,
                                             disable_web_page_preview=True,
                                             reply_markup=keyboard)
                    except BadRequest as excp:
                        if excp.message == "Wrong http url":
                            failtext = tl(
                                update.effective_message,
                                "Kesalahan: URL pada tombol tidak valid! Harap perbaruhi catatan ini."
                            )
                            failtext += "\n\n```\n{}```".format(
                                note.value + revert_buttons(buttons))
                            send_message(update.effective_message,
                                         failtext,
                                         parse_mode="markdown")
                        elif excp.message == "Button_url_invalid":
                            failtext = tl(
                                update.effective_message,
                                "Kesalahan: URL pada tombol tidak valid! Harap perbaruhi catatan ini."
                            )
                            failtext += "\n\n```\n{}```".format(
                                note.value + revert_buttons(buttons))
                            send_message(update.effective_message,
                                         failtext,
                                         parse_mode="markdown")
                        elif excp.message == "Message can't be deleted":
                            pass
                        elif excp.message == "Have no rights to send a message":
                            pass
                    except Unauthorized as excp:
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Hubungi saya di PM dulu untuk mendapatkan catatan ini."
                            ),
                            parse_mode="markdown")
                        pass
                else:
                    try:
                        if is_delete:
                            update.effective_message.delete()
                        if is_private:
                            ENUM_FUNC_MAP[note.msgtype](
                                user.id,
                                note.file,
                                caption=text,
                                parse_mode=parseMode,
                                disable_web_page_preview=True,
                                reply_markup=keyboard)
                        else:
                            ENUM_FUNC_MAP[note.msgtype](
                                send_id,
                                note.file,
                                caption=text,
                                reply_to_message_id=reply_id,
                                parse_mode=parseMode,
                                disable_web_page_preview=True,
                                reply_markup=keyboard)
                    except BadRequest as excp:
                        if excp.message == "Message can't be deleted":
                            pass
                        elif excp.message == "Have no rights to send a message":
                            pass
                    except Unauthorized as excp:
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Hubungi saya di PM dulu untuk mendapatkan catatan ini."
                            ),
                            parse_mode="markdown")
                        pass

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    send_message(
                        update.effective_message,
                        tl(
                            update.effective_message,
                            "Sepertinya Anda mencoba menyebutkan seseorang yang belum pernah saya lihat sebelumnya. "
                            "Jika kamu benar-benar ingin menyebutkannya, meneruskan salah satu pesan mereka kepada saya, "
                            "dan saya akan dapat untuk menandai mereka!"))
                elif FILE_MATCHER.match(note.value):
                    send_message(
                        update.effective_message,
                        tl(
                            update.effective_message,
                            "Catatan ini adalah file yang salah diimpor dari bot lain - saya tidak bisa menggunakan "
                            "ini. Jika Anda benar-benar membutuhkannya, Anda harus menyimpannya lagi. "
                            "Sementara itu, saya akan menghapusnya dari daftar catatan Anda."
                        ))
                    sql.rm_note(chat_id, notename)
                else:
                    send_message(
                        update.effective_message,
                        tl(
                            update.effective_message,
                            "Catatan ini tidak dapat dikirim karena formatnya salah."
                        ))
                    LOGGER.exception(
                        "Tidak dapat menguraikan pesan #%s di obrolan %s",
                        notename, str(chat_id))
                    LOGGER.warning("Pesan itu: %s", str(note.value))
        return
    elif show_none:
        send_message(update.effective_message,
                     tl(update.effective_message, "Catatan ini tidak ada"))