Skip to content

TDLib, Blocking after authorization #3466

@dafsas3

Description

@dafsas3

(Translation with the help of a translator)

Hello everyone.
I'm not very experienced in development, but I decided to create my own Telegram software using TDLib.
After authorizing the software on my account, it's almost immediately permanently frozen...
The project only implements the authorization method and that's it.
I'm using my own api_id and hash.

Code:

using System;
using System.Threading.Tasks;
using TdLib;
using static TdLib.TdApi;
using static TdLib.TdApi.AuthorizationState;

namespace ConsoleApp15
{

internal class Program
{


    private static TdApi.AuthorizationState _state = null;
    private static TdClient _client = null;
    private static volatile string _currentPrompt = null;
    private static volatile bool _haveAuthorization = false;
    private static volatile bool _needQuit = false;
    private static volatile bool _canQuit = false;
    private static readonly string _newLine = Environment.NewLine;
    private static volatile AutoResetEvent _gotAuthorization = new AutoResetEvent(false);



    static async Task Main()
    {
        Console.OutputEncoding = System.Text.Encoding.UTF8;

     
        _client = CreateTdClient();

       
        await _client.ExecuteAsync(new TdApi.SetLogVerbosityLevel { NewVerbosityLevel = 1 });

      
        Console.WriteLine("TDLib клиент запущен. Ожидание авторизации...");

     
        while (!_haveAuthorization)
        {
            await Task.Delay(500);
        }
   

        Console.WriteLine("✅ Авторизация успешно завершена!");
    }

    private static TdClient CreateTdClient()
    {
        var client = new TdClient();

        
        client.UpdateReceived += async (_, update) =>
        {      
            if (update is TdApi.Update updateObj)
            {           
                var property = updateObj.GetType().GetProperty("AuthorizationState");
                if (property != null)
                {
                    var authState = property.GetValue(updateObj) as TdApi.AuthorizationState;
                    if (authState != null)
                    {
                        await OnAuthorizationStateUpdate(authState);
                    }
                }
            }
            else
            {
                var prop = update.GetType().GetProperty("AuthorizationState");
                if (prop != null)
                {
                    var authState = prop.GetValue(update) as TdApi.AuthorizationState;
                    if (authState != null)
                    {
                        await OnAuthorizationStateUpdate(authState);
                    }
                }
            }
        };

        return client;
    }

    private static string ReadLine(string str)
    {
        Console.Write(str);
        _currentPrompt = str;
        var result = Console.ReadLine();
        _currentPrompt = null;
        return result;
    }

    private static void Print(string str)
    {
        if (_currentPrompt != null)
        {
            Console.WriteLine();
        }
        Console.WriteLine(str);
        if (_currentPrompt != null)
        {
            Console.Write(_currentPrompt);
        }
    }

    private static async Task OnAuthorizationStateUpdate(TdApi.AuthorizationState state)
    {
        if (state != null)
            _state = state;

        switch (_state)
        {
            case TdApi.AuthorizationState.AuthorizationStateWaitTdlibParameters:
                Console.WriteLine("Устанавливаем параметры TDLib...");
                await _client.ExecuteAsync(new TdApi.SetTdlibParameters
                {
                    DatabaseDirectory = "tdlib",
                    UseMessageDatabase = true,
                    UseSecretChats = true,
                    ApiId = text, 
                    ApiHash = "text",
                    SystemLanguageCode = "en",
                    DeviceModel = "Desktop",
                    ApplicationVersion = "1.0"
                });
                break;

            case TdApi.AuthorizationState.AuthorizationStateWaitPhoneNumber:
                string phone = ReadLine("Введите номер телефона: ");
                await _client.ExecuteAsync(new TdApi.SetAuthenticationPhoneNumber
                {
                    PhoneNumber = phone
                });
                break;

            case TdApi.AuthorizationState.AuthorizationStateWaitCode:
                string code = ReadLine("Введите код из Telegram: ");
                await _client.ExecuteAsync(new TdApi.CheckAuthenticationCode
                {
                    Code = code
                });
                break;

            case TdApi.AuthorizationState.AuthorizationStateWaitPassword:
                string pass = ReadLine("Введите пароль двухфакторки: ");
                await _client.ExecuteAsync(new TdApi.CheckAuthenticationPassword
                {
                    Password = pass
                });
                break;

            case TdApi.AuthorizationState.AuthorizationStateReady:
                _haveAuthorization = true;
                _gotAuthorization.Set();
                Console.WriteLine("✅ Авторизация завершена.");
                break;

            case TdApi.AuthorizationState.AuthorizationStateClosed:
                Console.WriteLine("❌ TDLib закрыт.");
                _canQuit = true;
                break;

            default:
                Console.WriteLine($"⚠️ Неизвестное состояние: {_state.GetType().Name}");
                break;
        }
    }
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions