static async Task LogIn() { Console.WriteLine("Please enter your phone number in international format:"); var phoneNumber = Console.ReadLine(); var hash = await telegram.SendCodeRequestAsync(phoneNumber); Console.WriteLine("You should have just received a login code. Enter it here:"); var code = Console.ReadLine(); TLUser user = null; try { user = await telegram.MakeAuthAsync(phoneNumber, hash, code); } catch (CloudPasswordNeededException ex) { var passwordSetting = await telegram.GetPasswordSetting(); Console.WriteLine("Your account is protected with 2SV. Enter your cloud password:"******"All logged in! You won't have to do this again."); Connect(); }
public virtual async Task DownloadFileFromWrongLocationTest() { TelegramClient client = this.NewClient(); TelegramAuthModel authModel = new TelegramAuthModel() { ApiId = this.ApiId, ApiHash = this.ApiHash }; await client.AuthenticateAsync(authModel); TeleSharp.TL.Contacts.TLContacts result = await client.GetContactsAsync(); TLUser user = result.Users .OfType <TLUser>() .FirstOrDefault(x => x.Id == 5880094); TLUserProfilePhoto photo = ((TLUserProfilePhoto)user.Photo); TLFileLocation photoLocation = (TLFileLocation)photo.PhotoBig; TeleSharp.TL.Upload.TLFile resFile = await client.GetFile(new TLInputFileLocation() { LocalId = photoLocation.LocalId, Secret = photoLocation.Secret, VolumeId = photoLocation.VolumeId }, 1024); TLAbsDialogs res = await client.GetUserDialogsAsync(); Assert.IsTrue(resFile.Bytes.Length > 0); }
async void AGetUsers() { TLDialogs Dialogs; //await client.ConnectAsync(); try { Dialogs = (TLDialogs)await client.GetUserDialogsAsync(); } catch (Exception ex) { hash = await client.SendCodeRequestAsync(login); user = await client.MakeAuthAsync(login, hash, code); Dialogs = (TLDialogs)await client.GetUserDialogsAsync(); } ActionResult = Dialogs.Users.Select(x => { TLUser user = x as TLUser; return(new ChatterUser() { Chatter = this, Name = user.FirstName, UserId = (user.AccessHash ?? 0).ToString() + "!" + user.Id.ToString(), Messages = new List <Message>() }); }); }
public virtual async Task SendBigFileToContactTest() { TelegramClient client = this.NewClient(); TelegramAuthModel authModel = new TelegramAuthModel() { ApiId = this.ApiId, ApiHash = this.ApiHash }; await client.AuthenticateAsync(authModel); TeleSharp.TL.Contacts.TLContacts result = await client.GetContactsAsync(); TLUser user = result.Users .OfType <TLUser>() .FirstOrDefault(x => x.Phone == this.NumberToSendMessage); TLInputFileBig fileResult = (TLInputFileBig)await client.UploadFile("some.zip", new StreamReader("<some big file path>")); await client.SendUploadedDocument( new TLInputPeerUser() { UserId = user.Id }, fileResult, "some zips", "application/zip", new TLVector <TLAbsDocumentAttribute>()); }
public async Task Start(Func <string> callbackCodeAuth) { if (!_settings.Enabled) { return; } _client = new TelegramClient(_settings.ApiKey, _settings.ApiHash, _store, "session"); var isUserAuthorized = _client.IsUserAuthorized(); Log.Information("Begin connect to telegram"); try { await _client.ConnectAsync(); var hash = await _client.SendCodeRequestAsync(_settings.PhoneNumber); var code = callbackCodeAuth(); _user = await _client.MakeAuthAsync(_settings.PhoneNumber, hash, code); Log.Information("Telegram api connected"); } catch (Exception ex) { Log.Error(ex.ToString()); } }
private void OnUserAuthenticated(TLUser TLUser) { session.TLUser = TLUser; session.SessionExpires = int.MaxValue; session.Save(); }
// Rerform authorizing process using Agent phone and early received Auth Hash and Code private static bool Authorize(string phone, string hash, string authCode) { Logger.Log("Authorizing on Telegram..."); try { TLUser myself = null; if (null == (myself = client.MakeAuthAsync(TLAPIData.phoneNo, hash, authCode).GetAwaiter().GetResult())) { return(!Logger.Err("Authorization failed.")); } Logger.Log("Telegram Authorized:\"{0}\".\n", new string[] { myself.FirstName }); } catch (CloudPasswordNeededException ex) { NoFlood.CheckFlood(ex); return(!Logger.Err("Telegram Cloud Passord authorization required:" + ex.Message)); } catch (InvalidPhoneCodeException ex) { NoFlood.CheckFlood(ex); return(!Logger.Err("Telegram Auth Code is invalid:" + ex.Message)); } return(true); }
private static async Task AuthUser() { if (string.IsNullOrWhiteSpace(Code)) { Thread.Sleep(10000); await AuthUser(); } await client.ConnectAsync(); TLUser user = null; try { user = await client.MakeAuthAsync("", Hash, Code); // IsAuthenticated = client.IsUserAuthorized(); } catch (CloudPasswordNeededException ex) { var password = await client.GetPasswordSetting(); var password_str = ""; user = await client.MakeAuthWithPasswordAsync(password, password_str); } catch (InvalidPhoneCodeException ex) { throw new Exception("CodeToAuthenticate is wrong in the app.config file, fill it with the code you just got now by SMS/Telegram", ex); } }
// Add 1 memeber to specified group Name from members.txt file private static int AddMemberToGroup(TLUser user, int gid, long hash) { int ret = 0; TLAbsUpdates up = null; try { user.Id = GetMemberIdByNickname(user); if (0 == hash) { up = client.AddChatUserAsync(user.Id, gid).GetAwaiter().GetResult(); } else { up = client.InviteToChannelAsync(user.Id, gid, hash).GetAwaiter().GetResult(); } if (0 != ((TLUpdates)up).Updates.Count) { Logger.Succ("Adding user:{0} to group successful.", new string[] { userTitle(user) }); ret++; } else { Logger.Warn("Adding user:{0} to group:{1} failed (USER_ALREADY_PARTICIPANT).", new string[] { userTitle(user), gid.ToString() }); } } catch (Exception ex) { Logger.Warn("Adding user:{0} to group failed: {1}", new string[] { userTitle(user), ex.Message }); } return(ret); }
private static async Task CallAuthenicate() { Console.Write("Please enter your mobile number (e.g: 14155552671): "); var phoneNumber = Console.ReadLine(); string requestHash; try { requestHash = await TClient.SendCodeRequestAsync(phoneNumber); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadKey(intercept: true); return; } Console.Write("Request is sent to your mobile, please enter the code here: "); var authCode = Console.ReadLine(); try { TUser = await TClient.MakeAuthAsync(phoneNumber, requestHash, authCode); Console.WriteLine($"Authenicaion was successfull for Person Name:{TUser.FirstName + " " + TUser.LastName}, Username={TUser.Username}"); } catch (Exception ex) { Console.WriteLine(ex.Message); return; } }
public async Task <bool> SendMessage(string phoneNumber, string contactName, string messageText) { try { await telegramClient?.ConnectAsync(); if (!telegramClient.IsUserAuthorized()) { SetHash(); throw new Exception("User is unauthorized!"); } TLUser user = GetUserByPhoneNumber(phoneNumber).Result; if (user == null) { await AddContact(phoneNumber, contactName, ""); user = await GetUserByPhoneNumber(phoneNumber); } await telegramClient?.SendMessageAsync(new TLInputPeerUser() { UserId = user.Id }, messageText); return(true); } catch (Exception ex) { return(false); } }
private async Task SignInOrRegister() { if (TbPhone.Text == "" || TbPhone.Text == "+" || TbCode.Text == "") { rtbOutput.AppendText("Enter phone number and code to authorize"); return; } try { TLUser user = await client.MakeAuthAsync(TbPhone.Text, hash, TbCode.Text); } catch (InvalidOperationException ex) { if (ex.Message == "PHONE_NUMBER_UNOCCUPIED") { await RegisterUser(); } else { rtbOutput.AppendText(ex.Message); rtbOutput.AppendText(Environment.NewLine); } } }
private void OnUserAuthenticated(TLUser user) { _session.TLUser = user; _session.SessionExpires = int.MaxValue; _session.Save(); }
public override bool OnStartJob(JobParameters @params) { Task.Run(() => { // Work is happening asynchronously int messageCount = 0; database = new SQLiteRepository(); contactRepository = new ContactRepository(database); userRepository = new UserRepository(database); messageRepository = new MessageRepository(database); loginService = new LoginService(); messageService = new MessageService(); client = loginService.Connect(); if (client.IsUserAuthorized()) { usuario = client.Session.TLUser; } messageCount = messageService.ReceiveMessages(client, messageRepository); //if (messageCount > 0) // Notification(messageCount.ToString()); // Have to tell the JobScheduler the work is done. JobFinished(@params, false); }); // Return true because of the asynchronous work return(false); }
private void OnUserAuthenticated(TLUser TLUser) { Session.TLUser = TLUser; Session.SessionExpires = int.MaxValue; this.store.Save(Session); }
public static string GetLabel(TLUser user, bool details) { if (user.Id == 777000) { return("Service notifications"); } else if (user.IsBot) { if (details) { return("Bot"); } return(user.IsBotChatHistory ? "Has access to messages" : "Has no access to messages"); } else if (user.IsSelf && details) { return("Chat with yourself"); } if (user.HasStatus && user.Status != null) { switch (user.Status) { case TLUserStatusOffline offline: var now = DateTime.Now; var seen = TLUtils.ToDateTime(offline.WasOnline); var time = string.Empty; if (details) { time = ((now.Date == seen.Date) ? "today at " : (((now.Date - seen.Date) == new TimeSpan(1, 0, 0, 0)) ? "yesterday at " : BindConvert.Current.ShortDate.Format(seen) + " ")) + BindConvert.Current.ShortTime.Format(seen); } else { time = (now.Date == seen.Date) ? ((now - seen).Hours < 1 ? ((now - seen).Minutes < 1 ? "moments ago" : (now - seen).Minutes.ToString() + ((now - seen).Minutes.ToString() == "1" ? " minute ago" : " minutes ago")) : ((now - seen).Hours.ToString()) + (((now - seen).Hours.ToString()) == "1" ? (" hour ago") : (" hours ago"))) : now.Date - seen.Date == new TimeSpan(24, 0, 0) ? "yesterday " + BindConvert.Current.ShortTime.Format(seen) : BindConvert.Current.ShortDate.Format(seen); } return(string.Format("Last seen {0}", time)); case TLUserStatusOnline online: return("online"); case TLUserStatusRecently recently: return("Last seen recently"); case TLUserStatusLastWeek lastWeek: return("Last seen within a week"); case TLUserStatusLastMonth lastMonth: return("Last seen within a month"); case TLUserStatusEmpty empty: default: return("Last seen a long time ago"); } } // Debugger.Break(); return("Last seen a long time ago"); }
public BitmapImage this[TLUser user] { get { if (user == null) { return(null); } var key = (object)user.Photo; if (key == null) { key = user.FullName; } if (_context.TryGetValue(key, out Tuple <TLBitmapSource, WeakReference <BitmapImage> > reference) && reference.Item2.TryGetTarget(out BitmapImage target)) { return(target); } var bitmap = new TLBitmapSource(user); _context[key] = new Tuple <TLBitmapSource, WeakReference <BitmapImage> >(bitmap, new WeakReference <BitmapImage>(bitmap.Image)); return(bitmap.Image); } }
public static Session FromStream(Stream stream) { using (var reader = new BinaryReader(stream)) { var id = reader.ReadUInt64(); var sequence = reader.ReadInt32(); var salt = reader.ReadUInt64(); var lastMessageId = reader.ReadInt64(); var timeOffset = reader.ReadInt32(); var serverAddress = Serializers.String.read(reader); var port = reader.ReadInt32(); var isAuthExsist = reader.ReadInt32() == 1; int sessionExpires = 0; TLUser TLUser = null; if (isAuthExsist) { sessionExpires = reader.ReadInt32(); TLUser = (TLUser)ObjectUtils.DeserializeObject(reader); } var authData = Serializers.Bytes.read(reader); var defaultDataCenter = new DataCenter(serverAddress, port); return(new Session(id, new AuthKey(authData), sequence, salt, timeOffset, lastMessageId, sessionExpires, TLUser, defaultDataCenter)); } }
// Verifies if member sent posts in a Group // TODO: Check activity for Chat also (!!!) private static bool IsMemberActive(TLUser user, int gid = 0) { try { var msg = client.GetUserHistoryAsync(user.Id).GetAwaiter().GetResult(); if (typeof(TLMessagesSlice) == msg.GetType()) { msg = (TLMessagesSlice)msg; if (null == msg || 0 == (msg as TLMessagesSlice).Messages.Count) { return(false); } } else if (typeof(TLMessages) == msg.GetType()) { msg = (TLMessages)msg; if (null == msg || 0 == (msg as TLMessages).Messages.Count) { return(false); } } else { return(false); } Logger.Succ("Active user:{0} found.", new string[] { userTitle(user) }); } catch (Exception ex) { return(!Logger.Warn("Active user:{0} check failed: {1}.", new string[] { userTitle(user), ex.Message })); } return(true); }
public static async Task <TLUser> AuthUser(TelegramClient client) { var hash = await client.SendCodeRequestAsync(_number); var code = Console.ReadLine(); if (String.IsNullOrWhiteSpace(code)) { throw new Exception("CodeToAuthenticate is empty in the app.config file, fill it with the code you just got now by SMS/Telegram"); } TLUser user = null; try { user = await client.MakeAuthAsync(_number, hash, code); } catch (InvalidPhoneCodeException ex) { throw new Exception("CodeToAuthenticate is wrong in the app.config file, fill it with the code you just got now by SMS/Telegram", ex); } return(user); }
private async void Button_Click_4(object sender, RoutedEventArgs e) { //var store = new FileSessionStore(); var client = new TelegramClient(1683198, "651cf34b8b68dd9fe0b144ae5889e8eb"); await client.ConnectAsync(); var hash = await client.SendCodeRequestAsync(tbNumbetTelega.Text); var code = "40835";//tbCodeTelega.Text; var user = await client.MakeAuthAsync(tbNumbetTelega.Text, hash, code); var result = await client.GetContactsAsync(); //var dialogs = (TLDialog)await client.GetUserDialogsAsync(); TLDialogs dialog = (TLDialogs)await client.GetUserDialogsAsync(); TLUser chat = (TLUser)dialog.Users[0]; await client.SendMessageAsync(new TLInputPeerUser() { UserId = chat.Id, AccessHash = chat.AccessHash.Value }, "*8088*79026885467*79087215309"); //var chat = dialogs.Chats //.Where(c => c.GetType() == typeof(TLChannel)) //.Cast<TLChannel>() //.FirstOrDefault(c => c.Title == "<channel_title>"); //await client.SendMessageAsync(new TLInputPeerChannel() { ChannelId=}); //var dd = (TLUser)dialogs.Users[0]; }
public async Task AuthUser() { var client = NewClient(); await client.ConnectAsync(); var hash = await client.SendCodeRequestAsync(NumberToAuthenticate); var code = CodeToAuthenticate; // you can change code in debugger too if (String.IsNullOrWhiteSpace(code)) { throw new Exception("CodeToAuthenticate is empty in the app.config file, fill it with the code you just got now by SMS/Telegram"); } TLUser user = null; try { user = await client.MakeAuthAsync(NumberToAuthenticate, hash, code); } catch (InvalidPhoneCodeException ex) { throw new Exception("CodeToAuthenticate is wrong in the app.config file, fill it with the code you just got now by SMS/Telegram", ex); } Assert.IsNotNull(user); Assert.IsTrue(client.IsUserAuthorized()); }
public virtual async Task AuthUser() { var client = NewClient(); await client.ConnectAsync(); var hash = await client.SendCodeRequestAsync(NumberToAuthenticate); var code = CodeToAuthenticate; // you can change code in debugger too if (String.IsNullOrWhiteSpace(code)) { throw new Exception("CodeToAuthenticate is empty in the app.config file, fill it with the code you just got now by SMS/Telegram"); } TLUser user = null; try { user = await client.MakeAuthAsync(NumberToAuthenticate, hash, code); } catch (CloudPasswordNeededException ex) { var password = await client.GetPasswordSetting(); var password_str = PasswordToAuthenticate; user = await client.MakeAuthWithPasswordAsync(password, password_str); } catch (InvalidPhoneCodeException ex) { throw new Exception("CodeToAuthenticate is wrong in the app.config file, fill it with the code you just got now by SMS/Telegram", ex); } }
private async void button2_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(this.textBox2.Text) || string.IsNullOrEmpty(this.textBox2.Text)) { return; } if (string.IsNullOrEmpty(this.hash)) { return; } try { TLUser tlUser = await Program.client.MakeAuthAsync(this.textBox1.Text, this.hash, this.textBox2.Text); this.Hide(); MainForm mainForm = new MainForm(); FormClosedEventHandler closedEventHandler = (FormClosedEventHandler)((s, args) => this.Close()); mainForm.FormClosed += closedEventHandler; int num = (int)mainForm.ShowDialog(); } catch (Exception ex) { int num = (int)MessageBox.Show(string.Format("Something went wrong. Exception: {0}", (object)ex.ToString()), "Error"); } }
public void Get() { int messageCount = 0; database = new SQLiteRepository(); contactRepository = new ContactRepository(database); userRepository = new UserRepository(database); messageRepository = new MessageRepository(database); loginService = new LoginService(); messageService = new MessageService(); client = loginService.Connect(); if (client.IsUserAuthorized()) { usuario = client.Session.TLUser; } messageCount = messageService.ReceiveMessages(client, messageRepository); if (messageCount > 0) { Notification(messageCount.ToString()); context.SendBroadcast(new Intent(context, typeof(MisChats.BroadcastMisChats))); context.SendBroadcast(new Intent(context, typeof(SingleChat.BroadcastSingle))); } }
private void OnUserAuthenticated(TLUser user) { Session.UserId = user.Id; Session.SessionExpires = int.MaxValue; this.store.Save(Session); }
private async void SendContactExecute() { var picker = new ContactPicker(); picker.SelectionMode = ContactSelectionMode.Fields; picker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber); var contact = await picker.PickContactAsync(); if (contact != null) { TLUser user = null; var annotationStore = await ContactManager.RequestAnnotationStoreAsync(ContactAnnotationStoreAccessType.AppAnnotationsReadWrite); var store = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite); if (store != null && annotationStore != null) { var full = await store.GetContactAsync(contact.Id); if (full != null) { var annotations = await annotationStore.FindAnnotationsForContactAsync(full); var first = annotations.FirstOrDefault(); if (first != null) { var remote = first.RemoteId; if (int.TryParse(remote.Substring(1), out int userId)) { user = CacheService.GetUser(userId) as TLUser; } } //contact = full; } } if (user == null) { var phone = contact.Phones.FirstOrDefault(); if (phone == null) { return; } user = new TLUser(); user.FirstName = contact.FirstName; user.LastName = contact.LastName; user.Phone = phone.Number; } if (user != null) { await SendContactAsync(user); } } }
protected override void OnResume() { base.OnResume(); nomusuario.Click += delegate { StopItems(); }; tipo.Click += delegate { StopItems(); }; velocidad.Click += delegate { StopItems(); }; activacion.Click += delegate { StopItems(); }; loginService = new LoginService(); userService = new UserService(); try { client = loginService.Connect(); if (client.IsUserAuthorized()) { usuario = client.Session.TLUser; } } catch (Exception ex) { this.FinishAffinity(); } database = new SQLiteRepository(); userRepository = new UserRepository(database); configRepository = new ConfigRepository(database); errorText = new ErrorText(); configuracion = configRepository.GetConfig(); speechReco = SpeechRecognizer.CreateSpeechRecognizer(this.ApplicationContext); speechReco.SetRecognitionListener(this); intentReco = new Intent(RecognizerIntent.ActionRecognizeSpeech); intentReco.PutExtra(RecognizerIntent.ExtraLanguagePreference, "es"); intentReco.PutExtra(RecognizerIntent.ExtraCallingPackage, this.PackageName); intentReco.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelWebSearch); intentReco.PutExtra(RecognizerIntent.ExtraMaxResults, 1); toSpeech = new TextToSpeech(this, this); gestureDetector = new GestureDetector(this); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.MisContactos); this.Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn); database = new SQLiteRepository(); contactRepository = new ContactRepository(database); loginService = new LoginService(); contactService = new ContactService(); deleteContact = null; errorText = new ErrorText(); try { client = loginService.Connect(); if (client.IsUserAuthorized()) { usuario = client.Session.TLUser; } } catch (Exception ex) { this.FinishAffinity(); } Button contactos = FindViewById <Button>(Resource.Id.btnContactos); Button estados = FindViewById <Button>(Resource.Id.btnEstados); Button bloqueados = FindViewById <Button>(Resource.Id.btnBloquear); Button eliminar = FindViewById <Button>(Resource.Id.btnEliminar); contactos.Click += delegate { StopItems(); StartActivity(typeof(ContactosNombre)); }; estados.Click += delegate { StopItems(); contactService.UpdateContacts(client, contactRepository); }; bloqueados.Click += delegate { StopItems(); StartActivity(typeof(ContactosBloqueados)); }; eliminar.Click += delegate { StopItems(); contactService.DeleteContact(client, deleteContact, contactRepository); }; }
public static string GetLabel(TLUser user, bool details) { if (user == null) { return(null); } if (user.Id == 777000) { return(Strings.Android.ServiceNotifications); } else if (user.IsBot) { if (details) { return(Strings.Android.Bot); } return(user.IsBotChatHistory ? Strings.Android.BotStatusRead : Strings.Android.BotStatusCantRead); } else if (user.IsSelf && details) { return(Strings.Android.ChatYourSelf); } if (user.Status is TLUserStatusOffline offline) { return(FormatDateOnline(offline.WasOnline)); } else if (user.Status is TLUserStatusOnline online) { if (online.Expires > Utils.CurrentTimestamp / 1000) { return(Strings.Android.Online); } else { return(FormatDateOnline(online.Expires)); } } else if (user.Status is TLUserStatusRecently recently) { return(Strings.Android.Lately); } else if (user.Status is TLUserStatusLastWeek lastWeek) { return(Strings.Android.WithinAWeek); } else if (user.Status is TLUserStatusLastMonth lastMonth) { return(Strings.Android.WithinAMonth); } else { return(Strings.Android.ALongTimeAgo); } }