Пример #1
0
        /// <summary>
        /// Аналитика слова, во всех чатах.
        /// </summary>
        /// <param name="analyticsTexts"></param>
        public static void GetAnaliticsInAllChatWord(AnalyticsText[] analyticsTexts, TelegramBotClient botClient, CallbackQuery _message, User user)
        {
            DataBase db = Singleton.GetInstance().Context;
            //создание файла
            String    file      = AppDomain.CurrentDomain.BaseDirectory + "\\newdoc.xls";
            Workbook  workbook  = new Workbook();
            Worksheet worksheet = new Worksheet("Аналитика по словам, во всех чатах");

            worksheet.Cells[0, 0] = new Cell("Название чата");
            worksheet.Cells[0, 1] = new Cell("Текст");
            worksheet.Cells[0, 2] = new Cell("Количество");

            Int32 count = 1;

            Channel[] channel = db.GetChannels();

            IQueryable <AnalyticsText> temp = analyticsTexts.OrderByDescending(p => p.Count).AsQueryable();

            foreach (Channel item in channel)
            {
                worksheet.Cells[count, 1] = new Cell(item.ChannelName, "Text");
                count++;
                foreach (AnalyticsText text in temp)
                {
                    if (item.IDChannel == text.channel.IDChannel)
                    {
                        worksheet.Cells[count, 0] = new Cell(text.channel.ChannelName);
                        worksheet.Cells[count, 1] = new Cell(text.AnaliticsTextAllChatId);
                        worksheet.Cells[count, 2] = new Cell(text.Count);
                        count++;
                    }
                }
            }
            workbook.Worksheets.Add(worksheet);
            workbook.Save(file);

            SendMessage(botClient, _message, user, "Аналитика по словам в чатах");
        }
        public async Task Execute(IJobExecutionContext context)
        {
            DataBase db = Singleton.GetInstance().Context;

            TMessage[] tmessages = db.GetTMessages();
            Channel[]  channels  = db.GetChannels();

            foreach (Channel item in channels)
            {
                foreach (TMessage message in tmessages)
                {
                    if (message.channel.IDChannel == item.IDChannel)
                    {
                        if (message.dateTime == System.DateTime.Today || message.Post == item.PostCount)
                        {
                            continue;
                        }
                        message.Post     = item.PostCount;
                        message.dateTime = System.DateTime.Today;
                    }
                }
            }

            db.Save();

            UserMessage[] userMessages = db.GetUserMessages();

            foreach (UserMessage userMessage in userMessages)
            {
                if (userMessage.dateTime == System.DateTime.Today)
                {
                    continue;
                }
                Singleton.GetInstance().Context._userMessages.Remove(userMessage);
            }
            db.Save();
        }
Пример #3
0
        private async Task <Boolean> SendNotificationAllUsers(TelegramBotClient botClient)
        {
            Channel[]    channels     = db.GetChannels();
            InlineButton inlineButton = new InlineButton();
            var          temp         = inlineButton.PublishNotification(CollectionNotification, true);
            var          picture      = db.GetListCollectionPictureNotification(TextAndButton);

            NotificationChat[] notificationChats = db.GetNotificationChats();
            Int32 Count = 0;

            foreach (var ThisUser in channels)
            {
                if (notificationChats == null)
                {
                    if (notificationChats.Any(p => p.IdChannel == ThisUser && p.IdNotification == TextAndButton.Id))
                    {
                        if (picture == null)
                        {
                            try
                            {
                                var mes = await botClient.SendTextMessageAsync(ThisUser.IDChannel, TextAndButton.Text.Text,
                                                                               replyMarkup : temp);

                                await botClient.PinChatMessageAsync(ThisUser.IDChannel, mes.MessageId, false);
                            }
                            catch (Exception e)
                            {
                            }
                        }
                        else
                        {
                            try
                            {
                                var mes = await botClient.SendPhotoAsync(ThisUser.IDChannel, picture[0].Picture,
                                                                         TextAndButton.Text.Text, replyMarkup : temp);

                                await botClient.PinChatMessageAsync(ThisUser.IDChannel, mes.MessageId, false);
                            }
                            catch (Exception e)
                            {
                            }
                        }
                    }
                }
                else
                {
                    if (picture == null)
                    {
                        try
                        {
                            var mes = await botClient.SendTextMessageAsync(ThisUser.IDChannel, TextAndButton.Text.Text,
                                                                           replyMarkup : temp);

                            await botClient.PinChatMessageAsync(ThisUser.IDChannel, mes.MessageId, false);
                        }
                        catch (Exception e)
                        {
                        }
                    }
                    else
                    {
                        try
                        {
                            var mes = await botClient.SendPhotoAsync(ThisUser.IDChannel, picture[0].Picture,
                                                                     TextAndButton.Text.Text, replyMarkup : temp);

                            await botClient.PinChatMessageAsync(ThisUser.IDChannel, mes.MessageId, false);
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
            }

            var tempList = db.GetListCollectionButtonNotification();

            foreach (CollectionButtonNotification collectionButtonNotification in tempList)
            {
                db.Remove(collectionButtonNotification);
            }

            foreach (CollectionPictureNotification collectionPictureNotification in picture)
            {
                db.Remove(collectionPictureNotification);
            }

            foreach (NotificationChat notificationChat in notificationChats)
            {
                db.Remove(notificationChat);
            }

            var TextTemp = db.GetTextNotification(TextAndButton.Text);

            db.Remove(TextAndButton);
            db.Remove(TextTemp);
            db.Save();

            return(true);
        }
Пример #4
0
        /// <summary>
        /// Аналитика по добавленых пользователей
        /// </summary>
        /// <param name="analiticsPhrases"></param>
        public static async void GetAnaliticsInUserAdd(InvitedUser[] invitedUsers, TelegramBotClient botClient, CallbackQuery _message, User user)
        {
            DataBase db = Singleton.GetInstance().Context;
            //

            /*var client = new TLSharp.Core.TelegramClient(833968, "a6c65fd9460c44e42c5268b5601c849f");
             * var isAuth = client.IsUserAuthorized();
             * Console.WriteLine($"Файл авторизации существует: {isAuth}");
             * client.ConnectAsync().Wait();
             *
             * ModelParserInfo temp2 = WorkingTelegramClient.ParserInfoAboutChannelAndSuperGroup("BuySellCarUBC", client).GetAwaiter().GetResult();
             *
             * foreach (var u2s in temp2.ChannelInfo.Users)
             * {
             *      Console.WriteLine(u2s.FirstName);
             * }*/

            //

            //создание файла
            String    files     = AppDomain.CurrentDomain.BaseDirectory + "\\newdoc.xls";
            Workbook  workbook  = new Workbook();
            Worksheet worksheet = new Worksheet("Аналитика по добавлению человек");

            worksheet.Cells[0, 0] = new Cell("Добавленый пользователь");
            worksheet.Cells[0, 1] = new Cell("Кто добавил");
            worksheet.Cells[0, 2] = new Cell("Группа");

            Int32 count = 1;

            Channel[] channels = db.GetChannels();

            IQueryable <InvitedUser> temp = invitedUsers.OrderByDescending(p => p.UserAddedId).AsQueryable();


            foreach (InvitedUser invitedUser in temp)
            {
                User Added    = db.GetUser(invitedUser.UserAddedId);
                User WhoAdded = db.GetUser(invitedUser.UserWhoAddedId);

                if (Added != null)
                {
                    worksheet.Cells[count, 0] = new Cell(value: Added.FIO + " " + Added.ID);
                }

                if (WhoAdded != null)
                {
                    worksheet.Cells[count, 1] = new Cell(value: WhoAdded.FIO + " " + WhoAdded.ID);
                }

                if (invitedUser.ChannelId != null)
                {
                    Channel channel = db.GetChannel(invitedUser.ChannelId);
                    if (channel != null)
                    {
                        worksheet.Cells[count, 2] = new Cell(channel.ChannelName);
                    }
                }


                count++;
            }

            workbook.Worksheets.Add(worksheet);
            workbook.Save(files);
            SendMessage(botClient, _message, user, "Аналитика по добавлению человек");
        }
        public async void ChekRegister(TelegramBotClient bot, System.Object message)
        {
            _message  = message as Message;
            db        = Singleton.GetInstance().Context;
            botClient = bot;

            try
            {
                Channel channel = db.GetChannel(_message);
                if (channel == null && _message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Supergroup)
                {
                    Channel[] channels = db.GetChannels();

                    Chat chat = await botClient.GetChatAsync(_message.Chat.Id);

                    System.String NewChannel = $"Здравствуйте у нас появился новая группа @{_message.Chat.Username}!\n{chat.Description}";

                    foreach (Channel ch in channels)
                    {
                        botClient.SendText(ch.IDChannel, NewChannel);
                    }

                    db.SetChannel(chat);
                    db.Save();

                    channel = db.GetChannel(_message);

                    await Task.Run(() => AddNewChannel.SetTmessage());
                }

                User user = db.GetUser(_message.From.Id);

                TMessage tmessage = db.GetMessage(_message);
                Settings settings = db.GetSettings();

                if ((user == null || user.FIO == null || user.Number == "0") && _message.Chat.Type != ChatType.Private)
                {
                    botClient.DeleteMessage(_message.Chat.Id, _message.MessageId, "Невозможно удалить сообщение так как оно не было отправленное!");

                    System.String textChannel = $"❗Здравствуйте, что бы писать в чатах UBC - пройдите регистрацию в боте, это занимает меньше 1 минуты.\nСсылка на бота/регистрацию: @{botClient.GetMeAsync().Result.Username}\n\n📜Полный список чатов UBC @allUBC";


                    try
                    {
                        if ((_message.Type != MessageType.Photo) || (_message.Caption != null))
                        {
                            await botClient.SendTextMessageAsync(_message.From.Id, textChannel,
                                                                 replyMarkup : _inlineButton.Register);
                        }
                    }
                    catch
                    {
                        Message mes = null;

                        if ((channel.IDMessage == 0 && _message.Type != MessageType.Photo) ||
                            (_message.Caption != null && channel.IDMessage == 0))
                        {
                            mes = await botClient.SendTextMessageAsync(_message.Chat.Id, textChannel);

                            channel.IDMessage = mes.MessageId;
                            db.SetValue(new ChannelMessage()
                            {
                                ChannelID         = channel.IDChannel,
                                MessageId         = mes.MessageId,
                                DateMessageDelete = DateTime.Now.AddSeconds(20)
                            });

                            db.Save();
                        }
                    }
                }
                else if (user.Chain > 0 && user.Chain < (System.Int32)Advertising.SetChain.GetPayments && _message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Private)
                {
                    FIO fIO = new FIO();
                    fIO.SetNext(
                        new Number()).SetNext(
                        new ChaingeFIO()).SetNext(
                        new ChaingeNumber()).SetNext(
                        new SetReviewsName()).SetNext(
                        new SearchIDUser()).SetNext(
                        new SearchNumberUser()).SetNext(
                        new ChangeReviewsName()).SetNext(
                        new SetSendComplaint()).SetNext(
                        new SetSendAppeal()).SetNext(
                        new Admin()).SetNext(
                        new SetAdminPassword()).SetNext(
                        new Ban()).SetNext(
                        new KickUser()).SetNext(
                        new AdminAdd()).SetNext(
                        new AdminDelete()).SetNext(
                        new PostCount()).SetNext(
                        new WordAdd()).SetNext(
                        new AddUsers()).SetNext(
                        new FludUser()).SetNext(
                        new ChannelAdd()).SetNext(
                        new NewAdmin2Lvl()).SetNext(
                        new WordDelete());

                    ChainOfResposnsibility(botClient, fIO, message, user);
                }
                else if (user.Chain >= (System.Int32)Advertising.SetChain.GetPayments && _message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Private)
                {
                    Advertising.Payments payments = new Advertising.Payments();
                    payments.SetNext(
                        new AddPhotoAdvertising()).SetNext(
                        new ContentEditorText()).SetNext(
                        new SetUserInTransaction()).SetNext(
                        new SetBlockChain()).SetNext(
                        new SetDiscriptionInTransaction()).SetNext(
                        new SetIdTransaction()).SetNext(
                        new SetPublicKeyUserTwo()).SetNext(
                        new AddPhotoChannel()).SetNext(
                        new AddCategotyInDataBase()).SetNext(
                        new AddChannelInCategoryInDataBase()).SetNext(
                        new LinkChat()).SetNext(
                        new LinkChatPharase()).SetNext(
                        new AnaliticsPhraseUser()).SetNext(
                        new AdminCallBlockchainUser()).SetNext(
                        new MessageUserBot()).SetNext(
                        new AddAccauntBotUser()).SetNext(
                        new AddAccauntCode()).SetNext(
                        new PostCountChannel()).SetNext(
                        new ThisRegulationsUBC()).SetNext(
                        new ThisDeleteChat()).SetNext(
                        new ThisDeleteCategory()).SetNext(
                        new SetPriceTime()).SetNext(
                        new SetPriceStandartMessage()).SetNext(
                        new SetStaticTimePinnedPrice()).SetNext(
                        new SetPriceStatic()).SetNext(
                        new SetStaticTimePinnedNotificationPrice()).SetNext(
                        new NotificationTextChain()).SetNext(
                        new NotificationButtonChain()).SetNext(
                        new PictureNotificationChain());

                    payments.Handle(user.Chain, botClient, message);
                }
                else
                {
                    FludChain fludChain = new FludChain();
                    fludChain.SetNext(
                        new AddPeopleChain()).SetNext(
                        new PostNullChain()).SetNext(
                        new CheckChannelChain()).SetNext(
                        new CheckWordAdnLinkChain()).SetNext(
                        new CheckInviteChain()).SetNext(
                        new CheckPhotoChain());

                    fludChain.Handle(botClient, message, user, settings, tmessage, channel);
                }
            }
            catch (System.Exception ex)
            {
                Log.Logging("Класс Analize - " + ex);
            }
        }
Пример #6
0
        private void AsycnCallBack(System.Object sender, Telegram.Bot.Args.CallbackQueryEventArgs e)
        {
            DateTime d;
            DataBase db = Singleton.GetInstance().Context;

            if (e.CallbackQuery.From.Username != null)
            {
                SetUserName(e.CallbackQuery, db);
            }

            if (DateTime.TryParseExact(e.CallbackQuery.Data.Replace("+", "").Replace('.', '/'), "d/M/yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out d))
            {
                try
                {
                    Advertising.Command.AbsCommand Command = AdvertisingCommands.FirstOrDefault(c => c.Equals(e.CallbackQuery.Data.Replace("+", "")));
                    if (Command == null && DateTime.ParseExact(e.CallbackQuery.Data.Replace("+", "").Replace('.', '/'), "d/M/yyyy", null) != null)
                    {
                        Command = AdvertisingCommands.FirstOrDefault(c => c.Equals(Advertising.CommandsText.ChoseDate));
                    }
                    Command.Execute(BotClient, e.CallbackQuery);
                }
                catch (Exception ex)
                {
                    Log.Logging(ex);
                }
            }
            else if (commands.Any(c => c.Equals(e.CallbackQuery.Data)))
            {
                try
                {
                    AbsCommand Command = commands.FirstOrDefault(c => c.Equals(e.CallbackQuery.Data));                     // вытягиваем класс
                    Command.Execute(BotClient, e.CallbackQuery);
                }
                catch (System.Exception ex)
                {
                    Log.Logging(ex);
                }
            }
            else if (commandSlashes.Any(c => c.Equals(e.CallbackQuery.Data)))
            {
                try
                {
                    ICommandSlash Command = commandSlashes.FirstOrDefault(c => c.Equals(e.CallbackQuery.Data));                     // вытягиваем класс
                    Command.Execute(BotClient, e.CallbackQuery);
                }
                catch (System.Exception ex)
                {
                    Log.Logging(ex);
                }
            }
            else if (AdvertisingCommands.Any(c => c.Equals(e.CallbackQuery.Data)))
            {
                try
                {
                    Advertising.Command.AbsCommand command = AdvertisingCommands.FirstOrDefault(c => c.Equals(e.CallbackQuery.Data));
                    command.Execute(BotClient, e.CallbackQuery);
                }
                catch (System.Exception ex)
                {
                    Log.Logging(ex);
                }
            }
            else if (db.GetChannels().Any(p => p.IDChannel == System.Convert.ToInt64(e.CallbackQuery.Data.Split(" ")[0])))
            {
                ThisChannel channel = new ThisChannel();
                channel.Execute(BotClient, e.CallbackQuery, System.Convert.ToInt64(e.CallbackQuery.Data.Split(" ")[0]));
            }
            else
            {
                User user = db.GetUser(e.CallbackQuery.From.Id);
                if (IsNullDataBase.IsNull(BotClient, e.CallbackQuery, user))
                {
                    return;
                }
                if (user.Chain == 53)
                {
                    SelectMyReviews selectReviews = new SelectMyReviews();
                    selectReviews.Execute(BotClient, e.CallbackQuery);
                }
                else if (user.Chain == 54)
                {
                    SelectOtherReviews selectReviews = new SelectOtherReviews();
                    selectReviews.Execute(BotClient, e.CallbackQuery);
                }
                else if (user.IsAdmin > 0)
                {
                    System.String[] words = e.CallbackQuery.Data.Split(new System.Char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
                    if (words[1] == "1")
                    {
                        SetBan setBan = new SetBan();
                        setBan.Execute(BotClient, e.CallbackQuery);
                    }
                    else if (words[1] == "2")
                    {
                        SetCancel setCancel = new SetCancel();
                        setCancel.Execute(BotClient, e.CallbackQuery);
                    }
                    else if (words[1] == "3")
                    {
                        SetAppeal setAppeal = new SetAppeal();
                        setAppeal.Execute(BotClient, e.CallbackQuery);
                    }
                    else if (words[1] == "4")
                    {
                        SetCancelAppeal setAppeal = new SetCancelAppeal();
                        setAppeal.Execute(BotClient, e.CallbackQuery);
                    }
                }
            }
        }
Пример #7
0
        private async void BotClient_OnInlineQuery(Object sender, Telegram.Bot.Args.InlineQueryEventArgs e)
        {
            List <InlineQueryResultBase> list = new List <InlineQueryResultBase>();

            DataBase db = Singleton.GetInstance().Context;

            Channel[]  channels   = db.GetChannels();
            Category[] categories = db.GetCategories();

            if (e.InlineQuery.Query == "")
            {
                list.Clear();

                foreach (Channel channel in channels)
                {
                    Settings settings = db._settings.FirstOrDefault();
                    if (channel.IDChannel != settings.ChannelAdmin)
                    {
                        String text = "";
                        if (channel.Description != null)
                        {
                            List <String> description = channel.Description.Split("\n").ToList();
                            for (Int32 i = 0; i < description.Count; i++)
                            {
                                if (description[i].StartsWith("ПРАВИЛА"))
                                {
                                    continue;
                                }

                                if (description[i].Length == 0)
                                {
                                    continue;
                                }

                                text += description[i] + "\n" + "\n";
                            }
                        }

                        List <List <InlineKeyboardButton> > button = new List <List <InlineKeyboardButton> >
                        {
                            new List <InlineKeyboardButton>()
                        };
                        button[button.Count - 1]
                        .Add(new InlineKeyboardButton()
                        {
                            Text = "Перейти в канал", Url = channel.LinkChannel
                        });
                        button.Add(new List <InlineKeyboardButton>());
                        button[button.Count - 1]
                        .Add(new InlineKeyboardButton()
                        {
                            Text = "Категории", SwitchInlineQueryCurrentChat = ""
                        });
                        button.Add(new List <InlineKeyboardButton>());
                        button[button.Count - 1]
                        .Add(new InlineKeyboardButton()
                        {
                            Text = "Закрыть", CallbackData = CommandText.Close
                        });

                        list.Add(new InlineQueryResultArticle(id: channel.IDChannel.ToString(),
                                                              title: channel.ChannelName,
                                                              inputMessageContent:
                                                              new
                                                              InputTextMessageContent($"{text}\nЗаходите - " +
                                                                                      channel.InviteLink))
                        {
                            Url         = "https://" + channel.LinkChannel,
                            Title       = channel.ChannelName,
                            Description = text,
                            HideUrl     = true,
                            ThumbUrl    = channel.PhotoLink,
                            ThumbHeight = 48,
                            ThumbWidth  = 48,
                            ReplyMarkup = button.ToArray()
                        });
                    }
                }
            }

            else if (categories.Any(p => p.Name == e.InlineQuery.Query))
            {
                list.Clear();
                Category category = categories.FirstOrDefault(p => p.Name == e.InlineQuery.Query);
                foreach (Channel channel in channels)
                {
                    if (category.Id != channel.CategoryId)
                    {
                        continue;
                    }

                    String text = "";
                    if (channel.Description != null)
                    {
                        List <String> description = channel.Description.Split("\n").ToList();
                        for (Int32 i = 0; i < description.Count; i++)
                        {
                            if (description[i].StartsWith("ПРАВИЛА"))
                            {
                                continue;
                            }

                            if (description[i].Length == 0)
                            {
                                continue;
                            }

                            text += description[i] + "\n" + "\n";
                        }
                    }

                    List <List <InlineKeyboardButton> > button = new List <List <InlineKeyboardButton> >
                    {
                        new List <InlineKeyboardButton>()
                    };
                    button[button.Count - 1]
                    .Add(new InlineKeyboardButton()
                    {
                        Text = "Перейти в канал", Url = channel.LinkChannel
                    });
                    button.Add(new List <InlineKeyboardButton>());
                    button[button.Count - 1]
                    .Add(new InlineKeyboardButton()
                    {
                        Text = "Категории", SwitchInlineQueryCurrentChat = ""
                    });
                    button.Add(new List <InlineKeyboardButton>());
                    button[button.Count - 1]
                    .Add(new InlineKeyboardButton()
                    {
                        Text = "Закрыть", CallbackData = CommandText.Close
                    });

                    list.Add(new InlineQueryResultArticle(id: channel.IDChannel.ToString(),
                                                          title: channel.ChannelName,
                                                          inputMessageContent:
                                                          new
                                                          InputTextMessageContent($"{text}\nЗаходите - " +
                                                                                  channel.InviteLink))
                    {
                        Url         = "https://" + channel.LinkChannel,
                        Title       = channel.ChannelName,
                        Description = text,
                        HideUrl     = true,
                        ThumbUrl    = channel.PhotoLink != "" ? channel.PhotoLink : "https://bipbap.ru/wp-content/uploads/2017/10/0_8eb56_842bba74_XL-640x400.jpg",
                        ThumbHeight = 48,
                        ThumbWidth  = 48,
                        ReplyMarkup = button.ToArray()
                    });
                }
            }
            try
            {
                await BotClient.AnswerInlineQueryAsync(e.InlineQuery.Id, list, isPersonal : true, cacheTime : 0);
            }
            catch (Exception b) { Log.Logging(b); }
        }