Example #1
0
def new_fed(bot: Bot, update: Update):
    chat = update.effective_chat
    user = update.effective_user
    message = update.effective_message
    if chat.type != "private":
        update.effective_message.reply_text(tld(chat.id, "common_cmd_pm_only"))
        return
    fednam = message.text.split(None, 1)[1]
    if not fednam == '':
        fed_id = str(uuid.uuid4())
        fed_name = fednam
        LOGGER.info(fed_id)
        if user.id == int(OWNER_ID):
            fed_id = fed_name

        x = sql.new_fed(user.id, fed_name, fed_id)
        if not x:
            update.effective_message.reply_text(
                tld(chat.id, "feds_create_fail"))
            return

        update.effective_message.reply_text(tld(chat.id,
                                                "feds_create_success").format(
                                                    fed_name, fed_id, fed_id),
                                            parse_mode=ParseMode.MARKDOWN)
        try:
            bot.send_message(MESSAGE_DUMP,
                             tld(chat.id, "feds_create_success_logger").format(
                                 fed_name, fed_id),
                             parse_mode=ParseMode.HTML)
        except Exception:
            LOGGER.warning("Cannot send a message to MESSAGE_DUMP")
    else:
        update.effective_message.reply_text(tld(chat.id, "feds_err_no_args"))
Example #2
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 load order names. Quitting.")
                sys.exit(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
Example #3
0
def main():
    # test_handler = CommandHandler("test", test) #Unused variable
    start_handler = CommandHandler("start", start, pass_args=True)

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

    start_callback_handler = CallbackQueryHandler(send_start,
                                                  pattern=r"bot_start")
    dispatcher.add_handler(start_callback_handler)

    cntrl_panel = CommandHandler("controlpanel", control_panel)
    cntrl_panel_callback_handler = CallbackQueryHandler(control_panel,
                                                        pattern=r"cntrl_panel")
    dispatcher.add_handler(cntrl_panel_callback_handler)
    dispatcher.add_handler(cntrl_panel)

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

    migrate_handler = MessageHandler(Filters.status_update.migrate,
                                     migrate_chats)
    source_handler = CommandHandler("source", source)

    # 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(source_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, clean=True)
        updater.start_polling(poll_interval=0.0,
                              timeout=10,
                              clean=True,
                              bootstrap_retries=-1,
                              read_latency=3.0)
    updater.idle()
Example #4
0
def main():
    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_")

    source_handler = CommandHandler("source", source)
    M_CONNECT_BTN_HANDLER = CallbackQueryHandler(m_connect_button,
                                                 pattern=r"main_connect")
    M_SETLANG_BTN_HANDLER = CallbackQueryHandler(m_change_langs,
                                                 pattern=r"main_setlang")

    # 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(source_handler)
    dispatcher.add_handler(M_CONNECT_BTN_HANDLER)
    dispatcher.add_handler(M_SETLANG_BTN_HANDLER)

    # dispatcher.add_error_handler(error_callback)

    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()
Example #5
0
def new_fed(bot: Bot, update: Update, args: List[str]):
    chat = update.effective_chat
    user = update.effective_user
    message = update.effective_message

    if chat.type != "private":
        update.effective_message.reply_text(tld(chat.id, "common_cmd_pm_only"))
        return

    if not args:
        update.effective_message.reply_text(tld(chat.id, "feds_err_no_args"))
        return

    fednam = args[0]
    if not fednam == '':
        fed_id = str(uuid.uuid4())
        fed_name = fednam
        LOGGER.info(fed_id)
        if user.id == int(OWNER_ID):
            fed_id = fed_name

        x = sql.new_fed(user.id, fed_name, fed_id)
        if not x:
            update.effective_message.reply_text(
                tld(chat.id, "feds_create_fail"))
            return

        update.effective_message.reply_text(tld(chat.id,
                                                "feds_create_success").format(
                                                    fed_name, fed_id, fed_id),
                                            parse_mode=ParseMode.MARKDOWN)
        try:
            bot.send_message(
                MESSAGE_DUMP,
                ("Federation <b>{}</b> has been created with ID: <pre>{}</pre>"
                 ).format(fed_name, fed_id),
                parse_mode=ParseMode.HTML)
        except Exception:
            LOGGER.warning("Cannot send a message to MESSAGE_DUMP")
    else:
        update.effective_message.reply_text(tld(chat.id, "feds_err_no_args"))
Example #6
0
def main():
    # test_handler = CommandHandler("test", test) #Unused variable
    start_handler = CommandHandler("start", start, pass_args=True)

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

    start_callback_handler = CallbackQueryHandler(send_start,
                                                  pattern=r"bot_start")

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

    # dispatcher.add_handler(test_handler)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(start_callback_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(help_callback_handler)
    dispatcher.add_handler(migrate_handler)
    # dispatcher.add_error_handler(error_callback)

    # add antiflood processor
    Dispatcher.process_update = process_update

    LOGGER.info("Using long polling.")
    # updater.start_polling(timeout=15, read_latency=4, clean=True)
    updater.start_polling(poll_interval=0.0,
                          timeout=10,
                          clean=True,
                          bootstrap_retries=-1,
                          read_latency=3.0)

    LOGGER.info("Successfully loaded")
    if len(argv) not in (1, 3, 4):
        tbot.disconnect()
    else:
        tbot.run_until_disconnected()

    updater.idle()
Example #7
0
        # 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 #8
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 chat.type == "private":
        update.effective_message.reply_text(
            tld(chat.id, "common_cmd_group_only"))
        return

    if not fed_id:
        update.effective_message.reply_text(
            tld(chat.id, "feds_nofed"))
        return

    if user.id in (777000, 1087968824):
        update.effective_message.reply_text(
            tld(chat.id, "feds_tg_bot"))
        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) is False:
        update.effective_message.reply_text(
            tld(chat.id, "feds_notfadmin"))
        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(tld(chat.id, "common_err_no_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) is True:
        message.reply_text("Why did you try the federation fban?")
        return

    if is_user_fed_admin(fed_id, user_id) is 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 @HitsukiAyaGroup 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 not in FBAN_ERRORS:
                    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 @HitsukiAyaGroup 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 #9
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.")
                sys.exit(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 #10
0
from telegram import Update, Bot
from telegram.ext import CommandHandler
from telegram.ext import run_async

from hitsuki import dispatcher, LOGGER
from hitsuki.modules.helper_funcs.misc import split_message

# DO NOT DELETE THIS, PLEASE.
# Originally 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.
# Command /getfw /magisk /twrp and /device were obtained thanks to corsicanu bot (originally kanged from UserBot PaperplaneExtended)
# Command /specs was only possible thanks to the help of AvinashReddy3108

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

WIKI = 'https://xiaomiwiki.github.io/wiki'
GITHUB = 'https://github.com'
DEVICES_DATA = 'https://raw.githubusercontent.com/androidtrackers/certified-android-devices/master/devices.json'


@run_async
def device(bot, update, args):
    if len(args) == 0:
        reply = f'No codename provided, write a codename for fetching informations.'
        update.effective_message.reply_text("{}".format(reply),
                                            parse_mode=ParseMode.MARKDOWN,
                                            disable_web_page_preview=True)
        return
Example #11
0
                '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__':
    timenow = datetime.datetime.now()
    LOGGER.info(f"Successfully loaded modules: {str(ALL_MODULES)}")
    tbot.start(bot_token=TOKEN)
    pbot.start()
    main()
    idle()
Example #12
0
from hitsuki.modules.helper_funcs.misc import send_to_list
from hitsuki.modules.helper_funcs.string_handling import markdown_parser
from hitsuki.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 #13
0
from hitsuki.modules.helper_funcs.alternate import send_message

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

for x in os.listdir('hitsuki/modules/langs'):
    if os.path.isdir('hitsuki/modules/langs/' + x):
        continue
    x = x.replace('.py', '')
    LOADED_LANGS_ID.append(x)
    imported_langs = importlib.import_module("hitsuki.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 = 'en'
    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
Example #14
0
from telethon import custom

from hitsuki import LOGGER
from hitsuki.events import register
from hitsuki.modules.tr_engine.strings import tld

# Greeting all bot owners that is using this module,
# - RealAkito (used to be peaktogoo) [Module Maker]
# have spent so much time of their life into making this module better, stable, and well more supports.
# Please don't remove these comment, if you're still respecting me, the module maker.
#
# This module was inspired by Android Helper Bot by Vachounet.
# None of the code is taken from the bot itself, to avoid confusion.

LOGGER.info(
    "android: Original Android Modules by @RealAkito on Telegram (modified by @Hitalo on Telegram)"
)


@register(pattern=r"^/los(?: |$)(\S*)")
async def los(event):
    if event.from_id is None:
        return

    chat_id = event.chat_id
    try:
        device_ = event.pattern_match.group(1)
        device = urllib.parse.quote_plus(device_)
    except Exception:
        device = ''
Example #15
0
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.

import rapidjson as json
from requests import get
from telethon import custom

from hitsuki import LOGGER
from hitsuki.events import register
from hitsuki.modules.tr_engine.strings import tld

API_HOST = 'https://api.orangefox.download/v2'

LOGGER.info(
    "orangefox: By @MrYacha, powered by OrangeFox API v2 (modified by @Hitalo on Telegram)"
)


@register(pattern=r"^/(orangefox|of|fox|ofox)(?: |$)(\S*)")
async def orangefox(event):
    if event.from_id is None:
        return

    chat_id = event.chat_id

    try:
        codename = event.pattern_match.group(2)
    except Exception:
        codename = ''