static void Main() { // disable TDLib log Td.Client.Execute(new TdApi.SetLogVerbosityLevel(0)); if (Td.Client.Execute(new TdApi.SetLogStream(new TdApi.LogStreamFile("tdlib.log", 1 << 27))) is TdApi.Error) { throw new System.IO.IOException("Write access to the current directory is required"); } // create Td.Client _client = CreateTdClient(); // test Client.Execute _defaultHandler.OnResult(Td.Client.Execute(new TdApi.GetTextEntities("@telegram /test_command https://telegram.org telegram.me @gif @test"))); // main loop while (!_quiting) { // await authorization _gotAuthorization.Reset(); _gotAuthorization.WaitOne(); _client.Send(new TdApi.GetChats(null, Int64.MaxValue, 0, 100), _defaultHandler); // preload main chat list while (_haveAuthorization) { GetCommand(); } } }
private static Td.Client CreateTdClient() { Td.Client result = Td.Client.Create(new UpdatesHandler()); new Thread(() => { Thread.CurrentThread.IsBackground = true; result.Run(); }).Start(); return(result); }
static void Main() { // disable TDLib log Td.Client.Execute(new TdApi.SetLogVerbosityLevel(0)); if (Td.Client.Execute(new TdApi.SetLogStream(new TdApi.LogStreamFile("tdlib.log", 1 << 27, false))) is TdApi.Error) { throw new System.IO.IOException("Write access to the current directory is required"); } new Thread(() => { Thread.CurrentThread.IsBackground = true; Td.Client.Run(); }).Start(); // create Td.Client _client = CreateTdClient(); // test Client.Execute _defaultHandler.OnResult(Td.Client.Execute(new TdApi.GetTextEntities("@telegram /test_command https://telegram.org telegram.me @gif @test"))); // main loop while (!_needQuit) { // await authorization _gotAuthorization.Reset(); _gotAuthorization.WaitOne(); _client.Send(new TdApi.LoadChats(null, 100), _defaultHandler); // preload main chat list while (_haveAuthorization) { GetCommand(); } } while (!_canQuit) { Thread.Sleep(1); } }
private static void OnAuthorizationStateUpdated(TdApi.AuthorizationState authorizationState) { if (authorizationState != null) { _authorizationState = authorizationState; } if (_authorizationState is TdApi.AuthorizationStateWaitTdlibParameters) { TdApi.TdlibParameters parameters = new TdApi.TdlibParameters(); parameters.DatabaseDirectory = "tdlib"; parameters.UseMessageDatabase = true; parameters.UseSecretChats = true; parameters.ApiId = 94575; parameters.ApiHash = "a3406de8d171bb422bb6ddf3bbd800e2"; parameters.SystemLanguageCode = "en"; parameters.DeviceModel = "Desktop"; parameters.ApplicationVersion = "1.0"; parameters.EnableStorageOptimizer = true; _client.Send(new TdApi.SetTdlibParameters(parameters), new AuthorizationRequestHandler()); } else if (_authorizationState is TdApi.AuthorizationStateWaitEncryptionKey) { _client.Send(new TdApi.CheckDatabaseEncryptionKey(), new AuthorizationRequestHandler()); } else if (_authorizationState is TdApi.AuthorizationStateWaitPhoneNumber) { string phoneNumber = ReadLine("Please enter phone number: "); _client.Send(new TdApi.SetAuthenticationPhoneNumber(phoneNumber, null), new AuthorizationRequestHandler()); } else if (_authorizationState is TdApi.AuthorizationStateWaitOtherDeviceConfirmation state) { Console.WriteLine("Please confirm this login link on another device: " + state.Link); } else if (_authorizationState is TdApi.AuthorizationStateWaitCode) { string code = ReadLine("Please enter authentication code: "); _client.Send(new TdApi.CheckAuthenticationCode(code), new AuthorizationRequestHandler()); } else if (_authorizationState is TdApi.AuthorizationStateWaitRegistration) { string firstName = ReadLine("Please enter your first name: "); string lastName = ReadLine("Please enter your last name: "); _client.Send(new TdApi.RegisterUser(firstName, lastName), new AuthorizationRequestHandler()); } else if (_authorizationState is TdApi.AuthorizationStateWaitPassword) { string password = ReadLine("Please enter password: "******"Logging out"); } else if (_authorizationState is TdApi.AuthorizationStateClosing) { _haveAuthorization = false; Print("Closing"); } else if (_authorizationState is TdApi.AuthorizationStateClosed) { Print("Closed"); _client.Dispose(); // _client is closed and native resources can be disposed now if (!_quiting) { _client = CreateTdClient(); // recreate _client after previous has closed } } else { Print("Unsupported authorization state:" + _newLine + _authorizationState); } }
/// <summary> /// initializes api instance /// </summary> /// <param name="debugMode">determines if software is in debug mode</param> /// <param name="token">cancellation token to stop tasks</param> internal void Initialize(bool debugMode, CancellationToken token) { #region tdlib log file path // file to write tdlib log in string tdlibLogFilePath = $"tdlibLog-{_setting.name}.txt"; // setting log file path if (tdLib.Client.Execute(new tdApi.SetLogStream(new tdApi.LogStreamFile(tdlibLogFilePath, 1 << 27, false))) is tdApi.Error) { throw new System.IO.IOException("Write access to the current directory is required"); } #endregion tdlib log file path // disabling log if software is not in debug mode if (!debugMode) { // fatal errors only tdLib.Client.Execute(new tdApi.SetLogVerbosityLevel(0)); } #region adding some global handlers addGlobalHandler(typeof(UpdateAuthorizationState), async(obj) => { // casting update AuthorizationState authorizationState = (obj as UpdateAuthorizationState).AuthorizationState; if (authorizationState is AuthorizationStateClosed) { _authorizationState = Enum.AuhtorizationState.Closed; } else if (authorizationState is AuthorizationStateClosing) { _authorizationState = Enum.AuhtorizationState.Closing; } else if (authorizationState is AuthorizationStateLoggingOut) { _authorizationState = Enum.AuhtorizationState.LoggingOut; } else if (authorizationState is AuthorizationStateReady) { _authorizationState = Enum.AuhtorizationState.Ready; // check if function to call when state is ready is set if (onReady is null) { throw new Exception("There is no function call when authentication is ready is not set"); } // invoking function onReady.Invoke(this); } else if (authorizationState is AuthorizationStateWaitEncryptionKey) { _authorizationState = Enum.AuhtorizationState.BackgroundActions; await executeCommand(new CheckDatabaseEncryptionKey(), typeof(Ok)); #region set proxy // check if proxy setting exists if (_setting.proxy != null) { ProxyType type; switch (_setting.proxy.type) { case Enum.ProxyType.MTProto: type = new ProxyTypeMtproto(); break; case Enum.ProxyType.Socks5: type = new ProxyTypeSocks5(); break; default: type = new ProxyTypeHttp(); break; } // sending and enabling proxy var res = await executeCommand(new AddProxy(_setting.proxy.ip, _setting.proxy.port, true, type), typeof(Proxy)); if (res.status == Enum.ResponseStatus.Success) { Logger.Debug("proxy enabled successfully"); } else { Logger.Debug("proxy enabling failed, => {0}", res.obj.JSONSerialize()); } } else { // disabling proxy var res = await executeCommand(new DisableProxy()); if (res.status == Enum.ResponseStatus.Success) { Logger.Debug("proxy disabled successfully"); } else { Logger.Debug("proxy enabdisabledling failed, => {0}", res.obj.JSONSerialize()); } } #endregion set proxy } else if (authorizationState is AuthorizationStateWaitOtherDeviceConfirmation) { _authorizationState = Enum.AuhtorizationState.BackgroundActions; } else if (authorizationState is AuthorizationStateWaitPhoneNumber) { _authorizationState = Enum.AuhtorizationState.WaitingForPhoneNumber; // check if function to get phone number is set if (onPhoneNumberRequired is null) { throw new Exception("There is no function to get phone number from"); } runLocked(async() => { // gathering phone number string phoneNumber = onPhoneNumberRequired(_setting.name); await executeCommand(new SetAuthenticationPhoneNumber(phoneNumber, new PhoneNumberAuthenticationSettings() { AllowFlashCall = true, AllowSmsRetrieverApi = true })); }); } else if (authorizationState is AuthorizationStateWaitCode) { _authorizationState = Enum.AuhtorizationState.WaitingForVerificationCode; // check if function to get phone number is set if (onVerificationCodeRequired is null) { throw new Exception("There is no function to get verification code from"); } runLocked(async() => { // gathering verification code form user provided function string code = onVerificationCodeRequired(_setting.name); await executeCommand(new CheckAuthenticationCode(code)); }); } else if (authorizationState is AuthorizationStateWaitPassword) { _authorizationState = Enum.AuhtorizationState.WaitingForVerificationPassword; // check if function to get password is set if (onPasswordRequired is null) { throw new Exception("There is no function to get password from"); } runLocked(async() => { // gathering password form user provided function string password = onPasswordRequired(_setting.name); await executeCommand(new CheckAuthenticationPassword(password)); }); } else if (authorizationState is AuthorizationStateWaitTdlibParameters) { _authorizationState = Enum.AuhtorizationState.BackgroundActions; var res = await executeCommand(new SetTdlibParameters(new TdlibParameters() { ApiHash = _setting.api_hash, ApiId = _setting.api_id, ApplicationVersion = "1.3.1", DeviceModel = "Desktop", SystemLanguageCode = "en", UseSecretChats = true, UseMessageDatabase = true, UseChatInfoDatabase = true, EnableStorageOptimizer = true, DatabaseDirectory = $"TDLibCoreData-{_setting.name}" }), typeof(Ok)); } else { _authorizationState = Enum.AuhtorizationState.InvalidData; } }); addGlobalHandler(typeof(UpdateConnectionState), (obj) => { // casting update ConnectionState update = (obj as UpdateConnectionState).State; if (update is ConnectionStateConnecting) { _connectionState = Enum.ConnectionState.Connecting; } else if (update is ConnectionStateConnectingToProxy) { _connectionState = Enum.ConnectionState.ConnectingToProxy; } else if (update is ConnectionStateReady) { _connectionState = Enum.ConnectionState.Connected; } else if (update is ConnectionStateUpdating) { _connectionState = Enum.ConnectionState.Updating; } else if (update is ConnectionStateWaitingForNetwork) { _connectionState = Enum.ConnectionState.WaitingForNetwork; } else { _connectionState = Enum.ConnectionState.InvalidData; } }); #endregion adding some global handlers // we run core only if it's first time in whole application if (!tdlibInitialized) { // starting client _ = Task.Factory.StartNew(() => { // we run core tdLib.Client.Run(); }, token); // preventing from double running tdlib tdlibInitialized = true; } // generating clinet instance _client = tdLib.Client.Create(_responseHandler); _initialized = true; }
private static void OnAuthorizationStateUpdated(TdApi.AuthorizationState authorizationState) { if (authorizationState != null) { _authorizationState = authorizationState; } if (_authorizationState is TdApi.AuthorizationStateWaitTdlibParameters) { TdApi.TdlibParameters parameters = new TdApi.TdlibParameters(); parameters.DatabaseDirectory = "tdlib"; parameters.UseMessageDatabase = true; parameters.UseSecretChats = true; parameters.ApiId = 94575; parameters.ApiHash = "a3406de8d171bb422bb6ddf3bbd800e2"; parameters.SystemLanguageCode = "en"; parameters.DeviceModel = "Desktop"; parameters.SystemVersion = "Unknown"; parameters.ApplicationVersion = "1.0"; parameters.EnableStorageOptimizer = true; _client.Send(new TdApi.SetTdlibParameters(parameters), new AuthorizationRequestHandler()); } else if (_authorizationState is TdApi.AuthorizationStateWaitEncryptionKey) { _client.Send(new TdApi.CheckDatabaseEncryptionKey(), new AuthorizationRequestHandler()); } else if (_authorizationState is TdApi.AuthorizationStateWaitPhoneNumber) { string phoneNumber = ReadLine("Please enter phone number: "); _client.Send(new TdApi.SetAuthenticationPhoneNumber(phoneNumber, false, false), new AuthorizationRequestHandler()); } else if (_authorizationState is TdApi.AuthorizationStateWaitCode) { string code = ReadLine("Please enter authentication code: "); _client.Send(new TdApi.CheckAuthenticationCode(code, "", ""), new AuthorizationRequestHandler()); } else if (_authorizationState is TdApi.AuthorizationStateWaitPassword) { string password = ReadLine("Please enter password: "******"Logging out"); } else if (_authorizationState is TdApi.AuthorizationStateClosing) { _haveAuthorization = false; Print("Closing"); } else if (_authorizationState is TdApi.AuthorizationStateClosed) { Print("Closed"); if (!_quiting) { _client = CreateTdClient(); // recreate _client after previous has closed } } else { Print("Unsupported authorization state:" + _newLine + _authorizationState); } }
public void OnAuthorizationStateUpdated(TdApi.AuthorizationState authorizationState) { if (authorizationState != null) { _authorizationState = authorizationState; } if (_authorizationState is TdApi.AuthorizationStateWaitTdlibParameters) { TdApi.TdlibParameters parameters = new TdApi.TdlibParameters(); parameters.DatabaseDirectory = _databaseDirectory; parameters.UseMessageDatabase = _useMessageDatabase; parameters.UseSecretChats = _useSecretChats; parameters.ApiId = _apiId; parameters.ApiHash = _apiHash; parameters.SystemLanguageCode = _systemLanguageCode; parameters.DeviceModel = _deviceModel; parameters.SystemVersion = _systemVersion; parameters.ApplicationVersion = _applicationVersion; parameters.EnableStorageOptimizer = _enableStorageOptimizer; _client.Send(new TdApi.SetTdlibParameters(parameters), new AuthorizationRequestHandler()); OnAuthorizationStateUpdatedEvent(EnumAuthorization.TdlibParameters); } else if (_authorizationState is TdApi.AuthorizationStateWaitEncryptionKey) { _client.Send(new TdApi.CheckDatabaseEncryptionKey(), new AuthorizationRequestHandler()); OnAuthorizationStateUpdatedEvent(EnumAuthorization.EncryptionKey); } else if (_authorizationState is TdApi.AuthorizationStateWaitPhoneNumber) { OnAuthorizationStateUpdatedEvent(EnumAuthorization.WaitPhoneNumber); } else if (_authorizationState is TdApi.AuthorizationStateWaitCode) { OnAuthorizationStateUpdatedEvent(EnumAuthorization.WaitCode); } else if (_authorizationState is TdApi.AuthorizationStateWaitPassword) { OnAuthorizationStateUpdatedEvent(EnumAuthorization.WaitPassword); } else if (_authorizationState is TdApi.AuthorizationStateReady) { _haveAuthorization = true; _gotAuthorization.Set(); OnAuthorizationStateUpdatedEvent(EnumAuthorization.Ready); } else if (_authorizationState is TdApi.AuthorizationStateLoggingOut) { _haveAuthorization = false; Print("Logging out"); OnAuthorizationStateUpdatedEvent(EnumAuthorization.LoggingOut); } else if (_authorizationState is TdApi.AuthorizationStateClosing) { _haveAuthorization = false; Print("Closing"); OnAuthorizationStateUpdatedEvent(EnumAuthorization.Closing); } else if (_authorizationState is TdApi.AuthorizationStateClosed) { Print("Closed"); if (!_quiting) { _client = CreateTdClient(); // recreate _client after previous has closed } OnAuthorizationStateUpdatedEvent(EnumAuthorization.Closed); } else { Print("Unsupported authorization state:" + _newLine + _authorizationState); OnAuthorizationStateUpdatedEvent(EnumAuthorization.None); } OnAuthorizationStateUpdatedEvent(EnumAuthorization.None); }
static TDLibClient() { _client = CreateTdClient(); }