sochix / TLSharp

Telegram client library implemented in C#
1.01k stars 380 forks source link

await client.ConnectAsync(); #945

Closed bliznec-89 closed 4 years ago

bliznec-89 commented 4 years ago

Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using TLSharp.Core;
using TeleSharp.TL;

namespace Tlg
{
    internal static class Program
    {
        static async Task AuthUser()
        {
            var apiId = api_id;
            var apiHash = "hash";
            var phoneNum = "phone";
            TelegramClient client = new TelegramClient(apiId, apiHash);
            await client.ConnectAsync();
            Console.WriteLine(client.IsConnected);
            var isAuth = client.IsUserAuthorized();
            Console.WriteLine(@"Файл авторизации существует: {0}", isAuth.ToString());
            if (!isAuth) // Если не найден файл session.dat, то пытаемся авторизоваться
            {
                TLUser user;
                try
                {
                    var hash = await client.SendCodeRequestAsync(phoneNum);
                    Console.WriteLine("Введите код из SMS:");
                    var code = Console.ReadLine();
                    try
                    {
                        user = await client.MakeAuthAsync(phoneNum, hash, code);
                    }
                    catch (TLSharp.Core.Exceptions.CloudPasswordNeededException)
                    {
                        // На данном аккаунте включена двухфакторная авторизация
                        var passwordSettings = await client.GetPasswordSetting();
                        Console.WriteLine("Введите пароль:");
                        var passwordStr = Console.ReadLine();
                        user = await client.MakeAuthWithPasswordAsync(passwordSettings, passwordStr);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    return;
                }
                Console.WriteLine(@"Пользователь '{user?.FirstName}' авторизован");
                isAuth = client.IsUserAuthorized();
                Console.WriteLine(@"Файл авторизации существует: {isAuth}");
            }
            try
            {
                // В качестве демонстрации работы узнаем количество контактов у пользователя
                var contacts = await client.GetContactsAsync();
                Console.WriteLine(@"У вас {contacts.Users.Count} контактов");
            }
            catch (InvalidOperationException ex) when (ex.Message == "AUTH_KEY_UNREGISTERED")
            {
                // Файл session.dat существует, но для сервера эта сессия уже мертва
                Console.WriteLine("Пользователь воспользовался другим устройством чтобы закрыть текущую сессию.");
                Console.WriteLine("Удалите файл session.dat и повторите попытку.");
            }
        }
        private static async Task Main()
        {
            await AuthUser();
            Console.ReadKey();
        }
    }
}

And then I get an error:

Error

What am I doing wrong?

bliznec-89 commented 4 years ago

Fixed, thx u =)

knocte commented 4 years ago

@bliznec-89 how did you fix it?

ahron33 commented 4 years ago

@bliznec-89 how did you fix it?

did you fixed it?