TdSharp .NET Wrapper for TDLib

repository·master·Indexed 42 days ago

https://github.com/egramtel/tdsharp

A .NET wrapper for the Telegram Database Library (TDLib) supporting .NET Standard 2.0 and later. It provides a strongly typed asynchronous API via TdClient and a raw JSON-based client via TdJsonClient for interacting with Telegram.

Tokens
1.7K
Snippets
9
Records
10
Agent score
4%

What's inside TdSharp

  1. Override native bindings with ITdLibBindings

    master
    By default, TdSharp automatically detects the platform and selects the appropriate native bindings. If you need to provide a custom implementation (for example, when using Xamarin), implement the ITdLibBindings interface and pass your implementation to the TdClient constructor.
  2. Configure native TDLib binaries

    master

    The TDLib package does not include the native TDLib binaries as a direct dependency. You have two options for providing the native library at runtime:

    1. Use precompiled artifacts (Recommended): Install the tdlib.native NuGet package. This is the main cross-platform package.
    2. Build from source: Build TDLib yourself following the official TDLib build instructions and place the resulting library in your project's output directory:
      • Windows: tdjson.dll (optionally include other DLLs from the build directory for OpenSSL and ZLib).
      • MacOS: libtdjson.dylib
      • Linux: libtdjson.so
    # Recommended: Install precompiled native artifacts
    Install-Package tdlib.native
  3. Use strongly typed APIs with TdClient

    master

    For most use cases, use TdClient. This client provides generated classes for all TDLib objects and functions, handling JSON serialization and deserialization automatically. You can execute functions asynchronously using ExecuteAsync or via provided extension methods. Errors returned by TDLib are thrown as ErrorException objects.

    using TdLib;
    
    using (var client = new TdClient())
    {
        try
        {
            // Option 1: Asynchronously execute function using ExecuteAsync
            TdApi.Ok ok = await client.ExecuteAsync(new TdApi.SetAuthenticationPhoneNumber
            {
                PhoneNumber = phoneNumber
            });
    
            // Option 2: Use the generated extension method
            ok = await client.SetAuthenticationPhoneNumberAsync(phoneNumber);
        }
        catch (ErrorException e)
        {
            // Access the underlying TdApi.Error
            TdApi.Error error = e.Error;
            // handle error...
        }
    }
  4. Use the TdJsonClient for JSON-based communication

    master

    The TdJsonClient is a wrapper around the native JSON APIs. Use this client if you prefer to send and receive data as raw JSON strings rather than using strongly typed objects.

    using TdLib;
    
    var json = ""; // your json data
    double timeout = 1.0; // 1 second
    
    using (var jsonClient = new TdJsonClient())
    {
        jsonClient.Send(json); // send request
        var result = jsonClient.Receive(timeout); // receive response
    }
  5. Use the TdApi.Client for TDLib interactions

    master

    The TdApi.Client is the base class for interacting with the TDLib JSON interface. It provides methods to send functions to the TDLib engine and receive updates. You can use it to execute requests synchronously, asynchronously, or via a fire-and-forget Send method. It also exposes an UpdateReceived event that triggers whenever TDLib sends an update.

    // Example usage pattern for a TdApi.Client implementation
    // Note: This code assumes an implementation of Client is provided by the library
    
    // 1. Subscribe to updates
    client.UpdateReceived += (sender, update) => {
        // Handle TDLib updates here
    };
    
    // 2. Execute a request asynchronously
    var result = await client.ExecuteAsync<TdApi.GetAuthorizationState>(() => new TdApi.GetAuthorizationState());
    
    // 3. Execute a request synchronously
    var syncResult = client.Execute(new TdApi.GetAuthorizationState());
    
    // 4. Send a request without waiting for a result (fire-and-forget)
    client.Send(() => new TdApi.GetAuthorizationState());
  6. Execute TDLib functions with ExecuteAsync<TResult>

    master

    Use ExecuteAsync<TResult>(Function<TResult> function) to send a TDLib function to the engine and await its response. This is the recommended way to perform non-blocking operations. The generic type TResult must inherit from TdApi.Object.

    public abstract Task<TResult> ExecuteAsync<TResult>(Function<TResult> function)
        where TResult : Object;
  7. Execute TDLib functions with Execute<TResult>

    master

    Use Execute<TResult>(Function<TResult> function) to send a TDLib function to the engine and wait for the result synchronously. The generic type TResult must inherit from TdApi.Object.

    public abstract TResult Execute<TResult>(Function<TResult> function)
        where TResult : Object;
  8. Send TDLib functions with Send<TResult>

    master

    Use Send<TResult>(Function<TResult> function) to send a TDLib function to the engine without waiting for a return value. This is useful for fire-and-forget operations where the response is not immediately required by the caller.

    public abstract void Send<TResut>(Function<TResut> function);
  9. Handle TDLib updates via UpdateReceived

    master

    The UpdateReceived event is triggered whenever the TDLib engine sends an update to the client. Subscribe to this event to react to state changes or incoming data from the TDLib server.

    public abstract event EventHandler<TdApi.Update> UpdateReceived;