Example #1
0
        await client.start()
        LOGGER.info("HarukaPyro started")
        await get_bot()
        await idle()
    except BaseException as error:
        LOGGER.error(f"Exiting due to a {type(error).__name__}: {error}")
    finally:
        await session.close()


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format=FORMAT,
                        datefmt="%d/%m/%Y %T")
    LOGGER.info(
        f"""Starting HarukaPyro, powered by Pyrogram (v{__version__}). Copyright (C) 2021 Intellivoid Technologies
    This program comes with ABSOLUTELY NO WARRANTY.
    This is free software, and you are welcome to redistribute it
    under certain conditions, check the LICENSE file for more information.
    Haruka Aya is a registered trademark owned by Haruka LLC and licensed to Intellivoid Technologies.
    All rights and trademarks belong to their respective owners.""")
    # Sets pyrogram logging to warning because info is too verbose
    logging.getLogger("pyrogram").setLevel(logging.WARNING)
    Session.notice_displayed = True
    try:
        asyncio.run(run_async(app, httpsession))
    except AttributeError:
        # Python < 3.6
        asyncio.get_event_loop().run_until_complete(run_async(
            app, httpsession))
Example #2
0
from haruka.modules.helper_funcs.extraction import extract_user, extract_user_and_text
from haruka.modules.helper_funcs.string_handling import markdown_parser

import haruka.modules.sql.feds_sql as sql

from haruka.modules.translations.strings import tld

from haruka.modules.connection import connected

# Hello bot owner, I spended for feds many hours of my life, i beg don't remove MrYacha from sudo to apprecate his work
# Federation by MrYacha 2018-2019
# Federation rework in process by Mizukito Akito 2019
# Thanks to @peaktogoo for /fbroadcast
# Time spended on feds = 10h
LOGGER.info(
    "Original federation module by MrYacha, reworked by Mizukito Akito (@peaktogoo) on Telegram."
)

FBAN_ERRORS = {
    "User is an administrator of the chat", "Chat not found",
    "Not enough rights to restrict/unrestrict chat member",
    "User_not_participant", "Peer_id_invalid", "Group chat was deactivated",
    "Need to be inviter of a user to kick it from a basic group",
    "Chat_admin_required",
    "Only the creator of a basic group can kick group administrators",
    "Channel_private", "Not in the chat"
}

UNFBAN_ERRORS = {
    "User is an administrator of the chat",
    "Chat not found",
Example #3
0
def fed_ban(bot: Bot, update: Update, args: List[str]):
    chat = update.effective_chat
    user = update.effective_user
    fed_id = sql.get_fed_id(chat.id)

    if not fed_id:
        update.effective_message.reply_text(
            "This group is not a part of any federation!")
        return

    info = sql.get_fed_info(fed_id)
    OW = bot.get_chat(info['owner'])
    HAHA = OW.id
    FEDADMIN = sql.all_fed_users(fed_id)
    FEDADMIN.append(int(HAHA))

    if is_user_fed_admin(fed_id, user.id) == False:
        update.effective_message.reply_text(
            "Only federation admins can do this!")
        return

    message = update.effective_message

    user_id, reason = extract_user_and_text(message, args)

    fban, fbanreason = sql.get_fban_user(fed_id, user_id)

    if not user_id:
        message.reply_text("You don't seem to be referring to a user")
        return

    if user_id == bot.id:
        message.reply_text(
            "What is funnier than fbanning the bot? Self sacrifice.")
        return

    if is_user_fed_owner(fed_id, user_id) == True:
        message.reply_text("Why did you try the federation fban?")
        return

    if is_user_fed_admin(fed_id, user_id) == True:
        message.reply_text("He is a federation admin, I can't fban him.")
        return

    if user_id == OWNER_ID:
        message.reply_text(
            "I don't want to fban my master, that's a very stupid idea!")
        return

    if int(user_id) in SUDO_USERS:
        message.reply_text("I will not fban sudos!")
        return

    if int(user_id) in WHITELIST_USERS:
        message.reply_text(
            "This person is whitelisted, so they can't be fbanned!")
        return

    try:
        user_chat = bot.get_chat(user_id)
    except BadRequest as excp:
        message.reply_text(excp.message)
        return

    if user_chat.type != 'private':
        message.reply_text("That's not a user!")
        return

    if fban:
        user_target = mention_html(user_chat.id, user_chat.first_name)
        fed_name = info['fname']
        starting = "The reason of federation ban has been replaced for {} in the Federation <b>{}</b>.".format(
            user_target, fed_name)
        update.effective_message.reply_text(starting,
                                            parse_mode=ParseMode.HTML)

        if reason == "":
            reason = "No reason given."

        temp = sql.un_fban_user(fed_id, user_id)
        if not temp:
            message.reply_text("Failed to update the reason for fban!")
            return
        x = sql.fban_user(fed_id, user_id, user_chat.first_name,
                          user_chat.last_name, user_chat.username, reason)
        if not x:
            message.reply_text(
                "Failed to ban from the federation! If this problem continues, ask in @HarukaAyaGroup for help!"
            )
            return

        fed_chats = sql.all_fed_chats(fed_id)
        for chat in fed_chats:
            try:
                bot.kick_chat_member(chat, user_id)
            except BadRequest as excp:
                if excp.message in FBAN_ERRORS:
                    pass
                else:
                    LOGGER.warning("Could not fban in {} because: {}".format(
                        chat, excp.message))
            except TelegramError:
                pass

        send_to_list(bot, FEDADMIN,
           "<b>FedBan reason updated</b>" \
              "\n<b>Federation:</b> {}" \
              "\n<b>Federation Admin:</b> {}" \
              "\n<b>User:</b> {}" \
              "\n<b>User ID:</b> <code>{}</code>" \
              "\n<b>Reason:</b> {}".format(fed_name, mention_html(user.id, user.first_name),
                  mention_html(user_chat.id, user_chat.first_name),
                   user_chat.id, reason),
          html=True)
        message.reply_text("FedBan reason has been updated.")
        return

    user_target = mention_html(user_chat.id, user_chat.first_name)
    fed_name = info['fname']

    starting = "Starting a federation ban for {} in the Federation <b>{}</b>.".format(
        user_target, fed_name)
    update.effective_message.reply_text(starting, parse_mode=ParseMode.HTML)

    if reason == "":
        reason = "No reason given."

    x = sql.fban_user(fed_id, user_id, user_chat.first_name,
                      user_chat.last_name, user_chat.username, reason)
    if not x:
        message.reply_text(
            "Failed to ban from the federation! If this problem continues, ask in @HarukaAyaGroup for help."
        )
        return

    fed_chats = sql.all_fed_chats(fed_id)
    for chat in fed_chats:
        try:
            bot.kick_chat_member(chat, user_id)
        except BadRequest as excp:
            if excp.message in FBAN_ERRORS:
                try:
                    dispatcher.bot.getChat(chat)
                except Unauthorized:
                    sql.chat_leave_fed(chat)
                    LOGGER.info(
                        "Chat {} has leave fed {} because bot is kicked".
                        format(chat, info['fname']))
                    continue
            else:
                LOGGER.warning("Cannot fban on {} because: {}".format(
                    chat, excp.message))
        except TelegramError:
            pass

    send_to_list(bot, FEDADMIN,
       "<b>New FedBan</b>" \
       "\n<b>Federation:</b> {}" \
       "\n<b>Federation Admin:</b> {}" \
       "\n<b>User:</b> {}" \
       "\n<b>User ID:</b> <code>{}</code>" \
       "\n<b>Reason:</b> {}".format(fed_name, mention_html(user.id, user.first_name),
              mention_html(user_chat.id, user_chat.first_name),
               user_chat.id, reason),
      html=True)
    message.reply_text("This person has been fbanned")
Example #4
0
from haruka import dispatcher, LOGGER
from haruka.__main__ import GDPR
from haruka.__main__ import STATS, USER_INFO
from haruka.modules.disable import DisableAbleCommandHandler
from haruka.modules.helper_funcs.extraction import extract_user
from haruka.modules.helper_funcs.filters import CustomFilters

from requests import get

# DO NOT DELETE THIS, PLEASE.
# Made by @AmTheHero on GitHub and Telegram.
# This module was inspired by Android Helper Bot by Vachounet.
# None of the code is taken from the bot itself, to avoid any more confusion.

LOGGER.info("Original Android Modules by @AmTheHero on Telegram")


@run_async
def havoc(bot: Bot, update: Update):
    message = update.effective_message
    device = message.text[len('/havoc '):]
    fetch = get(
        f'https://raw.githubusercontent.com/Havoc-Devices/android_vendor_OTA/pie/{device}.json'
    )

    if device == '':
        reply_text = "Please type your device **codename** into it!\nFor example, `/havoc tissot`"
        message.reply_text(reply_text,
                           parse_mode=ParseMode.MARKDOWN,
                           disable_web_page_preview=True)
Example #5
0
from haruka import dispatcher, LOGGER
from haruka.__main__ import GDPR
from haruka.__main__ import STATS, USER_INFO
from haruka.modules.disable import DisableAbleCommandHandler
from haruka.modules.helper_funcs.extraction import extract_user
from haruka.modules.helper_funcs.filters import CustomFilters

from requests import get

# DO NOT DELETE THIS, PLEASE.
# Made by @RealAkito on GitHub and Telegram.
# This module was inspired by Android Helper Bot by Vachounet.
# None of the code is taken from the bot itself, to avoid any more confusion.

LOGGER.info("Original Android Modules by @RealAkito on Telegram")


@run_async
def havoc(bot: Bot, update: Update):
    message = update.effective_message
    device = message.text[len('/havoc '):]
    fetch = get(
        f'https://raw.githubusercontent.com/Havoc-Devices/android_vendor_OTA/pie/{device}.json'
    )

    if device == '':
        reply_text = "Please type your device **codename** into it!\nFor example, `/havoc tissot`"
        message.reply_text(reply_text,
                           parse_mode=ParseMode.MARKDOWN,
                           disable_web_page_preview=True)
Example #6
0
def control_panel(bot, update):
    LOGGER.info("Control panel")
    chat = update.effective_chat
    user = update.effective_user

    # ONLY send help in PM
    if chat.type != chat.PRIVATE:

        update.effective_message.reply_text("Contact me in PM to access the control panel.",
                                            reply_markup=InlineKeyboardMarkup(
                                                [[InlineKeyboardButton(text="Control Panel",
                                                                       url=f"t.me/{bot.username}?start=controlpanel")]]))
        return

    #Support to run from command handler
    query = update.callback_query
    if query:
        query.message.delete()

        M_match = re.match(r"cntrl_panel_M", query.data)
        U_match = re.match(r"cntrl_panel_U", query.data)
        G_match = re.match(r"cntrl_panel_G", query.data)
        back_match = re.match(r"help_back", query.data)

        LOGGER.info(query.data)
    else:
        M_match = "ThaNos is the best bot" #LMAO, don't uncomment

    if M_match:
        text = "*Control panel* 🛠"

        keyboard = [[InlineKeyboardButton(text="👤 My settings", callback_data="cntrl_panel_U(1)")]]

        #Show connected chat and add chat settings button
        conn = connected(bot, update, chat, user.id, need_admin=False)

        if conn:
            chatG = bot.getChat(conn)
            #admin_list = chatG.get_administrators() #Unused variable

            #If user admin
            member = chatG.get_member(user.id)
            if member.status in ('administrator', 'creator'):
                text += f"\nConnected chat - *{chatG.title}* (you {member.status})"
                keyboard += [[InlineKeyboardButton(text="👥 Group settings", callback_data="cntrl_panel_G_back")]]
            elif user.id in SUDO_USERS:
                text += f"\nConnected chat - *{chatG.title}* (you sudo)"
                keyboard += [[InlineKeyboardButton(text="👥 Group settings (SUDO)", callback_data="cntrl_panel_G_back")]]
            else:
                text += f"\nConnected chat - *{chatG.title}* (you aren't an admin!)"
        else:
            text += "\nNo chat connected!"

        keyboard += [[InlineKeyboardButton(text="Back", callback_data="bot_start")]]

        update.effective_message.reply_text(text, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.MARKDOWN)

    elif U_match:

        mod_match = re.match(r"cntrl_panel_U_module\((.+?)\)", query.data)
        back_match = re.match(r"cntrl_panel_U\((.+?)\)", query.data)

        chatP = update.effective_chat  # type: Optional[Chat]
        if mod_match:
            module = mod_match.group(1)

            R = CHAT_SETTINGS[module].__user_settings__(bot, update, user)

            text = "You has the following settings for the *{}* module:\n\n".format(
                CHAT_SETTINGS[module].__mod_name__) + R[0]

            keyboard = R[1]
            keyboard += [[InlineKeyboardButton(text="Back", callback_data="cntrl_panel_U(1)")]]
                
            query.message.reply_text(text=text, arse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard))

        elif back_match:
            text = "*User control panel* 🛠"
            
            query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN,
                    reply_markup=InlineKeyboardMarkup(paginate_modules(user.id, 0, USER_SETTINGS, "cntrl_panel_U")))

    elif G_match:
        mod_match = re.match(r"cntrl_panel_G_module\((.+?)\)", query.data)
        prev_match = re.match(r"cntrl_panel_G_prev\((.+?)\)", query.data)
        next_match = re.match(r"cntrl_panel_G_next\((.+?)\)", query.data)
        back_match = re.match(r"cntrl_panel_G_back", query.data)

        chatP = chat
        conn = connected(bot, update, chat, user.id)

        if not conn == False:
            chat = bot.getChat(conn)
        else:
            query.message.reply_text(text="Error with connection to chat")
            exit(1)

        if mod_match:
            module = mod_match.group(1)
            R = CHAT_SETTINGS[module].__chat_settings__(bot, update, chat, chatP, user)

            if type(R) is list:
                text = R[0]
                keyboard = R[1]
            else:
                text = R
                keyboard = []

            text = "*{}* has the following settings for the *{}* module:\n\n".format(
                escape_markdown(chat.title), CHAT_SETTINGS[module].__mod_name__) + text

            keyboard += [[InlineKeyboardButton(text="Back", callback_data="cntrl_panel_G_back")]]
                
            query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard))

        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(tld(user.id, "send-group-settings").format(chat.title),
                                    reply_markup=InlineKeyboardMarkup(
                                        paginate_modules(curr_page - 1, 0, CHAT_SETTINGS, "cntrl_panel_G",
                                                        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(tld(user.id, "send-group-settings").format(chat.title),
                                    reply_markup=InlineKeyboardMarkup(
                                        paginate_modules(next_page + 1, 0, CHAT_SETTINGS, "cntrl_panel_G",
                                                        chat=chat_id)))

        elif back_match:
            text = "Test"
            query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(paginate_modules(user.id, 0, CHAT_SETTINGS, "cntrl_panel_G")))
Example #7
0
    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 load order 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"]
Example #8
0
from haruka.modules.helper_funcs.string_handling import markdown_parser
from haruka.modules.disable import DisableAbleCommandHandler

import haruka.modules.sql.feds_sql as sql

from haruka.modules.translations.strings import tld

from haruka.modules.connection import connected

# Hello bot owner, I spended for feds many hours of my life, Please don't remove this if you still respect MrYacha and peaktogoo
# Federation by MrYacha 2018-2019
# Federation rework in process by Mizukito Akito 2019
# Time spended on feds = 10h by #MrYacha
# Time spended on reworking on the whole feds = 20+ hours by @peaktogoo

LOGGER.info("Contact at [AVATAR](T.ME/REFUNDISILLEGAL) , if you are fbanned.")

FBAN_ERRORS = {
    "User is an administrator of the chat", "Chat not found",
    "Not enough rights to restrict/unrestrict chat member",
    "User_not_participant", "Peer_id_invalid", "Group chat was deactivated",
    "Need to be inviter of a user to kick it from a basic group",
    "Chat_admin_required",
    "Only the creator of a basic group can kick group administrators",
    "Channel_private", "Not in the chat"
}

UNFBAN_ERRORS = {
    "User is an administrator of the chat",
    "Chat not found",
    "Not enough rights to restrict/unrestrict chat member",
Example #9
0
                                            reply_markup=InlineKeyboardMarkup(
                                                [[InlineKeyboardButton(text="Control Panel",
                                                                       url=f"t.me/{bot.username}?start=controlpanel")]]))
        return

    #Support to run from command handler
    query = update.callback_query
    if query:
        query.message.delete()

        M_match = re.match(r"cntrl_panel_M", query.data)
        U_match = re.match(r"cntrl_panel_U", query.data)
        G_match = re.match(r"cntrl_panel_G", query.data)
        back_match = re.match(r"help_back", query.data)

        LOGGER.info(query.data)
    else:
        M_match = "ThaNos is the best bot" #LMAO, don't uncomment

    if M_match:
        text = "*Control panel* 🛠"

        keyboard = [[InlineKeyboardButton(text="👤 My settings", callback_data="cntrl_panel_U(1)")]]

        #Show connected chat and add chat settings button
        conn = connected(bot, update, chat, user.id, need_admin=False)

        if conn:
            chatG = bot.getChat(conn)
            #admin_list = chatG.get_administrators() #Unused variable

            #If user admin
Example #10
0
                                            reply_markup=InlineKeyboardMarkup(
                                                [[InlineKeyboardButton(text="Control Panel",
                                                                       url=f"t.me/{bot.username}?start=controlpanel")]]))
        return

    #Support to run from command handler
    query = update.callback_query
    if query:
        query.message.delete()

        M_match = re.match(r"cntrl_panel_M", query.data)
        U_match = re.match(r"cntrl_panel_U", query.data)
        G_match = re.match(r"cntrl_panel_G", query.data)
        back_match = re.match(r"help_back", query.data)

        LOGGER.info(query.data)
    else:
        M_match = "ThaNos is the best bot" #LMAO, don't uncomment

    if M_match:

        #Show connected chat and add chat settings button
        conn = connected(bot, update, chat, user.id, need_admin=False)

        if conn:
            chatG = bot.getChat(conn)
            #admin_list = chatG.get_administrators() #Unused variable

            #If user admin
            member = chatG.get_member(user.id)
            if member.status in ('administrator', 'creator'):
Example #11
0
from haruka.modules.disable import DisableAbleCommandHandler
from haruka.modules.helper_funcs.extraction import extract_user
from haruka.modules.helper_funcs.filters import CustomFilters

from haruka.modules.sql.translation import prev_locale

from haruka.modules.translations.strings import tld

from requests import get

# DO NOT DELETE THIS, PLEASE.
# Made by @peaktogoo on GitHub and Telegram.
# This module was inspired by Android Helper Bot by Vachounet.
# None of the code is taken from the bot itself, to avoid any more confusion.

LOGGER.info("Original Android Modules by @peaktogoo on Telegram")


@run_async
def havoc(bot: Bot, update: Update):
    message = update.effective_message
    device = message.text[len('/havoc '):]
    fetch = get(f'https://raw.githubusercontent.com/Havoc-Devices/android_vendor_OTA/pie/{device}.json')
    if fetch.status_code == 200:
        usr = fetch.json()
        response = usr['response'][0]
        filename = response['filename']
        url = response['url']
        buildsize = response['size']
        version = response['version']
Example #12
0
    if hasattr(imported_module, "__help__") and imported_module.__help__:
        HELPABLE[imported_module.__mod_name__.lower()] = imported_module

    # Chats to migrate on chat_migrated events
    if hasattr(imported_module, "__migrate__"):
        MIGRATEABLE.append(imported_module)

    if hasattr(imported_module, "__stats__"):
        STATS.append(imported_module)

    if hasattr(imported_module, "__user_info__"):
        USER_INFO.append(imported_module)

    if hasattr(imported_module, "__import_data__"):
        DATA_IMPORT.append(imported_module)

    if hasattr(imported_module, "__export_data__"):
        DATA_EXPORT.append(imported_module)

    if hasattr(imported_module, "__chat_settings__"):
        CHAT_SETTINGS[imported_module.__mod_name__.lower()] = imported_module

    if hasattr(imported_module, "__user_settings__"):
        USER_SETTINGS[imported_module.__mod_name__.lower()] = imported_module

if __name__ == "__main__":
    app.start()
    LOGGER.info("Haruka started! uwu")
    idle()
    httpsession.close()
Example #13
0
def control_panel(bot, update):
    LOGGER.info("Control panel")
    chat = update.effective_chat
    user = update.effective_user

    # ONLY send help in PM
    if chat.type != chat.PRIVATE:

        update.effective_message.reply_text(
            "Kontrol paneline erişmek için PM'de bana ulaşın.",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton(
                    text="Control Panel",
                    url=f"t.me/{bot.username}?start=controlpanel")
            ]]))
        return

    #Support to run from command handler
    query = update.callback_query
    if query:
        query.message.delete()

        M_match = re.match(r"cntrl_panel_M", query.data)
        U_match = re.match(r"cntrl_panel_U", query.data)
        G_match = re.match(r"cntrl_panel_G", query.data)
        back_match = re.match(r"help_back", query.data)

        LOGGER.info(query.data)
    else:
        M_match = "NightCrew En iyi bottur"  #LMAO, don't uncomment

    if M_match:
        text = "*Control panel* 🛠"

        keyboard = [[
            InlineKeyboardButton(text="👤 Ayarlarım",
                                 callback_data="cntrl_panel_U(1)")
        ]]

        #Show connected chat and add chat settings button
        conn = connected(bot, update, chat, user.id, need_admin=False)

        if conn:
            chatG = bot.getChat(conn)
            #admin_list = chatG.get_administrators() #Unused variable

            #If user admin
            member = chatG.get_member(user.id)
            if member.status in ('administrator', 'creator'):
                text += f"\nBağlı sohbet - *{chatG.title}* (you {member.status})"
                keyboard += [[
                    InlineKeyboardButton(text="👥 Grup Ayarları",
                                         callback_data="cntrl_panel_G_back")
                ]]
            elif user.id in SUDO_USERS:
                text += f"\nBağlı sohbet - *{chatG.title}* (you sudo)"
                keyboard += [[
                    InlineKeyboardButton(text="👥 Grup Ayarları (SUDO)",
                                         callback_data="cntrl_panel_G_back")
                ]]
            else:
                text += f"\nBağlı sohbet - *{chatG.title}* (bir yönetici değilsiniz!)"
        else:
            text += "\nBağlı sohbet yok!"

        keyboard += [[
            InlineKeyboardButton(text="Geri", callback_data="bot_start")
        ]]

        update.effective_message.reply_text(
            text,
            reply_markup=InlineKeyboardMarkup(keyboard),
            parse_mode=ParseMode.MARKDOWN)

    elif U_match:

        mod_match = re.match(r"cntrl_panel_U_module\((.+?)\)", query.data)
        back_match = re.match(r"cntrl_panel_U\((.+?)\)", query.data)

        chatP = update.effective_chat  # type: Optional[Chat]
        if mod_match:
            module = mod_match.group(1)

            R = CHAT_SETTINGS[module].__user_settings__(bot, update, user)

            text = " *{}* modülü için aşağıdaki ayarlara sahipsiniz:\n\n".format(
                CHAT_SETTINGS[module].__mod_name__) + R[0]

            keyboard = R[1]
            keyboard += [[
                InlineKeyboardButton(text="Back",
                                     callback_data="cntrl_panel_U(1)")
            ]]

            query.message.reply_text(
                text=text,
                arse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(keyboard))

        elif back_match:
            text = "*Kullanıcı kontrol paneli* 🛠"

            query.message.reply_text(text=text,
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             user.id, 0, USER_SETTINGS,
                                             "cntrl_panel_U")))

    elif G_match:
        mod_match = re.match(r"cntrl_panel_G_module\((.+?)\)", query.data)
        prev_match = re.match(r"cntrl_panel_G_prev\((.+?)\)", query.data)
        next_match = re.match(r"cntrl_panel_G_next\((.+?)\)", query.data)
        back_match = re.match(r"cntrl_panel_G_back", query.data)

        chatP = chat
        conn = connected(bot, update, chat, user.id)

        if not conn == False:
            chat = bot.getChat(conn)
        else:
            query.message.reply_text(text="Sohbet bağlantısında hata")
            exit(1)

        if mod_match:
            module = mod_match.group(1)
            R = CHAT_SETTINGS[module].__chat_settings__(
                bot, update, chat, chatP, user)

            if type(R) is list:
                text = R[0]
                keyboard = R[1]
            else:
                text = R
                keyboard = []

            text = "*{}*,*{}* modülü için şu ayarlara sahiptir:\n\n".format(
                escape_markdown(chat.title),
                CHAT_SETTINGS[module].__mod_name__) + text

            keyboard += [[
                InlineKeyboardButton(text="Geri",
                                     callback_data="cntrl_panel_G_back")
            ]]

            query.message.reply_text(
                text=text,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(keyboard))

        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(tld(
                user.id, "grup-ayarları gönder").format(chat.title),
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(curr_page - 1,
                                                          0,
                                                          CHAT_SETTINGS,
                                                          "cntrl_panel_G",
                                                          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(tld(
                user.id, "grup-ayarları gönder").format(chat.title),
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(next_page + 1,
                                                          0,
                                                          CHAT_SETTINGS,
                                                          "cntrl_panel_G",
                                                          chat=chat_id)))

        elif back_match:
            text = "Test"
            query.message.reply_text(text=text,
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             user.id, 0, CHAT_SETTINGS,
                                             "cntrl_panel_G")))
Example #14
0
        # Stop processing with any other handler.
        except DispatcherHandlerStop:
            self.logger.debug(
                'DispatcherHandlerStop nedeniyle diğer işleyicileri durdurma')
            break

        # Dispatch any error.
        except TelegramError as te:
            self.logger.warning(
                'Güncelleme işlenirken bir Telegram Hatası oluştu')

            try:
                self.dispatch_error(update, te)
            except DispatcherHandlerStop:
                self.logger.debug('Hata işleyici diğer işleyicileri durdurdu')
                break
            except Exception:
                self.logger.exception(
                    'Hatayı işlerken yakalanmamış bir hata ortaya çıktı')

        # Errors should not stop the thread.
        except Exception:
            self.logger.exception(
                'Güncelleme işlenirken yakalanmamış bir hata ortaya çıktı')


if __name__ == '__main__':
    LOGGER.info("Başarıyla yüklenen modüller: " + str(ALL_MODULES))
    LOGGER.info("Başarıyla yüklendi")
    main()
Example #15
0
def log_input(update):
    user = update.effective_user.id
    chat = update.effective_chat.id
    LOGGER.info("IN: {} (user={}, chat={})".format(
        update.effective_message.text, user, chat))
Example #16
0
def start(bot: Bot, update: Update, args: List[str]):
    LOGGER.info("Start")
Example #17
0
def send(msg, bot, update):
    LOGGER.info("OUT: '{}'".format(msg))
    bot.send_message(chat_id=update.effective_chat.id,
                     text="`{}`".format(msg),
                     parse_mode=ParseMode.MARKDOWN)
Example #18
0
import haruka.modules.sql.feds_sql as sql

from haruka.modules.tr_engine.strings import tld

# Greeting all bot owners that is using this module,
# The following people
# - MrYacha [Module Maker] - 10 Hours
# - RealAkito (used to be peaktogoo) [Module Reworker 01] - 22 Hours
# - AyraHikari [Module Reworker 03] - 26 Hours
# have spent so much time of their life into making this module better, stable, and well feature-rich.
# Please don't remove these comment, if you're still respecting us, the module maker and reworkers.
#
# Total times spend for this module is approx. 58+ hours

LOGGER.info(
    "feds: Original: MrYacha, Reworked 01: RealAkito, Reworked 02: AyraHikari."
)

FBAN_ERRORS = {
    "User is an administrator of the chat", "Chat not found",
    "Not enough rights to restrict/unrestrict chat member",
    "User_not_participant", "Peer_id_invalid", "Group chat was deactivated",
    "Need to be inviter of a user to kick it from a basic group",
    "Chat_admin_required",
    "Only the creator of a basic group can kick group administrators",
    "Channel_private", "Not in the chat", "Have no rights to send a message"
}

UNFBAN_ERRORS = {
    "User is an administrator of the chat", "Chat not found",
    "Not enough rights to restrict/unrestrict chat member",
Example #19
0
            for handler in (x for x in self.handlers[group] if x.check_update(update)):
                handler.handle_update(update, self)
                break

        # 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))
    LOGGER.info("Successfully loaded")
    main()
Example #20
0
def control_panel(bot, update):
    LOGGER.info("Control panel")
Example #21
0
def new_member(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user
    msg = update.effective_message
    chat_name = chat.title or chat.first or chat.usernam
    should_welc, cust_welcome, welc_type = sql.get_welc_pref(chat.id)
    welc_mutes = sql.welcome_mutes(chat.id)
    user_id = user.id
    human_checks = sql.get_human_checks(user_id, chat.id)

    should_welc, cust_welcome, welc_type = sql.get_welc_pref(chat.id)
    if should_welc:
        sent = None
        new_members = update.effective_message.new_chat_members
        for new_mem in new_members:
            # Give the owner a special welcome
            if new_mem.id == OWNER_ID:
                bot.send_message(chat.id, "Oh, Genos? Let's get this moving.")
                continue

            # Give start information when add bot to group
            elif new_mem.id == 1002584093:
                  bot.send_message(
                      636314540,
                     "I have been added to {} with ID: <pre>{}</pre>".format(chat.title, chat.id),
                     parse_mode=ParseMode.HTML
                  )               
                  bot.send_message(chat.id, "Thanks For Adding Me Here. Hit /help to know how to use me")
                  continue   
                  
                  


            else:
                # If welcome message is media, send with appropriate function
                if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT:
                    ENUM_FUNC_MAP[welc_type](chat.id, cust_welcome)
                    return
                # else, move on
                first_name = new_mem.first_name or "PersonWithNoName"  # edge case of empty name - occurs for some bugs.

                if cust_welcome:
                    if cust_welcome == sql.DEFAULT_WELCOME:
                        cust_welcome = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(first=first_name)
                    #LOGGER.info("Custom Message: {}".format(cust_welcome))
                    if new_mem.last_name:
                        fullname = "{} {}".format(first_name, new_mem.last_name)
                    else:
                        fullname = first_name
                    count = chat.get_members_count()
                    mention = mention_markdown(new_mem.id, first_name)
                    if new_mem.username:
                        username = "******" + escape_markdown(new_mem.username)
                    else:
                        username = mention

                    valid_format = escape_invalid_curly_brackets(cust_welcome, VALID_WELCOME_FORMATTERS)
                    res = valid_format.format(first=escape_markdown(first_name),
                                              last=escape_markdown(new_mem.last_name or first_name),
                                              fullname=escape_markdown(fullname), username=username, mention=mention,
                                              count=count, chatname=escape_markdown(chat.title), id=new_mem.id)
                    buttons = sql.get_welc_buttons(chat.id)
                    keyb = build_keyboard(buttons)
                else:
                    res = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(first=first_name)
                    LOGGER.info("res is {}".format(res))
                    keyb = []

                keyboard = InlineKeyboardMarkup(keyb)

                sent = send(update, res, keyboard, random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(first=escape_markdown(first_name)))  # type: Optional[Message]

                 #User exceptions from welcomemutes
                if is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)) or human_checks:
                    continue
                #Join welcome: soft mute
                if welc_mutes == "soft":
                    bot.restrict_chat_member(chat.id, new_mem.id, 
                                             can_send_messages=True, 
                                             can_send_media_messages=False, 
                                             can_send_other_messages=False, 
                                             can_add_web_page_previews=False, 
                                             until_date=(int(time.time() + 24 * 60 * 60)))
                #Join welcome: strong mute
                if welc_mutes == "strong":
                    new_join_mem = "[{}](tg://user?id={})".format(new_mem.first_name, user.id)
                    msg.reply_text("{}, click the button below to prove you're human.".format(new_join_mem),
                         reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Yes, I'm human.", 
                         callback_data="user_join_({})".format(new_mem.id))]]), parse_mode=ParseMode.MARKDOWN)
                    bot.restrict_chat_member(chat.id, new_mem.id, 
                                             can_send_messages=False, 
                                             can_send_media_messages=False, 
                                             can_send_other_messages=False, 
                                             can_add_web_page_previews=False)
        prev_welc = sql.get_clean_pref(chat.id)
        if prev_welc:
            try:
                bot.delete_message(chat.id, prev_welc)
            except BadRequest as excp:
                pass

            if sent:
                sql.set_clean_welcome(chat.id, sent.message_id)
Example #22
0
from haruka import dispatcher, LOGGER
from haruka.__main__ import GDPR
from haruka.__main__ import STATS, USER_INFO
from haruka.modules.disable import DisableAbleCommandHandler
from haruka.modules.helper_funcs.extraction import extract_user
from haruka.modules.helper_funcs.filters import CustomFilters

from requests import get

# DO NOT DELETE THIS, PLEASE.
# Made by @RealAkito on GitHub and Telegram.
# This module was inspired by Android Helper Bot by Vachounet.
# None of the code is taken from the bot itself, to avoid any more confusion.

LOGGER.info("Original Android Modules by @kavinduaj on Telegram")


@run_async
def havoc(bot: Bot, update: Update):
    message = update.effective_message
    device = message.text[len('/havoc '):]
    fetch = get(
        f'https://raw.githubusercontent.com/Havoc-Devices/android_vendor_OTA/pie/{device}.json'
    )

    if device == '':
        reply_text = "Please type your device **codename** into it!\nFor example, `/havoc tissot`"
        message.reply_text(reply_text,
                           parse_mode=ParseMode.MARKDOWN,
                           disable_web_page_preview=True)