Пример #1
0
        public override TLObject FromBytes(byte[] bytes, ref int position)
        {
            bytes.ThrowExceptionIfIncorrect(ref position, Signature);

            File = GetObject <TLInputFile>(bytes, ref position);

            return(this);
        }
Пример #2
0
        public void UploadProfilePhotoAsync(TLInputFile file, TLString caption, TLInputGeoPointBase geoPoint, TLInputPhotoCropBase crop, Action <TLPhotosPhoto> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLUploadProfilePhoto {
                File = file, Caption = caption, GeoPoint = geoPoint, Crop = crop
            };

            SendInformativeMessage("photos.uploadProfilePhoto", obj, callback, faultCallback);
        }
        public void UploadProfilePhotoAsync(TLInputFile file, Action <TLPhotosPhoto> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLUploadProfilePhoto {
                File = file
            };

            SendInformativeMessage("photos.uploadProfilePhoto", obj, callback, faultCallback);
        }
Пример #4
0
        /// <summary>
        /// Necesarios: NumeroDestino, Imagen, DescripcionImagen si se quiere
        /// </summary>
        /// <param name="nuevo"></param>
        /// <returns></returns>
        public async Task <Respuestas> EnviarImagen(Mensaje nuevo)
        {
            Respuestas respuesta = new Respuestas();

            try
            {
                var numeroformateado = nuevo.NumeroDestino.StartsWith("+") ?
                                       nuevo.NumeroDestino.Substring(1) :
                                       nuevo.NumeroDestino;
                contexto = Iniciar();
                await contexto.ConnectAsync();

                var contactos = new TLContacts();
                contactos = await contexto.GetContactsAsync();

                var usuariodestino = contactos.Users.OfType <TLUser>().FirstOrDefault(x => x.Phone == numeroformateado);
                if (usuariodestino == null)
                {
                    respuesta.MESSAGE = "El numero" + numeroformateado + " no esta en la lista de sus contactos";
                    respuesta.STATUS  = false;
                    return(respuesta);
                }
                MemoryStream imagen = new MemoryStream(Convert.FromBase64String(nuevo.Imagen));
                //var im = Image.FromStream(imagen);
                //Image imagen_redimensionada = ResizeImage(im, 300, 60);
                //args.Image = imagen_redimensionada;
                StreamReader imageStream = new StreamReader(imagen); //verificar encoding

                var archivo = new TLInputFile();
                archivo = (TLInputFile)await contexto.UploadFile("Image" + (new Random().Next()) + ".jpg", imageStream);

                if (archivo != null)
                {
                    await contexto.SendUploadedPhoto(new TLInputPeerUser()
                    {
                        UserId = usuariodestino.Id
                    }, archivo, nuevo.DescripcionImagen);

                    respuesta.MESSAGE = "Imagen enviada a: " + numeroformateado;
                    respuesta.STATUS  = true;
                    return(respuesta);
                }
                else
                {
                    respuesta.MESSAGE = "No se pudo enviar imagen, ERROR INTERNO...";
                    respuesta.STATUS  = false;
                    return(respuesta);
                }
            }
            catch (Exception e)
            {
                respuesta.MESSAGE = " no se pudo enviar imagen..." + e.Message;
                respuesta.STATUS  = false;
                return(respuesta);
            }
        }
Пример #5
0
        public async Task <Respuestas> EnviarImagenACanal(Mensaje nuevo)
        {
            Respuestas respuesta = new Respuestas();

            try
            {
                contexto = Iniciar();
                TLDialogs conversaciones = new TLDialogs();
                await contexto.ConnectAsync();

                conversaciones = (TLDialogs)await contexto.GetUserDialogsAsync();

                var grupodestino = conversaciones.Chats.OfType <TLChannel>().FirstOrDefault(x => x.Title.ToUpper() == nuevo.GrupoOCanalDestino.ToUpper());
                if (grupodestino == null)
                {
                    respuesta.STATUS  = false;
                    respuesta.MESSAGE = "No se pudo encontrar a usuario...";
                    return(respuesta);
                }


                MemoryStream imagen = new MemoryStream(Convert.FromBase64String(nuevo.Imagen));
                //var im = Image.FromStream(imagen);
                //Image imagen_redimensionada = ResizeImage(im, 300, 60);
                //args.Image = imagen_redimensionada;
                StreamReader imageStream = new StreamReader(imagen); //verificar encoding

                var archivo = new TLInputFile();
                archivo = (TLInputFile)await contexto.UploadFile("Image" + (new Random().Next()) + ".jpg", imageStream);

                if (archivo != null)
                {
                    await contexto.SendUploadedPhoto(new TLInputPeerChannel()
                    {
                        AccessHash = (long)grupodestino.AccessHash, ChannelId = grupodestino.Id
                    }, archivo, nuevo.DescripcionImagen);

                    respuesta.MESSAGE = "Imagen enviada a: " + grupodestino.Title;
                    respuesta.STATUS  = true;
                    return(respuesta);
                }
                else
                {
                    respuesta.MESSAGE = "No se pudo enviar imagen, ERROR INTERNO...";
                    respuesta.STATUS  = false;
                    return(respuesta);
                }
            }
            catch (Exception e)
            {
                respuesta.MESSAGE = " no se pudo enviar imagen..." + e.Message;
                respuesta.STATUS  = false;
                return(respuesta);
            }
        }
Пример #6
0
        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
            });
        public void Handle(UploadableItem item)
        {
            if (item.Owner is TLChannel)
            {
                Execute.BeginOnUIThread(() =>
                {
                    _uploadingPhoto = false;

                    _photo = new TLInputFile
                    {
                        Id = item.FileId,
                        MD5Checksum = new TLString(MD5Core.GetHashString(item.Bytes).ToLowerInvariant()),
                        Name = new TLString(Guid.NewGuid() + ".jpg"),
                        Parts = new TLInt(item.Parts.Count)
                    };

                    _uploadingCallback.SafeInvoke();
                });
            }
        }
Пример #8
0
        public virtual async Task SendPhotoToContactTest()
        {
            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);

            TLInputFile fileResult = (TLInputFile)await client.UploadFile("cat.jpg", new StreamReader("data/cat.jpg"));

            await client.SendUploadedPhoto(new TLInputPeerUser()
            {
                UserId = user.Id
            }, fileResult, "kitty");
        }
Пример #9
0
        private static async void OnMyTimedEvent(object source, ElapsedEventArgs e)
        {
            try
            {
                Console.WriteLine("On timer event");
                DateTime nowDateTime = DateTime.Now.ToLocalTime();
                // Check that we are well connected
                if (Client != null && Client.IsConnected && UserId != 0)
                {
                    if (ChannelId != null && ChannelId.Count > 0)
                    {
                        TLAbsDialogs = await Client.GetUserDialogsAsync();

                        foreach (TLAbsMessage tLAbsMessage in ((TLDialogs)TLAbsDialogs).Messages.Where(x => x is TLMessage message && TimeUnixTOWindows(message.Date, true) >= nowDateTime.AddMilliseconds(-(TimerIntervalInMs - 1))))
                        {
                            ((TLMessage)tLAbsMessage).Message = CalculOffset(((TLMessage)tLAbsMessage).Message);
                            if (((TLMessage)tLAbsMessage).ToId is TLPeerUser tLPeerUser)
                            {
                                // Personal Chat Do Not Forward!
                            }
                            else if (((TLMessage)tLAbsMessage).ToId is TLPeerChannel channel0 && ((TLMessage)tLAbsMessage).ReplyToMsgId != null)
                            {
                                int crtChannelId = channel0.ChannelId;
                                if (crtChannelId != MyChanId && ChannelId.ContainsKey(crtChannelId))
                                {
                                    Console.WriteLine("ReplyChannelId " + ((TLMessage)tLAbsMessage).ReplyToMsgId);
                                    await ReplyMessage((TLMessage)tLAbsMessage);
                                }
                            }
                            else if (((TLMessage)tLAbsMessage).ToId is TLPeerChat chat && ((TLMessage)tLAbsMessage).ReplyToMsgId != null)
                            {
                                Console.WriteLine("ReplyChatId " + ((TLMessage)tLAbsMessage).ReplyToMsgId);
                                await ReplyMessage((TLMessage)tLAbsMessage);
                            }
                            else if (((TLMessage)tLAbsMessage).ToId is TLPeerChannel channel && ((TLMessage)tLAbsMessage).ReplyToMsgId == null)
                            {
                                int crtChannelId = channel.ChannelId;
                                if (crtChannelId != MyChanId && ChannelId.ContainsKey(crtChannelId))
                                {
                                    Console.WriteLine("New Message Channel " + ChannelId[crtChannelId][0] + " \n" + ((TLMessage)tLAbsMessage).Message);
                                    if (ChannelId.ContainsKey(crtChannelId))
                                    {
                                        if (((TLMessage)tLAbsMessage).Message != "")
                                        {
                                            if (((TLMessage)tLAbsMessage).Message.ToLower().StartsWith("tp") || ((TLMessage)tLAbsMessage).Message.ToLower().StartsWith("sl"))
                                            {
                                                TLChannelMessages historyFromSourceCanal = (TLChannelMessages)await Client.GetHistoryAsync(new TLInputPeerChannel()
                                                {
                                                    ChannelId = channel.ChannelId, AccessHash = (long)ChannelId[channel.ChannelId][1]
                                                });

                                                List <TLAbsMessage> tLMessageList        = historyFromSourceCanal.Messages.ToList().Where(x => x is TLMessage tL).ToList();
                                                List <TLMessage>    orderedtLMessageList = tLMessageList.Cast <TLMessage>().OrderByDescending(x => x.Id).ToList();
                                                string newMessage = CalculOffset(orderedtLMessageList[1].Message + "\n" + ((TLMessage)tLAbsMessage).Message);
                                                if (orderedtLMessageList[1].Message.ToLower().Contains("sell") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                                else if (orderedtLMessageList[1].Message.ToLower().Contains("vente") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                                else if (orderedtLMessageList[1].Message.ToLower().Contains("buy") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                                else if (orderedtLMessageList[1].Message.ToLower().Contains("achat") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                            }
                                            else
                                            {
                                                await Client.SendMessageAsync(new TLInputPeerChannel()
                                                {
                                                    ChannelId = MyChanId, AccessHash = AccessHash
                                                }, ((TLMessage)tLAbsMessage).Message);
                                            }
                                        }
                                        else if (((TLMessage)tLAbsMessage).Media != null)
                                        {
                                            if (((TLMessage)tLAbsMessage).Media.GetType().ToString() == "TeleSharp.TL.TLMessageMediaPhoto")
                                            {
                                                TLMessageMediaPhoto    tLMessageMediaPhoto    = (TLMessageMediaPhoto)((TLMessage)tLAbsMessage).Media;
                                                TLPhoto                tLPhoto                = (TLPhoto)tLMessageMediaPhoto.Photo;
                                                TLPhotoSize            tLPhotoSize            = tLPhoto.Sizes.ToList().OfType <TLPhotoSize>().Last();
                                                TLFileLocation         tLFileLocation         = (TLFileLocation)tLPhotoSize.Location;
                                                TLAbsInputFileLocation tLAbsInputFileLocation = new TLInputFileLocation()
                                                {
                                                    LocalId  = tLFileLocation.LocalId,
                                                    Secret   = tLFileLocation.Secret,
                                                    VolumeId = tLFileLocation.VolumeId
                                                };
                                                TLInputFileLocation TLInputFileLocation = tLAbsInputFileLocation as TLInputFileLocation;
                                                TLFile buffer = await Client.GetFile(TLInputFileLocation, 1024 * 512);

                                                TLInputFile fileResult = (TLInputFile)await UploadHelper.UploadFile(Client, "", new StreamReader(new MemoryStream(buffer.Bytes)));

                                                await Client.SendUploadedPhoto(new TLInputPeerChannel()
                                                {
                                                    ChannelId = MyChanId, AccessHash = AccessHash
                                                }, fileResult, tLMessageMediaPhoto.Caption);
                                            }
                                            else if (((TLMessage)tLAbsMessage).Media.GetType().ToString() == "TeleSharp.TL.TLMessageMediaDocument")
                                            {
                                                TLMessageMediaDocument            tLMessageMediaDocument      = (TLMessageMediaDocument)((TLMessage)tLAbsMessage).Media;
                                                TLDocument                        tLDocument                  = (TLDocument)tLMessageMediaDocument.Document;
                                                TLVector <TLAbsDocumentAttribute> tLAbsDocumentAttributes     = tLDocument.Attributes;
                                                TLInputDocumentFileLocation       tLInputDocumentFileLocation = new TLInputDocumentFileLocation()
                                                {
                                                    AccessHash = tLDocument.AccessHash,
                                                    Id         = tLDocument.Id,
                                                    Version    = tLDocument.Version,
                                                };
                                                TLFile buffer = await Client.GetFile(tLInputDocumentFileLocation, 1024 * 512);

                                                TLInputFile fileResult = (TLInputFile)await UploadHelper.UploadFile(Client, ((TLDocumentAttributeFilename)tLAbsDocumentAttributes[0]).FileName, new StreamReader(new MemoryStream(buffer.Bytes)));

                                                await Client.SendUploadedDocument(new TLInputPeerChannel()
                                                {
                                                    ChannelId = MyChanId, AccessHash = AccessHash
                                                }, fileResult, tLMessageMediaDocument.Caption, tLDocument.MimeType, tLAbsDocumentAttributes);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
Пример #10
0
 public TlFileToSend(TLInputFile r2, string mimeType, TLVector <TLAbsDocumentAttribute> attributes)
 {
     _tlInputFile    = r2;
     this.mimeType   = mimeType;
     this.attributes = attributes;
 }
Пример #11
0
        public async Task <Respuestas> EnviarImagenAUsuarioN(Mensaje nuevo)
        {
            Respuestas respuesta = new Respuestas();

            try
            {
                var numeroformateado = nuevo.NumeroDestino.StartsWith("+") ?
                                       nuevo.NumeroDestino.Substring(1) :
                                       nuevo.NumeroDestino;
                contexto = Iniciar();
                await contexto.ConnectAsync();

                var nvoContacto = new TLInputPhoneContact()
                {
                    Phone = numeroformateado, FirstName = ((string.IsNullOrEmpty(nuevo.NombreNuevoUsuario) ? "user" + numeroformateado : nuevo.NombreNuevoUsuario)), LastName = string.Empty
                };
                var contactos = new List <TLInputPhoneContact>()
                {
                    nvoContacto
                };

                var req = new TLRequestImportContacts()
                {
                    Contacts = new TLVector <TLInputPhoneContact>()
                    {
                        nvoContacto
                    }
                };
                var resultado = await contexto.SendRequestAsync <TLImportedContacts>(req);

                //aqui carga 1ro infaliblemente el user_id 1ro... y es extraible...
                if (resultado.Users.Count > 0)
                {
                    var idnuevo        = resultado.Users.OfType <TLUser>().ElementAtOrDefault(0).Id;
                    var usuarioDestino = resultado.Users.OfType <TLUser>().FirstOrDefault(x => x.Id == idnuevo);
                    if (usuarioDestino == null)
                    {
                        respuesta.MESSAGE = "No se encontro usuario Destino, verifique que sea un número telefónico asociado a una cuenta Telegram...";
                        respuesta.STATUS  = false;
                        return(respuesta);
                    }


                    MemoryStream imagen = new MemoryStream(Convert.FromBase64String(nuevo.Imagen));
                    //var im = Image.FromStream(imagen);
                    //Image imagen_redimensionada = ResizeImage(im, 300, 60);
                    //args.Image = imagen_redimensionada;
                    StreamReader imageStream = new StreamReader(imagen); //verificar encoding

                    var archivo = new TLInputFile();
                    archivo = (TLInputFile)await contexto.UploadFile("Image" + (new Random().Next()) + ".jpg", imageStream);

                    if (archivo != null)
                    {
                        await contexto.SendUploadedPhoto(new TLInputPeerUser()
                        {
                            UserId = usuarioDestino.Id
                        }, archivo, nuevo.DescripcionImagen);

                        respuesta.MESSAGE = "Imagen enviada a: " + numeroformateado;
                        respuesta.STATUS  = true;
                        return(respuesta);
                    }
                    else
                    {
                        respuesta.MESSAGE = "No se pudo enviar imagen, ERROR INTERNO...";
                        respuesta.STATUS  = false;
                        return(respuesta);
                    }
                }
                else
                {
                    respuesta.MESSAGE = "Error interno, no se pudo enviar mensaje a nuevo usuario";
                    respuesta.STATUS  = false;
                    return(respuesta);
                }
            }
            catch (Exception e)
            {
                respuesta.MESSAGE = "No se pudo enviar mensaje error: " + e.Message;
                respuesta.STATUS  = false;
                return(respuesta);
            }
        }