5

I'm using Python's pyrogram lib to login to multiple accounts. I need to create a function just to send verification code to account and then read it from other user input (not the default pyrogram login prompt).

When I use send_code it sends code and waits for user input from console and that what I don't want it to do. I need simply a function that takes phone number as parameter and send confirmation code to it, and a function then to login with that confirmation code (got from user input somewhere else, e.g.: from telegram message to a linked bot or ....

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Khalil Abbas
  • 110
  • 2
  • 7

3 Answers3

1

I found a way to do it but with Telethon :

client = TelegramClient('sessionfile',api_id,api_hash)
def getcode():
    code = ... # get the code from somewhere ( bot, file etc.. )
    return code

client.start(phone=phone_number,password=password,code_callback=getcode)

this will login , gets confirmation code from specific function and then uses it to login , and store session file

Khalil Abbas
  • 110
  • 2
  • 7
0

Here's how you can achieve that with pyrogram:

from pyrogram import Client


async def main():
    api_id = YOUR_API_ID
    api_hash = "YOUR_API_HASH"
    phone_number = "YOUR_PHONE_NUMBER"
    client = Client(":memory:", api_id, api_hash)
    await client.connect()
    sent_code_info = await client.send_code(phone_number)
    phone_code = input("Please enter your phone code: ")  # Sent phone code using last function
    await client.sign_in(phone_number, sent_code_info.phone_code_hash, phone_code)

For more info check the implementation of String Session Bot which implements Pyrogram as well as Telethon, particularly this function.

Shivang Kakkar
  • 421
  • 3
  • 15
0

I faced the same problem, but none of the solutions worked because, in addition to the SMS code, a password was required. So I reworked one of the commenters solution and added the password there as needed

from pyrogram import Client
from pyrogram.errors import SessionPasswordNeeded, PhoneCodeInvalid, PasswordHashInvalid

api_id = YOUR_API_ID
api_hash = "YOUR_API_HASH"
phone_number = "YOUR_PHONE_NUMBER"
client = Client(":memory:", api_id, api_hash)
client.connect()
sent_code_info = client.send_code(phone_number)
phone_code = input("Please enter your phone code: ")  # Sent phone code using last function
while True:
    try:
        client.sign_in(phone_number, sent_code_info.phone_code_hash, phone_code)
        break
    except SessionPasswordNeeded:
        password = input("Please enter your pass: ")  # Sent phone code using last function
        try:
            client.check_password(password)
            break
        except PasswordHashInvalid:
            print("pass error try 1 more time")
    except PhoneCodeInvalid:
        print("code error try 1 more time")


client.send_message("me", "Thats work!") #Checking work
Hockep
  • 1
  • 1