Search code examples
c#telegramtelegram-api

C# How to get messages from channel/contact using Telegram API (not Bot API)


I found many examples using the bot api, however I need a simple client that implements an event when a message from a contact or group is received, as a user and not a bot (so the Telegram api, and not Bot api). TLSharp library doesn't implement this method. What is the best way to achieve it?


Solution

  • The provided link is old but it was a good starting point. Here is the updated working code:

     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);
                }