tdlight-team / tdlight-java

Complete Bot and Userbot Telegram library based on TDLib
https://t.me/TDLight
GNU Lesser General Public License v3.0
263 stars 43 forks source link

How to update API credentials dynamically #230

Closed TuralK closed 1 month ago

TuralK commented 2 months ago

I want to edit the apiId and apiHash values of TdlibParameters using backup apiId and apiHash values in case there is a problem when sending the code to the phone number in the login method. Changing the values directly (e.g., parameters.apiId = apiId;) does not seem to affect the session; it still sends requests with the previous API data. Is there a solution for this?

try (ClientFactory clientManager = ClientFactory.create()) {
    client = clientManager.createClient();
    client.initialize(MyApp::onUpdate, MyApp::onUpdateError, MyApp::onError);

    TdApi.SetTdlibParameters parameters = new TdApi.SetTdlibParameters(
        false,
        dataPath,
        null,
        null,
        true,
        true,
        true,
        true,
        apiId,
        apiHash,
        "en",
        "Windows 11",
        null,
        "1"
    );

    client.send(parameters, response -> {
        if (response instanceof TdApi.Ok) {
            System.out.println("TDLib parameters set successfully.");
            login();
        } else if (response instanceof TdApi.Error) {
            System.err.println("Error setting TDLib parameters: " + ((TdApi.Error) response).message);
        }
    });
}

private static void login() {
    String phoneNumber = "+";
    System.out.println("Phone number of Telegram account: " + phoneNumber);
    TdApi.PhoneNumberAuthenticationSettings settings = new TdApi.PhoneNumberAuthenticationSettings();
    client.send(new TdApi.SetAuthenticationPhoneNumber(phoneNumber, settings), response -> {
        if (response instanceof TdApi.Ok) {
            System.out.println("Authentication code sent to phone number. Check your Telegram for the code.");
            waitForAuthCode();
        } else {
            if (!paramReset) {
                // Change parameter values and call login again once
            }
        }
    });
}