コード例 #1
0
 public void AddAndFilterMessages(TLChannelMessages msgs)
 {
     try
     {
         for (int i = 0; i < msgs.Messages.Count; i++)
         {
             if (msgs.Messages[i].ToString() == "TeleSharp.TL.TLMessage")
             {
                 var    message = (TLMessage)msgs.Messages[i];
                 string tmp_msg = message.Message.ToString();
                 if (tmp_msg.Contains("instagram.com"))
                 {
                     filtered_messages.Add(message);
                 }
             }
             else
             {
                 //MessageBox.Show("To MessageService - pierdole to...");
             }
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.Write("sad " + ex.Message.ToString());
     }
 }
コード例 #2
0
 public TelegramMessages(TLChannelMessages messages)
 {
     Messages = messages.Messages;
     Chats    = messages.Chats;
     Users    = messages.Users;
     Count    = messages.Count;
 }
コード例 #3
0
ファイル: Message.cs プロジェクト: Anna-kl/Telegram_bot
        public async Task <TLChannelMessages> GetMessageFromChannelAsync(TLChannel channel, TelegramClient client)
        {
            TLChannelMessages res = await client.SendRequestAsync <TLChannelMessages>
                                        (new TLRequestGetHistory()
            {
                Peer = new TLInputPeerChannel {
                    ChannelId = channel.Id, AccessHash = channel.AccessHash.Value
                },
                Limit     = 400,
                AddOffset = 100,
                OffsetId  = 0
            });

            return(res);
        }
コード例 #4
0
        public async Task <List <Message> > GetChannelMessagesAsync(int channelId, long accessHash, int?offsetId, int?offsetDate, int?limit)
        {
            var req = new TLRequestGetHistory()
            {
                Peer = new TLInputPeerChannel()
                {
                    ChannelId = channelId, AccessHash = accessHash
                },
                OffsetId   = offsetId ?? 0,
                OffsetDate = offsetDate ?? 0,
                Limit      = limit ?? 0
            };
            TLChannelMessages messages = new TLChannelMessages();

            messages = await _client.SendRequestAsync <TLChannelMessages>(req);

            return(RefineMessages(messages));
        }
コード例 #5
0
        public static async Task <IEnumerable <TLMessage> > GetChannelUnreadmessages(string channelUsername, TLDialogs dialogs)
        {
            IEnumerable <TLMessage> unreadMessages;

            foreach (TLDialog dialog in dialogs.Dialogs.Where(lambdaDialog => lambdaDialog.Peer is TLPeerChannel /* && lambdaDialog.UnreadCount > 0*/))
            {
                TLPeerChannel peer    = (TLPeerChannel)dialog.Peer;
                TLChannel     channel = dialogs.Chats.OfType <TLChannel>().First(lambdaChannel => lambdaChannel.Id == peer.ChannelId);
                Console.WriteLine(channel.Username);


                if (channel.Username == channelUsername && dialog.UnreadCount > 0)
                {
                    var target = new TLInputPeerChannel
                    {
                        ChannelId = channel.Id, AccessHash = channel.AccessHash ?? 0
                    };


                    TLChannelMessages hist =
                        (TLChannelMessages)_client.GetHistoryAsync(target, 0, 0, 0).Result;


                    int takecount = 25;
                    if (dialog.UnreadCount < 25)
                    {
                        takecount = dialog.UnreadCount;
                    }

                    var hists = hist.Messages.OfType <TLMessage>().ToList();
                    unreadMessages = hist.Messages
                                     .Take(takecount).OfType <TLMessage>();


                    //MarkMessage as unread
                    MarkMessagesasRead(channel, unreadMessages.ToList()[0]).Wait();
                    return(unreadMessages);
                }
            }

            return(null);
        }
コード例 #6
0
        public async void first_channels()
        {
            foreach (var item in channels)
            {
                TLChannelMessages result = await client.SendRequestAsync <TLChannelMessages>
                                               (new TLRequestGetHistory()
                {
                    Peer      = item.channel,
                    Limit     = 1,
                    AddOffset = 0,
                    OffsetId  = 0,
                });

                foreach (var items in result.Messages)
                {
                    TLMessage tLMessage = items as TLMessage;
                    item.prevIds = tLMessage.Id;
                }
            }
        }
コード例 #7
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);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
コード例 #8
0
        public async Task UnRead2()
        {
            var rnd = new Random();

            while (true)
            {
                Task.Delay(rnd.Next(3000, 6000)).Wait();
                var dialogs = telegramClient.GetUserDialogsAsync().Result as TLDialogs;

                if (dialogs == null)
                {
                    Task.Delay(rnd.Next(3000, 6000)).Wait();
                    continue;
                }

                foreach (TLDialog dialog in dialogs.Dialogs.Where(lambdaDialog => lambdaDialog.Peer is TLPeerChannel && lambdaDialog.UnreadCount > 0))
                {
                    TLPeerChannel      peer    = (TLPeerChannel)dialog.Peer;
                    TLChannel          channel = dialogs.Chats.OfType <TLChannel>().First(lambdaChannel => lambdaChannel.Id == peer.ChannelId);
                    TLInputPeerChannel target  = new TLInputPeerChannel {
                        ChannelId = channel.Id, AccessHash = channel.AccessHash ?? 0
                    };

                    Task.Delay(rnd.Next(3000, 6000)).Wait();
                    TLChannelMessages hist = (TLChannelMessages)telegramClient.GetHistoryAsync(target, 0, -1, dialog.UnreadCount).Result;
                    if (hist == null)
                    {
                        continue;
                    }

                    var users    = hist.Users.OfType <TLUser>().ToList();
                    var messages = hist.Messages.OfType <TLMessage>().ToList();

                    foreach (TLMessage message in messages)
                    {
                        TLUser sentUser = users.Single(lambdaUser => lambdaUser.Id == message.FromId);
                        Console.WriteLine($"{channel.Title} {sentUser.FirstName} {sentUser.LastName} {sentUser.Username}: {message.Message}");
                    }

                    TLInputChannel channelToMarkRead = new TLInputChannel {
                        ChannelId = target.ChannelId, AccessHash = target.AccessHash
                    };
                    var firstAbsMessage = hist.Messages[0];
                    int firstUnreadMessageId;
                    if (firstAbsMessage is TLMessage)
                    {
                        firstUnreadMessageId = ((TLMessage)firstAbsMessage).Id;
                    }
                    else if (firstAbsMessage is TLMessageService)
                    {
                        firstUnreadMessageId = ((TLMessageService)firstAbsMessage).Id;
                    }
                    else
                    {
                        continue;
                    }

                    var markHistoryAsReadRequest = new TLSchema.Channels.TLRequestReadHistory
                    {
                        Channel         = channelToMarkRead,
                        MaxId           = -1,
                        ConfirmReceived = true,
                        Dirty           = true,
                        MessageId       = firstUnreadMessageId,
                        Sequence        = dialog.UnreadCount
                    };

                    Task.Delay(rnd.Next(3000, 6000)).Wait();
                    telegramClient.SendRequestAsync <bool>(markHistoryAsReadRequest).Wait();

                    Console.WriteLine("Mark messages as read");
                }
            }
        }
コード例 #9
0
ファイル: Telega.cs プロジェクト: Dims-M/ZapuskatorApp
        //public virtual async Task AuthUser()
        //{
        //    var client = NewClient();

        //    await client.ConnectAsync();

        //    var hash = await client.SendCodeRequestAsync(NumberToAuthenticate);
        //    var code = CodeToAuthenticate; // you can change code in debugger too

        //    if (String.IsNullOrWhiteSpace(code))
        //    {
        //        throw new Exception("CodeToAuthenticate is empty in the app.config file, fill it with the code you just got now by SMS/Telegram");
        //    }

        //    TLUser user = null;
        //    try
        //    {
        //        user = await client.MakeAuthAsync(NumberToAuthenticate, hash, code);
        //    }
        //    catch (CloudPasswordNeededException ex)
        //    {
        //        var passwordSetting = await client.GetPasswordSetting();
        //        var password = PasswordToAuthenticate;

        //        user = await client.MakeAuthWithPasswordAsync(passwordSetting, password);
        //    }
        //    catch (InvalidPhoneCodeException ex)
        //    {
        //        throw new Exception("CodeToAuthenticate is wrong in the app.config file, fill it with the code you just got now by SMS/Telegram",
        //                            ex);
        //    }
        //    Assert.IsNotNull(user);
        //    Assert.IsTrue(client.IsUserAuthorized());
        //}


        public async Task <string> button3_ClickAsync()
        {
            try
            {
                bool stop  = true;
                int  count = 2;

                client = new TelegramClient(apiId, apiHash);

                await client.ConnectAsync();

                //var hash = await client.SendCodeRequestAsync("+79179037140");

                //var code = "72772";
                //var user = await client.MakeAuthAsync("+79179037140", hash, code);

                // DownloadFileFromWrongLocationTest();

                sb.Append("#\tDate\tTime\tMID\tTUID\tText" + Environment.NewLine);
                TLDialogsSlice dialogs = (TLDialogsSlice)await client.GetUserDialogsAsync(); //Получаем список чатов(диалогов)

                // var tempDialogsChats = dialogs.Chats; // выгружаем  полученные список чатов

                foreach (var element in dialogs.Chats)
                {
                    if (element is TLChat)
                    {
                        TLChat chats = element as TLChat;
                        listChats += $"Название {chats.Title} ID чата {chats.Id} " + Environment.NewLine;
                    }

                    if (element is TLChannel)
                    {
                        TLChannel chats = element as TLChannel;
                        listChats += $"Название {chats.Title} ID чата {chats.Id} " + Environment.NewLine;
                    }

                    if (element is TLChatForbidden)
                    {
                        TLChatForbidden chats = element as TLChatForbidden;
                        listChats += $"Название {chats.Title} ID чата {chats.Id} " + Environment.NewLine;
                    }


                    //if (chats is TLDialogS)
                    //    continue;
                }
                SaveTextFile(listChats, "Список чатов.txt");


                TLChannel chat = dialogs.Chats.Where(c => c.GetType() == typeof(TLChannel)).Cast <TLChannel>().FirstOrDefault(c => c.Id == VKFID); //Выбираем нужный нам чат

                //if (chat == null)
                // {

                // }

                TLInputPeerChannel inputPeer = new TLInputPeerChannel()
                {
                    ChannelId = chat.Id, AccessHash = (long)chat.AccessHash
                };

                while (stop)
                {
                    if (n > count)
                    {
                        stop = false;
                    }
                    try
                    {
                        TLChannelMessages res = await client.SendRequestAsync <TLChannelMessages> //получаем список все собщений из выбранного чата
                                                    (new TLRequestGetHistory()
                        {
                            Peer = inputPeer, Limit = 1000, AddOffset = offset, OffsetId = 0
                        });

                        var msgs = res.Messages; // выгружаем список сообщений

                        count = res.Count++;

                        if (res.Count > offset)
                        {
                            offset += msgs.Count;
                            foreach (TLAbsMessage msg in msgs)
                            {
                                if (msg is TLMessage)
                                {
                                    TLMessage message = msg as TLMessage;
                                    sb.Append(n.ToString() + "\t" +
                                              ConvertFromUnixTimestamp(message.Date).ToLocalTime().ToString("dd'.'MM'.'yyyy") + "\t" +
                                              ConvertFromUnixTimestamp(message.Date).ToLocalTime().ToString("HH':'mm':'ss") + "\t" +
                                              message.Id + "\t" + message.FromId + "\t" + message.Message + Environment.NewLine);
                                }

                                if (msg is TLMessageService)
                                {
                                    continue;
                                }
                                n++;
                            }
                            SaveTextFile(sb.ToString());
                            SaveTextFileBuilder(sb);
                            Thread.Sleep(22000);
                            //Thread.Sleep(22000); //to avoid TelegramFloodException 36,67 минут https://www.yandex.ru/search/?lr=43&offline_search=1&text=%D0%BA%D0%B0%D0%BB%D1%8C%D0%BA%D1%83%D0%BB%D1%8F%D1%82%D0%BE%D1%80%20%D1%81%D0%B5%D0%BA%D1%83%D0%BD%D0%B4%20%D0%B2%20%D0%BC%D0%B8%D0%BD%D1%83%D1%82%D1%8B
                        }
                        else
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        SaveTextFile("Ошибка +" + ex, @"LogError.txt");
                        return(ex.Message);
                        // MessageBox.Show(ex.Message);
                        // break;
                    }
                    finally
                    {
                        await Task.Delay(22000);  //чтобы обойти TelegramFloodException

                        SaveTextFile("Завершение работы", "Завершение работы.txt");
                    }
                }
                return(listChats);
                //MessageBox.Show("Done");
            }
            catch (Exception ex)
            {
                SaveTextFile("Ошибка +" + ex, @"LogError.txt");
                return(ex.ToString());
            }
        }
コード例 #10
0
ファイル: Telega.cs プロジェクト: Dims-M/ZapuskatorApp
        /// <summary>
        /// Получаем все сообщения из текущих чатов
        /// </summary>
        /// <returns></returns>
        public async Task <StringBuilder> GetChatTelegram()
        {
            //StartText();
            try
            {
                TelegramClient client = new TelegramClient(apiId, apiHash);
                await client.ConnectAsync();

                //var hash = await client.SendCodeRequestAsync("+79179037140");

                //string stop = "";
                //var code = "13643";

                //var user = await client.MakeAuthAsync("+79179037140", hash, code);

                // var temp =  ConfigurationManager.AppSettings[nameof(ApiHash)];

                sb.Append("#\tDate\tTime\tMID\tTUID\tText" + Environment.NewLine);


                TLDialogsSlice dialogs = (TLDialogsSlice)await client.GetUserDialogsAsync(); // Получение списка чатов

                //var chat123 = dialogs.Chats.Where(c => c.GetType() == typeof(TLChannel)).ToList();

                //foreach (TeleSharp.TL.TLChannel myChat in chat123)
                //{
                //    sb.Append("***************" + Environment.NewLine +
                //                           "Id чата"+ myChat.Id + "\t" +
                //                           "Название чата"+ myChat.Title + "\t" +
                //                           "Хешш чата" +myChat.AccessHash + "\t" +
                //                            "***************" + Environment.NewLine);
                //}
                //SaveTextFileBuilder(sb, "Messages.txt");

                // Получаем  ВЫБРАНЫЙ ЧАТ ПО ID
                TLChannel chat = dialogs.Chats.Where(c => c.GetType() == typeof(TLChannel)).Cast <TLChannel>().FirstOrDefault(c => c.Id == VKFID);
                // TLChannel channel = dialogs.Dialogs.
                TLInputPeerChannel inputPeer = new TLInputPeerChannel()
                {
                    ChannelId = chat.Id, AccessHash = (long)chat.AccessHash
                };

                while (countMessa != 100)
                {
                    try
                    {
                        TLChannelMessages res = await client.SendRequestAsync <TLChannelMessages>
                                                    (new TLRequestGetHistory()
                        {
                            Peer = inputPeer, Limit = 1000, AddOffset = offset, OffsetId = 0
                        });

                        var msgs = res.Messages;
                        allCountMess = res.Count;


                        if (res.Count > offset)
                        {
                            offset += msgs.Count;

                            foreach (TLAbsMessage msg in msgs)
                            {
                                if (msg is TLMessage)
                                {
                                    TLMessage message = msg as TLMessage;

                                    sb.Append("***************" + Environment.NewLine +
                                              n.ToString() + "\t" +
                                              ConvertFromUnixTimestamp(message.Date).ToLocalTime().ToString("dd'.'MM'.'yyyy") + "\t" +
                                              //ConvertFromUnixTimestamp(message.Date).ToLocalTime().ToString("HH':'mm':'ss") + "\t" +
                                              ConvertFromUnixTimestamp(message.Date).ToLocalTime().ToString("HH':'mm':'ss") + "\t" +
                                              "ID message" + message.Id + "\t" + message.FromId + "\t" + message.Message + Environment.NewLine +
                                              "***************" + Environment.NewLine);
                                }
                                if (msg is TLMessageService)
                                {
                                    continue;
                                }
                                n++;
                                countMessa++;
                            }
                            Thread.Sleep(22000); //to avoid TelegramFloodException
                            SaveTextFileBuilder(sb, "Messages.txt");
                            Console.WriteLine($"Всего собщений в чате {allCountMess} + {Environment.NewLine} Получно {n}" + Environment.NewLine);
                        }
                        else
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        string tempEx = $"Ошибка при получении списка сособщения из чата {VKFID}" + Environment.NewLine + ex;
                        SaveTextFile(tempEx);
                        break;
                    }
                    finally
                    {
                        //  await Task.Delay(22000); //чтобы обойти TelegramFloodException
                    }
                }
            }

            catch (Exception ex)
            {
                string tempEx = $"Ошибка при получении списка сособщения из чата {VKFID}" + Environment.NewLine + ex;
                SaveTextFile(tempEx);
            }

            finally
            {
                // SaveTextFileBuilder(sb, "Messages.txt");
                // return sb;
            }
            return(sb);
        }
コード例 #11
0
        async private void getMessages()
        {
            while (true)
            {
                foreach (var channelPeer in channels)
                {
                    //TODO:реализовать полную последовательность получения сообщений со всеми внутренними файлами
                    Thread.Sleep(3000);
                    TLChannelMessages result = await client.SendRequestAsync <TLChannelMessages>
                                                   (new TLRequestGetHistory()
                    {
                        Peer      = channelPeer.channel,
                        Limit     = 30,
                        AddOffset = 0,
                        OffsetId  = 0,
                        MinId     = channelPeer.prevIds
                    });

                    var messages = result.Messages;
                    foreach (var item in messages.Reverse())
                    {
                        if (item is TLMessage)
                        {
                            TLMessage message = item as TLMessage;
                            //TODO: make korrect if to media content and take new photo if it is
                            var sizes = result.Messages
                                        .OfType <TLMessage>()
                                        .Where(m => m.Media != null)
                                        .Select(m => m.Media)
                                        .OfType <TLMessageMediaPhoto>()
                                        .Select(mp => mp.Photo)
                                        .OfType <TLPhoto>()
                                        .Where(sc => sc.Id != 1)
                                        .Select(sd => sd.Sizes)
                                        .FirstOrDefault();
                            if (sizes != null)
                            {
                                var photo = sizes
                                            .OfType <TLPhotoSize>()
                                            .Select(s => s.Location)
                                            .OfType <TLFileLocation>()
                                            .LastOrDefault();
                                var size = sizes
                                           .OfType <TLPhotoSize>()
                                           .LastOrDefault();
                                if (sizes != null && size != null && photo != null)
                                {
                                    var resFile = await client.GetFile(
                                        new TLInputFileLocation()
                                    {
                                        LocalId  = photo.LocalId,
                                        Secret   = photo.Secret,
                                        VolumeId = photo.VolumeId
                                    }, (int)Math.Pow(2, Math.Ceiling(Math.Log(size.Size, 2))));

                                    bot.sendMessage(message, channelPeer.name, resFile);
                                    channelPeer.prevIds++;
                                }
                            }
                            else if (message != null)
                            {
                                bot.sendMessage(message, channelPeer.name);
                                channelPeer.prevIds++;
                            }
                        }
                        if (item is TLMessageService)
                        {
                            continue;
                        }
                    }
                }
            }
        }
コード例 #12
0
ファイル: Message.cs プロジェクト: Anna-kl/Telegram_bot
        public async void GetLastMessage(TLChannel channel, TelegramClient client, string name_chat, int offsetId)
        {
            int temp_offset = 0;
            int now_time    = 0;

            if (offsetId == 0)
            {
                TimeSpan hours = new TimeSpan(-1, 0, 0);
                DateTime time  = DateTime.Now.Add(hours);
                now_time = DateTimeToUnixTimeStamp(time);
            }
            while (true)
            {
                TLChannelMessages res = await client.SendRequestAsync <TLChannelMessages>
                                            (new TLRequestGetHistory()
                {
                    Peer = new TLInputPeerChannel {
                        ChannelId = channel.Id, AccessHash = channel.AccessHash.Value
                    },
                    Limit     = 100,
                    AddOffset = temp_offset,
                    OffsetId  = 0
                });

                temp_offset += 100;

                var msgs = (TLChannelMessages)res;

                foreach (TLAbsMessage message in msgs.Messages)
                {
                    var tlMessage = message as TLMessage;
                    if (tlMessage == null)
                    {
                        continue;
                    }
                    if (offsetId == 0)
                    {
                        if (tlMessage.Date < now_time)
                        {
                            break;
                        }
                    }
                    else
                    {
                        if (tlMessage.Id < offsetId)
                        {
                            break;
                        }
                    }
                    int replyId = -1;
                    if (tlMessage.ReplyToMsgId != null)
                    {
                        replyId = Convert.ToInt16(tlMessage.ReplyToMsgId);
                    }
                    string insert = "INSERT INTO public.message(messageid, fromid, chatname, processing_dttm, message, replyid)VALUES(";
                    using (var conn = new NpgsqlConnection(connString))
                    {
                        conn.Open();

                        // Insert some data
                        using (var cmd = new NpgsqlCommand())
                        {
                            cmd.Connection  = conn;
                            cmd.CommandText = insert + tlMessage.Id.ToString() + "," + tlMessage.FromId + ",\'" + name_chat + "\'," + tlMessage.Date.ToString() + ",\'" + tlMessage.Message.Replace("'", "\"") + "\'," + replyId.ToString() + ");";
                            //cmd.Parameters.AddWithValue("p", "Hello world");
                            try
                            {
                                NpgsqlDataReader reader = cmd.ExecuteReader();
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show(e.Message);
                            }
                            conn.Close();
                        }
                    }
                }
            }
        }
コード例 #13
0
        public async Task <StringBuilder> GetChatTelegram()
        {
            TelegramClient client = new TelegramClient(apiId, apiHash);

            sb.Append("#\tDate\tTime\tMID\tTUID\tText" + Environment.NewLine);

            TLDialogsSlice dialogs = (TLDialogsSlice)await client.GetUserDialogsAsync(); // Получение списка чатов

            TLChannel chat = dialogs.Chats.Where(c => c.GetType() == typeof(TLChannel)).Cast <TLChannel>().FirstOrDefault(c => c.Id == VKFID);

            TLInputPeerChannel inputPeer = new TLInputPeerChannel()
            {
                ChannelId = chat.Id, AccessHash = (long)chat.AccessHash
            };


            while (countMessa == 100)
            {
                try
                {
                    TLChannelMessages res = await client.SendRequestAsync <TLChannelMessages>
                                                (new TLRequestGetHistory()
                    {
                        Peer = inputPeer, Limit = 1000, AddOffset = offset, OffsetId = 0
                    });

                    var msgs = res.Messages;
                    if (res.Count > offset)
                    {
                        offset += msgs.Count;
                        foreach (TLAbsMessage msg in msgs)
                        {
                            if (msg is TLMessage)
                            {
                                TLMessage message = msg as TLMessage;
                                sb.Append(n.ToString() + "\t" +
                                          ConvertFromUnixTimestamp(message.Date).ToLocalTime().ToString("dd'.'MM'.'yyyy") + "\t" +
                                          ConvertFromUnixTimestamp(message.Date).ToLocalTime().ToString("HH':'mm':'ss") + "\t" +
                                          message.Id + "\t" + message.FromId + "\t" + message.Message + Environment.NewLine);
                            }
                            if (msg is TLMessageService)
                            {
                                continue;
                            }
                            n++;
                            countMessa++;
                        }
                        Thread.Sleep(22000); //to avoid TelegramFloodException
                    }
                    else
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    string tempEx = $"Ошибка при получении списка сособщения из чата {VKFID}" + Environment.NewLine;
                    //MessageBox.Show(ex.Message);
                    break;
                }
                finally
                {
                    await Task.Delay(22000); //чтобы обойти TelegramFloodException
                }
            }
            return(sb);
            //  textBox2.Text = sb.ToString();
            // MessageBox.Show("Done");
        }
コード例 #14
0
        private List <Message> RefineMessages(TLChannelMessages messages)
        {
            List <Message> result = new List <Message>();

            for (int i = 0; i < messages.Messages.Count; i++)
            {
                if (!(messages.Messages[i] is TLMessage))
                {
                    continue;
                }
                TLMessage message     = messages.Messages[i] as TLMessage;
                Message   tempMessage = new Message
                {
                    Text          = message.Message,
                    SourceChannel = new Channel()
                    {
                        ChannelId = (message.ToId as TLPeerChannel).ChannelId
                    },
                    MessageId = message.Id,
                    Date      = message.Date,
                    Views     = new CountTime(message.Views.HasValue ? message.Views.Value : 0, DateTime.Now)
                };
                if (message.FwdFrom != null)
                {
                    if (message.FwdFrom.ChannelId != null)
                    {
                        tempMessage.SourceChannel.ChannelId = message.FwdFrom.ChannelId ?? 0;
                        tempMessage.MessageId    = message.FwdFrom.ChannelPost ?? 0;
                        tempMessage.OriginalDate = message.FwdFrom.Date;
                    }
                }
                if (message.Media != null)
                {
                    if (message.Media is TLMessageMediaPhoto)
                    {
                        tempMessage.MediaContent = new Media()
                        {
                            Caption = (message.Media as TLMessageMediaPhoto).Caption,
                            Type    = "photo",
                        };
                    }
                    else if (message.Media is TLMessageMediaDocument)
                    {
                        tempMessage.MediaContent = new Media()
                        {
                            Caption = (message.Media as TLMessageMediaDocument).Caption,
                            Type    = ((message.Media as TLMessageMediaDocument).Document as TLDocument).MimeType,
                            Size    = ((message.Media as TLMessageMediaDocument).Document as TLDocument).Size
                        };
                        try
                        {
                            tempMessage.MediaContent.FileName = ((TLDocumentAttributeFilename)(((message.Media as TLMessageMediaDocument).Document as TLDocument).Attributes.First(a => a.GetType() == typeof(TLDocumentAttributeFilename)))).FileName;
                        }
                        catch (Exception)
                        {
                            tempMessage.MediaContent.FileName = null;
                        }
                    }
                }
                // append source channel info
                foreach (var chat in messages.Chats)
                {
                    if (chat is TLChannel)
                    {
                        if ((chat as TLChannel).Id == tempMessage.SourceChannel.ChannelId)
                        {
                            tempMessage.SourceChannel.AccessHash = (chat as TLChannel).AccessHash;
                            tempMessage.SourceChannel.Title      = (chat as TLChannel).Title;
                            tempMessage.SourceChannel.Username   = (chat as TLChannel).Username;
                            break;
                        }
                    }
                }
                result.Add(tempMessage);
            }
            return(result);
        }
コード例 #15
0
ファイル: Main.cs プロジェクト: cexdelta/WeGramSharp
        private async WTask.Task GetMessages(int uID, long uAccess, string type = "chat")
        {
            Loading(null, true);
            TLRequestMessagesGetHistory reqH = new TLRequestMessagesGetHistory();

            reqH.setAddOffset(0);
            reqH.setLimit(100);
            reqH.setOffsetId(0);
            reqH.setOffsetDate(0);
            reqH.setMinId(0);
            reqH.setMaxId(999999);

            TLInputPeerUser    upeer  = new TLInputPeerUser();
            TLInputPeerChat    cpeer  = new TLInputPeerChat();
            TLInputPeerChannel chpeer = new TLInputPeerChannel();

            switch (type.ToLower())
            {
            case "user":
                upeer = new TLInputPeerUser();
                upeer.setAccessHash(uAccess);
                upeer.setUserId(uID);
                reqH.setPeer(upeer);
                break;

            case "chat":
                cpeer = new TLInputPeerChat();
                cpeer.setChatId(uID);
                reqH.setPeer(cpeer);
                break;

            case "channel":
                chpeer = new TLInputPeerChannel();
                chpeer.setAccessHash(uAccess);
                chpeer.setChannelId(uID);
                reqH.setPeer(chpeer);
                break;

            default:
                break;
            }


            //var res = NewApi.Api().doRpcCall(reqH);
            var res = await WTask.Task.Run(() => NewApi.Api().doRpcCall(reqH));

            string notify = "";

            if (res == null)
            {
                notify = "درخواست نتیجه ای نداشت!";
                //NotifyBar.ForeColor = Color.Orange;
            }
            else
            {
                MessagesDGV.Rows.Clear();
                if (res.GetType() == typeof(TLMessages))
                {
                    try
                    {
                        TLMessages Messages = (TLMessages)res;
                        foreach (var msg in Messages.getMessages())
                        {
                            try
                            {
                                TLMessage message = (TLMessage)msg;
                                MessagesDGV.Rows.Add(message.getDate(), message.getId(), message.getMessage(), uID, uAccess);
                            }
                            catch { }
                        }
                    }
                    catch { }
                }
                else if (res.GetType() == typeof(TLMessagesSlice))
                {
                    try
                    {
                        TLMessagesSlice Messages = (TLMessagesSlice)res;
                        foreach (var msg in Messages.getMessages())
                        {
                            try
                            {
                                TLMessage message = (TLMessage)msg;
                                MessagesDGV.Rows.Add(message.getDate(), message.getId(), message.getMessage(), uID, uAccess);
                            }
                            catch { }
                        }
                    }
                    catch { }
                }
                else if (res.GetType() == typeof(TLChannelMessages))
                {
                    TLChannelMessages Messages = (TLChannelMessages)res;

                    foreach (var msg in Messages.getMessages())
                    {
                        try
                        {
                            TLMessage message = (TLMessage)msg;
                            MessagesDGV.Rows.Add(message.getDate(), message.getId(), message.getMessage(), uID, uAccess);
                        }
                        catch { }
                    }
                }
            }

            Loading(null, false, notify);
        }
コード例 #16
0
        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);
        }