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

How to listen new message / use handle update? #580

Closed
munrocket opened this issue Sep 25, 2017 · 22 comments
Closed

How to listen new message / use handle update? #580

munrocket opened this issue Sep 25, 2017 · 22 comments

Comments

@munrocket
Copy link

munrocket commented Sep 25, 2017

According to #361 #43 right way to get new messages is TLRequestGetDifference or HandleUpdate usage. Also we can find official manual about processing updates: https://core.telegram.org/api/updates
Here we need an source code example. Same questions: #564 #239 #436 #457 #524 #538 #547 #570

@munrocket
Copy link
Author

munrocket commented Sep 26, 2017

If you need to catch new message from user or group after authorizing, you can check status in simple loop without getting FLOOD_EXCEPTION. But this not working with channels.

while (true) {
   var state = await telegram.SendRequestAsync<TLState>(new TLRequestGetState());
   if (state.unread_count > 0) { ... }
   await Task.Delay(500);
}

@munrocket
Copy link
Author

munrocket commented Sep 26, 2017

In general you need to create test channel, test group and second user and check whats happends with this code pattern (or try to use PUSH notification https://core.telegram.org/api/push-updates with TeleSharp.TL.Account.TLRequestRegisterDevice). General testing pattern:

while (true)
{
    var state = await telegram.SendRequestAsync<TLState>(new TLRequestGetState());
    var req = new TLRequestGetDifference() { date = state.date, pts = state.pts, qts = state.qts };
    var adiff = await telegram.SendRequestAsync<TLAbsDifference>(req);
    if (!(adiff is TLDifferenceEmpty))
    {
        if (adiff is TLDifference)
        {
            var diff = adiff as TLDifference;
            Console.WriteLine("chats:" + diff.chats.lists.Count);
            Console.WriteLine("encrypted:" + diff.new_encrypted_messages.lists.Count);
            Console.WriteLine("new:" + diff.new_messages.lists.Count);
            Console.WriteLine("user:" + diff.users.lists.Count);
            Console.WriteLine("other:" + diff.other_updates.lists.Count);
        }
        else if (adiff is TLDifferenceTooLong)
            Console.WriteLine("too long");
        else if (adiff is TLDifferenceSlice)
            Console.WriteLine("slice");
    }
    await Task.Delay(500);
}

@munrocket
Copy link
Author

munrocket commented Sep 26, 2017

Finnaly I use this code for reading my channels and mark message as read

while (true)
{
    var state = await telegram.SendRequestAsync<TLState>(new TLRequestGetState());
    var req = new TLRequestGetDifference() { date = state.date, pts = state.pts, qts = state.qts };
    var diff = await telegram.SendRequestAsync<TLAbsDifference>(req) as TLDifference;
    if (diff != null)
    {
        foreach (var upd in diff.other_updates.lists.OfType<TLUpdateNewChannelMessage>())
            Console.WriteLine((upd.message as TLMessage).message);

        foreach(var ch in diff.chats.lists.OfType<TLChannel>().Where(x => !x.left))
        {
            var ich = new TLInputChannel() { channel_id = ch.id, access_hash = (long)ch.access_hash };
            var readed = new TeleSharp.TL.Channels.TLRequestReadHistory() { channel = ich, max_id = -1 };
            await telegram.SendRequestAsync<bool>(readed);
        }
    }
    await Task.Delay(500);
}

@Rman77
Copy link

Rman77 commented Oct 5, 2017

        while (true)
        {
            var state = await client.SendRequestAsync<TLState>(new TLRequestGetState());
            var req = new TLRequestGetDifference() { date = state.date, pts = state.pts, qts = state.qts };
            var diff = await client.SendRequestAsync<TLAbsDifference>(req) as TLDifference;

            if (diff != null) {
                foreach (var x in diff.new_messages.lists.OfType<TLUpdateNewMessage>())
                {
                    listBox1.Items.Add((x.message as TLMessage).message);
                }
            }
            await Task.Delay(500);
        }

why my code doesn't work ? @mirror-neuron

@snrchang
Copy link

so "upd.message as TLMessage).message" get you the message but how would u get a photo in the message or know what channel the message came from?
Please help a brother out.

@snrchang
Copy link

munrocket thats nothing to do with the question i asked sir.

@snrchang
Copy link

while (true)
{
var state = await telegram.SendRequestAsync(new TLRequestGetState());
var req = new TLRequestGetDifference() { date = state.date, pts = state.pts, qts = state.qts };
var diff = await telegram.SendRequestAsync(req) as TLDifference;
if (diff != null)
{
foreach (var upd in diff.other_updates.lists.OfType())
Console.WriteLine((upd.message as TLMessage).message);

    foreach(var ch in diff.chats.lists.OfType<TLChannel>().Where(x => !x.left))
    {
        var ich = new TLInputChannel() { channel_id = ch.id, access_hash = (long)ch.access_hash };
        var readed = new TeleSharp.TL.Channels.TLRequestReadHistory() { channel = ich, max_id = -1 };
        await telegram.SendRequestAsync<bool>(readed);
    }
}
await Task.Delay(500);

}
This code is ideal but i would like to accept photos and get the name of the channel of the incoming message.

thanks

@GodSpeedXI
Copy link

GodSpeedXI commented Dec 26, 2017

Someone Please give me an example how to use TLRequestRegisterDevice.
I want to get notify when messages are coming from every chat.

I try to use something like this.

var tlRequestRegisterDevice = new TLRequestRegisterDevice(){ TokenType = 2, Token = _hash};
var notify = await _telegramClient.SendRequestAsync<TLMethod>(_tlRequestRegisterDevice);

Thanks.

@RiddlerKnight
Copy link

RiddlerKnight commented Dec 26, 2017

Hello I have tried this code so many times.

var state = await telegram.SendRequestAsync<TLState>(new TLRequestGetState());
var req = new TLRequestGetDifference() { date = state.date, pts = state.pts, qts = state.qts };
var diff = await telegram.SendRequestAsync<TLAbsDifference>(req) as TLDifference;

And I found that diff will be returned "TLDifferenceEmpty" always.

@Arvezz
Copy link

Arvezz commented Jan 5, 2018

Does anyone know why why compiler cant find "lists"? I am trying read last message

@amirvenus
Copy link

@ProjektAI

try to use .ToList() instead

@Maverick1983
Copy link

@pisitch I have same problem. Anyone resolve it?

@J1herm
Copy link

J1herm commented Sep 21, 2018

Ok I'm getting a few grey hairs now..

I am wanting to forward messages between groups. User sets up which group forwards to whom.

so select from group from drop down, and select to group. then config that from that point going forward all new messages are automatically forwarded from the one group to the other..

I am able to get the user to select To and From group and forward the last message sent to the from group gets forwarded to the To group with this code

   var tlAbsMessages = await client.GetHistoryAsync(new TLInputPeerChat { ChatId = chat1.Id }, 0, -1,  50 );
                    var tlChatMessage = (TLMessages)tlAbsMessages;
                    var tlAbsMessage = tlChatMessage.Messages.ToList()[0];
                    var message = (TLMessage)tlAbsMessage;
                    messageID = message.Id;


   //Request for Forward: 
                    TLRequestForwardMessages rq = new TLRequestForwardMessages();
                    rq.FromPeer = new TLInputPeerChat() { ChatId = chat2.Id };
                    rq.ToPeer = new TLInputPeerChat() { ChatId = chat1.Id };


                    TLVector<long> rn = new TLVector<long>();
                    TLVector<int> idd = new TLVector<int>();

                    rn.Add(rnd.Next(1000, 5000));
                    // messageID is the last post ID of the channel or group the last messages posted's ID
                    idd.Add(messageID); 
                    rq.RandomId = rn;
                    rq.MessageId = messageID; 
                    rq.Id = idd;
                    rq.Silent = true;
                    rq.WithMyScore = true;

                    TLUpdates rr = await client.SendRequestAsync<TLUpdates>(rq);

But now I am at the point where I want to forward any new messages received on the from group to that To group as well.

 var state = await client.SendRequestAsync<TLState>(new TLRequestGetState());
                var req = new TLRequestGetDifference() { Date = state.Date, Pts = state.Pts, Qts = state.Qts };
                var adiff = await client.SendRequestAsync<TLAbsDifference>(req) as TLDifference;

not sure how to hook this up to listen for new messages on a particular group to forward.
maybe I am on the wrong track
any help /direction will be much be appreciated...

@munrocket
Copy link
Author

munrocket commented Sep 21, 2018

But now I am at the point where I want to forward any new messages received on the from group to that To group as well.

As i know sending message much easier than listen updates. Try with sipmle message and another user at first.

@aroaddy
Copy link

aroaddy commented Oct 11, 2018

If you need to catch new message from user or group after authorizing, you can check status in simple loop without getting FLOOD_EXCEPTION. But this not working with channels.

while (true) {
   var state = await telegram.SendRequestAsync<TLState>(new TLRequestGetState());
   if (state.unread_count > 0) { ... }
   await Task.Delay(500);
}

Hello please i would like to know where to paste this code, how do I implement in a way that it always listens for a new message.

@Trinitron
Copy link

Trinitron commented Mar 3, 2019

@munrocket I want just simply track incoming messages from certain user. Why using this peace of code in while loop i miss approximately 5/6 of incoming messages? where are the rest?
await telegram.SendRequestAsync<TLState>(new TLRequestGetState());
Do i need subract 500ms from Date property of TLRequestGetDifference or how?

@munrocket
Copy link
Author

@Trinitron just use telethon and relax, TLSharp has an annoying verbouse api.

@Trinitron
Copy link

Trinitron commented Mar 7, 2019

If someone still uses this library and struggling between unobvious exceptions here is my small example how to listen incomming telegram messages:
_lastMessageStamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            while (true)
            {
                var state = await _client.SendRequestAsync<TLState>(new TLRequestGetState());
                TrackingState = state.Pts.ToString();
                var req = new TLRequestGetDifference() { Date = state.Date, Pts = state.Pts-10, Qts = state.Qts };
                var diff = await _client.SendRequestAsync<TLAbsDifference>(req);
                var msgs = diff as TLDifference;
                if (msgs!=null && msgs.NewMessages.Count>0)
                {
                    var mss = msgs.NewMessages.Where(x => x.GetType() == typeof(TLMessage))
                        .Cast<TLMessage>().ToList().Where(x => x.Date > _lastMessageStamp && x.Out == false)
                        .OrderBy(dt => dt.Date);

                    foreach (TLMessage upd in mss)
                    {
                        Console.WriteLine("New message ({0}): {1}", upd.Date, upd.Message);
                    }
                    _lastMessageStamp = mss.Any() ? mss.Max(x => x.Date) : _lastMessageStamp;
                }
                await Task.Delay(2500);
            }

state.Pts-10 shows that i need only 10 last messages;

@asensionacher
Copy link

_lastMessageStamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

I always receive TLDifferenceEmpty, do you know why?

@RomanSoloweow
Copy link

RomanSoloweow commented Jul 31, 2020

            while (true)
            {
                var state = await _Client.SendRequestAsync<TLState>(new TLRequestGetState());
                if(state.UnreadCount>0)
                {
                    var req = new TLRequestGetDifference() { Date = state.Date, Pts = state.Pts-state.UnreadCount, Qts = state.Qts, Sequence = state.Seq};
                    var diff = await _Client.SendRequestAsync<TLAbsDifference>(req) as TLDifference;
                }
                
                await Task.Delay(500);
            }

state.Pts-state.UnreadCount - it's solve

@Invectys
Copy link

ModernTLSharp solve this problem

@knocte
Copy link
Collaborator

knocte commented Oct 10, 2020

... solves this problem

Also this PR: #940 can anyone test it please?

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