コード例 #1
0
 public override void ConsumerReceived(object sender, BasicDeliverEventArgs e)
 {
     try
     {
         var qq = (NotiModel)System.Text.Json.JsonSerializer.Deserialize(Encoding.UTF8.GetString(e.Body.Span), typeof(NotiModel));
         if (qq.ChatId == 0)
         {
             foreach (long key in Bot.Core.Services.Bot.FSM <Bot.Core.Models.ObserverBot> .Factory.state.Keys)
             {
                 //messagesSender.AddItem(new TextMessage(null, key, qq.Link + "\n\n" + Math.Round(qq.Rank, 3) + "\n\n" + qq.Text, null));
                 messagesSender.AddItem(new TextMessage(null, key, qq.Link + "\n\n" + qq.Text, null));
             }
         }
         else
         {
             //messagesSender.AddItem(new TextMessage(null, qq.ChatId, qq.Link + "\n\n" + Math.Round(qq.Rank, 3) + "\n\n" + qq.Text, null));
             messagesSender.AddItem(new TextMessage(null, qq.ChatId, qq.Link + "\n\n" + qq.Text, null));
         }
     }
     catch (Exception ex)
     {
         listeningConnection.Dispose();
         listeningChannel.Dispose();
         Connect();
     }
 }
コード例 #2
0
        public async Task ProcessUpdate(Update update, Bot.FSM <SearchBot> fsm)
        {
            if (!await fsm.TryStartSubFSM(update) && !(asyncTaskExecutor == null))
            {
                if (update.Message.Text == "/start")
                {
                    messagesSender.AddItem(new TextMessage(null, update.Message.Chat.Id, "Приветствую! Для первого поиска просто отправьте мне слово/словосочетание.\n\nДля настройки параметров поиска нажмите /settings", null, new ReplyKeyboardRemove()));
                    return;
                }
                fsm.config.BotState     = PrivateChatState.Busy;
                CancellationTokenSource = new CancellationTokenSource();
                SearchReciever <SearchBot> searchClient = (SearchReciever <SearchBot>)serviceProvider.GetService(typeof(SearchReciever <SearchBot>));
                Task SearchingTask    = searchClient.Search(update.Message.From.Id, GetRequest(update, fsm.config), CancellationTokenSource.Token);
                Task searchFinalsTask = SearchingTask.ContinueWith((_) =>
                {
                    fsm.config.BotState = PrivateChatState.Ready;
                    messagesSender.AddItem(new TextMessage(null, update.Message.Chat.Id, "Завершено!", null, new ReplyKeyboardRemove()));
                    return(Task.CompletedTask);
                });

                //Task.WhenAll(SearchingTask, searchFinalsTask).Wait();
                asyncTaskExecutor.Add(Task.WhenAll(SearchingTask, searchFinalsTask));
                messagesSender.AddItem(Bot.Common.CreateOk(update, Bot.Constants.Keyboards.searchingKeyboard));
            }
        }
コード例 #3
0
ファイル: SearchState.cs プロジェクト: vladzvx/tg-data-miner
 public void SendPage(long user, Page page, CancellationToken token, Channel <int> channel = null)
 {
     if (!string.IsNullOrEmpty(page.Text))
     {
         TextMessage textMessage = page.GetTextMessage(null, user, channel);
         messagesSender.AddItem(textMessage);
     }
 }
コード例 #4
0
 public async Task ProcessUpdate <TBot>(Update update, Bot.FSM <TBot> fsm) where TBot : IConfig, new()
 {
     if (Constants.Cancells.Contains(update.Message.Text.ToLower()))
     {
         ISendedItem reply = fsm.readyProcessor.Stop(update);
         messagesSender.AddItem(reply);
         fsm.config.BotState = PrivateChatState.Ready;
     }
     else
     {
         messagesSender.AddItem(Bot.Common.CreateImBusy(update));
     }
 }
コード例 #5
0
        public async Task <bool> ProcessUpdate(Update update, SearchBot parentFSM, CancellationToken token)
        {
            switch (state)
            {
            case ConfiguringSubstates.Started:
            {
                TextMessage mess = new TextMessage(null, update.Message.Chat.Id, "Выберите глубину поиска", Channel.CreateBounded <int>(1), keyboard: Constants.Keyboards.settingKeyboard);
                messagesSender.AddItem(mess);
                state = ConfiguringSubstates.ConfiguringDepth;
                return(false);
            }

            case ConfiguringSubstates.ConfiguringDepth:
            {
                parentFSM.RequestDepth = ParseDepth(update);
                ISendedItem mess = Bot.Common.CreateOk(update, Constants.Keyboards.yesNoKeyboard, " Искать в группах?");
                messagesSender.AddItem(mess);
                state = ConfiguringSubstates.ConfiguringGroups;
                return(false);
            }

            case ConfiguringSubstates.ConfiguringGroups:
            {
                parentFSM.SearchInGroups = update.Message.Text.ToLower() == "да";
                ISendedItem mess = Bot.Common.CreateOk(update, Constants.Keyboards.yesNoKeyboard, " Искать в каналах?");
                messagesSender.AddItem(mess);
                state = ConfiguringSubstates.ConfiguringChannel;
                return(false);
            }

            case ConfiguringSubstates.ConfiguringChannel:
            {
                parentFSM.SearchInChannels = update.Message.Text.ToLower() == "да";
                ISendedItem mess = Bot.Common.CreateOk(update, new ReplyKeyboardRemove(), " Настройки завершены. Для поиска просто отправьте слово/словосочетание боту.");
                parentFSM.BotState = PrivateChatState.Ready;
                messagesSender.AddItem(mess);
                if (TextMessage.defaultClient != null && TextMessage.defaultClient.BotId.HasValue)
                {
                    await dataStorage.SaveChat(parentFSM, token, TextMessage.defaultClient.BotId.Value);
                }
                //current.Finished = true;
                state = ConfiguringSubstates.Started;
                return(true);
            }

            default:
            {
                return(true);
            }
            }
        }
コード例 #6
0
 public async Task <bool> Check <TBot>(Update update, Bot.FSM <TBot> fsm) where TBot : IConfig, new()
 {
     if (update.Type == Telegram.Bot.Types.Enums.UpdateType.Message && update.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Private)
     {
         if (fsm.config.Status > botSettings.BoundUserStatus)
         {
             messagesSender.AddItem(new TextMessage(null, update.Message.Chat.Id, "Пожалуйста, обратитесь к администратору для выдачи разрешения на продолжение работы.", null));
             return(false);
         }
         else
         {
             return(true);
         }
     }
     return(false);
 }
コード例 #7
0
        private async Task Check(long userId, string Username, string Name, long chatId, int messageId, Bot.Core.Services.Bot.FSM <Bot.Core.Models.GateKeeperBot> fsm)
        {
            var res = await userChecker.Check(userId);

            var user = new GateKeeperBot()
            {
                Id       = userId,
                Name     = Name,
                Username = Username,
                userType = Bot.Core.Enums.UserType.User,
                Status   = Bot.Core.Enums.UserStatus.common
            };

            if (res.Status <= Common.Enums.UserStatus.SimpleBad)
            {
                //if (fsm.config.Mode == ChatState.Overrun)
                //{
                await TextMessage.defaultClient.KickChatMemberAsync(chatId, userId, revokeMessages : true);

                user.Status = Bot.Core.Enums.UserStatus.banned;
                await dataStorage.SaveChat(user, CancellationToken.None, TextMessage.defaultClient.BotId.Value);

                TextMessage textMessage = new TextMessage(null, chatId, "Автоматически забанен антипрививочник. UserId:" + userId + "; Соцрейтинг: " + Math.Round(res.Score, 3), null);
                messagesSender.AddItem(textMessage);
                //}
                //else
                //{
                //    string commandBan = string.Format("{0}_{1}_{2}", chatId, userId, Command.Ban.ToString());
                //    string commandTrust = string.Format("{0}_{1}_{2}", chatId, userId, Command.Trust.ToString());
                //    InlineKeyboardMarkup keyb = new InlineKeyboardMarkup(new List<List<InlineKeyboardButton>>()
                //    {
                //        new List<InlineKeyboardButton>()
                //        {
                //            new InlineKeyboardButton()
                //            {
                //                CallbackData=commandBan,
                //                Text= "Бан"
                //            }
                //        }
                //    });
                //    TextMessage textMessage = new TextMessage(null, chatId, Environment.GetEnvironmentVariable("PreBanMessage") ?? "Обнаружена антивакса! " + "Соцрейтинг: " + Math.Round(res.Score, 3).ToString() + " Выберете действие:", null, null, messageId, null, keyb);
                //    messagesSender.AddItem(textMessage);
                //}
            }
            else if (res.Status == Common.Enums.UserStatus.Middle)
            {
                string commandBan    = string.Format("{0}_{1}_{2}", chatId, userId, Command.Ban.ToString());
                string commandTrust  = string.Format("{0}_{1}_{2}", chatId, userId, Command.Trust.ToString());
                string commandWait   = string.Format("{0}_{1}_{2}", chatId, userId, Command.Wait.ToString());
                string commandSearch = res.FirstPageId != ObjectId.Empty ? res.FirstPageId.ToString() : string.Empty;
                var    keybBase      = new List <List <InlineKeyboardButton> >()
                {
                    new List <InlineKeyboardButton>()
                    {
                        new InlineKeyboardButton()
                        {
                            CallbackData = commandBan,
                            Text         = "Бан"
                        },
                        new InlineKeyboardButton()
                        {
                            CallbackData = commandTrust,
                            Text         = "Оправдать"
                        },
                    }
                };
                if (!string.IsNullOrEmpty(commandSearch))
                {
                    keybBase.Add(new List <InlineKeyboardButton>()
                    {
                        new InlineKeyboardButton()
                        {
                            Text = "Личное дело", CallbackData = commandSearch
                        }
                    });
                }
                InlineKeyboardMarkup keyb        = new InlineKeyboardMarkup(keybBase);
                TextMessage          textMessage = new TextMessage(null, chatId, Environment.GetEnvironmentVariable("PreBanMessage") ?? "Обнаружен потенциальный антипрививочник! \n\nДля просмотра личного дела нужно иметь права администратора и стартовать личный диалог со мной." + "Соц рейтинг: " + Math.Round(res.Score, 3).ToString() + "\n\n Выберите действие:", null, null, messageId, null, keyb);
                messagesSender.AddItem(textMessage);
            }
        }
コード例 #8
0
        public async Task Search(long user, SearchRequest searchRequest, CancellationToken token)
        {
            Task searchTask     = searchClient.Search(searchRequest, token);
            Task processingTask = Task.Factory.StartNew(async(tok) =>
            {
                CancellationToken token1;
                if (tok is CancellationToken token2)
                {
                    token1 = token2;
                }
                else
                {
                    token1 = CancellationToken.None;
                }
                bool lastExecutionEnable = true;
                int number         = 1;
                Page PageForSave   = null;
                ObjectId currentId = ObjectId.GenerateNewId();
                ObjectId?nextId    = ObjectId.GenerateNewId();
                ObjectId?prevId    = null;
                List <Page> pages  = new List <Page>();
                Page currentPage   = new Page(currentId, prevId, nextId)
                {
                    position = Page.Position.First
                };
                Channel <int> channel   = Channel.CreateBounded <int>(1);
                bool sended             = false;
                HashSet <string> texts  = new HashSet <string>();
                HashSet <string> texts2 = new HashSet <string>();

                while ((!searchTask.IsCompleted || lastExecutionEnable) && !token1.IsCancellationRequested)
                {
                    while (searchClient.searchResultReciever.TryDequeueResult(out var result))
                    {
                        if (texts.Contains(result.Text))
                        {
                            continue;
                        }
                        else
                        {
                            texts.Add(result.Text);
                            try
                            {
                                var words = result.Text.Split(' ', '\n').Select(item => item.ToLower()).Distinct().ToList();
                                if (words.Count < 10)
                                {
                                    words.Sort((item1, item2) => item1.Length == item2.Length ? 0 : item1.Length < item2.Length ? -1 : 1);
                                    string str = "";
                                    foreach (string st in words)
                                    {
                                        str += st;
                                    }
                                    if (texts2.Contains(str))
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        texts2.Add(str);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }

                        if (!currentPage.TryAddResult(result))
                        {
                            int count   = currentPage.count;
                            PageForSave = currentPage;
                            number++;
                            prevId      = currentId;
                            currentId   = nextId.Value;
                            nextId      = ObjectId.GenerateNewId();
                            currentPage = new Page(currentId, prevId, nextId)
                            {
                                position = Page.Position.Last, count = count, Number = number
                            };
                            currentPage.TryAddResult(result);
                        }
                        else
                        {
                            if (PageForSave != null)
                            {
                                if (PageForSave.position != Page.Position.First)
                                {
                                    PageForSave.position = Page.Position.Middle;
                                }
                                try
                                {
                                    //PageForSave.Text += "\n\n" + PageForSave.Number.ToString();
                                    pages.Add(PageForSave);
                                    if (pages.Count == 1)
                                    {
                                        if (!string.IsNullOrEmpty(pages[0].Text))
                                        {
                                            TextMessage textMessage = pages[0].GetTextMessage(null, user, channel, true);
                                            messagesSender.AddItem(textMessage);
                                        }
                                        sended = true;
                                    }
                                }
                                catch (Exception ex)
                                {
                                }
                                //currentPage.MessageNumber = PageForSave.MessageNumber;
                                PageForSave = null;
                            }
                        }
                    }
                    if (searchTask.IsCompleted && lastExecutionEnable)
                    {
                        lastExecutionEnable = false;
                    }
                    await Task.Delay(50);
                }

                //    await searchState.SavePage(user, currentPage, token);

                if (!pages.Contains(currentPage) && string.IsNullOrEmpty(currentPage.Text))
                {
                    ;
                }
                pages.Add(currentPage);
                int i = 1;

                foreach (var pag in pages)
                {
                    if (string.IsNullOrEmpty(pag.Text))
                    {
                        continue;
                    }
                    int offset      = pag.Text.Length;
                    string pageSuff = "\n\nСтраница " + i.ToString() + " из " + pages.Count.ToString();
                    pag.Text       += pageSuff;
                    pag.Formatting.Add(new Telegram.Bot.Types.MessageEntity()
                    {
                        Offset = offset, Length = pageSuff.Length, Type = Telegram.Bot.Types.Enums.MessageEntityType.Bold
                    });
                    i++;
                }

                if (sended)
                {
                    int messNumber = await channel.Reader.ReadAsync();
                    messagesSender.AddItem(pages[0].GetEditTextMessage(null, user, messNumber));
                }
                else
                {
                    if (!string.IsNullOrEmpty(pages[0].Text))
                    {
                        TextMessage textMessage = pages[0].GetTextMessage(null, user, channel);
                        messagesSender.AddItem(textMessage);
                    }
                }


                await searchState.SavePages(pages, token);

                if (number == 1 && string.IsNullOrEmpty(currentPage.Text) && !token1.IsCancellationRequested)
                {
                    messagesSender.AddItem(new TextMessage(null, user, "Ничего не найдено! Попробуйте другой запрос.", null, new ReplyKeyboardRemove()));
                }
            }, token, TaskCreationOptions.LongRunning);
            await Task.WhenAll(searchTask, processingTask);
        }
コード例 #9
0
 public async Task ProcessUpdate(Update update, Bot.Core.Services.Bot.FSM <Bot.Core.Models.ObserverBot> fsm)
 {
     messagesSender.AddItem(new TextMessage(null, update.Message.Chat.Id, Environment.GetEnvironmentVariable("def_reply") ?? "Оповещаю о появляющихся в телеграме упоминаниях. \nЕсли ничего не приходит - просто подождите какое-то время (возможно - несколько часов), и тему обязательно упомянут, а я сообщу вам об этом. \n\nНе выключайте оповещения!", null, new ReplyKeyboardRemove()));
 }