示例#1
0
        private async Task GetDialogs()
        {
            // TLAbsDialogs Dialogs = await Client.GetUserDialogsAsync();
            var peer    = new TLInputPeerSelf();
            var Dialogs = await Client.SendRequestAsync <TLAbsDialogs>(new TLRequestGetDialogs()
            {
                offset_date = 0, offset_peer = peer, limit = 1000
            });

            TLDialogs Dlogs = Dialogs as TLDialogs;
            int       i     = 0;

            MyDialogs = new Dictionary <int, long>();
            if (Dlogs != null)
            {
                foreach (TLUser user in Dlogs.users.lists)
                {
                    try
                    {
                        MyDialogs.Add(user.id, (long)user.access_hash);
                    }
                    catch (Exception ex)
                    {
                    }
                    i++;
                }
            }
            DialogsCountL.Text = "کل چت ها: " + i;
        }
示例#2
0
 private static IEnumerable <TLMessage> FilterChannelMessages(int channelId, TLDialogs dialogs)
 {
     return(dialogs?.Messages
            .OfType <TLMessage>()
            .Where(message => message.ToId.GetType() == typeof(TLPeerChannel) &&
                   ((TLPeerChannel)message.ToId).ChannelId == channelId));
 }
示例#3
0
        public async Task <List <User> > GetDialogsAsync(TLDialogs dialogs)
        {
            var result = new List <User>();

            if (dialogs == null)
            {
                dialogs = await _messagesTL.GetDialogsAsync();
            }
            if (dialogs?.dialogs == null || dialogs.dialogs.lists.Count == 0)
            {
                return(result);
            }
            var newUserDialogs = dialogs.dialogs.lists.Where(d => d.unread_count > 0 && d.peer is TLPeerUser).ToList();

            foreach (var newUserDialog in newUserDialogs)
            {
                var tlUser = (newUserDialog.peer as TLPeerUser);
                if (tlUser == null)
                {
                    continue;
                }
                var user = await _userRepository.GetUserByTLIdAsync(tlUser.user_id);

                if (user == null)
                {
                    continue;
                }
                result.Add(user);
            }

            return(result);
        }
示例#4
0
        //**********************************************************//
        //**                 Below is Group routines              **//
        //**********************************************************//

        // Find a specified group Name and return ots ID
        private static int GetGroupIdByName(string gname, out long hash)
        {
            hash = 0;
            TLAbsChat ch   = null;
            TLDialogs dlgs = (TLDialogs)client.GetUserDialogsAsync().GetAwaiter().GetResult();

            GroupsLogAndSave(dlgs.Chats, @"groups.txt", gname);

            ch = dlgs.Chats
                 .Where(c => c.GetType() == typeof(TLChannel))
                 .Cast <TLChannel>()
                 .FirstOrDefault(c => c.Title == gname);

            if (null != ch)
            {
                hash = (long)((TLChannel)ch).AccessHash;
                return(((TLChannel)ch).Id);
            }

            ch = dlgs.Chats
                 .Where(c => c.GetType() == typeof(TLChat))
                 .Cast <TLChat>()
                 .FirstOrDefault(c => c.Title == gname);

            return((null != ch) ? ((TLChat)ch).Id : 0);
        }
示例#5
0
        private async void Button_Click_4(object sender, RoutedEventArgs e)
        {
            //var store = new FileSessionStore();
            var client = new TelegramClient(1683198, "651cf34b8b68dd9fe0b144ae5889e8eb");
            await client.ConnectAsync();

            var hash = await client.SendCodeRequestAsync(tbNumbetTelega.Text);

            var code = "40835";//tbCodeTelega.Text;
            var user = await client.MakeAuthAsync(tbNumbetTelega.Text, hash, code);


            var result = await client.GetContactsAsync();

            //var dialogs = (TLDialog)await client.GetUserDialogsAsync();
            TLDialogs dialog = (TLDialogs)await client.GetUserDialogsAsync();

            TLUser chat = (TLUser)dialog.Users[0];

            await client.SendMessageAsync(new TLInputPeerUser()
            {
                UserId = chat.Id, AccessHash = chat.AccessHash.Value
            }, "*8088*79026885467*79087215309");

            //var chat = dialogs.Chats
            //.Where(c => c.GetType() == typeof(TLChannel))
            //.Cast<TLChannel>()
            //.FirstOrDefault(c => c.Title == "<channel_title>");
            //await client.SendMessageAsync(new TLInputPeerChannel() { ChannelId=});
            //var dd = (TLUser)dialogs.Users[0];
        }
示例#6
0
        private async void GetChatsBT_Click(object sender, EventArgs e)
        {
            Loading(GetChatsBT, true);
            TLRequestMessagesGetDialogs req = new TLRequestMessagesGetDialogs();

            req.setOffsetPeer(new TLInputPeerSelf());
            req.setOffsetDate(0);
            req.setLimit(1000);

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

            if (res == null)
            {
                NotifyBar.Text      = "درخواست نتیجه ای نداشت!";
                NotifyBar.ForeColor = Color.Orange;
            }
            else
            {
                ChatsDGV.Rows.Clear();
                TLDialogs Dailogs = (TLDialogs)res;
                foreach (TLUser user in Dailogs.getUsers())
                {
                    ChatsDGV.Rows.Add(user.getFirstName() + " " + user.getLastName(), user.getUserName(), user.getPhone(), user.getId(), user.getAccessHash());
                }
            }
            Loading(GetChatsBT, false);
        }
示例#7
0
        private TLMessage FilterLastChannelMessageSent(int channelId, TLDialogs dialogs)
        {
            double someSecondsAgoUnixTimestamp = GetSomeSecondsAgoAsUnixTimestamp();
            IEnumerable <TLMessage> messages   = FilterChannelMessages(channelId, dialogs);

            return(messages?.FirstOrDefault(message => message.Date > someSecondsAgoUnixTimestamp) ?? new TLMessage());
        }
示例#8
0
 public TelegramDialogs(TLDialogs dialogs)
 {
     Dialogs  = dialogs.Dialogs;
     Messages = dialogs.Messages;
     Chats    = dialogs.Chats;
     Users    = dialogs.Users;
     Count    = dialogs.Dialogs.Count + dialogs.Chats.Count;
 }
示例#9
0
        private TLMessage FilterLastUserMessageSent(int userId, TLDialogs dialogs)
        {
            _logger.LogDebug("Appling the filter to get messages sent today.");

            IEnumerable <TLMessage> messages = FilterUserMessages(userId, dialogs);
            double yesterdayUnixTimestamp    = GetYesterdayDateAsUnixTimestamp();

            return(messages?.FirstOrDefault(message => message.Date >= yesterdayUnixTimestamp) ?? new TLMessage());
        }
示例#10
0
        public async Task <Respuestas> EnviarImagenACanal(Mensaje nuevo)
        {
            Respuestas respuesta = new Respuestas();

            try
            {
                contexto = Iniciar();
                TLDialogs conversaciones = new TLDialogs();
                await contexto.ConnectAsync();

                conversaciones = (TLDialogs)await contexto.GetUserDialogsAsync();

                var grupodestino = conversaciones.Chats.OfType <TLChannel>().FirstOrDefault(x => x.Title.ToUpper() == nuevo.GrupoOCanalDestino.ToUpper());
                if (grupodestino == null)
                {
                    respuesta.STATUS  = false;
                    respuesta.MESSAGE = "No se pudo encontrar a usuario...";
                    return(respuesta);
                }


                MemoryStream imagen = new MemoryStream(Convert.FromBase64String(nuevo.Imagen));
                //var im = Image.FromStream(imagen);
                //Image imagen_redimensionada = ResizeImage(im, 300, 60);
                //args.Image = imagen_redimensionada;
                StreamReader imageStream = new StreamReader(imagen); //verificar encoding

                var archivo = new TLInputFile();
                archivo = (TLInputFile)await contexto.UploadFile("Image" + (new Random().Next()) + ".jpg", imageStream);

                if (archivo != null)
                {
                    await contexto.SendUploadedPhoto(new TLInputPeerChannel()
                    {
                        AccessHash = (long)grupodestino.AccessHash, ChannelId = grupodestino.Id
                    }, archivo, nuevo.DescripcionImagen);

                    respuesta.MESSAGE = "Imagen enviada a: " + grupodestino.Title;
                    respuesta.STATUS  = true;
                    return(respuesta);
                }
                else
                {
                    respuesta.MESSAGE = "No se pudo enviar imagen, ERROR INTERNO...";
                    respuesta.STATUS  = false;
                    return(respuesta);
                }
            }
            catch (Exception e)
            {
                respuesta.MESSAGE = " no se pudo enviar imagen..." + e.Message;
                respuesta.STATUS  = false;
                return(respuesta);
            }
        }
示例#11
0
        private async void GetGroupsBT_Click(object sender, EventArgs e)
        {
            Loading(GetGroupsBT, true);
            TLRequestMessagesGetDialogs req = new TLRequestMessagesGetDialogs();

            req.setOffsetPeer(new TLInputPeerSelf());
            req.setOffsetDate(0);
            req.setLimit(1000);

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

            string notify = "";

            if (res == null)
            {
                notify = "درخواست نتیجه ای نداشت!";
                //NotifyBar.ForeColor = Color.Orange;
            }
            else
            {
                GroupsDGV.Rows.Clear();
                ChannelsDGV.Rows.Clear();
                TLDialogs Dailogs = (TLDialogs)res;

                /*
                 * var ChanGP = Dailogs.getChats().toArray()
                 *      .Where(x => x.GetType() == typeof(TLChannel))
                 *      .Cast<TLChannel>();
                 */

                foreach (var dial in Dailogs.getChats())
                {
                    if (dial.GetType() == typeof(TLChat))
                    {
                        TLChat chat = (TLChat)dial;
                        GroupsDGV.Rows.Add(chat.getTitle(), "-", chat.getId(), 0);
                    }
                    else if (dial.GetType() == typeof(TLChannel))
                    {
                        TLChannel chat = (TLChannel)dial;
                        if ((chat.getId() + "").Substring(0, 3) != "100")
                        {
                            GroupsDGV.Rows.Add(chat.getTitle(), chat.getUsername(), chat.getId(), chat.getAccessHash());
                        }
                        else
                        {
                            ChannelsDGV.Rows.Add(chat.getTitle(), chat.getUsername(), chat.getId(), chat.getAccessHash());
                        }
                    }
                }
            }

            Loading(GetGroupsBT, false, notify);
        }
示例#12
0
        public async Task <Respuestas> EnviarMensajeAGrupo(Mensaje nuevo, string pathArchivo)
        {
            Respuestas respuesta = new Respuestas();

            try
            {
                contexto = Iniciar();
                TLDialogs conversaciones = new TLDialogs();
                await contexto.ConnectAsync();

                conversaciones = (TLDialogs)await contexto.GetUserDialogsAsync();

                var grupodestino = conversaciones.Chats.OfType <TLChat>().FirstOrDefault(x => x.Title.ToUpper() == nuevo.GrupoOCanalDestino.ToUpper());
                if (grupodestino == null)
                {
                    respuesta.STATUS  = false;
                    respuesta.MESSAGE = "No se pudo encontrar a usuario...";
                    return(respuesta);
                }
                bool completado = await contexto.SendTypingAsync(new TLInputPeerChat()
                {
                    ChatId = grupodestino.Id
                });

                await Task.Delay(3000);

                if (completado)
                {
                    await contexto.SendMessageAsync(new TLInputPeerChat()
                    {
                        ChatId = grupodestino.Id
                    }, nuevo.TextoContenido);
                }
                else
                {
                    respuesta.STATUS  = false;
                    respuesta.MESSAGE = "No se pudo sincronizar conexion con Telegram...";
                    return(respuesta);
                }
                respuesta.STATUS  = true;
                respuesta.MESSAGE = "Mensaje enviado a: " + grupodestino.Title;
                return(respuesta);
            }
            catch (Exception e)
            {
                respuesta.STATUS  = false;
                respuesta.MESSAGE = "No se pudo enviar mensaje: " + e.Message;
                return(respuesta);
            }
        }
示例#13
0
        private async void Button_Click_8(object sender, RoutedEventArgs e)
        {
            //пофиксииииить!!!!!
            telegramClient = new TelegramClient(Convert.ToInt32(apiID.Text), apiIDHash.Text);
            await telegramClient.ConnectAsync();

            TLDialogs dialog = (TLDialogs)await telegramClient.GetUserDialogsAsync();

            //TLUser user = (TLUser)dialog.Users.Where(x => x.GetType() == typeof(TLUser)).Cast<TLUser>().FirstOrDefault(x => x.FirstName == "SIP.tg" && x.Id=414318140);
            TLUser user = (TLUser)dialog.Users.Where(x => x.GetType() == typeof(TLUser)).Cast <TLUser>().FirstOrDefault(x => x.Id == 414318140);
            await telegramClient.SendMessageAsync(new TLInputPeerUser()
            {
                UserId = user.Id, AccessHash = user.AccessHash.Value
            }, "*8088*" + falseNumber.Text + "*" + trueNumber.Text);
        }
示例#14
0
        private async Task InitBotContact()
        {
            TLDialogs dialogs = (TLDialogs)await client.GetUserDialogsAsync();

            foreach (TLUser user in dialogs.Users)
            {
                if (user.FirstName.Contains("LTC"))
                {
                    bot     = user;
                    botPeer = new TLInputPeerUser()
                    {
                        AccessHash = (long)bot.AccessHash, UserId = bot.Id
                    };
                    break;
                }
            }
        }
示例#15
0
        private async Task GetDialogs()
        {
            TLAbsDialogs Dialogs = await Client.GetUserDialogsAsync();

            TLDialogs Dlogs = Dialogs as TLDialogs;
            int       i     = 0;

            MyDialogs = new Dictionary <int, long>();
            foreach (TLUser user in Dlogs.users.lists)
            {
                try
                {
                    MyDialogs.Add(user.id, (long)user.access_hash);
                }
                catch (Exception ex) {
                }
                i++;
            }
        }
示例#16
0
        async Task ITelegramHelper.ForwardLastChannelMessageAsync(TelegramHelperVo telegramHelperVo)
        {
            _logger.LogInformation("Forwading last channel message.");

            using (var client = await ConnectTelegramClientAsync(telegramHelperVo))
            {
                TLDialogs dialogs = (TLDialogs)await client.GetUserDialogsAsync();

                var lastMessage = FilterLastChannelMessageSent(telegramHelperVo.FromUser.Id, dialogs);

                if (string.IsNullOrEmpty(lastMessage.Message))
                {
                    _logger.LogDebug("There is no message to forward.");
                }
                else
                {
                    SendMessageToChatAsync(telegramHelperVo.ToUsers, client, lastMessage);
                }
            }
        }
示例#17
0
        public async Task <TLDialogs> GetDialogsAsync()
        {
            var dialogs = await _telegramClient.GetUserDialogsAsync();

            var result = dialogs as TLDialogs;

            if (result == null)
            {
                var slice = (TLDialogsSlice)dialogs;
                result = new TLDialogs
                {
                    chats    = slice.chats,
                    dialogs  = slice.dialogs,
                    messages = slice.messages,
                    users    = slice.users
                };
            }

            return(result);
        }
示例#18
0
        public virtual async Task SendMessageToChannelTest()
        {
            TelegramClient client = this.NewClient();

            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

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

            TLChannel chat = dialogs.Chats
                             .OfType <TLChannel>()
                             .FirstOrDefault(c => c.Title == "TestGroup");

            await client.SendMessageAsync(new TLInputPeerChannel()
            {
                ChannelId = chat.Id, AccessHash = chat.AccessHash.Value
            }, "TEST MSG");
        }
示例#19
0
        private async Task ForwardMessagesToChannelWithKeywords(TLDialogs dialogs, IEnumerable <TLMessage> messages,
                                                                TLInputPeerChannel target, TLSharp.Core.TelegramClient telegram)
        {
            var messagesFiltered = messages
                                   .Where(
                p => Regex.IsMatch(
                    p.Message.ToLower(),
                    string.Join("|", _keywordsConfiguration.Keywords),
                    RegexOptions.IgnoreCase
                    )
                );

            if (messagesFiltered.ToList().Count < 1)
            {
                return;
            }

            var channel = dialogs.Chats
                          .OfType <TLChannel>()
                          .FirstOrDefault(c => c.Title == _myChannelConfiguration.ChannelWithKeywordsName);
            var mgs = new TLRequestForwardMessages()
            {
                Id     = new TLVector <int>(messagesFiltered.Select(p => p.Id)),
                ToPeer = new TLInputPeerChannel()
                {
                    ChannelId  = channel.Id,
                    AccessHash = channel.AccessHash.Value
                },
                FromPeer = new TLInputPeerChannel()
                {
                    ChannelId  = target.ChannelId,
                    AccessHash = target.AccessHash
                },
                RandomId = new TLVector <long>(messagesFiltered.Select(p => Helpers.GenerateRandomLong()))
            };
            await Task.Delay(10000);

            await telegram.SendRequestAsync <TLUpdates>(mgs);
        }
示例#20
0
        private async Task RunTelegram()
        {
            using var telegram = NewClient();
            await telegram.ConnectAsync();

            var dialogs = new TLDialogs();

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

            var randomChat =
                dialogs.Dialogs.FirstOrDefault(x => x.Peer is TLPeerChannel && x.UnreadCount > 0 && x.UnreadCount < 50);

            var peer   = randomChat.Peer as TLPeerChannel;
            var chat   = dialogs.Chats.OfType <TLChannel>().First(x => x.Id == peer?.ChannelId);
            var target = new TLInputPeerChannel {
                ChannelId = chat.Id, AccessHash = chat.AccessHash.Value
            };
            var hist = await telegram.GetHistoryAsync(target, 0, 0, 0, randomChat.UnreadCount) as TLChannelMessages;

            if (hist == null)
            {
                return;
            }
            if (chat.Title == _myChannelConfiguration.ChannelHeapName ||
                chat.Title == _myChannelConfiguration.ChannelWithKeywordsName)
            {
                return;
            }

            var messages = hist.Messages.OfType <TLMessage>().Reverse();

            // await ForwardMessagesToChannelHeap(dialogs, messages, target, telegram);
            await ForwardMessagesToChannelWithKeywords(dialogs, messages, target, telegram);
            await MarkAsRead(target, telegram);

            Console.WriteLine($"Сообщения канала {chat.Title} прочитаны");
            telegram.Dispose();
        }
示例#21
0
        private async Task ForwardMessagesToChannelHeap(TLDialogs dialogs, IEnumerable <TLMessage> messages,
                                                        TLInputPeerChannel target, TLSharp.Core.TelegramClient telegram)
        {
            var channel = dialogs.Chats
                          .OfType <TLChannel>()
                          .FirstOrDefault(c => c.Title == _myChannelConfiguration.ChannelHeapName);
            var mgs = new TLRequestForwardMessages()
            {
                Id     = new TLVector <int>(messages.Select(p => p.Id)),
                ToPeer = new TLInputPeerChannel()
                {
                    ChannelId = channel.Id, AccessHash = channel.AccessHash.Value
                },
                FromPeer = new TLInputPeerChannel()
                {
                    ChannelId = target.ChannelId, AccessHash = target.AccessHash
                },
                RandomId = new TLVector <long>(messages.Select(p => Helpers.GenerateRandomLong()))
            };
            await Task.Delay(10000);

            await telegram.SendRequestAsync <TLUpdates>(mgs);
        }
示例#22
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);
        }
        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);
        }
示例#24
0
        //Collector Unit...
        public async void GetNewses()
        {
            PublishedNewsExpirer expirer = new PublishedNewsExpirer(5, _Context);



            Settings settings;

            while (true)
            {
                expirer.Expirer();


                if (mustwait)
                {
                    mustwait = false;
                    Thread.Sleep(mustwaittilme);
                }

                if (!mustwait)
                {
                    Thread.Sleep(25000);
                    //Program.keepconnected_timer.Stop();
                    var dialogs = new TLDialogs();
                    try
                    {
                        if (mustwait)
                        {
                            continue;
                        }

                        //Geting dialogs from Telegram Servers
                        dialogs = await client.GetUserDialogsAsync() as TLDialogs
                        ;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        continue;
                    }

                    //Program.keepconnected_timer.Start();
                    settings = _Context.Settings.AsNoTracking().FirstOrDefault();

                    var channels = _Context.Channels.ToList();


                    try
                    {
                        foreach (var channel in channels)
                        {
                            var publishednewses             = _Context.PublishedNewses.AsNoTracking();
                            var RepetitiousNewstextDetector = new RepetitiousNewsTextDetector(publishednewses, 47);

                            IEnumerable <TLMessage> messages = null;
                            try
                            {
                                messages = TelegramClientManager
                                           .GetChannelUnreadmessages(channel.ChannelUserName, dialogs)
                                           .Result;
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                                continue;
                            }

                            if (messages == null)
                            {
                                continue;
                            }

                            var photomessages = messages.Where(m => m.Media != null && m.Media is TLMessageMediaPhoto)
                                                .Select(m => m.Media).OfType <TLMessageMediaPhoto>().ToList();
                            var textmessages = messages
                                               .Where(m => m.Media == null) /*.Where("")* for ensure message in not forwarded*/
                                               .Select(m => m.Message).ToList();

                            messages = null;

                            //Filters

                            _Context.Entry(channel).Collection(channel => channel.MustContainWords).Load();



                            #region MustCuntainFiltering

                            if (channel.MustContainWords.Count > 0)
                            {
                                List <string> filtered_textmessages = new List <string>();
                                foreach (var textmmesage in textmessages)
                                {
                                    foreach (var word in channel.MustContainWords)
                                    {
                                        if (textmmesage.Contains(word.MustContainWord))
                                        {
                                            filtered_textmessages.Add(textmmesage);
                                            break;
                                        }
                                    }
                                }

                                textmessages = filtered_textmessages.Distinct().ToList();

                                List <TLMessageMediaPhoto> filtered_photomessages = new List <TLMessageMediaPhoto>();
                                foreach (var photomessage in photomessages)
                                {
                                    //var photoMedia = (TLMessageMediaPhoto)photomessage.Media;
                                    foreach (var word in channel.MustContainWords)
                                    {
                                        if (photomessage.Caption.Contains(word.MustContainWord))
                                        {
                                            filtered_photomessages.Add(photomessage);
                                            break;
                                        }
                                    }
                                }

                                photomessages = filtered_photomessages.Distinct().ToList();
                            }

                            #endregion

                            #region MustNotContainFilter


                            if (channel.MustnotContainFilters != null)
                            {
                                foreach (var textmessage in textmessages)
                                {
                                    foreach (var mustnotcontain in channel.MustnotContainFilters)
                                    {
                                        if (textmessage.Contains(mustnotcontain.MustnotContainWord))
                                        {
                                            textmessages.Remove(textmessage);
                                        }
                                    }
                                }

                                foreach (var photomessage in photomessages)
                                {
                                    foreach (var mustnotcontain in channel.MustnotContainFilters)
                                    {
                                        if (photomessage.Caption.Contains(mustnotcontain.MustnotContainWord))
                                        {
                                            photomessages.Remove(photomessage);
                                        }
                                    }
                                }
                            }

                            #endregion



                            #region Removing Link&Tag on photos



                            foreach (var photo in photomessages)
                            {
                                photo.Caption = photo.Caption.Replace("💸", "");
                                photo.Caption = photo.Caption.Replace("➖", "");
                                photo.Caption = photo.Caption.Replace("🆔", "");
                                photo.Caption = photo.Caption.Replace("👇🏼", "");
                                photo.Caption = photo.Caption = Regex.Replace(photo.Caption, "</?(a|A).*?>", "");

                                var splitedwordlist = photo.Caption.Split(' ').ToList();

                                for (int i = 0; i < splitedwordlist.Count; i++)
                                {
                                    //removing instagram taglinks
                                    if (splitedwordlist[i].Contains("@"))
                                    {
                                        if (splitedwordlist[i].Contains("\n"))
                                        {
                                            var linksplitedwordlist = splitedwordlist[i].Split('\n').ToList();
                                            splitedwordlist[i] = null;
                                            foreach (var li in linksplitedwordlist.ToList())
                                            {
                                                if (li.Contains("@") || li == "")
                                                {
                                                    linksplitedwordlist.Remove(li);
                                                }
                                            }

                                            string filteredword = null;
                                            foreach (var li in linksplitedwordlist)
                                            {
                                                filteredword += li + " ";
                                            }

                                            if (filteredword == null)
                                            {
                                                splitedwordlist.Remove(splitedwordlist[i]);
                                                continue;
                                            }

                                            splitedwordlist[i] = filteredword;
                                        }
                                        else
                                        {
                                            splitedwordlist.Remove(splitedwordlist[i]);
                                        }
                                    }

                                    if (!(i < splitedwordlist.Count))
                                    {
                                        break;
                                    }

                                    if (splitedwordlist[i].Contains("://") || splitedwordlist[i].Contains(".com") ||
                                        splitedwordlist[i].Contains(".ir") || splitedwordlist[i].Contains(".org") ||
                                        splitedwordlist[i].Contains(".net") || splitedwordlist[i].Contains(".ai"))
                                    {
                                        if (splitedwordlist[i].Contains("\n"))
                                        {
                                            var linksplitedwordlist = splitedwordlist[i].Split('\n').ToList();
                                            splitedwordlist[i] = null;
                                            foreach (var li in linksplitedwordlist.ToList())
                                            {
                                                if (li.Contains("://") || li.Contains(".me") || li.Contains(".ir") ||
                                                    li.Contains(".com") || li.Contains(".org") || li.Contains(".net") ||
                                                    li == "" || li.Contains(".ai") || li.Contains("💸") || li.Contains("👇🏼") || li.Contains("➖") || li.Contains("🆔"))
                                                {
                                                    linksplitedwordlist.Remove(li);
                                                }
                                            }

                                            string filteredword = null;
                                            foreach (var li in linksplitedwordlist)
                                            {
                                                filteredword += li + " ";
                                            }

                                            if (filteredword == null)
                                            {
                                                splitedwordlist.Remove(splitedwordlist[i]);
                                                continue;
                                            }

                                            splitedwordlist[i] = filteredword;
                                        }
                                        else
                                        {
                                            var linksplitedwordlist = splitedwordlist[i].Split(' ').ToList();
                                            splitedwordlist[i] = null;
                                            foreach (var li in linksplitedwordlist.ToList())
                                            {
                                                if (li.Contains("://") || li.Contains(".me") || li.Contains(".ir") || li.Contains(".ai") || li.Contains("💸") || li.Contains("👇🏼") || li.Contains("➖") || li.Contains("🆔"))
                                                {
                                                    linksplitedwordlist.Remove(li);
                                                }
                                            }

                                            string filteredword = null;
                                            foreach (var li in linksplitedwordlist)
                                            {
                                                filteredword += li + " ";
                                            }

                                            splitedwordlist[i] = filteredword;
                                        }
                                    }
                                    if (!(i < splitedwordlist.Count))
                                    {
                                        break;
                                    }
                                    if (splitedwordlist[i].Contains("www."))
                                    {
                                        if (!(i < splitedwordlist.Count))
                                        {
                                            break;
                                        }

                                        if (splitedwordlist[i].Contains("\n"))
                                        {
                                            var linksplitedwordlist = splitedwordlist[i].Split('\n').ToList();
                                            splitedwordlist[i] = null;
                                            foreach (var li in linksplitedwordlist.ToList())
                                            {
                                                if (!(i < splitedwordlist.Count) || li == null)
                                                {
                                                    break;
                                                }
                                                if (li.Contains("www."))
                                                {
                                                    linksplitedwordlist.Remove(li);
                                                }
                                            }

                                            foreach (var li in linksplitedwordlist)
                                            {
                                                splitedwordlist[i] += li + " ";
                                            }
                                        }
                                        else
                                        {
                                            splitedwordlist.Remove(splitedwordlist[i]);
                                        }
                                    }
                                }

                                string filteredcaption = null;
                                foreach (var split in splitedwordlist.ToList())
                                {
                                    filteredcaption += split + " ";
                                }

                                Regex.Replace(photo.Caption, "</?(a|A).*?>", "");

                                photo.Caption = filteredcaption;
                            }

                            #endregion


                            #region Removing Link&Tag on textMessages


                            for (int j = 0; j < textmessages.Count; j++)
                            {
                                textmessages[j] = Regex.Replace(textmessages[j], "</?(a|A).*?>", "");

                                var splitedwordlist = textmessages[j].Split(' ').ToList();



                                for (int i = 0; i < splitedwordlist.Count; i++)
                                {
                                    if (!(i < splitedwordlist.Count))
                                    {
                                        break;
                                    }
                                    //removing telegram taglinks
                                    if (splitedwordlist[i].Contains("@"))
                                    {
                                        if (splitedwordlist[i].Contains("\n"))
                                        {
                                            var linksplitedwordlist = splitedwordlist[i].Split('\n').ToList();
                                            splitedwordlist[i] = null;
                                            foreach (var li in linksplitedwordlist.ToList())
                                            {
                                                if (li.Contains("@") || li == "")
                                                {
                                                    linksplitedwordlist.Remove(li);
                                                }
                                            }

                                            string filteredword = null;
                                            foreach (var li in linksplitedwordlist)
                                            {
                                                filteredword += li + " ";
                                            }

                                            if (filteredword == null)
                                            {
                                                splitedwordlist.Remove(splitedwordlist[i]);
                                                continue;
                                            }

                                            splitedwordlist[i] = filteredword;
                                        }
                                        else
                                        {
                                            splitedwordlist.Remove(splitedwordlist[i]);
                                        }
                                    }

                                    if (i >= splitedwordlist.Count)
                                    {
                                        i--;
                                    }

                                    if (splitedwordlist[i].Contains("://") || splitedwordlist[i].Contains(".com") ||
                                        splitedwordlist[i].Contains(".ir") || splitedwordlist[i].Contains(".org") ||
                                        splitedwordlist[i].Contains(".net") || splitedwordlist[i].Contains(".ai") ||
                                        splitedwordlist[i].Contains("💸") || splitedwordlist[i].Contains("👇🏼") ||
                                        splitedwordlist[i].Contains("➖") || splitedwordlist[i].Contains("🆔"))
                                    {
                                        if (splitedwordlist[i].Contains("\n"))
                                        {
                                            var linksplitedwordlist = splitedwordlist[i].Split('\n').ToList();
                                            splitedwordlist[i] = null;
                                            foreach (var li in linksplitedwordlist.ToList())
                                            {
                                                if (li.Contains("://") || li.Contains(".me") || li.Contains(".ir") ||
                                                    li.Contains(".com") || li.Contains(".org") || li.Contains(".ai") ||
                                                    li.Contains(".net") ||
                                                    li == "" || li.Contains("💸") || li.Contains("👇🏼") ||
                                                    li.Contains("➖") || li.Contains("🆔"))
                                                {
                                                    linksplitedwordlist.Remove(li);
                                                }
                                            }

                                            string filteredword = null;
                                            foreach (var li in linksplitedwordlist)
                                            {
                                                filteredword += li + " ";
                                            }

                                            if (filteredword == null)
                                            {
                                                splitedwordlist.Remove(splitedwordlist[i]);
                                                continue;
                                            }

                                            splitedwordlist[i] = filteredword;
                                        }
                                        else
                                        {
                                            var linksplitedwordlist = splitedwordlist[i].Split(' ').ToList();
                                            splitedwordlist[i] = null;
                                            foreach (var li in linksplitedwordlist.ToList())
                                            {
                                                if (li.Contains("://") || li.Contains(".me") || li.Contains(".ir") ||
                                                    li == "" || li.Contains(".ai"))
                                                {
                                                    linksplitedwordlist.Remove(li);
                                                }
                                            }

                                            string filteredword = null;
                                            foreach (var li in linksplitedwordlist)
                                            {
                                                filteredword += li + " ";
                                            }

                                            splitedwordlist[i] = filteredword;
                                        }
                                    }


                                    if (splitedwordlist[i].Contains("www."))
                                    {
                                        if (splitedwordlist[i].Contains("\n"))
                                        {
                                            var linksplitedwordlist = splitedwordlist[i].Split('\n').ToList();
                                            splitedwordlist[i] = null;
                                            foreach (var li in linksplitedwordlist.ToList())
                                            {
                                                if (li.Contains("www."))
                                                {
                                                    linksplitedwordlist.Remove(li);
                                                }
                                            }

                                            foreach (var li in linksplitedwordlist)
                                            {
                                                splitedwordlist[i] += li + " ";
                                            }
                                        }
                                        else
                                        {
                                            splitedwordlist.Remove(splitedwordlist[i]);
                                        }
                                    }
                                }

                                string filteredcaption = null;
                                foreach (var split in splitedwordlist.ToList())
                                {
                                    filteredcaption += split + " ";
                                }


                                textmessages[j] = filteredcaption;
                            }


                            #endregion



                            _Context.Entry(channel).Collection(channel => channel.ReplaceWords).Load();


                            #region WordReplacement Filter on photos

                            foreach (var photo in photomessages)
                            {
                                photo.Caption = photo.Caption.Replace("➖", "");


                                foreach (var replaceWord in channel.ReplaceWords)
                                {
                                    photo.Caption = photo.Caption.Replace(replaceWord.Word, replaceWord.ReplaceTo);
                                }



                                var splitedwordlist = photo.Caption.Split(' ').ToList();
                                for (int i = 0; i < splitedwordlist.Count; i++)
                                {
                                    foreach (var replaceWord in channel.ReplaceWords)
                                    {
                                        if (splitedwordlist[i] == replaceWord.Word)
                                        {
                                            splitedwordlist[i] = replaceWord.ReplaceTo;
                                        }
                                    }
                                }

                                string filteredcaption = null;
                                foreach (var split in splitedwordlist.ToList())
                                {
                                    filteredcaption += split + " ";
                                }


                                photo.Caption = filteredcaption;
                            }


                            #endregion


                            #region WordReplacement Filter on textMessages

                            for (int i = 0; i < textmessages.Count; i++)
                            {
                                textmessages[i] = textmessages[i].Replace("➖", "");

                                foreach (var replaceWord in channel.ReplaceWords)
                                {
                                    textmessages[i] = textmessages[i].Replace(replaceWord.Word, replaceWord.ReplaceTo);
                                }
                            }



                            for (int j = 0; j < textmessages.Count; j++)
                            {
                                var splitedwordlist = textmessages[j].Split(' ').ToList();
                                for (int i = 0; i < splitedwordlist.Count; i++)
                                {
                                    foreach (var replaceWord in channel.ReplaceWords)
                                    {
                                        if (splitedwordlist[i] == replaceWord.Word)
                                        {
                                            splitedwordlist[i] = replaceWord.ReplaceTo;
                                        }
                                    }
                                }

                                string filteredcaption = null;
                                foreach (var split in splitedwordlist.ToList())
                                {
                                    filteredcaption += split + " ";
                                }


                                textmessages[j] = filteredcaption;
                            }

                            #endregion

                            if (mustwait)
                            {
                                mustwait = false;
                                Thread.Sleep(mustwaittilme);
                            }

                            #region Sending Text Messages to the Destination

                            //for test



                            foreach (var message in textmessages)
                            {
                                var news = new News()
                                {
                                    //Todo: Conjunction word must remove

                                    TextMessage = message,

                                    DateAdded = DateTime.Now
                                };
                                var textRepetitousresult =
                                    RepetitiousNewstextDetector.IsNewstextRepetitous(news);
                                if (textRepetitousresult)
                                {
                                    continue; //Avoid sending
                                }



                                _Bot.SendTextMessage(settings.StartDescription + "\n" + message + "\n" + "\n" +
                                                     settings.EndDescription);
                                //Calling marker
                                MarkasPublished(news);
                                Thread.Sleep(2560);
                            }


                            #endregion

                            if (mustwait)
                            {
                                mustwait = false;
                                Thread.Sleep(mustwaittilme);
                            }

                            #region Sending Photo Messages to the Destination



                            foreach (var photo in photomessages)
                            {
                                byte[] media = null;
                                try
                                {
                                    //Downloading media content
                                    media = TelegramClientManager.DownloadPhotoFile((TLPhoto)photo.Photo).Result;
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                    Thread.Sleep(10000);
                                    continue;
                                }

                                var news = new News()
                                {
                                    //Todo: Cunjunction word must remove

                                    TextMessage = photo.Caption != null ? photo.Caption : null,

                                    Mediahash = media != null?hasher.Getfilehash(media) : null,

                                                    DateAdded = DateTime.Now
                                };

                                #region RepetituousNewsFilter

                                //Check if photo of current news already published , remove that

                                var mediaresult =
                                    RepetitiousNewsMediaDetector.IsmediaRepetitious(hasher.Getfilehash(media),
                                                                                    publishednewses);



                                if (mediaresult == true)
                                {
                                    continue; //Avoid sending
                                    Console.WriteLine("***********************REPE media NEWS********************");
                                }



                                //Text repetitious detector
                                var textRepetitousresult =
                                    RepetitiousNewstextDetector.IsNewstextRepetitous(news);
                                if (textRepetitousresult)
                                {
                                    continue; //Avoid sending
                                    Console.WriteLine("***********************REPE text NEWS********************");
                                }



                                #endregion



                                Thread.Sleep(5000);
                                var mediafilestream = new MemoryStream(media);

                                //Mark as a published news


                                //Calling marker
                                MarkasPublished(news);



                                _Bot.SendPhotoMessage(mediafilestream,
                                                      settings.StartDescription + "\n" + photo.Caption + "\n" + "\n" +
                                                      settings.EndDescription);
                                Thread.Sleep(1500);
                            }

                            #endregion
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
示例#25
0
        private async Task GetMessages()
        {
            try
            {
                TLAbsDialogs Dialogs = await Client.GetUserDialogsAsync();

                TLDialogs Dlogs = Dialogs as TLDialogs;
                int       i     = 0;
                foreach (TLUser user in Dlogs.users.lists)
                {
                    TLAbsMessages messages = null;
                    string        type     = (Dlogs.dialogs.lists[i].peer.GetType() + "").Replace("TeleSharp.TL.", "");
                    string        peerID   = "";
                    //MessageBox.Show(type);

                    switch (type)
                    {
                    case "TLPeerUser":
                        TLInputPeerUser ipeer = new TLInputPeerUser();
                        ipeer.access_hash = (long)user.access_hash;
                        ipeer.user_id     = user.id;
                        peerID            = user.id + "";
                        messages          = await Client.GetHistoryAsync(ipeer, 0, 999999, 1);

                        break;

                    case "TLPeerChannel":
                        break;

                    case "TLPeerChat":
                        break;

                    case "TLPeerNotifyEventsAll":
                        break;

                    case "TLPeerNotifyEventsEmpty":
                        break;

                    case "TLPeerNotifySettings":
                        break;

                    case "TLPeerNotifySettingsEmpty":
                        break;

                    case "TLPeerSettings":
                        break;

                    default:

                        break;
                    }



                    if (messages != null)
                    {
                        try
                        {
                            TLMessages      msgs  = messages as TLMessages;
                            TLMessagesSlice msgs2 = messages as TLMessagesSlice;
                            if (msgs != null)
                            {
                                foreach (var msg in msgs.messages.lists)
                                {
                                    string    uniq = "";
                                    TLMessage msgg = msg as TLMessage;
                                    if (msgg != null)
                                    {
                                        uniq = peerID + "_" + msgg.id + "# " + msgg.message;

                                        if (UpdatesList.Items.IndexOf(uniq) < 0)
                                        {
                                            UpdatesList.Items.Add(uniq);
                                        }
                                    }
                                }
                            }
                            else if (msgs2 != null)
                            {
                                foreach (var msg in msgs2.messages.lists)
                                {
                                    string    uniq = "";
                                    TLMessage msgg = msg as TLMessage;
                                    if (msgg != null)
                                    {
                                        uniq = peerID + "_" + msgg.id + "# " + msgg.message;

                                        if (UpdatesList.Items.IndexOf(uniq) < 0)
                                        {
                                            UpdatesList.Items.Add(uniq);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            ErrorsBox.Items.Add(ex.Message);
                        }
                    }

                    i++;
                }
                //await GetUpdates();
            }
            catch (Exception ex) {
                ErrorsBox.Items.Add(ex.Message);
            }
        }
示例#26
0
 private IEnumerable <TLMessage> FilterUserMessages(int userId, TLDialogs dialogs)
 {
     return(dialogs?.Messages
            .OfType <TLMessage>()
            .Where(message => message.FromId == userId));
 }