Exemplo n.º 1
0
        private void PrepareToTesting()
        {
            var clientTask = ClientFactory.BuildClientAsync(
                new FactorySettings
            {
                AppHash         = Configuration["AppHash"],
                AppId           = int.Parse(Configuration["AppId"]),
                ServerAddress   = Configuration["ServerAddress"],
                ServerPublicKey = Configuration["PublicKey"],
                ServerPort      = Convert.ToInt32(Configuration["Port"]),
                SessionTag      = "session",
                ProxyConfig     = FillProxyConfig(),
                Properties      = new ApplicationProperties
                {
                    AppVersion     = "1.0.0",
                    DeviceModel    = "PC",
                    LangCode       = "en",
                    LangPack       = "tdesktop",
                    SystemLangCode = "en",
                    SystemVersion  = "Win 10 Pro"
                }
            });

            clientTask.Wait();

            ClientApi = clientTask.Result;
        }
Exemplo n.º 2
0
        internal static async Task ConfigureClient()
        {
            Log.WriteLine("Configuring settings");
            var settings = new FactorySettings
            {
                AppHash         = Properties.Settings.Default.TelegramApiHash,
                AppId           = Properties.Settings.Default.TelegramAppId,
                ServerAddress   = Properties.Settings.Default.TelegramIp,
                ServerPublicKey = Properties.Settings.Default.PublicKey,
                ServerPort      = Properties.Settings.Default.TelegramPort,
                SessionTag      = "telecord", // by defaut
                Properties      = new ApplicationProperties
                {
                    AppVersion     = "1.0.0",     // You can leave as in the example
                    DeviceModel    = "PC",        // You can leave as in the example
                    LangCode       = "en",        // You can leave as in the example
                    LangPack       = "tdesktop",  // You can leave as in the example
                    SystemLangCode = "en",        // You can leave as in the example
                    SystemVersion  = "Win 10 Pro" // You can leave as in the example
                }
            };

            clientApi = await ClientFactory.BuildClientAsync(settings).ConfigureAwait(false);

            Log.WriteLine("Connected, creating event handler");
            clientApi.UpdatesService.RecieveUpdates += UpdatesService_RecieveUpdates;
            clientApi.KeepAliveConnection();

            if (clientApi.AuthService.CurrentUserId.HasValue)
            {
                await clientApi.UsersService.GetCurrentUserFullAsync();
            }
        }
Exemplo n.º 3
0
        public async Task <IClientApi> BuildAsync(string hash)
        {
            if (_cache.TryGetValue(hash, out IClientApi clientApi))
            {
                return(clientApi);
            }

            IClientApi client = await ClientFactory.BuildClientAsync(BuildSettings(hash)).ConfigureAwait(false);

            _cache.Set(hash, client, new MemoryCacheEntryOptions().SetSlidingExpiration(SlidingExpiration));

            return(client);
        }
Exemplo n.º 4
0
        public async Task Init(IFactorySettings factorySettings)
        {
            _clientApi = await ClientFactory.BuildClientAsync(factorySettings).ConfigureAwait(false);

            _clientApi.UpdatesService.AutoReceiveUpdates += update =>
            {
                Console.WriteLine($"updates: {JsonConvert.SerializeObject(update)}");
            };

            if (_clientApi.AuthService.CurrentUserId.HasValue)
            {
                _clientApi.UpdatesService.StartReceiveUpdates(TimeSpan.FromSeconds(1));
            }
        }
Exemplo n.º 5
0
 protected async Task <IClientApi> GenerateClientApi(int index)
 {
     return(await ClientFactory.BuildClientAsync(
                new FactorySettings
     {
         AppHash = Configuration["AppHash"],
         AppId = int.Parse(Configuration["AppId"]),
         ServerAddress = Configuration["ServerAddress"],
         ServerPublicKey = Configuration["PublicKey"],
         ServerPort = Convert.ToInt32(Configuration["Port"]),
         SessionTag = "session_" + index,
         Properties = new ApplicationProperties
         {
             AppVersion = "1.0.0",
             DeviceModel = "PC",
             LangCode = "en",
             LangPack = "tdesktop",
             SystemLangCode = "en",
             SystemVersion = "Win 10 Pro"
         }
     }));
 }
Exemplo n.º 6
0
 public async Task Init(IFactorySettings factorySettings)
 {
     _clientApi = await ClientFactory.BuildClientAsync(factorySettings).ConfigureAwait(false);
 }
Exemplo n.º 7
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            new Task(async() =>
            {
                int id;
                var hash = txtTGApiHash.Text;
                var key  = txtKey.Text;
                var ip   = txtIp.Text;
                var port = int.Parse(txtPort.Text);
                ip       = ip.Replace(":443", "");
                if (int.TryParse(txtTGAppId.Text, out id))
                {
                    try
                    {
                        var settings = new FactorySettings
                        {
                            AppHash         = hash,
                            AppId           = id,
                            ServerAddress   = ip,
                            ServerPublicKey = txtKey.Text,
                            ServerPort      = port,
                            SessionTag      = "telecord", // by defaut
                            Properties      = new ApplicationProperties
                            {
                                AppVersion     = "1.0.0",     // You can leave as in the example
                                DeviceModel    = "PC",        // You can leave as in the example
                                LangCode       = "en",        // You can leave as in the example
                                LangPack       = "tdesktop",  // You can leave as in the example
                                SystemLangCode = "en",        // You can leave as in the example
                                SystemVersion  = "Win 10 Pro" // You can leave as in the example
                            }
                        };

                        var clientApi = await ClientFactory.BuildClientAsync(settings).ConfigureAwait(false);

                        //Telegram.Client = new TelegramClient(id, hash, null, "session");
                        //Task.Run(() => Telegram.Client.ConnectAsync(false)).Wait();
                        Properties.Settings.Default.TelegramApiHash = hash;
                        Properties.Settings.Default.TelegramAppId   = id;
                        Properties.Settings.Default.TelegramIp      = ip;
                        Properties.Settings.Default.PublicKey       = key;
                        Properties.Settings.Default.TelegramPort    = port;
                        Properties.Settings.Default.Save();
                        MessageBox.Show("App settings saved!");
                    }
                    catch (AggregateException ex)
                    {
                        MessageBox.Show(ex.InnerExceptions[0].Message, "Error");
                        //txtTGApiHash.Text = "";
                        //txtTGAppId.Text = "";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error");
                        //txtTGApiHash.Text = "";
                        //txtTGAppId.Text = "";
                    }
                }
                else
                {
                    MessageBox.Show("App Id must be a number");
                    txtTGAppId.Text = "";
                }
            }).Start();
        }
        public static async Task <IClientApi> CreateTelegramClient()
        {
            Socks5ProxyConfig ProxyCreate(string ip, int port, string user = null, string pass = null)
            {
                Socks5ProxyConfig proxyConfig = null;

                if (!string.IsNullOrEmpty(ip))
                {
                    proxyConfig = new Socks5ProxyConfig
                    {
                        Endpoint = new IPEndPoint(IPAddress.Parse(ip), port),
                        Password = string.IsNullOrEmpty(pass) ? null : pass,
                        Username = string.IsNullOrEmpty(user) ? null : user,
                    };
                }

                return(proxyConfig);
            }

            var settings = new FactorySettings
            {
                AppHash         = "",
                AppId           = 23838383,
                ServerAddress   = "149.154.167.50",
                ServerPublicKey = @"-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6
lyDONS789shrhrVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcifefexlEKzwKENj1Yz/s7daS
an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7ajtht+XYl9sluzHRyVVaTTveB2GazTw
Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+
8hdlLmAjfefbCVfaigxX0CDqWeRhrhr1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n
Slv8kg9qv1m6XHVfefeQY3PnEw+QQtqSIXklHwIDAQAB
-----END RSA PUBLIC KEY-----",
                ServerPort      = 443,
                //ProxyConfig = ProxyCreate("127.0.0.1",1080),
                SessionTag = "session",
                Properties = new ApplicationProperties
                {
                    AppVersion     = "1.0.0",
                    DeviceModel    = "PC",
                    LangCode       = "en",
                    LangPack       = "tdesktop",
                    SystemLangCode = "en",
                    SystemVersion  = "Win 10 Pro"
                }
            };

            IClientApi clientApi = await ClientFactory.BuildClientAsync(settings).ConfigureAwait(false);

            if (!clientApi.AuthService.CurrentUserId.HasValue)
            {
                Console.WriteLine("Please Enter Your Telegram Account Number To Signin:");
                var phone = Console.ReadLine();

                var sentCode = await clientApi.AuthService.SendCodeAsync(phone).ConfigureAwait(false);

                Console.WriteLine("\nEnter Telegram Verification Code:");
                var code = Console.ReadLine();

                TUser user;
                try
                {
                    user = await clientApi.AuthService.SignInAsync(phone, sentCode, code).ConfigureAwait(false);
                }
                catch (PhoneCodeInvalidException)
                {
                    Console.WriteLine("\nTelegram Communication Account is Invalid!!!");
                }
                catch (CloudPasswordNeededException)
                {
                    Console.WriteLine("\nYou Have Telegram Two-Step Auth Password And This App Cant Handle That!!! Please Turn Of Your Telegram Cloud Password To Use This App And After That you Can Turn it On again!");
                }
            }
            clientApi.KeepAliveConnection();

            return(clientApi);
        }
Exemplo n.º 9
0
        async void Test1()
        {
            var settings = new FactorySettings
            {
                AppHash         = apiHash,
                AppId           = apiId,
                ServerAddress   = "149.154.167.50",
                ServerPort      = 443,
                SessionTag      = $"session", // by defaut
                ServerPublicKey = "-----BEGIN RSA PUBLIC KEY-----\n" +
                                  "MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6\n" +
                                  "lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS\n" +
                                  "an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw\n" +
                                  "Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+\n" +
                                  "8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n\n" +
                                  "Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB\n" +
                                  "-----END RSA PUBLIC KEY-----"
                ,
                Properties = new ApplicationProperties()
                {
                    AppVersion     = Assembly.GetExecutingAssembly().GetName().Version.ToString(), // You can leave as in the example
                    DeviceModel    = "PC",                                                         // You can leave as in the example
                    LangCode       = "ko",                                                         // You can leave as in the example
                    LangPack       = "tdesktop",                                                   // You can leave as in the example
                    SystemLangCode = "ko",                                                         // You can leave as in the example
                    SystemVersion  = "Win 10 Pro"                                                  // You can leave as in the example
                }

                /*
                 * -----BEGIN RSA PUBLIC KEY-----
                 * MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6
                 * lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS
                 * an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw
                 * Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+
                 * 8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n
                 * Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
                 * -----END RSA PUBLIC KEY-----
                 */
            };

            var clientApi = await ClientFactory.BuildClientAsync(settings).ConfigureAwait(false);

            //clientApi.KeepAliveConnection();

            // If the user is not authenticated
            if (!clientApi.AuthService.CurrentUserId.HasValue)
            {
                Console.WriteLine("Request Code : ");
                var sentCode = await clientApi.AuthService.SendCodeAsync(phone); // .ConfigureAwait(false);

                Console.WriteLine("Code : ");
                var   code = "63914";//Console.ReadLine();
                TUser user = await clientApi.AuthService.SignInAsync(phone, sentCode, code).ConfigureAwait(false);

                //await clientApi.UpdatesService.AutoReceiveUpdates

                clientApi.UpdatesService.AutoReceiveUpdates += UpdatesService_AutoReceiveUpdates;
                var dialogs = await clientApi.MessagesService.GetUserDialogsAsync() as TDialogs;

                var chats = dialogs.Chats.OfType <TChannel>().ToList();

                foreach (var o in chats)
                {
                    if (o.Title == "kook test")
                    {
                        ForwardChannelId         = o.Id;
                        ForwardChannelName       = o.Title;
                        ForwardChannelAccessHash = o.AccessHash;
                        break;
                    }
                }

                foreach (var o in chats)
                {
                    if (o.Title.Contains("Rose Challenge"))
                    {
                        var messages = await clientApi.MessagesService.GetHistoryAsync(new TInputPeerChannel { AccessHash = o.AccessHash, ChannelId = o.Id }, 0, 0, 10) as TChannelMessages;

                        var chatMsg = messages.Messages.OfType <TMessage>().OrderBy(m => m.Date).ToList();

                        foreach (var msg in chatMsg)
                        {
                            if (msg.Media != null)
                            {
                                if (msg.Media is TMessageMediaPhoto)
                                {
                                    var mediaPhto = msg.Media as TMessageMediaPhoto;
                                    var photo     = mediaPhto.Photo as TPhoto;
                                    //(photo.Photo as TPhoto).
                                    var from = new TInputPeerChannel {
                                        ChannelId = o.Id, AccessHash = o.AccessHash
                                    };
                                    var to = new TInputPeerChannel {
                                        ChannelId = ForwardChannelId, AccessHash = ForwardChannelAccessHash
                                    };
                                    List <int> msgIds = new List <int>();
                                    msgIds.Add(msg.Id);
                                    var forwardResult = await clientApi.MessagesService.ForwardMessagesAsync(from, to, msgIds, false, false);

                                    TPhotoSize photosize = photo.Sizes.OfType <TPhotoSize>().OrderByDescending(m => m.Size).FirstOrDefault();
                                    string     photoName = $"{photo.Id}.jpg";
                                    // Be sure to do this in a seperate task, else it will wait indefinately because you cannot process messages and sending requests at the same thread
                                    await Task.Run(() =>
                                    {
                                        byte[] fileBytes = clientApi.FileService.DownloadFullFileAsync(new TInputFileLocation
                                        {
                                            FileReference = (photosize.Location as TFileLocation).FileReference,
                                            VolumeId      = photosize.Location.VolumeId,
                                            LocalId       = photosize.Location.LocalId,
                                            Secret        = photosize.Location.Secret
                                        }, CancellationToken.None).Result;

                                        File.WriteAllBytes(photoName, fileBytes);
                                    });

                                    IInputFile inputFile;
                                    using (FileStream fileStream = File.Open(photoName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                                    {
                                        inputFile = clientApi.FileService.UploadFileAsync(photoName, fileStream).Result;
                                    }
                                    var result = clientApi.MessagesService.SendMediaAsync(to, new TInputMediaUploadedPhoto {
                                        File = inputFile
                                    }, "Test PHOTO").Result;
                                }
                            }
                        }
                    }
                }
            }
        }