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();
}
}
}
Here is my code:
And then I get an error:
What am I doing wrong?