Пример #1
0
        public static async Task <TdClient> NewClientAsync()
        {
            try
            {
                var client = new TdClient();
                await client.ExecuteAsync(new TdApi.SetTdlibParameters
                {
                    Parameters = new TdApi.TdlibParameters
                    {
                        ApiId              = ApiId,
                        ApiHash            = ApiHash,
                        ApplicationVersion = "1.6.0",
                        DeviceModel        = "VPS",
                        SystemLanguageCode = "en",
                        SystemVersion      = "Win Server 2016"
                    }
                });

                await client.ExecuteAsync(new TdApi.CheckDatabaseEncryptionKey());

                return(client);
            }
            catch (TdException e)
            {
                var error = e.Error;
                Information.AppendLine("NewClient-1" + error.Message);
            }
            catch (Exception ex)
            {
                Information.AppendLine("NewClient-2" + ex.Message);
            }

            return(null);
        }
Пример #2
0
 public void SendPhone(string phone)
 {
     if (this.authorizationState is TdApi.AuthorizationState.AuthorizationStateWaitPhoneNumber)
     {
         client.ExecuteAsync(new TdApi.SetAuthenticationPhoneNumber
         {
             PhoneNumber = phone,
             Settings    = new TdApi.PhoneNumberAuthenticationSettings()
             {
                 AllowFlashCall       = false,
                 IsCurrentPhoneNumber = true
             }
         });
     }
 }
Пример #3
0
        public async Task Execute_WhenErrorExpected_ThrowsTdException()
        {
            using (var client = new TdClient())
            {
                TdException exception = null;

                try
                {
                    await client.ExecuteAsync(new TdApi.TestReturnError
                    {
                        Error = new TdApi.Error
                        {
                            Code    = 0,
                            Message = "Error"
                        }
                    });
                }
                catch (TdException e)
                {
                    exception = e;
                }

                Assert.NotNull(exception);
                Assert.NotNull(exception.Error);
            }
        }
Пример #4
0
        private async IAsyncEnumerable <TdApi.Chat> GetChannels(TdClient client, long offsetOrder = long.MaxValue,
                                                                long offsetId = 0, int limit = 1000)
        {
            var chats = await client.ExecuteAsync(new TdApi.GetChats
            {
                OffsetOrder = offsetOrder, Limit = limit, OffsetChatId = offsetId
            });

            foreach (var chatId in chats.ChatIds)
            {
                var chat = await client.ExecuteAsync(new TdApi.GetChat {
                    ChatId = chatId
                });

                yield return(chat);
            }
        }
Пример #5
0
        public async Task Execute_WhenEmptyCallPassed_ReturnsOk()
        {
            using (var client = new TdClient())
            {
                var result = await client.ExecuteAsync(new TdApi.TestCallEmpty());

                Assert.NotNull(result);
            }
        }
Пример #6
0
        public static async IAsyncEnumerable <TdApi.Chat> GetChannels(long offsetOrder = long.MaxValue, long offsetId = 0, int limit = 1000)
        {
            var chats = await _client.ExecuteAsync(new TdApi.GetChats {
                OffsetOrder = offsetOrder, Limit = limit, OffsetChatId = offsetId
            });

            foreach (var chatId in chats.ChatIds)
            {
                var chat = await _client.ExecuteAsync(new TdApi.GetChat {
                    ChatId = chatId
                });

                if (chat.Type is TdApi.ChatType.ChatTypeSupergroup || chat.Type is TdApi.ChatType.ChatTypeBasicGroup || chat.Type is TdApi.ChatType.ChatTypePrivate)
                {
                    yield return(chat);
                }
            }
        }
Пример #7
0
        public async Task Execute_WhenNetworkCallIsMade_ReturnsOk()
        {
            using (var client = new TdClient())
            {
                var result = await client.ExecuteAsync(new TdApi.TestNetwork());

                Assert.NotNull(result);
            }
        }
Пример #8
0
        public async Task Dispose_WhenCalled_DoesNotThrowException()
        {
            var client = new TdClient();

            // do some stuff
            await client.ExecuteAsync(new TdApi.TestCallEmpty());

            // dispose client from other thread
            await Task.Run(() => client.Dispose());
        }
Пример #9
0
        public async Task Dispose_WhenCalledOnDifferentClients_DoesNotThrowException()
        {
            using (var client1 = new TdClient())
                using (var client2 = new TdClient())
                    using (var client3 = new TdClient())
                    {
                        // do some stuff
                        await client1.ExecuteAsync(new TdApi.TestCallEmpty());

                        await client2.ExecuteAsync(new TdApi.TestCallEmpty());

                        await client3.ExecuteAsync(new TdApi.TestCallEmpty());
                    }
        }
Пример #10
0
        public async Task Execute_WhenStringPassed_ReturnsTheSameString()
        {
            using (var client = new TdClient())
            {
                var arg    = "test";
                var result = await client.ExecuteAsync(new TdApi.TestCallString
                {
                    X = arg
                });

                Assert.NotNull(result);
                Assert.NotNull(result.Value);
                Assert.Equal(arg, result.Value);
            }
        }
Пример #11
0
        public async Task Execute_WhenStringArrayPassed_ReturnsTheSameArray()
        {
            using (var client = new TdClient())
            {
                var arg    = new[] { "foo", "bar" };
                var result = await client.ExecuteAsync(new TdApi.TestCallVectorString
                {
                    X = arg
                });

                Assert.NotNull(result);
                Assert.NotNull(result.Value);
                Assert.Equal(arg, result.Value);
            }
        }
Пример #12
0
        public async Task Execute_WhenByteArrayPassed_ReturnsTheSameByteArray()
        {
            using (var client = new TdClient())
            {
                var arg    = new byte[] { 1, 2, 3 };
                var result = await client.ExecuteAsync(new TdApi.TestCallBytes
                {
                    X = arg
                });

                Assert.NotNull(result);
                Assert.NotNull(result.Value);
                Assert.Equal(arg, result.Value);
            }
        }
Пример #13
0
        public async Task Execute_WhenErrorExpected_ThrowsTdException()
        {
            using (var client = new TdClient())
            {
                TdException exception = null;
                try
                {
                    await client.ExecuteAsync(new TdApi.TestUseError());
                }
                catch (TdException e)
                {
                    exception = e;
                }

                Assert.NotNull(exception);
                Assert.NotNull(exception.Error);
            }
        }
Пример #14
0
        public async Task Execute_WhenUpdateTriggered_FiresEvent()
        {
            using (var client = new TdClient())
            {
                var tcs = new TaskCompletionSource <TdApi.Update>();

                void Handler(object sender, TdApi.Update update)
                {
                    tcs.SetResult(update);
                    client.UpdateReceived -= Handler;
                }

                client.UpdateReceived += Handler;

#pragma warning disable 4014
                client.ExecuteAsync(new TdApi.TestUseUpdate());
#pragma warning restore 4014

                var result = await tcs.Task;

                Assert.NotNull(result);
            }
        }
Пример #15
0
        public static BaseBotClient FromToken(string token)
        {
            var tdClient = new TdClient();
            var bot      = new BaseBotClient
            {
                Token  = token,
                Client = tdClient,
            };

            tdClient.Bindings.SetLogVerbosityLevel(0);

            tdClient.UpdateReceived += async(sender, update) =>
            {
                switch (update)
                {
                case TdApi.Update.UpdateOption option:
                    /*await tdClient.ExecuteAsync(new TdApi.SetOption
                     * {
                     *  DataType = option.DataType,
                     *  Extra = option.Extra,
                     *  Name = option.Name,
                     *  Value = option.Value,
                     * });*/
                    break;

                case TdApi.Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(TdApi.AuthorizationState.AuthorizationStateWaitTdlibParameters):
                    Directory.CreateDirectory($"bots/{bot.RawId}");

                    await tdClient.ExecuteAsync(new TdApi.SetTdlibParameters
                    {
                        Parameters = new TdApi.TdlibParameters
                        {
                            ApiId              = 94575,
                            ApiHash            = "a3406de8d171bb422bb6ddf3bbd800e2",
                            ApplicationVersion = "1.3.0",
                            DeviceModel        = "PC",
                            SystemLanguageCode = "en",
                            SystemVersion      = "Win 10.0",
                            DatabaseDirectory  = $"bots/{bot.RawId}",
                        }
                    });

                    bot._initialized.Set();
                    break;

                case TdApi.Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(TdApi.AuthorizationState.AuthorizationStateWaitEncryptionKey):
                    await tdClient.ExecuteAsync(new TdApi.CheckDatabaseEncryptionKey());

                    break;

                case TdApi.Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(TdApi.AuthorizationState.AuthorizationStateWaitPhoneNumber):
                    await tdClient.ExecuteAsync(new TdApi.CheckAuthenticationBotToken {
                        Token = token
                    });

                    break;

                case TdApi.Update.UpdateUser updateUser:
                    break;

                case TdApi.Update.UpdateConnectionState updateConnectionState when updateConnectionState.State.GetType() == typeof(TdApi.ConnectionState.ConnectionStateReady):
                    break;

                case TdApi.Update.UpdateNewMessage newMessage:
                    if (bot.LastUpdateId.TryGetValue(UpdateTypeEnum.NewMessage, out var updateId))
                    {
                        if (bot.Updates[UpdateTypeEnum.NewMessage].Count > MaxStoredUpdatesCount)
                        {
                            bot.Updates[UpdateTypeEnum.NewMessage].RemoveAt(0);
                        }

                        bot.Updates[UpdateTypeEnum.NewMessage].Add(updateId, newMessage);
                        bot.LastUpdateId.TryUpdate(UpdateTypeEnum.NewMessage, updateId + 1, updateId);
                    }
                    break;

                default:
                    ;     // add a breakpoint here to see other events
                    break;
                }
            };

            return(bot);
        }
Пример #16
0
        static async Task Main(string[] args)
        {
            TdLog.SetVerbosityLevel(0);
            _client = new TdClient();

            _client.UpdateReceived += async(sender, update) =>
            {
                switch (update)
                {
                case TdApi.Update.UpdateOption option:
                    await _client.ExecuteAsync(new TdApi.SetOption
                    {
                        DataType = option.DataType,
                        Extra    = option.Extra,
                        Name     = option.Name,
                        Value    = option.Value
                    });

                    break;

                case TdApi.Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(TdApi.AuthorizationState.AuthorizationStateWaitTdlibParameters):
                    await _client.ExecuteAsync(new TdApi.SetTdlibParameters
                    {
                        Parameters = new TdApi.TdlibParameters
                        {
                            ApiId              = ApiId,
                            ApiHash            = ApiHash,
                            ApplicationVersion = "1.3.0",
                            DeviceModel        = "PC",
                            SystemLanguageCode = "en",
                            SystemVersion      = "Win 10.0"
                        }
                    });

                    break;

                case TdApi.Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(TdApi.AuthorizationState.AuthorizationStateWaitEncryptionKey):
                    await _client.ExecuteAsync(new TdApi.CheckDatabaseEncryptionKey());

                    break;

                case TdApi.Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(TdApi.AuthorizationState.AuthorizationStateWaitPhoneNumber):
                    _authNeeded = true;

                    ResetEvent.Set();
                    break;

                case TdApi.Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(TdApi.AuthorizationState.AuthorizationStateWaitCode):
                    _authNeeded = true;

                    ResetEvent.Set();
                    break;

                case TdApi.Update.UpdateUser updateUser:
                    ResetEvent.Set();
                    break;

                case TdApi.Update.UpdateConnectionState updateConnectionState when updateConnectionState.State.GetType() == typeof(TdApi.ConnectionState.ConnectionStateReady):
                    break;

                default:
                    ;     // add a breakpoint here to see other events
                    break;
                }
            };

            ResetEvent.Wait();
            if (_authNeeded)
            {
                await _client.ExecuteAsync(new TdApi.SetAuthenticationPhoneNumber
                {
                    PhoneNumber = PhoneNumber
                });

                Console.Write("Insert the login code: ");
                var code = Console.ReadLine();
                await _client.ExecuteAsync(new TdApi.CheckAuthenticationCode
                {
                    Code = code
                });
            }

            await foreach (var chat in GetChannels())
            {
                Console.WriteLine(chat.Title);
            }

            Console.ReadLine();
        }
Пример #17
0
 public async Task Connect(string governorAccountPhoneNumber = null, string responseCode = null, string mfaPassword = null)
 {
     if (State == TelegramSessionState.PendingServiceAccount && !string.IsNullOrEmpty(governorAccountPhoneNumber))
     {
         ChangeState(TelegramSessionState.Unauthorized);
         await _client.ExecuteAsync(new TdApi.SetAuthenticationPhoneNumber
         {
             PhoneNumber = governorAccountPhoneNumber
         });
     }
     if (State == TelegramSessionState.PendingCode && !string.IsNullOrEmpty(responseCode))
     {
         ChangeState(TelegramSessionState.Unauthorized);
         await _client.ExecuteAsync(new TdApi.CheckAuthenticationCode
         {
             Code = responseCode
         });
     }
     if (State == TelegramSessionState.PendingPassword && !string.IsNullOrEmpty(mfaPassword))
     {
         ChangeState(TelegramSessionState.Unauthorized);
         await _client.ExecuteAsync(new TdApi.CheckAuthenticationCode
         {
             Code = responseCode
         });
     }
 }
Пример #18
0
        public async Task CreateInstance()
        {
            TDLibHostBot = this;

            _client = new TdClient();
            TdLog.SetVerbosityLevel(0);

            _client.UpdateReceived += async(sender, update) =>
            {
                switch (update)
                {
                case Update.UpdateOption option:
                    await _client.ExecuteAsync(new SetOption
                    {
                        DataType = option.DataType,
                        Extra    = option.Extra,
                        Name     = option.Name,
                        Value    = option.Value
                    });

                    break;

                case Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitTdlibParameters):
                    await _client.ExecuteAsync(new SetTdlibParameters
                    {
                        Parameters = new TdlibParameters
                        {
                            ApiId                  = SecretKeys.API_ID,
                            ApiHash                = SecretKeys.API_HASH,
                            ApplicationVersion     = "1.0.0",
                            DeviceModel            = "PC",
                            SystemLanguageCode     = "en",
                            SystemVersion          = "Win 10.0",
                            DatabaseDirectory      = Path.Combine(Directory.GetCurrentDirectory(), "tdlib"),
                            EnableStorageOptimizer = true,
                            FilesDirectory         = Path.Combine(Directory.GetCurrentDirectory(), "tdlib")
                        }
                    });

                    break;

                case Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitEncryptionKey):
                    await _client.ExecuteAsync(new CheckDatabaseEncryptionKey());

                    break;

                case Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitCode):
                case Update.UpdateAuthorizationState updateAuthorizationState2 when updateAuthorizationState2.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitPhoneNumber):
                    _authNeeded = true;

                    ResetEvent.Set();
                    break;

                case Update.UpdateUser updateUser:
                    break;

                case Update.UpdateConnectionState updateConnectionState when updateConnectionState.State.GetType() == typeof(ConnectionState.ConnectionStateReady):
                    ResetEvent.Set();

                    ReadyEvent.Set();
                    break;

                case Update.UpdateMessageSendFailed uwu:
                case Update.UpdateMessageSendSucceeded uwu2:
                    //what happens ?
                    //BIG *RIP*
                    UploadedEvent.Set();
                    break;

                default:
                    break;
                }
            };

#if !PRODUCTION
            await Cont(TelegramBotSettings.DEV_CHANNEL);
#else
            await Cont(TelegramBotSettings.PROD_CHANNEL);
#endif
        }