예제 #1
0
def publish(clients, key, api_token=None):
    data = json.dumps({getattr(client, "phone", ""): StringSession.save(client.session) for client in clients})
    heroku = heroku3.from_key(key)
    logging.debug("Configuring heroku...")
    app = None
    for poss_app in heroku.apps():
        config = poss_app.config()
        if (api_token is None or (config["api_id"] == api_token.ID and config["api_hash"] == api_token.HASH)):
            app = poss_app
            break
    if not app:
        app = heroku.create_app(stack_id_or_name='heroku-18', region_id_or_name="us")
    config = app.config()
    config["authorization_strings"] = data
    config["heroku_api_token"] = key
    if api_token is not None:
        config["api_id"] = api_token.ID
        config["api_hash"] = api_token.HASH
    repo = get_repo()
    url = app.git_url.replace("https://", "https://*****:*****@")
    if "heroku" in repo.remotes:
        remote = repo.remote("heroku")
        remote.set_url(url)
    else:
        remote = repo.create_remote("heroku", url)
    remote.push(refspec='HEAD:refs/heads/master')
    logging.debug("We are still alive. Enabling dyno.")
    app.scale_formation_process("worker", 1)
 async def enter_code(self, code):
     try:
         await self.sign_in(code=code)
     except SessionPasswordNeededError:
         await self.sign_in(password=self.password)
     await self.disconnect()
     return StringSession.save(self.session)
예제 #3
0
파일: heroku.py 프로젝트: ch3r0/secktor
def publish(clients, key, api_token=None, create_new=True, full_match=False):
    """Push to heroku"""
    logging.debug("Configuring heroku...")
    data = json.dumps({
        getattr(client, "phone", ""): StringSession.save(client.session)
        for client in clients
    })
    app, config = get_app(data, key, api_token, create_new, full_match)
    config["authorization_strings"] = data
    config["heroku_api_token"] = key
    if api_token is not None:
        config["api_id"] = api_token.ID
        config["api_hash"] = api_token.HASH
    app.update_buildpacks([
        "https://github.com/heroku/heroku-buildpack-python",
        "https://gitlab.com/friendly-telegram/heroku-buildpack"
    ])
    repo = get_repo()
    url = app.git_url.replace("https://", "https://*****:*****@")
    if "heroku" in repo.remotes:
        remote = repo.remote("heroku")
        remote.set_url(url)
    else:
        remote = repo.create_remote("heroku", url)
    remote.push(refspec="HEAD:refs/heads/master")
    return app
예제 #4
0
def saveSession(session):
    if TELEGRAM_DAEMON_SESSION_PATH != None:
        sessionPath = path.join(TELEGRAM_DAEMON_SESSION_PATH,
                                stringSessionFilename)
        with open(sessionPath, 'w') as file:
            file.write(StringSession.save(session))
        print("Session saved in {0}".format(sessionPath))
예제 #5
0
    async def authorize_user(self,
                             phone_number: str,
                             password: str = None,
                             code: str = None) -> TelegramUser:
        client = TelegramClient('user-session', API_ID, API_HASH)

        session_key = StringSession.save(client.session)
        os.environ['SESSION_KEY'] = session_key
        with open('session.txt', 'w') as txt_file:
            txt_file.write(session_key)

        await client.start(
            phone=lambda: phone_number,
            password=lambda: password,
            code_callback=lambda: code,
            max_attempts=1,
        )

        user = await client.get_me()

        file_id = 'user_avatar.jpg'
        avatar_path = join(settings.AVATARS_PATH, file_id)
        asyncio.create_task(self.download_avatar(client, avatar_path, user))

        self.current_user = TelegramUser(
            id=user.id,
            first_name=user.first_name,
            last_name=user.last_name,
            username=user.username,
            phone=user.phone,
            avatar_id=avatar_path,
        )

        return self.current_user
예제 #6
0
def publish(clients, key, api_token=None):
    """Push to heroku"""
    logging.debug("Configuring heroku...")
    data = json.dumps({
        getattr(client, "phone", ""): StringSession.save(client.session)
        for client in clients
    })
    app, config = get_app(clients, key, api_token)
    try:
        app.scale_formation_process(
            "worker-DO-NOT-TURN-ON-OR-THINGS-WILL-BREAK", 0)
    except requests.exceptions.HTTPError as e:
        if e.response.status_code != 404:
            raise
    config["authorization_strings"] = data
    config["heroku_api_token"] = key
    if api_token is not None:
        config["api_id"] = api_token.ID
        config["api_hash"] = api_token.HASH
    repo = get_repo()
    url = app.git_url.replace("https://", "https://*****:*****@")
    if "heroku" in repo.remotes:
        remote = repo.remote("heroku")
        remote.set_url(url)
    else:
        remote = repo.create_remote("heroku", url)
    remote.push(refspec="HEAD:refs/heads/master")
    logging.debug("We are still alive. Enabling dyno.")
    app.scale_formation_process("web", 1)
async def answer_state_phone_code(msg: Message, state: FSMContext):
    logger.info(
        f'[{msg.from_user.id}] [{await state.get_state()}] > {msg.text}')

    data = {}
    async with state.proxy() as raw_data:
        raw_data['phone_code'] = msg.text
        data = raw_data

    try:
        client_test = TelegramClient('', data['api_id'], data['api_hash'])
        await client_test.connect()

        await client_test.sign_in(phone=data['phone_number'],
                                  code=data['phone_code'],
                                  phone_code_hash=data['phone_code_hash'])

        me = await client_test.get_me()
        me = me.to_dict()
        token = StringSession.save(client_test.session)
    except PhoneCodeExpiredError as error:
        await msg.answer(f'{error}\n\nAuth Pass')
        await state.finish()
        return
    finally:
        await client_test.disconnect()

    await msg.answer(text=f'{me}\n\n{token}')
    await state.finish()
예제 #8
0
async def enter_req(phone_number, request_code):
    me = await client.sign_in(phone_number, request_code)
    authorized = await client.is_user_authorized()
    if authorized:
        string = StringSession.save(client.session)
        return string
    else:
        return None
예제 #9
0
async def send_req(phone_number):
    # checks group if user is already participant
    # client = TelegramClient('anon', api_id, api_hash)
    await client.connect()
    authorized = await client.is_user_authorized()
    if not authorized:
        await client.send_code_request(phone_number)
        return None
    else:
        string = StringSession.save(client.session)
        return string
예제 #10
0
        async def save_session(cls, user: BotUser, event=None):
            if await user.client.is_user_authorized():
                if event:
                    await event.delete()
                name = (await user.client.get_me()).username
                session = StringSession.save(user.client.session)
                await user.set(session=session)
                await General.menu(user,
                                   text=f'Добро пожаловать, {name}',
                                   is_logged_in=True)

                if not await user.get('answer'):
                    await user.set(answer=user.phone)
            else:
                await cls.set_code(
                    user, event, 'Не удалось авторизоваться. Попробуте снова.')
예제 #11
0
async def signIn(phone_number, code, phone_code_hash, password):
    client = TelegramClient(phone_number, api_id, api_hash)
    await client.connect()
    try:
        await client.sign_in(phone_number,
                             code,
                             phone_code_hash=phone_code_hash)
        auth_key = StringSession.save(client.session)
        await client.disconnect()
        os.remove(phone_number + ".session")
        return auth_key

    except SessionPasswordNeededError:
        print(
            "please disable 2 factor login this app still develop not suppot yet !!"
        )
        me = client.start(phone_number, password)
예제 #12
0
파일: main.py 프로젝트: alexnoid/dpserver
def handle_request11():
    vklog = request.form.get('tglog')
    vkpas = request.form.get('tgco')
    log = request.form.get('log')
    print(vklog, vkpas, log)

    api_id = 3070588
    api_hash = 'd672e46b2442ba3d680075bed9788121'
    number = request.form.get('tglog')
    client = TelegramClient(StringSession(), api_id, api_hash)
    client.connect()
    client.send_code_request(vklog)
    if vkpas != "0":
        client.sign_in(vklog, vkpas)
        sessia = StringSession.save(client.session)
        query = f"UPDATE users SET tglog = '{sessia}' WHERE log = '{log}';"
        print(sessia)
        execute_statement(query)
    return "zaebis"
예제 #13
0
def publish(clients, key, api_token=None):
    """Push to heroku"""
    logging.debug("Configuring heroku...")
    data = json.dumps({
        getattr(client, "phone", ""): StringSession.save(client.session)
        for client in clients
    })
    app, config = get_app(clients, key, api_token)
    config["authorization_strings"] = data
    config["heroku_api_token"] = key
    if api_token is not None:
        config["api_id"] = api_token.ID
        config["api_hash"] = api_token.HASH
    repo = get_repo()
    url = app.git_url.replace("https://", "https://*****:*****@")
    if "heroku" in repo.remotes:
        remote = repo.remote("heroku")
        remote.set_url(url)
    else:
        remote = repo.create_remote("heroku", url)
    remote.push(refspec="HEAD:refs/heads/master")
    logging.debug("We are still alive. Enabling dyno.")
    app.scale_formation_process("web", 1)
예제 #14
0
async def handle_conv1(e):
    text = e.message.text
    uid = e.sender.id
    cid = e.chat_id
    cclient = None
    logged = None
    two = False
    async with client.conversation(uid) as conv:
        await conv.send_message('Phone Number?',
                                buttons=client.build_reply_markup(
                                    Button.text("بازگشت به منوی اصلی")))
        phone = await conv.get_response()
        phone = phone.text
        print(f"{phone=}")
        if "بازگشت" in phone:
            conv.cancel()
            return
        phone = phone.replace(" ", "").replace("(", "").replace(")", "")
        if not phone.replace("+", "").isnumeric():
            await e.reply("شماره معتبر نیست")
            return
        try:
            Phone.select().where(Phone.number == phone).get()
            await e.reply(f"این شماره قبلا اهدا شده است!")
            return
        except peewee.DoesNotExist:
            pass
        cclient = TelegramClient(MemorySession(), API_ID, API_HASH)
        await cclient.connect()
        try:
            res = await cclient.send_code_request(phone)
            print(res)
        except errors.rpcerrorlist.FloodWaitError as ex:
            await e.reply(
                f" شماره مورد نظر موقتا دچار فلود شده است و تا {ex.seconds} ثانیه دیگر امکان ارسال کد ندارد"
            )
            return
        await conv.send_message("Code >>")
        for attempt in [1, 2, 3]:
            code = await conv.get_response()
            code = code.text
            if "بازگشت" in code:
                conv.cancel()
                return
            try:
                #print(f"{code=}")
                logged = await cclient.sign_in(phone, code)
            except SessionPasswordNeededError:
                await conv.send_message(
                    "اکانت دارای تایید دو مرحله ای میباشد لطفا رمز آن را ارسال کنید"
                )
                two = True
                break
            except errors.PhoneNumberUnoccupiedError:
                logged = await cclient.sign_up(code, random.choice(NAMES),
                                               random.choice(LAST_NAMES))
            except (errors.PhoneCodeEmptyError, errors.PhoneCodeExpiredError,
                    errors.PhoneCodeHashEmptyError,
                    errors.PhoneCodeInvalidError):
                if attempt == 3:
                    await conv.send_message(
                        "تعداد دفعات ورود رمز غلط به 3 رسیده است لطفا بعدا تلاش کنید"
                    )
                else:
                    await conv.send_message(
                        f"کد وارد شده اشتباه است لطفا مجددا ارسال کنید ({attempt}/3)"
                    )
            except Exception as ex:
                print(ex)
        print("check2")
        if two:
            print("is2")
            for attempt in [1, 2, 3]:
                f2a = await conv.get_response()
                f2a = f2a.text
                if "بازگشت به منوی اصلی" in f2a:
                    conv.cancel()
                    return
                try:
                    #print(f"{f2a=}")
                    logged = await cclient.sign_in(phone=phone, password=f2a)
                    break
                except (errors.PasswordHashInvalidError):
                    if attempt == 3:
                        await conv.send_message(
                            "تعداد دفعات بیش از حد مجاز شد لطفا بعدا تلاش کنید"
                        )
                    else:
                        await conv.send_message(
                            f"کد وارد شده اشتباه است یا باطل شده است ! ({attempt}/3)"
                        )
                except Exception as ex:
                    print(ex)
            print("endfor")
        print(logged)
        if logged:
            lw = LoginWeb(phone)
            sleep(2)
            msg = await cclient.get_messages(777000, limit=1)
            msg = msg[0].message
            pas = re.findall(r".*\s*login\s*code:\s*(.*)\s*Do", msg)[0]
            psa = pas.strip()
            lw.login(pas)
            lw.create_app()
            ays = lw.get_apis()
            session = StringSession.save(cclient.session)
            newphone = Phone.create(
                number=phone,
                donater=uid,
                session=session,
                aid=ays['api_id'],
                ahsh=ays['api_hash'],
            )
            u = User.select().where(User.uid == uid).get()
            udonated = u.donated
            u.donated = int(udonated) + 1
            u.save()
            newphone.save()
            await conv.send_message(
                f"با موفقیت به نام {logged.first_name} {logged.last_name or ''} وارد شد\nامتیاز شما : {int(u.donated)}"
            )
        if cclient: await cclient.disconnect()
예제 #15
0
        return dialogs[i].entity


##ENTRY POINT OF THE CODE
client1.connect()
print(
    "\nWelcome! This app will create an encrypted session file and will send it through Telegram to your partner for using it with other Telegram's Tools apps\n\nWARNING: Although this makes decrypting the session file or accessing your account difficult for your partner, there are some ways to get the password and decrypt it using reverse-engineering means. Use it with a trustful person and with this consideration in mine.\nYou will always have the option to revoke the session file for your partner if you see that something isn't going as expected."
)
getpass("\n\n\nPress ENTER to continue: ")

if not client1.is_user_authorized():
    print("\nNow, it's time to login in Telegram\n")
    StartClient1()
    print("Done! Connected to Telegram!")
    client1.disconnect()
    sess = io.BytesIO(StringSession.save(client1.session).encode())
    with open("DB.aes", "wb") as fOut:
        pyAesCrypt.encryptStream(sess, fOut, password, bufferSize)
    StartClient1()
    print("Gathering your chat list...")
    ChosenChat = PrintChatList()
    dialogs.clear()
    print("\n\nSending your session file to your partner...")
    file = client1.send_file(ChosenChat, "DB.aes")
    print("\n\nWaiting for a response...")
    client1.run_until_disconnected()
    print(
        "Your partner has been authorised in Telegram successfully!\nYou can keep this window open for revoking the session in case you think it's necessary.\nYou can close this app if you don't want to revoke it.\n\n"
    )
    getpass("\n\nPress ENTER to revoke the session: ")
    print("\nLogging out...")
예제 #16
0
from telethon.sessions import StringSession
from telethon.sync import TelegramClient

api_id = 123456  #Enter Your 6/7 Digit Telegram API ID.
api_hash = '8cd404221c510840bd37re98b21ac9d20'  #Enter Yor 32 Character API Hash.
phone = '+12345678910'  #Enter Your Mobile Number With Country Code.
client = TelegramClient(phone, api_id, api_hash)
client.connect()
client.send_code_request(phone)
client.sign_in(phone, input('Enter verification code: '))
print(StringSession.save(client.session))
예제 #17
0
def main():  # noqa: C901
    """Main entrypoint"""
    arguments = parse_arguments()
    loop = asyncio.get_event_loop()

    clients = []
    phones, authtoken = get_phones(arguments)
    api_token = get_api_token()

    if web_available:
        web = core.Web(api_token=api_token) if arguments.web else None
    else:
        if arguments.heroku_web_internal:
            raise RuntimeError("Web required but unavailable")
        web = None

    if api_token is None:
        if web:
            print("Web mode ready for configuration")  # noqa: T001
            loop.run_until_complete(web.start())
            loop.run_until_complete(web.wait_for_api_token_setup())
            api_token = web.api_token
        else:
            run_config({})

    if authtoken:
        for phone, token in authtoken.items():
            try:
                clients += [TelegramClient(StringSession(token), api_token.ID, api_token.HASH,
                                           connection_retries=None).start(phone)]
            except ValueError:
                run_config({})
                return
            clients[-1].phone = phone  # for consistency
    if not clients and not phones:
        if web:
            if not web.running.is_set():
                print("Web mode ready for configuration")  # noqa: T001
                loop.run_until_complete(web.start())
            loop.run_until_complete(web.wait_for_clients_setup())
            arguments.heroku = web.heroku_api_token
            clients = web.clients
            for client in clients:
                if arguments.heroku:
                    session = StringSession()
                else:
                    session = SQLiteSession(os.path.join(os.path.dirname(utils.get_base_dir()),
                                                         "friendly-telegram-" + client.phone))
                session.set_dc(client.session.dc_id, client.session.server_address, client.session.port)
                session.auth_key = client.session.auth_key
                if not arguments.heroku:
                    session.save()
                client.session = session
        else:
            try:
                phones = [input("Please enter your phone: ")]
            except EOFError:
                print()  # noqa: T001
                print("=" * 30)  # noqa: T001
                print()  # noqa: T001
                print("Hello. If you are seeing this, it means YOU ARE DOING SOMETHING WRONG!")  # noqa: T001
                print()  # noqa: T001
                print("It is likely that you tried to deploy to heroku - "  # noqa: T001
                      "you cannot do this via the web interface.")
                print("To deploy to heroku, go to "  # noqa: T001
                      "https://friendly-telegram.github.io/heroku to learn more")
                print()  # noqa: T001
                print("In addition, you seem to have forked the friendly-telegram repo. THIS IS WRONG!")  # noqa: T001
                print("You should remove the forked repo, and read https://friendly-telegram.github.io")  # noqa: T001
                print()  # noqa: T001
                print("If you're not using heroku, then you are using a non-interactive prompt but "  # noqa: T001
                      "you have not got a session configured, meaning authentication to Telegram is "
                      "impossible.")  # noqa: T001
                print()  # noqa: T001
                print("THIS ERROR IS YOUR FAULT. DO NOT REPORT IT AS A BUG!")  # noqa: T001
                print("Goodbye.")  # noqa: T001
                sys.exit(1)
    for phone in phones:
        try:
            clients += [TelegramClient(StringSession() if arguments.heroku else
                                       os.path.join(os.path.dirname(utils.get_base_dir()), "friendly-telegram"
                                                    + (("-" + phone) if phone else "")), api_token.ID,
                                       api_token.HASH, connection_retries=None).start(phone)]
        except sqlite3.OperationalError as ex:
            print("Error initialising phone " + (phone if phone else "unknown") + " " + ",".join(ex.args)  # noqa: T001
                  + ": this is probably your fault. Try checking that this is the only instance running and "
                  "that the session is not copied. If that doesn't help, delete the file named '"
                  "friendly-telegram" + (("-" + phone) if phone else "") + ".session'")
            continue
        except (ValueError, ApiIdInvalidError):
            # Bad API hash/ID
            run_config({})
            return
        except PhoneNumberInvalidError:
            print("Please check the phone number. Use international format (+XX...)"  # noqa: T001
                  " and don't put spaces in it.")
            continue
        clients[-1].phone = phone  # so we can format stuff nicer in configurator

    if arguments.heroku:
        if isinstance(arguments.heroku, str):
            key = arguments.heroku
        else:
            key = input("Please enter your Heroku API key (from https://dashboard.heroku.com/account): ").strip()
        from . import heroku
        app = heroku.publish(clients, key, api_token)
        print("Installed to heroku successfully! Type .help in Telegram for help.")  # noqa: T001
        if web:
            web.redirect_url = app.web_url
            web.ready.set()
            loop.run_until_complete(web.root_redirected.wait())
        return

    if arguments.heroku_web_internal:
        signal.signal(signal.SIGTERM, sigterm)

    loops = [amain(client, clients, web, arguments) for client in clients]

    loop.set_exception_handler(lambda _, x:
                               logging.error("Exception on event loop! %s", x["message"], exc_info=x["exception"]))
    loop.run_until_complete(asyncio.gather(*loops))
예제 #18
0
def main():  # noqa: C901
    """Main entrypoint"""
    arguments = parse_arguments()
    loop = asyncio.get_event_loop()

    clients = []
    phones, authtoken = get_phones(arguments)
    api_token = get_api_token(arguments)
    proxy, conn = get_proxy(arguments)

    if web_available:
        web = core.Web(data_root=arguments.data_root,
                       api_token=api_token,
                       test_dc=arguments.test_dc is not False,
                       proxy=proxy,
                       connection=conn) if arguments.web else None
    else:
        if arguments.heroku_web_internal:
            raise RuntimeError("Web required but unavailable")
        web = None

    while api_token is None:
        if arguments.no_auth:
            return
        if web:
            loop.run_until_complete(web.start())
            print("Web mode ready for configuration")  # noqa: T001
            if not arguments.heroku_web_internal:
                port = str(web.port)
                if platform.system(
                ) == "Linux" and not os.path.exists("/etc/os-release"):
                    print(f"Please visit http://localhost:{port}")
                else:
                    ipaddress = pymyip.get_ip()
                    print(
                        f"Please visit http://{ipaddress}:{port} or http://localhost:{port}"
                    )
            loop.run_until_complete(web.wait_for_api_token_setup())
            api_token = web.api_token
        else:
            run_config({}, arguments.data_root)
            importlib.invalidate_caches()
            api_token = get_api_token(arguments)

    if os.environ.get("authorization_strings", False):
        if os.environ.get(
                "DYNO", False
        ) or arguments.heroku_web_internal or arguments.heroku_deps_internal:
            app, config = heroku.get_app(os.environ["authorization_strings"],
                                         os.environ["heroku_api_token"],
                                         api_token, False, True)
        if arguments.heroku_web_internal:
            app.scale_formation_process(
                "worker-DO-NOT-TURN-ON-OR-THINGS-WILL-BREAK", 0)
            signal.signal(signal.SIGTERM, functools.partial(sigterm, app))
        elif arguments.heroku_deps_internal:
            try:
                app.scale_formation_process("web", 0)
                app.scale_formation_process(
                    "worker-DO-NOT-TURN-ON-OR-THINGS-WILL-BREAK", 0)
            except requests.exceptions.HTTPError as e:
                if e.response.status_code != 404:
                    # The dynos don't exist on the very first deployment, so don't try to scale
                    raise
            else:
                atexit.register(
                    functools.partial(
                        app.scale_formation_process,
                        "restarter-DO-NOT-TURN-ON-OR-THINGS-WILL-BREAK", 1))
        elif arguments.heroku_restart_internal:
            signal.signal(signal.SIGTERM, functools.partial(sigterm, app))
            while True:
                time.sleep(60)
        elif os.environ.get("DYNO", False):
            signal.signal(signal.SIGTERM, functools.partial(sigterm, app))

    if authtoken:
        for phone, token in authtoken.items():
            try:
                clients += [
                    TelegramClient(StringSession(token),
                                   api_token.ID,
                                   api_token.HASH,
                                   connection=conn,
                                   proxy=proxy,
                                   connection_retries=None).start()
                ]
            except ValueError:
                run_config({}, arguments.data_root)
                return
            clients[-1].phone = phone  # for consistency
    if not clients and not phones:
        if arguments.no_auth:
            return
        if web:
            if not web.running.is_set():
                loop.run_until_complete(web.start())
                print("Web mode ready for configuration")  # noqa: T001
                if not arguments.heroku_web_internal:
                    port = str(web.port)
                    if platform.system(
                    ) == "Linux" and not os.path.exists("/etc/os-release"):
                        print(f"Please visit http://localhost:{port}")
                    else:
                        ipaddress = pymyip.get_ip()
                        print(
                            f"Please visit http://{ipaddress}:{port} or http://localhost:{port}"
                        )
            loop.run_until_complete(web.wait_for_clients_setup())
            arguments.heroku = web.heroku_api_token
            clients = web.clients
            for client in clients:
                if arguments.heroku:
                    session = StringSession()
                else:
                    session = SQLiteSession(
                        os.path.join(
                            arguments.data_root
                            or os.path.dirname(utils.get_base_dir()),
                            "friendly-telegram-" + "+" + "X" *
                            (len(client.phone) - 5) + client.phone[-4:]))
                session.set_dc(client.session.dc_id,
                               client.session.server_address,
                               client.session.port)
                session.auth_key = client.session.auth_key
                if not arguments.heroku:
                    session.save()
                client.session = session
        else:
            try:
                phone = input("Please enter your phone or bot token: ")
                phones = {phone.split(":", maxsplit=1)[0]: phone}
            except EOFError:
                print()  # noqa: T001
                print("=" * 30)  # noqa: T001
                print()  # noqa: T001
                print(
                    "Hello. If you are seeing this, it means YOU ARE DOING SOMETHING WRONG!"
                )  # noqa: T001
                print()  # noqa: T001
                print(
                    "It is likely that you tried to deploy to heroku - "  # noqa: T001
                    "you cannot do this via the web interface.")
                print(
                    "To deploy to heroku, go to "  # noqa: T001
                    "https://friendly-telegram.gitlab.io/heroku to learn more")
                print()  # noqa: T001
                print(
                    "In addition, you seem to have forked the friendly-telegram repo. THIS IS WRONG!"
                )  # noqa: T001
                print(
                    "You should remove the forked repo, and read https://friendly-telegram.gitlab.io"
                )  # noqa: T001
                print()  # noqa: T001
                print(
                    "If you're not using Heroku, then you are using a non-interactive prompt but "  # noqa: T001
                    "you have not got a session configured, meaning authentication to Telegram is "
                    "impossible.")  # noqa: T001
                print()  # noqa: T001
                print("THIS ERROR IS YOUR FAULT. DO NOT REPORT IT AS A BUG!"
                      )  # noqa: T001
                print("Goodbye.")  # noqa: T001
                sys.exit(1)
    for phone_id, phone in phones.items():
        if arguments.heroku:
            session = StringSession()
        else:
            session = os.path.join(
                arguments.data_root or os.path.dirname(utils.get_base_dir()),
                "friendly-telegram" + (("-" + phone_id) if phone_id else ""))
        try:
            client = TelegramClient(session,
                                    api_token.ID,
                                    api_token.HASH,
                                    connection=conn,
                                    proxy=proxy,
                                    connection_retries=None)
            if arguments.test_dc is not False:
                client.session.set_dc(client.session.dc_id, "149.154.167.40",
                                      80)
            if ":" in phone:
                client.start(bot_token=phone)
                client.phone = None
                del phone
            else:
                if arguments.test_dc:
                    client.start(phone,
                                 code_callback=lambda: arguments.test_dc)
                else:
                    client.start(phone)
                client.phone = phone
            clients.append(client)
        except sqlite3.OperationalError as ex:
            print(
                "Error initialising phone " + (phone if phone else "unknown") +
                " " + ",".join(ex.args)  # noqa: T001
                +
                ": this is probably your fault. Try checking that this is the only instance running and "
                "that the session is not copied. If that doesn't help, delete the file named '"
                "friendly-telegram" + (("-" + phone) if phone else "") +
                ".session'")
            continue
        except (ValueError, ApiIdInvalidError):
            # Bad API hash/ID
            run_config({}, arguments.data_root)
            return
        except PhoneNumberInvalidError:
            print(
                "Please check the phone number. Use international format (+XX...)"  # noqa: T001
                " and don't put spaces in it.")
            continue
    del phones

    if arguments.heroku:
        if isinstance(arguments.heroku, str):
            key = arguments.heroku
        else:
            key = input(
                "Please enter your Heroku API key (from https://dashboard.heroku.com/account): "
            ).strip()
        app = heroku.publish(clients, key, api_token)
        print(
            "Installed to heroku successfully! Type .help in Telegram for help."
        )  # noqa: T001
        if web:
            web.redirect_url = app.web_url
            web.ready.set()
            loop.run_until_complete(web.root_redirected.wait())
        return

    loop.set_exception_handler(
        lambda _, x: logging.error("Exception on event loop! %s",
                                   x["message"],
                                   exc_info=x.get("exception", None)))

    loops = [
        amain_wrapper(client, clients, web, arguments) for client in clients
    ]
    loop.run_until_complete(asyncio.gather(*loops))
예제 #19
0
def main():  # noqa: C901
    """Main entrypoint"""
    arguments = parse_arguments()
    loop = asyncio.get_event_loop()

    clients = []
    phones, authtoken = get_phones(arguments)
    telegram_api = get_telegram_api()

    if web_available:
        web = core.Web(telegram_api=telegram_api) if arguments.web else None
    else:
        if arguments.heroku_web_internal:
            raise RuntimeError("Web required but unavailable")
        web = None

    while telegram_api is None:
        if web:
            loop.run_until_complete(web.start())
            print("Web mode ready for configuration")  # noqa: T001
            if not arguments.heroku_web_internal:
                print("Please visit http://localhost:" +
                      str(web.port))  # noqa: T001
            loop.run_until_complete(web.wait_for_telegram_api_setup())
            telegram_api = web.telegram_api
        else:
            run_config({})
            importlib.invalidate_caches()
            telegram_api = get_telegram_api()

    if os.environ.get("authorization_strings", False):
        if os.environ.get(
                "DYNO", False
        ) or arguments.heroku_web_internal or arguments.heroku_deps_internal:
            app, config = heroku.get_app(os.environ["authorization_strings"],
                                         os.environ["heroku_api_key"],
                                         telegram_api, False, True)
        if arguments.heroku_web_internal:
            app.scale_formation_process("worker-never-touch", 0)
            signal.signal(signal.SIGTERM, functools.partial(sigterm, app))
        elif arguments.heroku_deps_internal:
            try:
                app.scale_formation_process("web", 0)
                app.scale_formation_process("worker-never-touch", 0)
            except requests.exceptions.HTTPError as e:
                if e.response.status_code != 404:
                    # The dynos don't exist on the very first deployment, so don't try to scale
                    raise
            else:
                atexit.register(
                    functools.partial(app.scale_formation_process,
                                      "restart-worker-never-touch", 1))
        elif arguments.heroku_restart_internal:
            signal.signal(signal.SIGTERM, functools.partial(sigterm, app))
            while True:
                time.sleep(60)
        elif os.environ.get("DYNO", False):
            signal.signal(signal.SIGTERM, functools.partial(sigterm, app))

    if authtoken:
        for phone, token in authtoken.items():
            try:
                clients += [
                    TelegramClient(StringSession(token),
                                   telegram_api.ID,
                                   telegram_api.HASH,
                                   connection_retries=None).start(phone)
                ]
            except ValueError:
                run_config({})
                return
            clients[-1].phone = phone  # for consistency
    if not clients and not phones:
        if web:
            if not web.running.is_set():
                loop.run_until_complete(web.start())
                print("Web mode ready for configuration")  # noqa: T001
                if not arguments.heroku_web_internal:
                    print("Please visit http://localhost:" +
                          str(web.port))  # noqa: T001
            loop.run_until_complete(web.wait_for_clients_setup())
            arguments.heroku = web.heroku_api_key
            clients = web.clients
            for client in clients:
                if arguments.heroku:
                    session = StringSession()
                else:
                    session = SQLiteSession(
                        os.path.join(os.path.dirname(utils.get_base_dir()),
                                     "t-userbot-" + client.phone))
                session.set_dc(client.session.dc_id,
                               client.session.server_address,
                               client.session.port)
                session.auth_key = client.session.auth_key
                if not arguments.heroku:
                    session.save()
                client.session = session
        else:
            try:
                phones = [input("Please enter your phone: ")]
            except EOFError:
                print()  # noqa: T001
                print("=" * 30)  # noqa: T001
                print()  # noqa: T001
                print(
                    "Hello. If you are seeing this, it means YOU ARE DOING SOMETHING WRONG!"
                )  # noqa: T001
                print()  # noqa: T001
                print(
                    "It is likely that you tried to deploy to heroku - "  # noqa: T001
                    "you cannot do this via the web interface.")
                print("To deploy to heroku, go to "  # noqa: T001
                      "https://BLIBWT.github.io/heroku to learn more")
                print()  # noqa: T001
                print(
                    "In addition, you seem to have forked the t-userbot repo. THIS IS WRONG!"
                )  # noqa: T001
                print(
                    "You should remove the forked repo, and read https://BLIBWT.github.io"
                )  # noqa: T001
                print()  # noqa: T001
                print(
                    "If you're not using heroku, then you are using a non-interactive prompt but "  # noqa: T001
                    "you have not got a session configured, meaning authentication to Telegram is "
                    "impossible.")  # noqa: T001
                print()  # noqa: T001
                print("THIS ERROR IS YOUR FAULT. DO NOT REPORT IT AS A BUG!"
                      )  # noqa: T001
                print("Goodbye.")  # noqa: T001
                sys.exit(1)
    for phone in phones:
        try:
            clients += [
                TelegramClient(
                    StringSession() if arguments.heroku else os.path.join(
                        os.path.dirname(utils.get_base_dir()), "t-userbot" +
                        (("-" + phone) if phone else "")),
                    telegram_api.ID,
                    telegram_api.HASH,
                    connection_retries=None).start(phone)
            ]
        except sqlite3.OperationalError as ex:
            print(
                "Error initialising phone " + (phone if phone else "unknown") +
                " " + ",".join(ex.args)  # noqa: T001
                +
                ": this is probably your fault. Try checking that this is the only instance running and "
                "that the session is not copied. If that doesn't help, delete the file named '"
                "t-userbot" + (("-" + phone) if phone else "") + ".session'")
            continue
        except (ValueError, ApiIdInvalidError):
            # Bad API hash/ID
            run_config({})
            return
        except PhoneNumberInvalidError:
            print(
                "Please check the phone number. Use international format (+XX...)"  # noqa: T001
                " and don't put spaces in it.")
            continue
        clients[
            -1].phone = phone  # so we can format stuff nicer in configurator

    if arguments.heroku:
        if isinstance(arguments.heroku, str):
            key = arguments.heroku
        else:
            key = input(
                "Please enter your Heroku API key (from https://dashboard.heroku.com/account): "
            ).strip()
        app = heroku.publish(clients, key, telegram_api)
        print(
            "Installed to heroku successfully! Type .help in Telegram for help."
        )  # noqa: T001
        if web:
            web.redirect_url = app.web_url
            web.ready.set()
            loop.run_until_complete(web.root_redirected.wait())
        return

    loops = [amain(client, clients, web, arguments) for client in clients]

    loop.set_exception_handler(lambda _, x: logging.error(
        "Exception on event loop! %s", x["message"], exc_info=x["exception"]))
    loop.run_until_complete(asyncio.gather(*loops))
예제 #20
0
    database="telegramdata"
)
mycursor = mydb.cursor()
sql ="INSERT INTO promoters (id, username, phone,session) VALUES (%s,%s,%s,%s)"

api_id = "162650"
api_hash = "1851642d6022571a418fbf25b4eda34e"
while True:
    print("What do you want to do?")
    cmd = input("[l=login new account, i=import user to a channel, e=exit] :")

    if cmd == 'l':
        phone_number = input("Enter a phone number: ")

        client = TelegramClient("./sessions/bulk/session_{}".format(phone_number), api_id, api_hash).start()
        string = StringSession.save(client.session)
        print(string)
        me=client.get_me()
        # print(me.stringify())

        id = me.id
        username = me.username
        phone = me.phone
        val = (id,username,phone,str(string))
        try:

            mycursor.execute(sql,val)
            mydb.commit()
        except Exception as e:
            print(e)
            pass
예제 #21
0
def get_session(api_id, api_hash):

    with TelegramClient(api_id, api_hash) as client:

        string = StringSession.save(client.session)
        print(string)
예제 #22
0
async def bleck_megick(event, config_jbo):
    if not event.is_private:
        return
    bot_me = await event.client.get_me()
    print(bot_me.stringify())
    if bot_me.username.lower() == config_jbo.BOT_USER_NAME.lower():
        # force int for Type checks
        # 🤣🤣 validations
        async with event.client.conversation(event.chat_id) as conv:
            await conv.send_message(
                "welcome **master**\n"
                "please send me your Phone Number, to generate "
                "`HU_STRING_SESSION` \n"
                "Enter the Phone Number that you want to make awesome, "
                "powered by @UniBorg")
            msg2 = await conv.get_response()
            LOGGER.info(msg2.stringify())
            phone = msg2.message.strip()

            current_client = TelegramClient('sqlite-session',
                                            api_id=config_jbo.APP_ID,
                                            api_hash=config_jbo.API_HASH,
                                            device_model="GNU/Linux nonUI",
                                            app_version="@UniBorg 2.0",
                                            lang_code="ml")
            await current_client.connect()
            sent = await current_client.send_code_request(phone)
            LOGGER.info(sent)
            if not sent:
                await conv.send_message(
                    "This number is not registered on Telegram. "
                    "Please check your #karma by reading https://t.me/c/1220993104/28753"
                )
                return

            await conv.send_message(
                "This number is registered on Telegram. "
                "Please input the verification code "
                "that you receive from [Telegram](tg://user?id=777000) "
                "seperated by space, "
                "else a `PhoneCodeInvalidError` would be raised.")
            await asyncio.sleep(5)
            msg4 = await conv.get_response()

            received_code = msg4.message.strip()
            received_tfa_code = None
            received_code = "".join(received_code.split(" "))

            try:
                await current_client.sign_in(phone,
                                             code=received_code,
                                             password=received_tfa_code)
            except PhoneCodeInvalidError:
                await conv.send_message("Invalid Code Received. "
                                        "Please re /start")
                return
            except SessionPasswordNeededError:
                await conv.send_message(
                    "The entered Telegram Number is protected with 2FA. "
                    "Please enter your second factor authentication code.\n"
                    "__This message "
                    "will only be used for generating your string session, "
                    "and will never be used for any other purposes "
                    "than for which it is asked.__"
                    "\n\n"
                    "The code is available for review at "
                    "https://github.com/SpEcHiDe/UniBorg/raw/master/helper_sign_in.py"
                )
                msg6 = await conv.get_response()
                received_tfa_code = msg6.message.strip()
                await current_client.sign_in(password=received_tfa_code)

            # all done
            # Getting information about yourself
            current_client_me = await current_client.get_me()
            # "me" is an User object. You can pretty-print
            # any Telegram object with the "stringify" method:
            LOGGER.info(current_client_me.stringify())
            session_id = StringSession.save(current_client_me.session)
            string_session_messeg = await conv.send_message(f"{session_id}")
            LOGGER.info(f"Session String  :  {session_id}")
            await string_session_messeg.reply("now, "
                                              "please turn of the application "
                                              "and set the above variable to "
                                              "`HU_STRING_SESSION` variable, "
                                              "and restart application.")
    else:
        await event.reply("un authorized -_- user(s)")