.NET WTelegramClient in-memory data store for Saved session

41 Views Asked by At

I'm creating a api telegram app that uses this library telegra-api

The issue is that it seems that the creating Client() is taking so much resources. For now I've resolved this with Factory Pattern but in general it seems like having more then few users would be a bottleneck for whole application.

namespace TelegramMicroservice.Services.Telegram
{
    public class WTelegramClientFactory : IWTelegramClientFactory
    {
        const string ApiId = "";
        const string ApiHash = "";

        private readonly object _lock = new();
        private readonly Dictionary<string, WTelegram.Client> _clients = new();

        public Client GetOrCreateClient(string phoneNumber)
        {
            lock (_lock)
            {
                if (!_clients.TryGetValue(phoneNumber, out var client))
                {
                    client = CreateClient(phoneNumber);
                    _clients[phoneNumber] = client;
                }
                return client;
            }
        }
        private Client CreateClient(string phoneNumber)
        {
            string Config(string what)
            {
                return what switch
                {
                    "api_id" => ApiId,
                    "api_hash" => ApiHash,
                    "phone_number" => phoneNumber,
                    _ => null,
                };
            }

            return new WTelegram.Client(Config);
        }
    }
}

Is it possible to store saved session in a more efficient way? The plan is at the end to use it in cloud and store clients in the in-memory data store for example "azure redis cache".

1

There are 1 best solutions below

0
Wizou On

WTelegramClient documentation shows how to provide a specific SessionStore (as a custom Stream) on the constructor in order to store it anywhere you want.

It includes a demo of storing sessions in PostgreSQL database.

https://wiz0u.github.io/WTelegramClient/EXAMPLES#sessionStore