Skip to content
This repository has been archived by the owner on Dec 5, 2021. It is now read-only.

how to fix fileref_upgrade_needed for download photo from message? #1019

Open
rocket-builder opened this issue Apr 5, 2021 · 1 comment
Open

Comments

@rocket-builder
Copy link

I use this code

TLAbsInputFileLocation inputLocation = new TLInputFileLocation()
{
    LocalId = 304506,
    Secret = -6845803839726843347,
    VolumeId = 200165900695
};
TLInputFileLocation inputFileLocation = inputLocation as TLInputFileLocation;

var photoFile = await client.GetFile(inputFileLocation, 1024 * 512);
File.WriteAllBytes("test.jpg", photoFile.Bytes);

But i have fileref_upgrade_needed exception.

When i try download photo from actual messages, i have flood prevention exception.
I use this code

using OnlyFansBot.DataAccess;
using OnlyFansBot.Extensions;
using OnlyFansBot.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using TLSchema;
using TLSchema.Messages;
using TLSharp;
using TLSharp.Utils;

namespace OnlyFansBot.Util
{
    class TelegramChatHandler
    {
        private TelegramClient _client { get; set; }
        private TLInputPeerChat _chatPeer { get; set; }

        public string _userNumber { get; set; }
        public string _chatTitle { get; set; }

        public string imgPath = "/img/";

        public TelegramChatHandler(TelegramClient client, string userNumber, string chatTitle)
        {
            _client = client;
            _userNumber = userNumber;
            _chatTitle = chatTitle;
        }

        public async Task Connect()
        {
            await _client.ConnectAsync();

            //send auth
            var hash = _client.SendCodeRequestAsync(_userNumber).Result;

            //get auth code
            Console.Write("Enter auth tg code: ");
            var code = Console.ReadLine(); // you can change code in debugger

            var user = _client.MakeAuthAsync(_userNumber, hash, code).Result;

            //get user dialogs
            var dialogs = _client.GetUserDialogsAsync().Result as TLDialogs;

            //find channel by title
            var chat = dialogs.Chats
              .Where(c => c.GetType() == typeof(TLChat))
              .Cast<TLChat>()
              .FirstOrDefault(c => c.Title == _chatTitle);

            _chatPeer = new TLInputPeerChat()
            {
                ChatId = chat.Id
            };
        }


        public async Task<List<TLAbsMessage>> GetMessages()
        {
            var tlAbsMessages = await _client.GetHistoryAsync(_chatPeer, 0, 0, 0, 400);
            var history = tlAbsMessages as TLMessagesSlice;
            return history.Messages.ToList();
        }

        public async Task<List<TLMessage>> RecivePostMessages()
        {
            var messagesToSend = new List<TLMessage>();
            var isStarted = false;

            var origin = await GetMessages();
            while(true)
            {
                await Task.Delay(5500);
                var update = await GetMessages();

                var lastOrigin = origin.Last() as TLMessage;
                var lastUpdate = update.Last() as TLMessage;
                if (lastOrigin.Id != lastUpdate.Id)
                {
                    var diff = MessDiff(update, origin);
                    origin.AddRange(diff);

                    foreach(var elm in diff)
                    {
                        try
                        {
                            var message = elm;
                            Console.WriteLine($"{message.FromId}: {message.Message}");

                            switch (message.Message)
                            {
                                case Phrase.DropAfterMe:
                                case Phrase.PrepareLinks:
                                    {
                                        isStarted = true;                                     
                                    } break;
                                case Phrase.Closed:
                                    {
                                        isStarted = false;
                                        return messagesToSend;
                                    }                             
                            }

                            if (isStarted)
                            {
                                messagesToSend.Add(message);
                                if(messagesToSend.Count == 2)
                                {
                                    await SendPost();
                                }

                                Console.WriteLine($"{message.FromId}: {message.Message} added");
                            }
                        }
                        catch (Exception) { }
                    }; 
                }

                await Task.Delay(5500);
            }
        }

        private async Task SendPost()
        {
            var photo = await _client.UploadFile("cat.jpg", new StreamReader("cat.jpg"));
            var text = OnlyFansBotAPI.GetPostText();

            await _client.SendUploadedPhoto(_chatPeer, photo, text);
            await Task.Delay(5500);
        }

        public async Task<Post> GetPostFromMessage(TLMessage message)
        {
            try
            {
                switch (message.Media.GetType().ToString())
                {
                    case "TLSchema.TLMessageMediaDocument":
                        var mediaDocument = message.Media as TLMessageMediaDocument;
                        var document = mediaDocument.Document as TLDocument;

                        var input = new TLInputDocumentFileLocation()
                        {
                            AccessHash = document.AccessHash,
                            Id = document.Id,
                            Version = document.Version
                        };
                        var documentFile = await _client.GetFile(input,document.Size);
                        var documentPath = $"{imgPath}{document.Id}.{document.MimeType.MimeToShort()}";

                        ByteArrayToFile(documentPath, documentFile.Bytes);
 
                        return new Post()
                        {
                            PhotoPath = documentPath,
                            Text = mediaDocument.Caption
                        };

                    case "TLSchema.TLMessageMediaPhoto":
                        var mediaPhoto = message.Media as TLMessageMediaPhoto;

                        var photo = mediaPhoto.Photo as TLPhoto;

                        TLPhotoSize photoSize = photo.Sizes.ToList().OfType<TLPhotoSize>().Last();
                        TLFileLocation location = (TLFileLocation)photoSize.Location;

                        TLAbsInputFileLocation inputLocation = new TLInputFileLocation()
                        {
                            LocalId = location.LocalId,
                            Secret = location.Secret,
                            VolumeId = location.VolumeId
                        };
                        TLInputFileLocation inputFileLocation = inputLocation as TLInputFileLocation;

                        var photoFile = await _client.GetFile(inputFileLocation, 1024 * 512);
                        var photoPath = $"{imgPath}{photo.Id}.png";

                        ByteArrayToFile(photoPath, photoFile.Bytes);

                        return new Post()
                        {
                            PhotoPath = photoPath,
                            Text = mediaPhoto.Caption
                        }; 

                    default:
                        return null;
                }            
            }
            catch(Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                return null;
            }
        }

        public bool ByteArrayToFile(string fileName, byte[] byteArray)
        {
            try
            {
                using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(byteArray, 0, byteArray.Length);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught in process: {0}", ex);
                return false;
            }
        }

        private List<TLMessage> MessDiff(List<TLAbsMessage> l1, List<TLAbsMessage> l2)
        {
            var l1fixed = ConvertToNormal(l1);
            var l2fixed = ConvertToNormal(l2);

            var result = new List<TLMessage>();

            foreach(var mess in l1fixed)
            {
                if(!MessContain(l2fixed, mess))
                {
                    result.Add(mess);
                }
            }

            return result;
        }

        private List<TLMessage> ConvertToNormal(List<TLAbsMessage> list)
        {
            var res = new List<TLMessage>();

            list.ForEach(elm =>
            {
                var mess = elm as TLMessage;
                if(mess != null)
                {
                    res.Add(mess);
                }
            });

            return res;
        }

        private bool MessContain(List<TLMessage> list, TLMessage message)
        {
            foreach (var mess in list)
            {
                if (mess.Id == message.Id)
                {
                    return true;
                }
            }

            return false;
        }

        public async void SendMessage(string text)
        {
            await _client.SendMessageAsync(_chatPeer, text);
        }

        public async Task PrintMessages()
        {
            var messages = await GetMessages();
            foreach (var elm in messages)
            {
                try
                {
                    var message = elm as TLMessage;
                    Console.WriteLine((int)message.FromId + ": " + message.Message);
                }
                catch (Exception) { }
            }
        }
    }
}

I came across this in the previous issue, but did not find an answer there. Is there anyone alive here? Does anyone know what to do with this or how to get a photo from a message without errors?

@SmaGMan
Copy link

SmaGMan commented Nov 2, 2021

You need to use the TgSharp fork that supports the file references. There you can find examples https://github.com/SmaGMan/TgSharp#working-with-files

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants