public string GetFileName(TLDocument filedata) { var attributes = filedata.Attributes; TLDocumentAttributeFilename file_name = (TLDocumentAttributeFilename)attributes.AsEnumerable().ElementAt(0); return(file_name.FileName); }
private async void enviarMensaje(Stream tmp) { if (client.IsUserAuthorized()) { var result = await client.GetContactsAsync(); var user = result.Users .Where(x => x.GetType() == typeof(TLUser)) .Cast <TLUser>() .FirstOrDefault(x => x.Phone == "34" + u.Telefono); bool enviar = true; if (user == null) { var phoneContact = new TLInputPhoneContact() { Phone = "34" + u.Telefono, FirstName = u.Nombre, LastName = u.Apellidos }; var contacts = new List <TLInputPhoneContact>() { phoneContact }; var req = new TLRequestImportContacts() { Contacts = new TLVector <TLInputPhoneContact>(contacts) }; var rrr = await client.SendRequestAsync <TLImportedContacts>(req); if (rrr.Imported.Count == 1) { user = result.Users .Where(x => x.GetType() == typeof(TLUser)) .Cast <TLUser>() .FirstOrDefault(x => x.Phone == "34" + u.Telefono); } else { enviar = false; } } if (enviar && user != null) { var fileResult = await client.UploadFile(Strings.Factura + i.Mes + "/" + i.Año, new StreamReader(tmp)); TLDocumentAttributeFilename name = new TLDocumentAttributeFilename(); name.FileName = Strings.Factura + i.Mes + "/" + i.Año + ".pdf"; await client.SendUploadedDocument(new TLInputPeerUser() { UserId = user.Id }, fileResult, "", "application/pdf", new TLVector <TLAbsDocumentAttribute>() { name }); } } }
public override async Task <TlFileToSend> GetMediaTl(TelegramClient client) { _stream.Seek(0, SeekOrigin.Begin); var streamReader = new StreamReader(_stream); var r = await client.UploadFile(_fileName, streamReader); var attributes = new TLVector <TLAbsDocumentAttribute>(); TLAbsDocumentAttribute att1 = new TLDocumentAttributeFilename { FileName = _fileName }; attributes.Add(att1); return(r switch { null => null, TLInputFile r2 => new TlFileToSend(r2, _mimeType, attributes), _ => null });
/* This function accepts downloaded music from YouTube and sends it to Telegram channel */ private async void SendMusicToChannel() { if (user == null) { MessageBox.Show("Telegram user is not authorized"); return; } var dialogs = (TLDialogs)await client.GetUserDialogsAsync(); // find Telegram channel by name TLChannel chat = dialogs.Chats.Where(c => c.GetType() == typeof(TLChannel)).Cast <TLChannel>().FirstOrDefault(c => c.Title == "Music"); string filePath = this.DownloadFromYoutube(); if (string.IsNullOrEmpty(filePath)) { return; } // upload file var fileResult = await client.UploadFile(filePath, new StreamReader(filePath)); // create an attribute for a file TLDocumentAttributeFilename s = new TLDocumentAttributeFilename { FileName = filePath.Replace(".mp3", "") }; TLVector <TLAbsDocumentAttribute> attributes = new TLVector <TLAbsDocumentAttribute> { s }; // finally, send the file to the channel client.SendUploadedDocument( new TLInputPeerChannel() { ChannelId = chat.Id, AccessHash = (long)chat.AccessHash }, fileResult, "", "audio/mpeg", attributes); }
public Task PutAsync(string remotename, Stream stream, CancellationToken cancelToken) { SafeExecute(() => { cancelToken.ThrowIfCancellationRequested(); Authenticate(); cancelToken.ThrowIfCancellationRequested(); var channel = GetChannel(); cancelToken.ThrowIfCancellationRequested(); using (var sr = new StreamReader(new StreamReadHelper(stream))) { cancelToken.ThrowIfCancellationRequested(); EnsureConnected(cancelToken); cancelToken.ThrowIfCancellationRequested(); var file = m_telegramClient.UploadFile(remotename, sr, cancelToken).GetAwaiter().GetResult(); cancelToken.ThrowIfCancellationRequested(); var inputPeerChannel = new TLInputPeerChannel { ChannelId = channel.Id, AccessHash = (long)channel.AccessHash }; var fileNameAttribute = new TLDocumentAttributeFilename { FileName = remotename }; EnsureConnected(cancelToken); m_telegramClient.SendUploadedDocument(inputPeerChannel, file, remotename, "application/zip", new TLVector <TLAbsDocumentAttribute> { fileNameAttribute }, cancelToken).GetAwaiter().GetResult(); } }, nameof(PutAsync)); return(Task.CompletedTask); }
protected string ExportAudio(TLMessageMediaDocument media, TLDocument document) { // Find TLDocumentAttributeFilename from list of attributes TLDocumentAttributeAudio attrAudio = null; TLDocumentAttributeFilename attrFile = null; foreach (TLAbsDocumentAttribute absAttr in document.attributes.lists) { if (absAttr is TLDocumentAttributeAudio) { attrAudio = (TLDocumentAttributeAudio)absAttr; } else if (absAttr is TLDocumentAttributeFilename) { attrFile = (TLDocumentAttributeFilename)absAttr; } } if (attrAudio == null && attrFile == null) { throw new TLCoreException("The TLDocumentAttributeAudio and TLDocumentAttributeFilename have not been found"); } string key; if (attrFile != null) { // Key: YYYY-MM-DD-Caption{0:00}.EXT key = String.Format("{0}-{1}{2}", m_sPrefix, "{0:00}", attrFile.file_name); } else { string sCaption = attrAudio.voice ? c_sVoice : c_sAudio; string ext = document.mime_type.Substring(document.mime_type.Length - 3).Trim(); // Key: YYYY-MM-DD-Caption{0:00}.EXT key = String.Format("{0}-{1}{2}.{3}", m_sPrefix, sCaption, "{0:00}", ext); } string sFileName = GetUniqueFileName(key); // YYYY-MM-DD-AudioXX.EXT if (m_config.ExportVoiceMessages) { // Export the document to a file string sFullFileName = Path.Combine(m_sDialogDirectory, sFileName); using (FileStream f = new FileStream(sFullFileName, FileMode.Create, FileAccess.Write)) foreach (TLFile file in m_archiver.GetDocument(document)) { if (file.type.GetType() == typeof(TLFileUnknown)) { throw new TLCoreException("File unknown: " + sFileName); } f.Write(file.bytes, 0, file.bytes.Length); } } return(sFileName); // YYYY-MM-DD-AudioXX.EXT }
protected string ExportDocument(TLMessageMediaDocument media) { // TLPhoto contains a collection of TLPhotoSize TLDocument document = media.document as TLDocument; if (document == null) { throw new TLCoreException("The document is not an instance of TLDocument"); } if (document.attributes.lists.Count <= 0) { throw new TLCoreException("TLDocument does not have any attributes"); } if (document.mime_type.StartsWith("audio")) { return(ExportAudio(media, document)); } // Find TLDocumentAttributeFilename from list of attributes TLDocumentAttributeFilename attr = null; foreach (TLAbsDocumentAttribute absAttr in document.attributes.lists) { attr = absAttr as TLDocumentAttributeFilename; if (attr != null) { break; } } if (attr == null) { throw new TLCoreException("The TLDocumentAttributeFilename has not been found"); } if (String.IsNullOrEmpty(attr.file_name)) { throw new TLCoreException("The file_name of the document is empty"); } // Key: YYYY-MM-DD-Caption{0:00}.EXT string key = String.Format("{0}-{1}{2}", m_sPrefix, "{0:00}", attr.file_name); string sFileName = GetUniqueFileName(key); // YYYY-MM-DD-CaptionXX.EXT if (m_config.ExportFiles) { // Export the document to a file string sFullFileName = Path.Combine(m_sDialogDirectory, sFileName); using (FileStream f = new FileStream(sFullFileName, FileMode.Create, FileAccess.Write)) foreach (TLFile file in m_archiver.GetDocument(document)) { if (file.type.GetType() == typeof(TLFileUnknown)) { throw new TLCoreException("File unknown: " + sFileName); } f.Write(file.bytes, 0, file.bytes.Length); } } return(sFileName); // YYYY-MM-DD-CaptionXX.EXT }
private static async Task RunClient(string fileName, string caption) { Console.WriteLine("Logging in"); var client = new TelegramClient(_config.ApiId, _config.ApiHash); await client.ConnectAsync(); TLUser me; if (!client.IsUserAuthorized()) { string hash = await client.SendCodeRequestAsync(_config.Number); Console.Write("Please enter the code you received: "); string code = Console.ReadLine(); try { me = await client.MakeAuthAsync(_config.Number, hash, code); } catch (CloudPasswordNeededException) { var passwordSetting = await client.GetPasswordSetting(); Console.Write("Enter your 2FA password: "******"CodeToAuthenticate is wrong in the app.config file, fill it with the code you just got now by SMS/Telegram", ex); } catch (Exception ex) { Console.WriteLine("An exception occured: " + ex); Console.WriteLine("If you want a fresh start just remove session.dat file and restart."); return; } } else { var result = await client.GetContactsAsync(); //find recipient in contacts me = result.Users .Where(x => x.GetType() == typeof(TLUser)) .Cast <TLUser>() .FirstOrDefault(x => x.Self); } Console.WriteLine("Uploading file"); var attr = new TLVector <TLAbsDocumentAttribute>(); var docAttr = new TLDocumentAttributeFilename { FileName = Path.GetFileName(fileName) }; attr.Add(docAttr); var fileResult = await client.UploadFile(Path.GetFileName(fileName), new StreamReader(fileName)); Console.WriteLine("Uploaded; Sending file"); await client.SendUploadedDocument( new TLInputPeerUser { UserId = me.Id }, fileResult, caption, "application/octet-stream", attr); Console.WriteLine("Done"); }
private async void GetHistory_Click(object sender, EventArgs e) { try { string path1 = Path.Combine(Application.StartupPath, "Download"); string path2 = Path.Combine(Application.StartupPath, "Download", tbNumber.Text); if (!Directory.Exists(path1)) { Directory.CreateDirectory(path1); } if (!Directory.Exists(path2)) { Directory.CreateDirectory(path2); } TxtHistory.Clear(); _resultUserMessages.Clear(); NumberToSendMessage = tbNumber.Text; if (string.IsNullOrWhiteSpace(NumberToSendMessage)) { return; } // this is because the contacts in the address come without the "+" prefix var normalizedNumber = NumberToSendMessage.StartsWith("+") ? NumberToSendMessage.Substring(1, NumberToSendMessage.Length - 1) : NumberToSendMessage; var client = NewClient(); await client.ConnectAsync(); var result = await client.GetContactsAsync(); var user = result.users.lists.ToList() .OfType <TLUser>() .FirstOrDefault(x => x.phone == normalizedNumber); if (user == null) { throw new System.Exception("Number was not found in Contacts List of user: "******"TeleSharp.TL.TLMessageMediaDocument": { var media = (TLMessageMediaDocument)item.Media; var document = (TLDocument)media.document; TLDocumentAttributeFilename filename = null; try { var count = document.attributes.lists.ToList().Count; switch (count) { case 1: { filename = (TLDocumentAttributeFilename)(document.attributes.lists.ToList()[0]); break; } case 2: { filename = (TLDocumentAttributeFilename)(document.attributes.lists.ToList()[1]); break; } case 3: { try { filename = (TLDocumentAttributeFilename)(document.attributes.lists.ToList()[2]); } catch { filename = (TLDocumentAttributeFilename)(document.attributes.lists.ToList()[1]); TxtHistory.Text += "==>" + item.FromId + " : " + "@Gif \n"; } break; } default: break; } } catch (Exception) { } var resFile = await client.GetFile( new TLInputDocumentFileLocation() { access_hash = document.access_hash, id = document.id, version = document.version, }, document.size); SaveData(resFile.bytes, filename.file_name); break; } case "TeleSharp.TL.TLMessageMediaPhoto": { var media = (TLMessageMediaPhoto)item.Media; var caption = media.caption; var photo = (TLPhoto)media.photo; var count = photo.sizes.lists.ToList().Count(); var photosize = (TLPhotoSize)photo.sizes.lists.ToList()[count - 1]; var photoLocation = (TLFileLocation)photosize.location; var resFile = await client.GetFile(new TLInputFileLocation() { local_id = photoLocation.local_id, secret = photoLocation.secret, volume_id = photoLocation.volume_id }, photosize.size, 0); string filenamet = ""; Guid name; var imageType = resFile.type; switch (imageType.Constructor) { case 8322574: { name = Guid.NewGuid(); filenamet = name.ToString() + ".jpg"; break; } case -891180321: { name = Guid.NewGuid(); filenamet = name.ToString() + ".gif"; break; } case 172975040: { name = Guid.NewGuid(); filenamet = name.ToString() + ".png"; break; } default: { name = Guid.NewGuid(); filenamet = name.ToString(); break; } } SaveData(resFile.bytes, filenamet); break; } default: { break; } } } else { TxtHistory.Text += "==>" + item.FromId + " : " + item.Message + Environment.NewLine; TxtHistory.AppendText("\n"); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }