Пример #1
0
        //public virtual async Task<string> GetLastMessageFromUser(string sUserName)
        //{
        //    string sResult;
        //    var client = new TLSharp.Core.TelegramClient(apiId, apiHash);
        //    await client.ConnectAsync();
        //    var normalizedUser = (sUserName.StartsWith("@") ?
        //        sUserName.Substring(1, sUserName.Length - 1) :
        //        sUserName).ToLower();
        //    var dialogs = (TLDialogs)await client.GetUserDialogsAsync();
        //    var user = dialogs.Users
        //        .Where(x => x.GetType() == typeof(TLUser))
        //        .OfType<TLUser>()
        //        .FirstOrDefault(x => x.Username != null && x.Username.ToLower() == normalizedUser);

        //    TLAbsMessages tlAbsMessages = await client.GetHistoryAsync(new TLInputPeerUser() {
        //        UserId = user.Id,
        //        AccessHash = user.AccessHash.Value
        //    }, 0, -1, 100);
        //    TLMessages tlMessages = (TLMessages)tlAbsMessages;
        //    TLMessage lastmessage = (TLMessage)tlMessages.Messages[0];
        //    sResult = lastmessage.FromId.ToString() + ":" + lastmessage.Message;
        //    return sResult;
        //}
        public virtual async Task <TLMessage> GetLastMessageFromUser(string sUserName)
        {
            TLMessage lastmessage = null;
            var       client      = new TLSharp.Core.TelegramClient(apiId, apiHash);
            await client.ConnectAsync();

            var normalizedUser = (sUserName.StartsWith("@") ?
                                  sUserName.Substring(1, sUserName.Length - 1) :
                                  sUserName).ToLower();
            var dialogs = (TLDialogs)await client.GetUserDialogsAsync();

            var user = dialogs.Users
                       .Where(x => x.GetType() == typeof(TLUser))
                       .OfType <TLUser>()
                       .FirstOrDefault(x => x.Username != null && x.Username.ToLower() == normalizedUser);

            TLAbsMessages tlAbsMessages = await client.GetHistoryAsync(new TLInputPeerUser()
            {
                UserId     = user.Id,
                AccessHash = user.AccessHash.Value
            }, 0, -1, 100);

            if (tlAbsMessages.GetType() == typeof(TLMessagesSlice))
            {
                var castMessages = (TLMessagesSlice)tlAbsMessages;
                lastmessage = (TLMessage)castMessages.Messages[0];
            }
            else if (tlAbsMessages.GetType() == typeof(TLMessages))
            {
                TLMessages tlMessages = (TLMessages)tlAbsMessages;
                lastmessage = (TLMessage)tlMessages.Messages[0];
            }
            return(lastmessage);
        }
        /// <summary>
        /// Возвращает код-во людей
        /// </summary>
        /// <param name="channelName"></param>
        /// <returns>Получение кол-во людей (int) в канале  , если что-то пошло не так вернет -1</returns>
        public async Task <Int32> GetCountParticipantsChannelandSuperGroup(String channelName)
        {
            if (client == null)
            {
                return(-1);
            }
            TLAbsDialogs dialogs_temp = await client.GetUserDialogsAsync();

            TLDialogsSlice dialogs = dialogs_temp as TLDialogsSlice;

            TeleSharp.TL.Messages.TLChatFull res = new TeleSharp.TL.Messages.TLChatFull();
            try
            {
                TLChannel channelInfo = (await client.SendRequestAsync <TeleSharp.TL.Contacts.TLResolvedPeer>(
                                             new TeleSharp.TL.Contacts.TLRequestResolveUsername
                {
                    Username = channelName
                }).ConfigureAwait(false)).Chats.Last() as TeleSharp.TL.TLChannel;

                TLRequestGetFullChannel req = new TLRequestGetFullChannel()
                {
                    Channel = new TLInputChannel()
                    {
                        AccessHash = channelInfo.AccessHash.Value, ChannelId = channelInfo.Id
                    }
                };

                res = await client.SendRequestAsync <TeleSharp.TL.Messages.TLChatFull>(req);
            }
            catch
            {
                return(-1);
            }
            return((res.FullChat as TLChannelFull).ParticipantsCount.Value);
        }
Пример #3
0
        public virtual async Task SendMessageToUser(string toUserName, string message)
        {
            var client = new TLSharp.Core.TelegramClient(apiId, apiHash);
            await client.ConnectAsync();

            var normalizedUser = (toUserName.StartsWith("@") ?
                                  toUserName.Substring(1, toUserName.Length - 1) :
                                  toUserName).ToLower();
            var dialogs = (TLDialogs)await client.GetUserDialogsAsync();

            var user = dialogs.Users
                       .Where(x => x.GetType() == typeof(TLUser))
                       .OfType <TLUser>()
                       .FirstOrDefault(x => x.Username != null && x.Username.ToLower() == normalizedUser);

            if (user != null)
            {
                await client.SendTypingAsync(new TLInputPeerUser()
                {
                    UserId = user.Id, AccessHash = user.AccessHash.Value
                });

                await client.SendMessageAsync(new TLInputPeerUser()
                {
                    UserId = user.Id, AccessHash = user.AccessHash.Value
                }, message);
            }

            //await client.SendMessageAsync(new TLInputPeerUser() {  UserId = user.Id, AccessHash = user.AccessHash.Value }, message);


            //send message
            //await client.SendMessageAsync(new TLInputPeerChannel() { ChannelId = chat.Id, AccessHash = chat.AccessHash.Value }, "OUR_MESSAGE");
            //var result = await client.SearchUserAsync(normalizedUser, 10);
            //if (result.Users.Count > 0)
            //{
            //    TLUser user = (TLUser)result.Users[0];
            //    await client.SendMessageAsync(new TLInputPeerUser() { UserId = user.Id }, message);
            //}
            //var normalizedNumber1 = toUserName.StartsWith("@") ?
            //    toUserName.Substring(1, toUserName.Length - 1) :
            //    toUserName;

            //var user = result.Users
            //   .OfType<TLUser>()
            //   .FirstOrDefault(x => x.Username == toUserName);
            //await client.SendMessageAsync(new TLInputPeerUser() { UserId = user.Id }, message);
        }
Пример #4
0
        public virtual async Task SendMessage(string toNumber, string message)
        {
            var client = new TLSharp.Core.TelegramClient(apiId, apiHash);
            await client.ConnectAsync();

            var dialogs = (TLDialogs)await client.GetUserDialogsAsync();

            // this is because the contacts in the address come without the "+" prefix
            var normalizedNumber = toNumber.StartsWith("+") ?
                                   toNumber.Substring(1, toNumber.Length - 1) :
                                   toNumber;



            var user = dialogs.Users
                       .OfType <TLUser>()
                       .FirstOrDefault(x => x.Phone == normalizedNumber);
            await client.SendMessageAsync(new TLInputPeerUser()
            {
                UserId = user.Id, AccessHash = user.AccessHash.Value
            }, message);
        }
Пример #5
0
        /// <summary>
        /// 채팅 리스트를 가지고 온다.(개인 채팅은 제외)
        /// </summary>
        /// <returns></returns>
        public async Task <DataTable> ChatListGet()
        {
            //TeleSharp.TL.Messages.TLAbsDialogs dial = await client.GetUserDialogsAsync();

            TLDialogs dialogs = (TLDialogs)await client.GetUserDialogsAsync();


            if (_chatList == null)
            {
                _chatList = Fnc.DataTable_SchemaByObject("TelegramChatList", dialogs.chats.lists[0]);

                //_chatList.Columns.Add("access_hash", typeof(System.String));
            }

            _chatList.Rows.Clear();
            //DataRow dr;



            Fnc.DataTable_InsDataFromObject(_chatList, dialogs.chats.lists);

            return(_chatList);
        }
Пример #6
0
        public async Task <List <TLMessage> > GatherChannelHistory(string channelName, int offset = 0, int maxId = -1, int limit = 50)
        {
            List <TLMessage> _resultMessages = new List <TLMessage>();
            var client = new TLSharp.Core.TelegramClient(apiId, apiHash);
            await client.ConnectAsync();

            var dialogs = (TLDialogs)await client.GetUserDialogsAsync();

            var chat = dialogs.Chats.ToList()
                       .OfType <TLChannel>()
                       .FirstOrDefault(c => c.Title == channelName);

            if (chat.AccessHash != null)
            {
                TLChannel channel = new TLChannel()
                {
                    Id = chat.Id, AccessHash = chat.AccessHash
                };

                var request = new TLRequestGetFullChannel();

                var fullChat = await client.SendRequestAsync <TLRequestGetFullChannel>(request);

                //var request = new TLRequestGetFullChat() { ChatId = chat.Id };
                //var fullChat = await client.SendRequestAsync<TeleSharp.TL.Messages.TLChatFull>(request);
                //var request = new TLRequestGetMessages() { Id = chat. };
                //var fullChat = await client.SendRequestAsync<TeleSharp.TL.Channels.TLRequestGetMessages>(request);
                //var request = new TLRequestGetAllChats() { };
                //var fullChat = await client.SendRequestAsync<TeleSharp.TL.Messages.TLRequestGetAllChats>(request);

                var tlAbsMessages =
                    await client.GetHistoryAsync(
                        new TLInputPeerChannel { ChannelId = chat.Id, AccessHash = chat.AccessHash.Value }, offset,
                        maxId, limit);

                var tlChannelMessages = (TLChannelMessages)tlAbsMessages;

                for (var index = 0; index < tlChannelMessages.Messages.Count - 1; index++)
                {
                    var tlAbsMessage = tlChannelMessages.Messages.ToList()[index];
                    var message      = (TLMessage)tlAbsMessage;
                    //Now you have the message and you can do what you need with it
                    //the code below is an example of messages classification
                    if (message.Media == null)
                    {
                        _resultMessages.Add(new TLMessage()
                        {
                            Id      = message.Id,
                            FromId  = chat.Id,
                            Message = message.Message,
                            Views   = message.Views,
                        });
                    }
                    else
                    {
                        switch (message.Media.GetType().ToString())
                        {
                        case "TeleSharp.TL.TLMessageMediaPhoto":
                            var tLMessageMediaPhoto = (TLMessageMediaPhoto)message.Media;

                            _resultMessages.Add(new TLMessage()
                            {
                                Id      = message.Id,
                                FromId  = chat.Id,
                                Message = message.Message,
                                Views   = message.Views,
                                Media   = message.Media,
                            });
                            break;
                            //case "TeleSharp.TL.TLMessageMediaDocument":
                            //    var tLMessageMediaDocument = (TLMessageMediaDocument)message.media;

                            //    _resultMessages.Add(new ChannelMessage()
                            //    {
                            //        Id = message.id,
                            //        ChannelId = chat.id,
                            //        Content = tLMessageMediaDocument.caption,
                            //        Type = EnChannelMessage.MediaDocument,
                            //        Views = message.views ?? 0,
                            //    });
                            //    break;
                            //case "TeleSharp.TL.TLMessageMediaWebPage":
                            //    var tLMessageMediaWebPage = (TLMessageMediaWebPage)message.media;
                            //    string url = string.Empty;
                            //    if (tLMessageMediaWebPage.webpage.GetType().ToString() != "TeleSharp.TL.TLWebPageEmpty")
                            //    {
                            //        var webPage = (TLWebPage)tLMessageMediaWebPage.webpage;
                            //        url = webPage.url;
                            //    }

                            //    _resultMessages.Add(new ChannelMessage
                            //    {
                            //        Id = message.id,
                            //        ChannelId = chat.id,
                            //        Content = message.message + @" : " + url,
                            //        Type = EnChannelMessage.WebPage,
                            //        Views = message.views ?? 0,
                            //    });
                            //    break;
                        }
                    }
                }
            }
            return(_resultMessages);
        }
        private async Task ExportMessagesToWord()
        {
            using var telegram = new TLSharp.Core.TelegramClient(_authConfiguration.ApiId, _authConfiguration.ApiHash,
                                                                 null,
                                                                 _authConfiguration.SessionUserId);
            await telegram.ConnectAsync();

            await Task.Delay(10000);

            var dialogs = (TLDialogs)await telegram.GetUserDialogsAsync();

            var channel = dialogs.Chats
                          .OfType <TLChannel>()
                          .FirstOrDefault(c => c.Title == _myChannelConfiguration.ChannelHeapName);
            var inputPeer = new TLInputPeerChannel()
            {
                ChannelId  = channel.Id,
                AccessHash = (long)channel.AccessHash
            };

            var offset = 0;
            var sig    = false;

            await using var fs = new FileStream(
                            Path.Combine(
                                _reportConfiguration.FullPath,
                                $"{_reportConfiguration.Name}-{DateTime.Now:MM-dd-yyyy}.docx"
                                ),
                            FileMode.Create,
                            FileAccess.Write
                            );
            var doc       = new XWPFDocument();
            var paragraph = doc.CreateParagraph();
            var run       = paragraph.CreateRun();

            while (true)
            {
                if (sig)
                {
                    break;
                }

                await Task.Delay(10000);

                var res = await telegram.SendRequestAsync <TLChannelMessages>(
                    new TLRequestGetHistory()
                {
                    Peer      = inputPeer,
                    Limit     = 100,
                    AddOffset = offset,
                    OffsetId  = 0
                }
                    );

                var msgs = res.Messages;

                if (res.Count <= offset)
                {
                    break;
                }
                offset += msgs.Count;

                foreach (var msg in msgs)
                {
                    if (!(msg is TLMessage message))
                    {
                        continue;
                    }

                    if (string.IsNullOrEmpty(message.Message))
                    {
                        continue;
                    }

                    if (message.Date > (int)DateTimeOffset.Parse(DateTime.UtcNow.ToString("MM/dd/yyyy"))
                        .ToUnixTimeSeconds())
                    {
                        continue;
                    }

                    if (message.Date < (int)DateTimeOffset.Parse(DateTime.UtcNow.AddDays(-1).ToString("MM/dd/yyyy"))
                        .ToUnixTimeSeconds())
                    {
                        sig = true;
                        break;
                    }

                    await Task.Delay(1000);

                    var ch = dialogs.Chats
                             .OfType <TLChannel>()
                             .FirstOrDefault(c => c.Id == message.FwdFrom.ChannelId);

                    if (ch == null)
                    {
                        continue;
                    }
                    run.AppendText(@$ "Канал: {ch.Title}");
                    run.AddCarriageReturn();
                    run.AppendText(
                        @$ "Дата: {new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(message.Date):d-M-yyyy HH:mm:ss}"
                        );
                    run.AddCarriageReturn();
                    run.AppendText(
                        @$ "Сообщение: {message.Message.Replace(" \ n ", string.Empty).Replace(" \ r ", string.Empty).Replace(" \ t ", string.Empty)}"
                        );
                    run.AddCarriageReturn();
                    run.AddCarriageReturn();
                    run.AddCarriageReturn();
                }
            }

            doc.Write(fs);
        }
        public static async Task <ModelParserInfo> ParserInfoAboutChannelAndSuperGroup(String channelName, TLSharp.Core.TelegramClient client, Int32 countMessageParse = 200)
        {
            ModelParserInfo info   = new ModelParserInfo();
            ChannelInfo     result = new ChannelInfo();

            List <Int32> AverageViews = new List <Int32>();
            TLChannel    channelInfo;

            if (client == null)
            {
                return(null);
            }
            var            dialogs_temp = client.GetUserDialogsAsync().GetAwaiter().GetResult();
            TLDialogsSlice dialogs      = dialogs_temp as TLDialogsSlice;

            TeleSharp.TL.Messages.TLChatFull res = new TeleSharp.TL.Messages.TLChatFull();

            channelInfo = (client.SendRequestAsync <TeleSharp.TL.Contacts.TLResolvedPeer>(
                               new TeleSharp.TL.Contacts.TLRequestResolveUsername
            {
                Username = channelName
            }).ConfigureAwait(false)).GetAwaiter().GetResult().Chats.Last() as TeleSharp.TL.TLChannel;

            TLRequestGetFullChannel req = new TLRequestGetFullChannel()
            {
                Channel = new TLInputChannel()
                {
                    AccessHash = channelInfo.AccessHash.Value, ChannelId = channelInfo.Id
                }
            };

            res = client.SendRequestAsync <TeleSharp.TL.Messages.TLChatFull>(req).GetAwaiter().GetResult();
            Int32 offset = 0;

            result.Channel   = channelInfo;
            result.ChatFull  = res;
            info.ChannelInfo = result;
            info.CountPeople = (res.FullChat as TLChannelFull).ParticipantsCount.Value;
            info.Avatar      = (res.FullChat as TLChannelFull).ChatPhoto as TLPhoto;
            info.About       = (res.FullChat as TLChannelFull).About;
            TLChannelMessages       temp = new TLChannelMessages();
            TLVector <TLAbsMessage> msgs = new TLVector <TLAbsMessage>();

            do
            {
                try
                {
                    temp = client.SendRequestAsync <TLChannelMessages>
                               (new TLRequestGetHistory()
                    {
                        Peer = new TLInputPeerChannel()
                        {
                            ChannelId = result.Channel.Id, AccessHash = (long)result.Channel.AccessHash
                        },
                        Limit     = 500,
                        AddOffset = offset,
                        OffsetId  = 0
                    }).GetAwaiter().GetResult();
                    msgs = temp.Messages;
                }
                catch
                {
                    await Task.Delay(3000);
                }
                if (countMessageParse != 0)
                {
                    offset            = temp.Count - countMessageParse;
                    countMessageParse = 0;
                }
                if (temp.Count > offset || temp.Count == 0)
                {
                    offset += msgs.Count;
                    foreach (var msg in msgs)
                    {
                        if (msg is TLMessage)
                        {
                            TLMessage sms = msg as TLMessage;
                            if (sms.Views != null)
                            {
                                AverageViews.Add(sms.Views.Value);
                            }
                            info.CountMessage++;
                            if (sms.Media != null)
                            {
                                info.CountMediaFiles++;

                                if (sms.Media is TLMessageMediaDocument)
                                {
                                    info.ChannelParserMediaInfo.CountVideo++;
                                }
                                else if (sms.Media is TLMessageMediaPhoto)
                                {
                                    info.ChannelParserMediaInfo.CountPhoto++;
                                }
                                else if (sms.Media is TLMessageMediaWebPage)
                                {
                                    info.ChannelParserMediaInfo.CountWebPag++;
                                }
                                else if (sms.Media is TLMessageMediaContact)
                                {
                                    info.ChannelParserMediaInfo.CountContact++;
                                }
                            }
                        }
                        if (msg is TLMessageService)
                        {
                            continue;
                        }
                    }
                }
                else
                {
                    break;
                }
            } while (temp.Count > offset || temp.Count == 0);

            if (AverageViews.Count != 0)
            {
                info.AverageViews = AverageViews.Sum() / AverageViews.Count;
            }

            return(info);
        }