コード例 #1
0
async def lazy():
    # noinspection PyTypeChecker
    manager_lang: Optional[str] = await db.User.get_or_none(id=env.MANAGER).values_list('lang', flat=True)

    set_bot_commands_tasks = (
        loop.create_task(
            command.utils.set_bot_commands(scope=types.BotCommandScopeDefault(),
                                           lang_code='',
                                           commands=get_commands_list())
        ),
        *(
            loop.create_task(
                command.utils.set_bot_commands(scope=types.BotCommandScopeDefault(),
                                               lang_code=i18n[lang]['iso_639_code'],
                                               commands=get_commands_list(lang=lang))
            )
            for lang in ALL_LANGUAGES if len(i18n[lang]['iso_639_code']) == 2
        ),
        loop.create_task(
            command.utils.set_bot_commands(scope=types.BotCommandScopePeer(types.InputPeerUser(env.MANAGER, 0)),
                                           lang_code='',
                                           commands=get_commands_list(lang=manager_lang, manager=True))
        ),
    )

    # get set_bot_commands tasks result
    try:
        await asyncio.gather(*set_bot_commands_tasks)
    except RPCError as _e:
        logger.warning('Set command error: ', exc_info=_e)
コード例 #2
0
ファイル: asyncpg.py プロジェクト: ukinti/telethon_asyncpg
    async def get_input_entity(self, key):
        try:
            if key.SUBCLASS_OF_ID in (0xc91c90b6, 0xe669bf46, 0x40f202fd):
                # hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))
                # We already have an Input version, so nothing else required
                return key
            # Try to early return if this key can be casted as input peer
            return utils.get_input_peer(key)
        except (AttributeError, TypeError):
            # Not a TLObject or can't be cast into InputPeer
            if isinstance(key, types.TLObject):
                key = utils.get_peer_id(key)
                exact = True
            else:
                exact = not isinstance(key, int) or key < 0

        result = None
        if isinstance(key, str):
            phone = utils.parse_phone(key)
            if phone:
                result = await self.get_entity_rows_by_phone(phone)
            else:
                username, invite = utils.parse_username(key)
                if username and not invite:
                    result = await self.get_entity_rows_by_username(username)
                else:
                    tup = utils.resolve_invite_link(key)[1]
                    if tup:
                        result = await self.get_entity_rows_by_id(tup, exact=False)

        elif isinstance(key, int):
            result = await self.get_entity_rows_by_id(key, exact)

        if not result and isinstance(key, str):
            result = await self.get_entity_rows_by_name(key)

        if result:
            entity_id, entity_hash = result  # unpack resulting tuple
            entity_id, kind = utils.resolve_id(entity_id)
            # removes the mark and returns type of entity
            if kind == types.PeerUser:
                return types.InputPeerUser(entity_id, entity_hash)
            elif kind == types.PeerChat:
                return types.InputPeerChat(entity_id)
            elif kind == types.PeerChannel:
                return types.InputPeerChannel(entity_id, entity_hash)
        else:
            raise ValueError('Could not find input entity with key ', key)
コード例 #3
0
    def iter_resume_entities(self, context_id):
        """
        Returns an iterator over the entities that need resuming for the
        given context_id. Note that the entities are *removed* once the
        iterator is consumed completely.
        """
        c = self.conn.execute("SELECT ID, AccessHash FROM ResumeEntity "
                              "WHERE ContextID = ?", (context_id,))
        row = c.fetchone()
        while row:
            kind = resolve_id(row[0])[1]
            if kind == types.PeerUser:
                yield types.InputPeerUser(row[0], row[1])
            elif kind == types.PeerChat:
                yield types.InputPeerChat(row[0])
            elif kind == types.PeerChannel:
                yield types.InputPeerChannel(row[0], row[1])
            row = c.fetchone()

        c.execute("DELETE FROM ResumeEntity WHERE ContextID = ?",
                  (context_id,))
コード例 #4
0
ファイル: dumper.py プロジェクト: Skactor/telegram-export
 async def get_resume_entities(self, context_id):
     """
     Returns an iterator over the entities that need resuming for the
     given context_id. Note that the entities are *removed* once the
     iterator is consumed completely.
     """
     rows = db_resume_entity.find({'context_id': context_id})
     count = await db_resume_entity.count_documents(
         {'context_id': context_id})
     logger.info(f'加载了【{count}】条待恢复数据')
     result = []
     async for row in rows:
         kind = resolve_id(row['id'])[1]
         if kind == types.PeerUser:
             result.append(
                 types.InputPeerUser(row['id'], row['access_hash']))
         elif kind == types.PeerChat:
             result.append(types.InputPeerChat(row['id']))
         elif kind == types.PeerChannel:
             result.append(
                 types.InputPeerChannel(row['id'], row['access_hash']))
     await db_resume_entity.delete_many({'context_id': context_id})
     return result
コード例 #5
0
async def pre():
    logger.info(
        f"RSS-to-Telegram-Bot ({', '.join(env.VERSION.split())}) started!\n"
        f"MANAGER: {env.MANAGER}\n"
        f"T_PROXY (for Telegram): {env.TELEGRAM_PROXY if env.TELEGRAM_PROXY else 'not set'}\n"
        f"R_PROXY (for RSS): {env.REQUESTS_PROXIES['all'] if env.REQUESTS_PROXIES else 'not set'}\n"
        f"DATABASE: {env.DATABASE_URL.split('://', 1)[0]}\n"
        f"TELEGRAPH: {f'Enable ({tgraph.apis.count} accounts)' if tgraph.apis else 'Disable'}\n"
        f"UVLOOP: {f'Enable' if uvloop is not None else 'Disable'}\n"
        f"MULTIUSER: {f'Enable' if env.MULTIUSER else 'Disable'}")

    await db.init()

    # enable redirect server for Railway, Heroku, etc
    if env.PORT:
        from . import redirect_server
        await redirect_server.run(port=env.PORT)

    # noinspection PyTypeChecker
    manager_lang: Optional[str] = await db.User.get_or_none(id=env.MANAGER
                                                            ).values_list(
                                                                'lang',
                                                                flat=True)

    try:  # set bot command
        await asyncio.gather(
            command.utils.set_bot_commands(
                scope=types.BotCommandScopeDefault(),
                lang_code='',
                commands=get_commands_list()),
            *(command.utils.set_bot_commands(
                scope=types.BotCommandScopeDefault(),
                lang_code=i18n[lang]['iso_639_code'],
                commands=get_commands_list(lang=lang))
              for lang in ALL_LANGUAGES
              if len(i18n[lang]['iso_639_code']) == 2),
            command.utils.set_bot_commands(
                scope=types.BotCommandScopePeer(
                    types.InputPeerUser(env.MANAGER, 0)),
                lang_code='',
                commands=get_commands_list(lang=manager_lang, manager=True)),
        )
    except Exception as e:
        logger.warning('Set command error: ', exc_info=e)

    bare_target_matcher = r'(?P<target>@\w{5,}|-100\d+)'
    target_matcher = rf'(\s+{bare_target_matcher})?'
    # command handler
    bot.add_event_handler(
        command.sub.cmd_sub,
        events.NewMessage(pattern=r'(?P<command>/add|/sub)(@\w+)?' +
                          target_matcher + r'(\s+(?P<url>.*))?\s*$'))
    bot.add_event_handler(command.sub.cmd_sub,
                          command.utils.PrivateMessage(pattern=r'https?://'))
    bot.add_event_handler(command.sub.cmd_sub,
                          command.utils.ReplyMessage(pattern=r'https?://'))
    bot.add_event_handler(
        command.sub.cmd_unsub,
        events.NewMessage(pattern=r'(?P<command>/remove|/unsub)(@\w+)?' +
                          target_matcher + r'(\s+(?P<url>.*))?\s*$'))
    bot.add_event_handler(
        command.sub.cmd_or_callback_unsub_all,
        events.NewMessage(
            pattern=r'(?P<command>/remove_all|/unsub_all)(@\w+)?' +
            target_matcher))
    bot.add_event_handler(
        command.sub.cmd_list_or_callback_get_list_page,
        events.NewMessage(pattern=r'(?P<command>/list)(@\w+)?' +
                          target_matcher))
    bot.add_event_handler(
        command.opml.cmd_import,
        events.NewMessage(pattern=r'(?P<command>/import)(@\w+)?' +
                          target_matcher))
    bot.add_event_handler(
        command.opml.cmd_export,
        events.NewMessage(pattern=r'(?P<command>/export)(@\w+)?' +
                          target_matcher))
    bot.add_event_handler(
        command.customization.cmd_set_or_callback_get_set_page,
        events.NewMessage(pattern=r'(?P<command>/set(?!_))(@\w+)?' +
                          target_matcher))
    bot.add_event_handler(
        command.customization.cmd_set_default,
        events.NewMessage(pattern=r'(?P<command>/set_default)(@\w+)?' +
                          target_matcher))
    bot.add_event_handler(
        command.customization.cmd_set_title,
        events.NewMessage(pattern=r'(?P<command>/set_title)(@\w+)?' +
                          target_matcher))
    bot.add_event_handler(
        command.customization.cmd_set_interval,
        events.NewMessage(pattern=r'(?P<command>/set_interval)(@\w+)?' +
                          target_matcher))
    bot.add_event_handler(
        command.customization.cmd_set_hashtags,
        events.NewMessage(pattern=r'(?P<command>/set_hashtags)(@\w+)?' +
                          target_matcher))
    bot.add_event_handler(
        command.opml.opml_import,
        command.utils.NewFileMessage(pattern='.*?' + bare_target_matcher + '?',
                                     filename_pattern=r'^.*\.opml$'))
    bot.add_event_handler(command.misc.cmd_start,
                          events.NewMessage(pattern='/start'))
    bot.add_event_handler(command.misc.cmd_or_callback_help,
                          events.NewMessage(pattern='/help'))
    bot.add_event_handler(
        partial(command.customization.cmd_activate_or_deactivate_subs,
                activate=True),
        events.NewMessage(pattern=r'(?P<command>/activate_subs)(@\w+)?' +
                          target_matcher))
    bot.add_event_handler(
        partial(command.customization.cmd_activate_or_deactivate_subs,
                activate=False),
        events.NewMessage(pattern=r'(?P<command>/deactivate_subs)(@\w+)?' +
                          target_matcher))
    bot.add_event_handler(command.misc.cmd_lang,
                          events.NewMessage(pattern='/lang'))
    bot.add_event_handler(command.misc.cmd_version,
                          events.NewMessage(pattern='/version'))
    bot.add_event_handler(command.administration.cmd_test,
                          events.NewMessage(pattern='/test'))
    bot.add_event_handler(
        command.administration.cmd_user_info_or_callback_set_user,
        events.NewMessage(pattern='/user_info'))
    bot.add_event_handler(command.administration.cmd_set_option,
                          events.NewMessage(pattern='/set_option'))

    callback_target_matcher = r'(%(?P<target>\d+))?'
    # callback query handler
    bot.add_event_handler(
        command.misc.callback_del_buttons,  # delete buttons
        events.CallbackQuery(pattern='^del_buttons$'))
    bot.add_event_handler(
        command.misc.callback_null,  # null callback query
        events.CallbackQuery(pattern='^null$'))
    bot.add_event_handler(command.misc.callback_cancel,
                          events.CallbackQuery(pattern='^cancel$'))
    bot.add_event_handler(
        command.misc.callback_get_group_migration_help,
        events.CallbackQuery(pattern=r'^get_group_migration_help=[\w_\-]+$'))
    bot.add_event_handler(
        command.sub.cmd_list_or_callback_get_list_page,
        events.CallbackQuery(
            pattern=rf'^get_list_page\|\d+{callback_target_matcher}$'))
    bot.add_event_handler(
        command.sub.callback_unsub,
        events.CallbackQuery(
            pattern=rf'^unsub=\d+(\|\d+)?{callback_target_matcher}$'))
    bot.add_event_handler(
        command.sub.callback_get_unsub_page,
        events.CallbackQuery(
            pattern=rf'^get_unsub_page\|\d+{callback_target_matcher}$'))
    bot.add_event_handler(
        command.sub.cmd_or_callback_unsub_all,
        events.CallbackQuery(pattern=rf'unsub_all{callback_target_matcher}$'))
    bot.add_event_handler(command.misc.callback_set_lang,
                          events.CallbackQuery(pattern=r'^set_lang=[\w_\-]+$'))
    bot.add_event_handler(command.misc.cmd_or_callback_help,
                          events.CallbackQuery(pattern='^help$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_all_subs,
                activate=True),
        events.CallbackQuery(
            pattern=rf'^activate_all_subs{callback_target_matcher}$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_all_subs,
                activate=False),
        events.CallbackQuery(
            pattern=rf'^deactivate_all_subs{callback_target_matcher}$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_sub,
                activate=True),
        events.CallbackQuery(
            pattern=rf'^activate_sub=\d+(\|\d+)?{callback_target_matcher}$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_sub,
                activate=False),
        events.CallbackQuery(
            pattern=rf'^deactivate_sub=\d+(\|\d+)?{callback_target_matcher}$'))
    bot.add_event_handler(
        partial(command.customization.callback_get_activate_or_deactivate_page,
                activate=True),
        events.CallbackQuery(
            pattern=rf'^get_activate_page\|\d+{callback_target_matcher}$'))
    bot.add_event_handler(
        partial(command.customization.callback_get_activate_or_deactivate_page,
                activate=False),
        events.CallbackQuery(
            pattern=rf'^get_deactivate_page\|\d+{callback_target_matcher}$'))
    bot.add_event_handler(
        command.customization.cmd_set_or_callback_get_set_page,
        events.CallbackQuery(
            pattern=rf'^get_set_page\|\d+{callback_target_matcher}$'))
    bot.add_event_handler(
        partial(command.customization.callback_set, set_user_default=False),
        events.CallbackQuery(
            pattern=
            rf'^set(=\d+(,\w+(,\w+)?)?)?(\|\d+)?{callback_target_matcher}$'))
    bot.add_event_handler(
        partial(command.customization.callback_set, set_user_default=True),
        events.CallbackQuery(
            pattern=rf'^set_default(=\w+(,\w+)?)?{callback_target_matcher}$'))
    bot.add_event_handler(
        command.customization.callback_reset,
        events.CallbackQuery(
            pattern=rf'^reset=\d+(\|\d+)?{callback_target_matcher}$'))
    bot.add_event_handler(
        command.customization.callback_reset_all,
        events.CallbackQuery(pattern=rf'^reset_all{callback_target_matcher}$'))
    bot.add_event_handler(
        command.customization.callback_reset_all_confirm,
        events.CallbackQuery(
            pattern=rf'^reset_all_confirm{callback_target_matcher}$'))
    bot.add_event_handler(
        command.customization.callback_del_subs_title,
        events.CallbackQuery(pattern=r'^del_subs_title=(\d+-\d+\|)*(\d+-\d+)'
                             rf'{callback_target_matcher}$'))
    bot.add_event_handler(
        command.administration.cmd_user_info_or_callback_set_user,
        events.CallbackQuery(pattern=r'^set_user=-?\d+,(-1|0|1)$'))
    # inline query handler
    bot.add_event_handler(command.misc.inline_command_constructor,
                          events.InlineQuery())
    # being added to a group handler
    bot.add_event_handler(command.misc.cmd_start,
                          command.utils.AddedToGroupAction())
    bot.add_event_handler(command.misc.cmd_start,
                          command.utils.GroupMigratedAction())
コード例 #6
0
async def pre():
    logger.info(
        f"RSS-to-Telegram-Bot ({', '.join(env.VERSION.split())}) started!\n"
        f"MANAGER: {env.MANAGER}\n"
        f"T_PROXY (for Telegram): {env.TELEGRAM_PROXY if env.TELEGRAM_PROXY else 'not set'}\n"
        f"R_PROXY (for RSS): {env.REQUESTS_PROXIES['all'] if env.REQUESTS_PROXIES else 'not set'}\n"
        f"DATABASE: {env.DATABASE_URL.split('://', 1)[0]}\n"
        f"TELEGRAPH: {f'Enable ({tgraph.apis.count} accounts)' if tgraph.apis else 'Disable'}\n"
        f"UVLOOP: {f'Enable' if uvloop is not None else 'Disable'}\n"
        f"MULTIUSER: {f'Enable' if env.MULTIUSER else 'Disable'}")

    await db.init()

    # noinspection PyTypeChecker
    manager_lang: Optional[str] = await db.User.get_or_none(id=env.MANAGER
                                                            ).values_list(
                                                                'lang',
                                                                flat=True)

    try:  # set bot command
        await asyncio.gather(
            command.utils.set_bot_commands(
                scope=types.BotCommandScopeDefault(),
                lang_code='',
                commands=command.utils.get_commands_list()),
            *(command.utils.set_bot_commands(
                scope=types.BotCommandScopeDefault(),
                lang_code=i18n[lang]['iso_639_code'],
                commands=command.utils.get_commands_list(lang=lang))
              for lang in ALL_LANGUAGES
              if len(i18n[lang]['iso_639_code']) == 2),
            command.utils.set_bot_commands(
                scope=types.BotCommandScopePeer(
                    types.InputPeerUser(env.MANAGER, 0)),
                lang_code='',
                commands=command.utils.get_commands_list(lang=manager_lang,
                                                         manager=True)),
        )
    except Exception as e:
        logger.warning('Set command error: ', exc_info=e)

    # command handler
    bot.add_event_handler(command.sub.cmd_sub,
                          events.NewMessage(pattern='/add|/sub'))
    bot.add_event_handler(command.sub.cmd_sub,
                          command.utils.PrivateMessage(pattern=r'https?://'))
    bot.add_event_handler(command.sub.cmd_sub,
                          command.utils.ReplyMessage(pattern=r'https?://'))
    bot.add_event_handler(
        command.sub.cmd_unsub,
        events.NewMessage(pattern='(/remove|/unsub)([^_]|$)'))
    bot.add_event_handler(command.sub.cmd_unsub_all,
                          events.NewMessage(pattern='/remove_all|/unsub_all'))
    bot.add_event_handler(command.sub.cmd_list_or_callback_get_list_page,
                          events.NewMessage(pattern='/list'))
    bot.add_event_handler(command.opml.cmd_import,
                          events.NewMessage(pattern='/import'))
    bot.add_event_handler(command.opml.cmd_export,
                          events.NewMessage(pattern='/export'))
    bot.add_event_handler(
        command.customization.cmd_set_or_callback_get_set_page,
        events.NewMessage(pattern='/set([^_]|$)'))
    bot.add_event_handler(
        command.opml.opml_import,
        command.utils.NewFileMessage(filename_pattern=r'^.*\.opml$'))
    bot.add_event_handler(command.management.cmd_start,
                          events.NewMessage(pattern='/start'))
    bot.add_event_handler(command.management.cmd_or_callback_help,
                          events.NewMessage(pattern='/help'))
    bot.add_event_handler(
        partial(command.customization.cmd_activate_or_deactivate_subs,
                activate=True), events.NewMessage(pattern='/activate_subs'))
    bot.add_event_handler(
        partial(command.customization.cmd_activate_or_deactivate_subs,
                activate=False), events.NewMessage(pattern='/deactivate_subs'))
    bot.add_event_handler(command.management.cmd_version,
                          events.NewMessage(pattern='/version'))
    bot.add_event_handler(command.management.cmd_lang,
                          events.NewMessage(pattern='/lang'))
    bot.add_event_handler(command.administration.cmd_test,
                          events.NewMessage(pattern='/test'))
    bot.add_event_handler(command.administration.cmd_set_option,
                          events.NewMessage(pattern='/set_option'))
    # callback query handler
    bot.add_event_handler(
        command.utils.answer_callback_query_null,  # null callback query
        events.CallbackQuery(data='null'))
    bot.add_event_handler(command.sub.cmd_list_or_callback_get_list_page,
                          events.CallbackQuery(pattern=r'^get_list_page_\d+$'))
    bot.add_event_handler(command.sub.callback_unsub,
                          events.CallbackQuery(pattern=r'^unsub_\d+(\|\d+)$'))
    bot.add_event_handler(
        command.sub.callback_get_unsub_page,
        events.CallbackQuery(pattern=r'^get_unsub_page_\d+$'))
    bot.add_event_handler(command.management.callback_set_lang,
                          events.CallbackQuery(pattern=r'^set_lang_[\w_\-]+$'))
    bot.add_event_handler(command.management.cmd_or_callback_help,
                          events.CallbackQuery(pattern=r'^help$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_all_subs,
                activate=True),
        events.CallbackQuery(pattern=r'^activate_all_subs$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_all_subs,
                activate=False),
        events.CallbackQuery(pattern=r'^deactivate_all_subs$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_sub,
                activate=True),
        events.CallbackQuery(pattern=r'^activate_sub_\d+(\|\d+)$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_sub,
                activate=False),
        events.CallbackQuery(pattern=r'^deactivate_sub_\d+(\|\d+)$'))
    bot.add_event_handler(
        partial(command.customization.callback_get_activate_or_deactivate_page,
                activate=True),
        events.CallbackQuery(pattern=r'^get_activate_page_\d+$'))
    bot.add_event_handler(
        partial(command.customization.callback_get_activate_or_deactivate_page,
                activate=False),
        events.CallbackQuery(pattern=r'^get_deactivate_page_\d+$'))
    bot.add_event_handler(
        command.customization.callback_set,
        events.CallbackQuery(pattern=r'^set(_\d+(_\w+(_\w+)?)?)?(\|\d+)?$'))
    bot.add_event_handler(
        command.customization.cmd_set_or_callback_get_set_page,
        events.CallbackQuery(pattern=r'^get_set_page_\d+$'))
    # being added to a group handler
    bot.add_event_handler(command.management.cmd_start,
                          command.utils.AddedToGroupAction())
    bot.add_event_handler(command.management.cmd_start,
                          command.utils.GroupMigratedAction())