Example #1
2
        public static void GetLang(Update update, string[] args)
        {
            var glangs = Directory.GetFiles(Bot.LanguageDirectory)
                                                        .Select(x => XDocument.Load(x)
                                                                    .Descendants("language")
                                                                    .First()
                                                                    .Attribute("name")
                                                                    .Value
                                                        ).ToList();
            glangs.Insert(0, "All");

            foreach (var lang in glangs)
            {
                var test =
                    $"getlang|-1001049529775|" + lang;
                var count = Encoding.UTF8.GetByteCount(test);
                if (count > 64)
                {
                    Send("Problem with " + lang + ": name is too long!", update.Message.Chat.Id);
                }
            }
            var gbuttons = glangs.Select(x => new InlineKeyboardButton(x, $"getlang|{update.Message.Chat.Id}|{x}")).ToList();
            var baseMenu = new List<InlineKeyboardButton[]>();
            for (var i = 0; i < gbuttons.Count; i++)
            {
                if (gbuttons.Count - 1 == i)
                {
                    baseMenu.Add(new[] { gbuttons[i] });
                }
                else
                    baseMenu.Add(new[] { gbuttons[i], gbuttons[i + 1] });
                i++;
            }

            var gmenu = new InlineKeyboardMarkup(baseMenu.ToArray());
            try
            {
                var result =
                    Bot.Api.SendTextMessage(update.Message.Chat.Id, "Get which language file?",
                        replyToMessageId: update.Message.MessageId, replyMarkup: gmenu).Result;
            }
            catch (AggregateException e)
            {
                foreach (var ex in e.InnerExceptions)
                {
                    var x = ex as ApiRequestException;

                    Send(x.Message, update.Message.Chat.Id);
                }
            }
            catch (ApiRequestException ex)
            {
                Send(ex.Message, update.Message.Chat.Id);
            }
        }
Example #2
1
        internal static InlineKeyboardMarkup GetConfigMenu(long id)
        {
            List<InlineKeyboardButton> buttons = new List<InlineKeyboardButton>();
            //base menu
            buttons.Add(new InlineKeyboardButton("Show Online Message", $"online|{id}"));
            buttons.Add(new InlineKeyboardButton("Change Language", $"lang|{id}"));
            buttons.Add(new InlineKeyboardButton("Show Roles On Death", $"roles|{id}"));
            buttons.Add(new InlineKeyboardButton("Show Roles At Game End", $"endroles|{id}"));
            buttons.Add(new InlineKeyboardButton("Allow Fleeing", $"flee|{id}"));
            buttons.Add(new InlineKeyboardButton("Set Max Players", $"maxplayer|{id}"));
            buttons.Add(new InlineKeyboardButton("Change Game Mode", $"mode|{id}"));
            buttons.Add(new InlineKeyboardButton("Set Day Timer", $"day|{id}"));
            buttons.Add(new InlineKeyboardButton("Set Lynch Timer", $"lynch|{id}"));
            buttons.Add(new InlineKeyboardButton("Set Night Timer", $"night|{id}"));
            buttons.Add(new InlineKeyboardButton("Allow Fool", $"fool|{id}"));
            buttons.Add(new InlineKeyboardButton("Allow Tanner", $"tanner|{id}"));
            buttons.Add(new InlineKeyboardButton("Allow Cult", $"cult|{id}"));
            buttons.Add(new InlineKeyboardButton("Done", $"done|{id}"));
            var twoMenu = new List<InlineKeyboardButton[]>();
            for (var i = 0; i < buttons.Count; i++)
            {
                if (buttons.Count - 1 == i)
                {
                    twoMenu.Add(new[] { buttons[i] });
                }
                else
                    twoMenu.Add(new[] { buttons[i], buttons[i + 1] });
                i++;
            }

            var menu = new InlineKeyboardMarkup(twoMenu.ToArray());
            return menu;
        }
Example #3
0
        public static void GetLang(Update update, string[] args)
        {
            var glangs = Directory.GetFiles(Bot.LanguageDirectory)
                                                        .Select(x => XDocument.Load(x)
                                                                    .Descendants("language")
                                                                    .First()
                                                                    .Attribute("name")
                                                                    .Value
                                                        ).ToList();
            glangs.Insert(0, "All");

            var gbuttons = glangs.Select(x => new InlineKeyboardButton(x, $"getlang|{update.Message.Chat.Id}|{x}")).ToList();
            var baseMenu = new List<InlineKeyboardButton[]>();
            for (var i = 0; i < gbuttons.Count; i++)
            {
                if (gbuttons.Count - 1 == i)
                {
                    baseMenu.Add(new[] { gbuttons[i] });
                }
                else
                    baseMenu.Add(new[] { gbuttons[i], gbuttons[i + 1] });
                i++;
            }

            var gmenu = new InlineKeyboardMarkup(baseMenu.ToArray());
            Bot.Api.SendTextMessage(update.Message.Chat.Id, "Get which language file?", replyToMessageId: update.Message.MessageId, replyMarkup: gmenu);
        }
Example #4
0
        public RaidPollResponse Execute(SendRaidPollRequest request)
        {
            var raid      = request.Raid;
            var votes     = request.Votes;
            var pokeNames = request.PokeNames;

            var text = new StringBuilder();

            if (string.IsNullOrWhiteSpace(raid.Title))
            {
                text.Append(this.GetRaidLevelSymbol(raid.Level));
                if (raid.PokeId == 0)
                {
                    text.Append(" ?");
                }
                else
                {
                    text.Append($" {pokeNames[raid.PokeId].Trim()}{this.GetForm(raid.PokeForm)}{this.GetMoveTypeSymbols(raid.MoveId)}");
                }
            }
            else
            {
                text.Append(raid.Title);
            }

            text.Append(" " + CLOCK + " ");

            var start = TimeZoneInfo.ConvertTimeFromUtc(raid.Start, timezone);

            text.AppendLine($"{start.ToString("HH:mm:ss")}");

            var gymName = raid.GymName; //.Replace(" ", NON_BREAK_SPACE);

            if (gymName.Length > 22)
            {
                gymName = gymName.Substring(0, 19) + "...";
            }

            if (request.SpecialGymSettings.Any(x => x.Type == (int)GymType.ExRaid))
            {
                text.Append(GEM + NON_BREAK_SPACE);
            }
            else
            {
                text.Append(PIN + NON_BREAK_SPACE);
            }


            text.AppendLine($"[{gymName}](https://maps.google.com/?q={raid.Latitude.ToString(CultureInfo.InvariantCulture)},{raid.Longitude.ToString(CultureInfo.InvariantCulture)})");

            var invitesNeeded = request.Votes.Where(x => LikesInvite(x.Comment)).ToList();

            if (invitesNeeded.Count > 0)
            {
                text.AppendLine();
                text.Append("Einladung gewünscht:");
                foreach (var user in invitesNeeded)
                {
                    text.AppendLine();
                    AppendUser(text, user, request.RaidPreferences);
                }

                text.AppendLine();
            }


            if (request.Votes.Where(x => x.Attendee != 0 && !LikesInvite(x.Comment)).Count() == 0)
            {
                //text.AppendLine();
                text.Append("Bisher keine Zusagen");
            }
            else
            {
                var z = votes.Where(x => x.Attendee != 0 && !LikesInvite(x.Comment)).GroupBy(x => x.Time, (key, g) => new { Time = key, Users = g.ToList() }).OrderBy(x => x.Time);
                foreach (var y in z)
                {
                    text.AppendLine();
                    var numberOfAttendee = y.Users.Sum(x => x.Attendee);
                    var numberOfRemotes  = y.Users.Where(x => x.Comment == PogoUserVoteComments.Remote).Sum(x => x.Attendee);

                    var numberOfAttendeesFormatted = $"{SATELLITE}{numberOfRemotes}{(numberOfRemotes > 8 ? WARNING_SIGN : string.Empty)} / {numberOfAttendee}{(numberOfAttendee > 18 ? WARNING_SIGN : string.Empty)}";

                    if (string.IsNullOrEmpty(y.Time))
                    {
                        text.Append($"Interessenten : {numberOfAttendeesFormatted} ");
                    }
                    else
                    {
                        text.Append($"{y.Time} - Zusagen : {numberOfAttendeesFormatted} ");
                    }

                    foreach (var a in y.Users.OrderBy(b => b.IngameName))
                    {
                        if (a.Attendee != 0)
                        {
                            text.AppendLine();

                            AppendUser(text, a, request.RaidPreferences);
                        }
                    }
                }
            }

            var startFrames         = CreateStartTimes(start, request.TimeOffsets, 5).Select(x => x.ToString("HH:mm")).ToArray();
            var keyBoardStartFrames = new InlineKeyboardButton[] {
                new InlineKeyboardButton(THUMBS_UP)
                {
                    CallbackData = "t|"
                }
                , new InlineKeyboardButton(startFrames[0])
                {
                    CallbackData = $"t|{startFrames[0]}"
                }
                , new InlineKeyboardButton(startFrames[1])
                {
                    CallbackData = $"t|{startFrames[1]}"
                }
                , new InlineKeyboardButton(startFrames[2])
                {
                    CallbackData = $"t|{startFrames[2]}"
                }
                , new InlineKeyboardButton(startFrames[3])
                {
                    CallbackData = $"t|{startFrames[3]}"
                }
            };

            // var extendedStartFrames = CreateStartTimes(start.AddMinutes(45), request.TimeOffsets, 5).Select(x => x.ToString("HH:mm")).ToArray();
            // var extendedKeyBoardStartFrames = new InlineKeyboardButton[] {
            //       new InlineKeyboardButton { Text = extendedStartFrames[0], CallbackData = $"t|{extendedStartFrames[0]}" }
            //     , new InlineKeyboardButton { Text = extendedStartFrames[1], CallbackData = $"t|{extendedStartFrames[1]}" }
            //     , new InlineKeyboardButton { Text = extendedStartFrames[2], CallbackData = $"t|{extendedStartFrames[2]}" }
            //     , new InlineKeyboardButton { Text = extendedStartFrames[3], CallbackData = $"t|{extendedStartFrames[3]}" }
            // };

            var keyBoardNumberOfPersons = new[] {
                new InlineKeyboardButton(SATELLITE)
                {
                    CallbackData = "c|r"
                }
                //, new InlineKeyboardButton { Text = THUMBS_UP, CallbackData = "t|"}
                , new InlineKeyboardButton("-1")
                {
                    CallbackData = "a|-1"
                }
                , new InlineKeyboardButton("0")
                {
                    CallbackData = "a|0"
                }
                , new InlineKeyboardButton("+1")
                {
                    CallbackData = "a|1"
                }
                , new InlineKeyboardButton(ADMISSION_TICKET)
                {
                    CallbackData = "c|i"
                }
            };

            //var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton[3][] { keyBoardStartFrames, extendedKeyBoardStartFrames, keyBoardNumberOfPersons });
            var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton[2][] { keyBoardStartFrames, keyBoardNumberOfPersons });

            return(new RaidPollResponse(Text: text.ToString(), InlineKeyboardMarkup: inlineKeyboard, ParseMode: ParseMode.Markdown));
        }
Example #5
0
        private static async void OnText(MessageEventArgs e)
        {
            log.Info(e.Message.Text + " | " + e.Message.From.FirstName + "  " + e.Message.From.LastName + "(" + e.Message.From.Id + ") chatId:" + e.Message.Chat.Id + " (" + (!string.IsNullOrEmpty(e.Message.Chat.Title) ? e.Message.Chat.Title : e.Message.Chat.Username) + ")");

            if (e.Message.Text.ToLower().Contains("удали"))
            {
                int toRemove;

                if (!int.TryParse(e.Message.Text.ToLower().Substring("удали ".Length), out toRemove))
                {
                    return;
                }

                if (toRemove > 10)
                {
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "А не слішком дохуя?");

                    return;
                }

                var chatId = e.Message.Chat.Id;
                var text   = e.Message.Text;
                if (text.Contains("вморе"))
                {
                    text   = string.Join(" ", text.Split(' ').Where(x => x != "вморе"));
                    chatId = ChatIds.moreSquad;
                }
                int startMessageId   = e.Message.MessageId - 1;
                int currentMessageId = startMessageId;
                while (toRemove > 0)
                {
                    try
                    {
                        var msg = await Bot.DeleteMessageAsync(chatId, currentMessageId);

                        toRemove--;
                    }
                    catch (Exception) {}
                    currentMessageId--;
                }
            }
            if (e.Message.Text.ToLower().Contains("гріша привіт"))
            {
                Bot.SendTextMessageAsync(e.Message.Chat.Id, "привііііт!");
                alive = true;
            }
            else if (!alive)
            {
                return;
            }
            else if (e.Message.Text.ToLower().Contains("гріша пока"))
            {
                var damn = GetDamn(e.Message.From.FirstName).Result;
                if (!string.IsNullOrEmpty(damn))
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, damn);
                }
                Bot.SendTextMessageAsync(e.Message.Chat.Id, "пока =(");
                alive = false;
            }
            else if (e.Message.Text.ToLower().Contains("help"))
            {
                await Bot.SendTextMessageAsync(e.Message.Chat.Id, @"Що я умію:
1) скажи [текст] - озвучка тексту (російською)
2) обізви [ім'я] - обізву кого скажеш (жостко)
3) відосік [текст] - топовий відосік по запиту
4) випадковий відосік [текст] - випадковий відосік по запиту
5) випадковий відосік - випадкове відео з усього простору ютубу
6) gif [text] - гіфка пов'язана з текстом
7) коте - трішки няшності в чатік
8) голосування: [питання]?: [варіант 1], [варіант 2] - анонімне голосування
9) відкрите голосування: [питання]?: [варіант 1], [варіант 2] - голосування
10) погода - поточна погода у Вінниці
11) 2 * 3 + (23 - 2)^3 = - таке я вмію рахувати
12) можу якось відповісти на рандомне повідомлення
13) анекдот - спробую шутканути"
                                               );
            }
            else if (e.Message.Text.ToLower().Contains("обізви"))
            {
                var words = e.Message.Text.ToLower().Split(' ');

                var name = words[words.ToList().IndexOf("обізви") + 1];
                if (!string.IsNullOrEmpty(name))
                {
                    var damn = GetDamn(name).Result;
                    if (!string.IsNullOrEmpty(damn))
                    {
                        //Bot.SendTextMessageAsync(e.Message.Chat.Id, damn);
                        using (var stream = new MemoryStream(GetSpeach(damn).Result))
                        {
                            stream.Seek(0, SeekOrigin.Begin);
                            var x = Bot.SendVoiceAsync(e.Message.Chat.Id, new FileToSend("speech.mp3", stream), damn, 10);


                            while (x.Status == TaskStatus.WaitingForActivation)
                            {
                                Thread.Sleep(1000);
                            }
                        }
                    }
                }
            }

            else if (e.Message.Text.ToLower().Contains("частота"))
            {
                try
                {
                    var words = e.Message.Text.ToLower().Split(' ');
                    switch (words[1])
                    {
                    case "відповідь":
                        answerPosibility = int.Parse(words[2]);
                        break;

                    case "хуй":
                        huiPosibility = int.Parse(words[2]);
                        break;

                    case "картинка":
                        imagePosibility = int.Parse(words[2]);
                        break;

                    case "стікер":
                        stickerPosibility = int.Parse(words[2]);
                        break;

                    default: return;
                    }
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, "Частота оновлена.");
                }
                catch
                {
                }
            }

            else if (e.Message.Text.ToLower().Split(' ').Contains("скажи"))
            {
                var text = string.Join(" ", e.Message.Text.ToLower().Split(' ').Where(x => x != "скажи"));

                if (string.IsNullOrEmpty(text))
                {
                    return;
                }

                long chatId = e.Message.Chat.Id;

                if (text.Contains("вморе"))
                {
                    text   = string.Join(" ", text.Split(' ').Where(x => x != "вморе"));
                    chatId = ChatIds.moreSquad;
                }
                if (text.Contains("вревол"))
                {
                    text   = string.Join(" ", text.Split(' ').Where(x => x != "вревол"));
                    chatId = ChatIds.itRevolution;
                }

                using (var stream = new MemoryStream(GetSpeach(text).Result))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    var x = Bot.SendVoiceAsync(chatId, new FileToSend("speech.mp3", stream), "", 10);


                    while (x.Status == TaskStatus.WaitingForActivation)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
            else if ((e.Message.Text.ToLower().Split(' ').Contains("випадковий") ||
                      e.Message.Text.ToLower().Split(' ').Contains("рандомний")) &&
                     e.Message.Text.ToLower().Split(' ').Contains("відосік"))
            {
                var text = string.Join(" ", e.Message.Text.ToLower().Split(' ').Where(x => x != "випадковий" && x != "відосік" && x != "рандомний"));
                Bot.SendTextMessageAsync(e.Message.Chat.Id, GetRandomVideo(text).Result);
            }
            else if (e.Message.Text.ToLower().Split(' ').Contains("відосік"))
            {
                var text = string.Join(" ", e.Message.Text.ToLower().Split(' ').Where(x => x != "відосік"));
                var link = GetVideo(text).Result;
                if (string.IsNullOrEmpty(link))
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, "що ща брєд, нема таких відосів");
                }
                else
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, GetVideo(text).Result);
                }
            }
            else if (e.Message.Text.ToLower().Contains("погода"))
            {
                Bot.SendTextMessageAsync(e.Message.Chat.Id, GetWeather().Result);
            }
            else if (e.Message.Text.ToLower().EndsWith("триста") || e.Message.Text.ToLower().EndsWith("300"))
            {
                Bot.SendTextMessageAsync(e.Message.Chat.Id, "отсоси у тракториста");
            }
            else if (e.Message.Text.ToLower().EndsWith("="))
            {
                var calc = GetCalc(e.Message.Text.ToLower().Substring(0, e.Message.Text.Length - 1)).Result;
                if (!string.IsNullOrEmpty(calc))
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, calc);
                }
                else
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, "Не по мені задачка, сам рішай цю дічь");
                }
            }
            else if (e.Message.Text.ToLower().EndsWith("совпадение?") || e.Message.Text.ToLower().EndsWith("співпадіння?"))
            {
                Bot.SendTextMessageAsync(e.Message.Chat.Id, "не думаю!");
            }
            else if (e.Message.Text.ToLower().Contains("ахах"))
            {
                Bot.SendTextMessageAsync(e.Message.Chat.Id, "ахахахах");
            }
            else if (e.Message.Text.ToLower().Contains("анекдот"))
            {
                var anekdot = GetAnecdot().Result;
                if (!string.IsNullOrEmpty(anekdot))
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, anekdot);
                }
                else
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, "У мене нема настрою для анекдоту, розважай себе сам.");
                }
            }

            else if (e.Message.Text.ToLower().Split(' ').Contains("gif"))
            {
                var tag = string.Join(" ", e.Message.Text.ToLower().Split(' ').Where(x => x != "gif"));
                if (GetGif(tag).Result == null)
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, "Сорі чувак, у мене таких гіфок немає :(");
                    return;
                }
                using (var stream = new MemoryStream(GetGif(tag).Result))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    var x = Bot.SendDocumentAsync(e.Message.Chat.Id, new FileToSend("gif.gif", stream));


                    while (x.Status == TaskStatus.WaitingForActivation)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }

            else if (e.Message.Text.ToLower().Contains("коте"))
            {
                if (e.Message.Text.ToLower().Split(" ,.&!?-0123456789*-+//_^:;\"\'".ToCharArray()).Any(x => x == "коте"))
                {
                    var type = random.Next(5) == 0 ? "jpg" : "gif";
                    using (var stream = new MemoryStream(GetCat(type).Result))
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        Task x;
                        if (type == "gif")
                        {
                            x = Bot.SendDocumentAsync(e.Message.Chat.Id, new FileToSend("cat." + type, stream));
                        }
                        else
                        {
                            x = Bot.SendPhotoAsync(e.Message.Chat.Id, new FileToSend("cat." + type, stream));
                        }

                        while (x.Status == TaskStatus.WaitingForActivation)
                        {
                            Thread.Sleep(1000);
                        }
                    }
                }
                else
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, "Хуй тобі а не кота, розумний самий? хоч кота, пиши коте окремо і не вийобуйся.");
                }
            }
            else if (e.Message.Text.ToLower().Contains("хуй"))
            {
                var stickerSet = Bot.GetStickerSetAsync("Thngs");
                Bot.SendStickerAsync(e.Message.Chat.Id, new FileToSend(stickerSet.Result.Stickers[random.Next(stickerSet.Result.Stickers.Count)].FileId));
            }
            else if (e.Message.Text.ToLower().Contains("лисий"))
            {
                var stickerSet = Bot.GetStickerSetAsync("johnnysinsbrazzers");
                Bot.SendStickerAsync(e.Message.Chat.Id, new FileToSend(stickerSet.Result.Stickers[random.Next(stickerSet.Result.Stickers.Count)].FileId));
            }
            else if (e.Message.Text.ToLower().Contains("секс"))
            {
                var stickerSet = Bot.GetStickerSetAsync("SigmundFreud");
                Bot.SendStickerAsync(e.Message.Chat.Id, new FileToSend(stickerSet.Result.Stickers[random.Next(stickerSet.Result.Stickers.Count)].FileId));
            }
            else if (e.Message.Text.ToLower().EndsWith("омг"))
            {
                var stickerSet = Bot.GetStickerSetAsync("More_Faces");
                Bot.SendStickerAsync(e.Message.Chat.Id, new FileToSend(stickerSet.Result.Stickers[1].FileId));
            }
            else if (e.Message.Text.ToLower().EndsWith("ізі"))
            {
                Bot.SendTextMessageAsync(e.Message.Chat.Id, "Риал толк");
            }
            else if (e.Message.Text.ToLower().EndsWith("нет") || e.Message.Text.ToLower().EndsWith("нєт"))
            {
                Bot.SendTextMessageAsync(e.Message.Chat.Id, "пидора отвєт");
            }
            else if (e.Message.Text.ToLower().Contains("бухати"))
            {
                Bot.SendTextMessageAsync(e.Message.Chat.Id,
                                         e.Message.Date.DayOfWeek != DayOfWeek.Friday
                                                ? "Хтось сказав бухати? Я завжди не проти"
                                                : "Бухати?? Пфф.. звііісно! сьогоодні ж пятниця, котіки, чекаю вас всіх в СпортПабі в 19.00 ");
            }
            else if (e.Message.Text.ToLower().Contains("макс"))
            {
                var mssg = Bot.SendTextMessageAsync(e.Message.Chat.Id, "Аве Макс!!!");
            }
            else if (Can(answerPosibility))
            {
                var answers = Constants.Phrases
                              .Where(x => x.UserId == User.Any || (int)x.UserId == e.Message.From.Id)
                              .ToList();
                Bot.SendTextMessageAsync(e.Message.Chat.Id, answers[random.Next(answers.Count)].Text);
            }
            if (e.Message.Text.ToLower().Contains("голосованіє") || e.Message.Text.ToLower().Contains("голосування"))
            {
                try
                {
                    var answer   = e.Message.Text.Split(':')[1];
                    var variants = e.Message.Text.Split(':')[2].Split(',');

                    var buttons = new InlineKeyboardCallbackButton[variants.Length];
                    for (var i = 0; i < variants.Length; i++)
                    {
                        buttons[i] = new InlineKeyboardCallbackButton(variants[i], "callbackVoice" + i);
                    }

                    var keyboard = new InlineKeyboardMarkup(new InlineKeyboardButton[][] { buttons });

                    var isOpen = e.Message.Text.ToLower().Contains("відкрите");
                    var mess   = Bot.SendTextMessageAsync(e.Message.Chat.Id, answer, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboard).Result;
                    Settings.VoiceList.Add(new Voice(mess.MessageId, answer, variants, isOpen));
                    SaveSettings();
                }
                catch (Exception ex)
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, "Це так не работає");
                }
            }
            else if (Can(stickerPosibility))
            {
                var stickerSet1 = Bot.GetStickerSetAsync("More_Faces");
                var stickerSet3 = Bot.GetStickerSetAsync("BlueRobots");
                var stickerSet4 = Bot.GetStickerSetAsync("Druzhko");
                var stickerSet5 = Bot.GetStickerSetAsync("terebonk_2");
                var stickerSet6 = Bot.GetStickerSetAsync("teadosug");
                var stickers    = stickerSet1.Result.Stickers;
                stickers.AddRange(stickerSet3.Result.Stickers);
                stickers.AddRange(stickerSet4.Result.Stickers);
                stickers.AddRange(stickerSet5.Result.Stickers);
                stickers.AddRange(stickerSet6.Result.Stickers);
                Bot.SendStickerAsync(e.Message.Chat.Id, new FileToSend(stickers[random.Next(stickers.Count)].FileId));
            }
            else if (Can(huiPosibility))
            {
                if (e.Message.Text.Length >= 4)
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, "хуй" + e.Message.Text.Substring(e.Message.Text.Length - 4));
                }
            }
        }
        private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var message = messageEventArgs.Message;

            if (message == null || message.Type != MessageType.TextMessage) return;

            if (message.Text.StartsWith("/inline")) // send inline keyboard
            {
                await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

                var keyboard = new InlineKeyboardMarkup(new[]
                {
                    new[] // first row
                    {
                        new InlineKeyboardButton("1.1"),
                        new InlineKeyboardButton("1.2"),
                    },
                    new[] // second row
                    {
                        new InlineKeyboardButton("2.1"),
                        new InlineKeyboardButton("2.2"),
                    }
                });

                await Task.Delay(500); // simulate longer running task

                await Bot.SendTextMessageAsync(message.Chat.Id, "Choose",
                    replyMarkup: keyboard);
            }
            else if (message.Text.StartsWith("/keyboard")) // send custom keyboard
            {
                var keyboard = new ReplyKeyboardMarkup(new[]
                {
                    new [] // first row
                    {
                        new KeyboardButton("1.1"),
                        new KeyboardButton("1.2"),  
                    },
                    new [] // last row
                    {
                        new KeyboardButton("2.1"),
                        new KeyboardButton("2.2"),  
                    }
                });

                await Bot.SendTextMessageAsync(message.Chat.Id, "Choose",
                    replyMarkup: keyboard);
            }
            else if (message.Text.StartsWith("/photo")) // send a photo
            {
                await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto);

                const string file = @"<FilePath>";

                var fileName = file.Split('\\').Last();

                using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var fts = new FileToSend(fileName, fileStream);

                    await Bot.SendPhotoAsync(message.Chat.Id, fts, "Nice Picture");
                }
            }
            else if (message.Text.StartsWith("/request")) // request location or contact
            {
                var keyboard = new ReplyKeyboardMarkup(new []
                {
                    new KeyboardButton("Location")
                    {
                        RequestLocation = true
                    },
                    new KeyboardButton("Contact")
                    {
                        RequestContact = true
                    }, 
                });

                await Bot.SendTextMessageAsync(message.Chat.Id, "Who or Where are you?", replyMarkup: keyboard);
            }
            else
            {
                var usage = @"Usage:
/inline   - send inline keyboard
/keyboard - send custom keyboard
/photo    - send a photo
/request  - request location or contact
";

                await Bot.SendTextMessageAsync(message.Chat.Id, usage,
                    replyMarkup: new ReplyKeyboardHide());
            }
        }
Example #7
0
        public override async Task Invoke(CallbackQuery callbackQuery, TelegramBotClient client)
        {
            var message = callbackQuery.Message;
            var data    = callbackQuery.Data.Split("@");


            if (data[1] == "referalProgram")
            {
                var backButton = new InlineKeyboardButton()
                {
                    Text         = "<<< Назад",
                    CallbackData = "referalProgram@back"
                };

                var payOutButton = new InlineKeyboardButton()
                {
                    Text         = "\uD83D\uDCB5 Вывод",
                    CallbackData = "referalProgram@payOut"
                };

                var keyboard = new InlineKeyboardMarkup(new List <List <InlineKeyboardButton> >()
                {
                    new List <InlineKeyboardButton>()
                    {
                        payOutButton
                    },
                    new List <InlineKeyboardButton>()
                    {
                        backButton
                    }
                });

                decimal currentBalans = 0;
                int     referalCount  = 0;

                string sendingText = Resourses.TextResourses.ReferMessage;

                string refLink = BotSettings.BotLink + "?start=" + callbackQuery.From.Id;

                await client.EditMessageTextAsync(
                    chatId : message.Chat.Id,
                    messageId : message.MessageId,
                    text : String.Format(sendingText, refLink, referalCount, currentBalans),
                    parseMode : Telegram.Bot.Types.Enums.ParseMode.Html,
                    replyMarkup : keyboard);
            }

            else if (data[1] == "back")
            {
                foreach (var item in Bot.Commands)
                {
                    if (item.Contains("menu"))
                    {
                        await item.CallbackInvoke(callbackQuery, client);

                        break;
                    }
                    ;
                }
            }

            else if (data[1] == "payOut")
            {
                await client.AnswerCallbackQueryAsync(
                    callbackQueryId : callbackQuery.Id,
                    text : "");
            }

            else
            {
                await client.EditMessageTextAsync(
                    chatId : message.Chat.Id,
                    messageId : message.MessageId,
                    text : "How do you done it?");
            }

            await client.AnswerCallbackQueryAsync(
                callbackQueryId : callbackQuery.Id);
        }
Example #8
0
        public override void BotOnUpdateRecieved(object sender, UpdateEventArgs updateEventArgs)
        {
            try
            {
                switch (updateEventArgs.Update.Type)
                {
                case UpdateType.CallbackQuery:
                {
                    long chatId = updateEventArgs.Update.CallbackQuery.Message.Chat.Id;
                    switch (updateEventArgs.Update.CallbackQuery.Data)
                    {
                    case deffer:
                    {
                        if (WorkModes.TryGetValue(chatId, out Mode mode))
                        {
                            sender_to_tg.Put(factory.CreateMessage(chatId, "Отправьте время публикации в формате, аналогичном текущему времени:" +
                                                                   "\n\n " + DateTime.Now.ToString()));
                            if (mode == Mode.PostCreation)
                            {
                                Stages.AddOrUpdate(chatId, 5, (oldkey, oldvalue) => 5);
                            }
                            else if (mode == Mode.RePostCreation)
                            {
                                Stages.AddOrUpdate(chatId, 2, (oldkey, oldvalue) => 2);
                            }
                        }
                        break;
                    }

                    case publicNow:
                    {
                        ClearUnderChatMenu(chatId, "Успешно опубликовано!");
                        dBWorker.update_task_time(chatId, token, DateTime.UtcNow);
                        SetMode(chatId);
                        Stages.TryRemove(chatId, out int v);
                        SendDefaultMenu(chatId);
                        break;
                    }

                    case reactionsNo:
                    {
                        Stages.AddOrUpdate(chatId, 4, (oldkey, oldvalue) => 4);
                        sender_to_tg.Put(factory.CreateMessage(chatId, "Опубликовать пост сейчас или отложить?",
                                                               keyboardMarkup: CreateShedulerQuestion()));
                        break;
                    }

                    case reactionsYes:
                    {
                        CreateUnderChatReactionsMenu(chatId, "Выберите или введите реакции. " +
                                                     "Один символ - один лайк. Если нужно добавить текст введите их в виде [реакция1][реакция2]");
                        Stages.AddOrUpdate(chatId, 3, (oldkey, oldvalue) => 3);
                        break;
                    }

                    case CreatePostCommand:
                    {
                        Task.Factory.StartNew(CreatePostCommandButtonReaction, chatId);
                        break;
                    }

                    case CreateRePostCommand:
                    {
                        Task.Factory.StartNew(CreateRePostCommandButtonReaction, chatId);
                        break;
                    }

                    case DefferedPostsCommand:
                    {
                        Mode mode = Mode.DefferedManaging;
                        WorkModes.AddOrUpdate(chatId, mode, (oldkey, oldvalue) => mode);
                        List <DataBaseWorker.PostingTask> postingTasks = dBWorker.get_future_tasks(token);
                        if (postingTasks.Count > 0)
                        {
                            List <List <string> > texts  = new List <List <string> >();
                            List <List <string> > values = new List <List <string> >();
                            foreach (var tsk in postingTasks)
                            {
                                string ButtonText    = string.Format("{0} {1}", tsk.channel_name, tsk.PublishTime);
                                string ReturnedValue = "task_" + tsk.id.ToString();
                                texts.Add(new List <string>()
                                        {
                                            ButtonText
                                        });
                                values.Add(new List <string>()
                                        {
                                            ReturnedValue
                                        });
                            }
                            InlineKeyboardMarkup keyboard = CommonFunctions.CreateInlineKeyboard(texts, values);
                            sender_to_tg.Put(factory.CreateMessage(chatId, "Выберете отложенное сообщение:", keyboardMarkup: keyboard));
                            CreateUnderChatMenu(chatId, "Или отмените действие");
                        }
                        else
                        {
                            ClearUnderChatMenu(chatId, "Нет ни одного отложенного сообщения!");
                            SendDefaultMenu(chatId);
                            SetMode(chatId);
                        }

                        break;
                    }

                    case EditPostsCommand:
                    {
                        Mode mode = Mode.PostEditing;
                        WorkModes.AddOrUpdate(chatId, mode, (oldkey, oldvalue) => mode);
                        break;
                    }

                    case AddChannelCommand:
                    {
                        Task.Factory.StartNew(AddChannelButtonReaction, chatId);
                        break;
                    }

                    default:
                    {
                        if (long.TryParse(updateEventArgs.Update.CallbackQuery.Data, out long channel_id) &&
                            WorkModes.TryGetValue(chatId, out Mode currentMode))
                        {
                            if (currentMode == Mode.PostCreation)
                            {
                                if (!Stages.TryGetValue((long)chatId, out int st))
                                {
                                    Stages.AddOrUpdate((long)chatId, 1, (oldkey, oldvalue) => 1);
                                    dBWorker.add_task((long)chatId, channel_id, token, Mode.PostCreation.ToString());
                                    CreateUnderChatMenu((long)chatId, "Канал выбран! Отправьте боту то, что хотите опубликовать. " +
                                                        "Это может быть всё, что угодно – текст, фото, альбом, видео, даже стикеры.");
                                }
                            }
                            else if (currentMode == Mode.RePostCreation)
                            {
                                Stages.AddOrUpdate((long)chatId, 1, (oldkey, oldvalue) => 1);
                                dBWorker.add_task((long)chatId, channel_id, token, Mode.RePostCreation.ToString());
                                CreateUnderChatMenu((long)chatId, "Канал выбран! Перешлите боту сообщение, которое хотите репостнуть. " +
                                                    "Это может быть текст, фото, видео, даже стикеры, но не альбом.");
                            }
                            break;
                        }
                        Match ReactionMatch = ReactionReg.Match(updateEventArgs.Update.CallbackQuery.Data);
                        if (ReactionMatch.Success && int.TryParse(ReactionMatch.Groups[1].Value, out int ReactionId))
                        {
                            dBWorker.count_reaction(ReactionId, updateEventArgs.Update.CallbackQuery.From.Id);
                            var reactions = dBWorker.get_counted_reactions(ReactionId);
                            if (reactions != null && reactions.Count > 0)
                            {
                                InlineKeyboardMarkup keybpard = CommonFunctions.CreateInlineKeyboard(GetReactionsTexts(reactions),
                                                                                                     GetReactionsData(reactions));
                                sender_to_tg.Put(factory.CreateKeyboardEditingRequest(updateEventArgs.Update.CallbackQuery.Message.Chat.Id,
                                                                                      updateEventArgs.Update.CallbackQuery.Message.MessageId, keybpard));
                            }

                            break;
                        }

                        Match TaskMatch = TaskReg.Match(updateEventArgs.Update.CallbackQuery.Data);
                        if (TaskMatch.Success && int.TryParse(TaskMatch.Groups[1].Value, out int TaskId))
                        {
                            dBWorker.task_rejected(TaskId);
                            ClearUnderChatMenu(chatId, "Сообщение успешно отменено!");
                            SendDefaultMenu(chatId);
                            SetMode(chatId);
                        }

                        break;
                    }
                    }
                    break;
                }
                }
            }
            catch (Exception ex) { logger.Error(ex); }
        }
Example #9
0
        //private static void ApiOnOnReceiveGeneralError(object sender, ReceiveGeneralErrorEventArgs receiveGeneralErrorEventArgs)
        //{
        //    if (!Api.IsReceiving)
        //    {
        //        Api.StartReceiving();// cancellationToken: new CancellationTokenSource(1000).Token);
        //    }
        //    var e = receiveGeneralErrorEventArgs.Exception;
        //    using (var sw = new StreamWriter(Path.Combine(RootDirectory, "..\\Logs\\apireceiveerror.log"), true))
        //    {
        //        sw.WriteLine($"{DateTime.UtcNow} {e.Message} - {e.StackTrace}\n{e.Source}");
        //    }
        //}

        //private static async Task ApiOnOnMessage(ITelegramBotClient bot, Update update, CancellationToken token)
        //{
        //    new Task(() =>
        //    {
        //        switch (update.Type)
        //        {
        //            // UpdateType.Unknown:
        //            // UpdateType.ChannelPost:
        //            // UpdateType.EditedChannelPost:
        //            // UpdateType.ShippingQuery:
        //            // UpdateType.PreCheckoutQuery:
        //            // UpdateType.Poll:
        //            case UpdateType.InlineQuery:
        //                UpdateHandler.InlineQueryReceived(bot, update.InlineQuery);
        //                break;
        //            case UpdateType.CallbackQuery:
        //                UpdateHandler.CallbackReceived(bot, update.CallbackQuery);
        //                break;
        //            default:
        //                UpdateHandler.UpdateReceived(bot, update);
        //                break;
        //                //Api.OnInlineQuery += UpdateHandler.InlineQueryReceived;
        //                //Api.OnUpdate += UpdateHandler.UpdateReceived;
        //                //Api.OnCallbackQuery += UpdateHandler.CallbackReceived;
        //                //Api.OnReceiveError += ApiOnReceiveError;
        //                ////Api.OnReceiveGeneralError += ApiOnOnReceiveGeneralError;
        //                ////Api.OnStatusChanged += ApiOnStatusChanged;
        //                ////Api.UpdatesReceived += ApiOnUpdatesReceived;
        //                //UpdateType.Message            => BotOnMessageReceived(botClient, update.Message!),
        //                //UpdateType.EditedMessage      => BotOnMessageReceived(botClient, update.EditedMessage!),
        //                //UpdateType.CallbackQuery      => BotOnCallbackQueryReceived(botClient, update.CallbackQuery!),
        //                //UpdateType.InlineQuery        => BotOnInlineQueryReceived(botClient, update.InlineQuery!),
        //                //UpdateType.ChosenInlineResult => BotOnChosenInlineResultReceived(botClient, update.ChosenInlineResult!),
        //                //_                             => UnknownUpdateHandlerAsync(botClient, update)
        //        }
        //    }).Start();
        //    //try
        //    //{
        //    //    await handler;
        //    //}
        //    //catch (Exception exception)
        //    //{
        //    //    await HandleErrorAsync(botClient, exception, cancellationToken);
        //    //}
        //}

        //private static void ApiOnUpdatesReceived(object sender, UpdateEventArgs updateEventArgs)
        //{
        //    //MessagesReceived += updateEventArgs.UpdateCount;
        //}

        internal static void ReplyToCallback(CallbackQuery query, string text = null, bool edit = true, bool showAlert = false, InlineKeyboardMarkup replyMarkup = null, ParseMode parsemode = ParseMode.Html, bool disableWebPagePreview = false)
        {
            //first answer the callback
            Bot.Api.AnswerCallbackQueryAsync(query.Id, edit ? null : text, showAlert);
            //edit the original message
            if (edit)
            {
                Edit(query, text, replyMarkup, parsemode, disableWebPagePreview);
            }
        }
Example #10
0
 internal static Task <Message> Edit(long id, int msgId, string text, InlineKeyboardMarkup replyMarkup = null, ParseMode parsemode = ParseMode.Html, bool disableWebPagePreview = false)
 {
     return(Bot.Api.EditMessageTextAsync(id, msgId, text, parsemode, null, disableWebPagePreview, replyMarkup));
 }
Example #11
0
        /// <summary>
        /// Edits captions of the message with the provided identifier sent by the bot or via the bot (for
        /// inline bots).
        /// </summary>
        /// <param name="chatId">
        /// Unique identifier for the target chat or username of the target channel (in the format
        /// @channelusername). Required if <paramref name="inlineMessageId" /> is not specified.
        /// </param>
        /// <param name="messageId">
        /// Unique identifier of the sent message. Required if <paramref name="inlineMessageId" /> is not
        /// specified.
        /// </param>
        /// <param name="inlineMessageId">
        /// Identifier of the inline message. Required if <paramref name="chatId" /> and
        /// <paramref name="messageId" /> are not specified.
        /// </param>
        /// <param name="caption">New caption of the message.</param>
        /// <param name="replyMarkup">
        /// An <see cref="InlineKeyboardMarkup" /> object for a custom reply keyboard.
        /// </param>
        /// <param name="cancellationToken">
        /// A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for the task to
        /// complete.
        /// </param>
        /// <returns>
        /// A task that represents the asynchronous operation. On success the task results contains the edited
        /// Message is returned.
        /// </returns>
        private Task <Message> EditMessageCaptionAsync(string chatId, long messageId, string inlineMessageId, [NotNull] string caption, InlineKeyboardMarkup replyMarkup = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Contracts.EnsureNotNull(caption, nameof(caption));

            var parameters = new NameValueCollection();

            parameters.AddIf(!string.IsNullOrWhiteSpace(chatId), "chat_id", chatId);
            parameters.AddIf(messageId > 0, "message_id", messageId.ToString());
            parameters.AddIf(!string.IsNullOrWhiteSpace(inlineMessageId), "inline_message_id", inlineMessageId);
            parameters.Add("caption", caption);

            return(this.CallTelegramMethodAsync <Message>(cancellationToken, "editMessageText", parameters, replyMarkup: replyMarkup));
        }
        public async Task <bool?> Handle(InlineQuery data, object context = default, CancellationToken cancellationToken = default)
        {
            var results = new List <InlineQueryResult>();

            var    query     = data.Query;
            string encodedId = null;

            if (Regex.Match(query, PATTERN) is { Success : true } match)
            {
                encodedId = match.Groups["Id"].Value;
                query     = query.Remove(match.Index, match.Length);
            }
            query = query.Trim();

            var matchedZones = myDateTimeZoneProvider.Ids.Where(id =>
            {
                // check tz id
                if (id.Contains(query, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                // check Region name
                return(myTimeZoneService.TryGetRegion(id, out var region) && (
                           region.EnglishName.Contains(query, StringComparison.OrdinalIgnoreCase) ||
                           region.NativeName.Contains(query, StringComparison.OrdinalIgnoreCase)));
            }).ToList();

            InlineKeyboardMarkup replyMarkup = null;

            if (myTimeZoneNotifyService.DecodeId(encodedId, out var chatId, out var messageId))
            {
                (_, replyMarkup) = await myTimeZoneNotifyService.GetSettingsMessage(new Chat { Id = chatId, Type = ChatType.Sender }, messageId, cancellationToken);
            }
            var instant = myClock.GetCurrentInstant();

            int.TryParse(data.Offset, out var offset);
            for (var index = offset; index < matchedZones.Count && index < offset + PAGE_SIZE; index++)
            {
                var id = matchedZones[index];
                if (myDateTimeZoneProvider.GetZoneOrNull(id) is { } timeZone)
                {
                    var title   = $"{timeZone.Id} ({timeZone.GetUtcOffset(instant)})";
                    var builder = new TextBuilder()
                                  .Append($"{title}\x00A0") // trailing space is necessary to allow edit it further to the same message
                                  .NewLine();

                    string countryString = null;
                    if (myTimeZoneService.TryGetRegion(timeZone.Id, out var country))
                    {
                        countryString = $"{country.EnglishName} {country.NativeName}";
                        builder.Sanitize(countryString).NewLine();
                    }

                    results.Add(new InlineQueryResultArticle($"{PREFIX}:{encodedId}:{timeZone.Id}", title, builder.ToTextMessageContent())
                    {
                        Description = countryString,
                        ReplyMarkup = replyMarkup
                    });
                }
            }

            string nextOffset = default;

            if (results.Count == 0 && offset == 0)
            {
                results.Add(new InlineQueryResultArticle("NothingFound", "Nothing found",
                                                         new TextBuilder($"Nothing found by request ").Code(builder => builder.Sanitize(query)).ToTextMessageContent())
                {
                    Description = $"Request {query}",
                    ThumbUrl    = myUrlHelper.AssetsContent(@"static_assets/png/btn_close_normal.png").AbsoluteUri
                });
            }
            else
            {
                nextOffset = (offset + PAGE_SIZE).ToString();
            }

            await myBot.AnswerInlineQueryWithValidationAsync(data.Id, results, nextOffset : nextOffset, cacheTime : 0, isPersonal : true, cancellationToken : cancellationToken);

            return(true);
        }
Example #13
0
        private void runBot()
        {
            Bot = new Telegram.Bot.TelegramBotClient(Token);

            this.Invoke(new Action(() =>
            {
                lblStatus.Text      = "Online";
                lblStatus.ForeColor = Color.Green;
            }));
            int offset = 0;

            while (true)
            {
                try
                {
                    Telegram.Bot.Types.Update[] Update = Bot.GetUpdatesAsync(offset).Result;

                    foreach (Telegram.Bot.Types.Update Up in Update)
                    {
                        offset = Up.Id + 1;
                        while (Up.CallbackQuery != null)
                        {
                            //Contatct To Me Inline
                            if (Up.CallbackQuery.Data.Contains("gmail"))
                            {
                                Bot.SendTextMessageAsync(Up.CallbackQuery.Message.Chat.Id, "My Gmail address is : [email protected]"); Up.CallbackQuery = null; break;
                            }
                            else if (Up.CallbackQuery.Data.Contains("outlook"))
                            {
                                Bot.SendTextMessageAsync(Up.CallbackQuery.Message.Chat.Id, "My Outlook address is : [email protected]"); Up.CallbackQuery = null; break;
                            }
                            //Poll Inline
                            var user = db.PollManager.SingleOrDefault(u => u.UserID == Up.CallbackQuery.From.Id);
                            if (user == null)
                            {
                                user = new PollManager()
                                {
                                    UserID      = Up.CallbackQuery.From.Id,
                                    VotedByUser = ""
                                };
                                db.PollManager.Add(user);
                                db.SaveChanges();
                            }
                            var UserID       = Up.CallbackQuery.From.Id;
                            var pUserID      = db.PollManager.Select(p => p.UserID).ToList();
                            var pVotedByUSer = db.PollManager.Select(p => p.VotedByUser).ToList();
                            var query        = Up.CallbackQuery.Data;

                            string VotedNow = Up.CallbackQuery.Data;
                            if (db.PollManager.Any(p => (p.UserID == Up.CallbackQuery.From.Id) && (p.VotedByUser != VotedNow)))
                            {
                                Poll(Up, db.PollManager.SingleOrDefault(a => a.UserID == UserID).VotedByUser, VotedNow);

                                InlineKeyboardMarkup PollButons = PollInline();
                                Bot.EditMessageReplyMarkupAsync(Up.CallbackQuery.Message.Chat.Id, Up.CallbackQuery.Message.MessageId, replyMarkup: PollButons);
                                Up.CallbackQuery = null;
                            }
                            else
                            {
                                Bot.SendTextMessageAsync(Up.CallbackQuery.Message.Chat.Id, "You have rated before");
                            }
                            Up.CallbackQuery = null;
                        }


                        if (Up.Message == null)
                        {
                            continue;
                        }

                        string MessageFromUser           = Up.Message.Text.ToLower();
                        Telegram.Bot.Types.User   Upfrom = Up.Message.From;
                        Telegram.Bot.Types.ChatId ChatID = Up.Message.Chat.Id;

                        StringBuilder SB = new StringBuilder();
                        if (MessageFromUser.Contains("start"))
                        {
                            ReplyKeyboardMarkup MainKeyboardMarkup = StartKeyboards();
                            SB.AppendLine("Welcome To My Bot");
                            SB.AppendLine("Contact To Me : /ContactToMe");
                            SB.AppendLine("About Me : /AboutMe");
                            Bot.SendTextMessageAsync(ChatID, SB.ToString(), parseMode: default, false, true, 0, MainKeyboardMarkup);
Example #14
0
        private static async void Bot_OnCallbackQueryReseived(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e)
        {
            string[] userRequest = e.CallbackQuery.Data.Split('※');

            switch (userRequest[1])
            {
            case "1":                                                                            //search by color
            {
                FindUser findUser = new FindUser();
                findUser.color = userRequest[0];

                var json = JsonConvert.SerializeObject(findUser);
                var data = new StringContent(json, Encoding.UTF8, "application/json");

                using var client = new HttpClient();
                var content = await client.PostAsync("https://wallpaperapi.azurewebsites.net/api/Wallpaper/color", data);

                string result = content.Content.ReadAsStringAsync().Result;

                WallhavenResponse wallhaven = JsonConvert.DeserializeObject <WallhavenResponse>(result);

                if (result == "BAD")
                {
                    await Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, "Very bad");

                    break;
                }
                if (wallhaven.results.Count == null || wallhaven.results.Count == 0)
                {
                    await Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, "Very bad");

                    break;
                }

                List <List <InlineKeyboardButton> > inlineKeyboardList = new List <List <InlineKeyboardButton> >();

                int a = 0;

                foreach (var photo in wallhaven.results)            //dynamic buttons
                {
                    List <InlineKeyboardButton> ts = new List <InlineKeyboardButton>();
                    ts.Add(InlineKeyboardButton.WithUrl(photo.id, photo.urls.full));
                    ts.Add(InlineKeyboardButton.WithCallbackData("Add", photo.id + "※3"));
                    inlineKeyboardList.Add(ts);
                }

                var inline = new InlineKeyboardMarkup(inlineKeyboardList);
                await Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, "________________________________________", replyMarkup : inline);

                break;
            }

            case "2":                                                  // search by category
            {
                FindUser findUser = new FindUser();
                findUser.category = userRequest[0];

                var json = JsonConvert.SerializeObject(findUser);
                var data = new StringContent(json, Encoding.UTF8, "application/json");

                using var client = new HttpClient();
                var content = await client.PostAsync("https://wallpaperapi.azurewebsites.net/api/Wallpaper/category", data);

                string result = content.Content.ReadAsStringAsync().Result;

                WallhavenResponse wallhaven = JsonConvert.DeserializeObject <WallhavenResponse>(result);

                if (result == "BAD")
                {
                    await Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, "Very bad");

                    break;
                }
                if (wallhaven.results.Count == null || wallhaven.results.Count == 0)
                {
                    await Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, "Very bad");

                    break;
                }

                List <List <InlineKeyboardButton> > inlineKeyboardList = new List <List <InlineKeyboardButton> >();

                int a = 0;

                foreach (var photo in wallhaven.results)
                {
                    List <InlineKeyboardButton> ts = new List <InlineKeyboardButton>();
                    ts.Add(InlineKeyboardButton.WithUrl(photo.id, photo.urls.full));
                    ts.Add(InlineKeyboardButton.WithCallbackData("Add", photo.id + "※3"));
                    inlineKeyboardList.Add(ts);
                }

                var inline = new InlineKeyboardMarkup(inlineKeyboardList);
                await Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, "________________________________________", replyMarkup : inline);

                break;
            }

            case "3":                                                    //add to favourite
            {
                try
                {
                    Console.WriteLine("Using DB");

                    FindUser findUser = new FindUser();
                    findUser.id      = e.CallbackQuery.From.Id;
                    findUser.photoId = userRequest[0];

                    var json = JsonConvert.SerializeObject(findUser);
                    var data = new StringContent(json, Encoding.UTF8, "application/json");

                    using var client = new HttpClient();
                    var content = await client.PostAsync("https://wallpaperapi.azurewebsites.net/api/Wallpaper/addfavourite", data);

                    string result = content.Content.ReadAsStringAsync().Result;

                    await Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, result);

                    break;
                }
                catch
                {
                    Console.WriteLine("Exeption");
                    break;
                }
            }

            case "4":                                               //delete from favourite
            {
                try
                {
                    Console.WriteLine("Using DB");

                    FindUser findUser = new FindUser();
                    findUser.id      = e.CallbackQuery.From.Id;
                    findUser.photoId = userRequest[0];

                    var json = JsonConvert.SerializeObject(findUser);
                    var data = new StringContent(json, Encoding.UTF8, "application/json");

                    using var client = new HttpClient();
                    var content = await client.PutAsync("https://wallpaperapi.azurewebsites.net/api/Wallpaper/delfavourite", data);

                    string result = content.Content.ReadAsStringAsync().Result;

                    await Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, result);

                    break;
                }
                catch
                {
                    Console.WriteLine("Exeption");
                    break;
                }
            }

            default:
            {
                Console.WriteLine("Doupe");
                break;
            }
            }
            string name = $"{e.CallbackQuery.From.FirstName}  {e.CallbackQuery.From.LastName}";

            Console.WriteLine($"{name} tap on {userRequest}");
        }
Example #15
0
        public static async void BotOnMassegeReseived(object sendere, Telegram.Bot.Args.MessageEventArgs e)
        {
            var message = e.Message;

            if (message == null || message.Type != MessageType.Text)
            {
                return;
            }



            string name = $"{message.From.FirstName} {message.From.LastName} ";

            Console.WriteLine($"{name} send {message.Text}");

            switch (message.Text)
            {
            case "/start":
                string text =
                    @"
This bot has several commands, check it out before you start.
List of commands:
/searchbygenre - this command will give you several genres for image search. 
Choose ganre and click on the link issued to open the image. Click 'Add' to add to your favorite list.
/searchbycolor - this command provides the ability to search pictures by a specific color. 
If you have favourite color, this comand special 4u.
/random - Random is the most interesting comand that generates a random image.
It's useful if your imagination runs out. Try your luck)
/favourite - the comand gives a list of favorite photos that can be saved by clicking the Add button while you using bot.
You can make changes to the list by deleting items from it. Just click on the 'Delete' button.

Еnjoy using!
";
                await Bot.SendPhotoAsync(message.From.Id, "https://images.unsplash.com/photo-1477959858617-67f85cf4f1df?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjEzMTIxNX0");

                await Bot.SendTextMessageAsync(message.From.Id, text);


                break;

            case "/searchbycolor":
            {
                var keyboard = new InlineKeyboardMarkup(new[]
                    {
                        new[]
                        {
                            InlineKeyboardButton.WithCallbackData("Black and White", "Black and White※1"),
                            InlineKeyboardButton.WithCallbackData("Pink", "Pink※1"),
                            InlineKeyboardButton.WithCallbackData("Yellow", "Yellow※1")
                        },
                        new[]
                        {
                            InlineKeyboardButton.WithCallbackData("Blue", "Blue※1"),
                            InlineKeyboardButton.WithCallbackData("Red", "Red※1"),
                            InlineKeyboardButton.WithCallbackData("Green", "Green※1")
                        },
                        new[]
                        {
                            InlineKeyboardButton.WithCallbackData("Purpure", "Purpure※1"),
                            InlineKeyboardButton.WithCallbackData("Orange", "Orange※1"),
                            InlineKeyboardButton.WithCallbackData("Brown", "Brown※1")
                        }
                    });

                await Bot.SendPhotoAsync(message.From.Id,
                                         "https://images.unsplash.com/photo-1433888104365-77d8043c9615?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1053&q=80");

                await Bot.SendTextMessageAsync(message.From.Id, "Select color for serch", replyMarkup : keyboard);

                break;
            }

            case "/searchbygenre":
            {
                var genrekeyboard = new InlineKeyboardMarkup(new[]
                    {
                        new[] {
                            InlineKeyboardButton.WithCallbackData("anime", "anime※2"),
                            InlineKeyboardButton.WithCallbackData("general", "general※2"),
                            InlineKeyboardButton.WithCallbackData("NSFW", "NSFW※2"),
                            InlineKeyboardButton.WithCallbackData("Abstract", "Abstract※2")
                        },
                        new[]
                        {
                            InlineKeyboardButton.WithCallbackData("Astrophotography", "Astrophotography※2"),
                            InlineKeyboardButton.WithCallbackData("Architecture", "Architecture※2"),
                            InlineKeyboardButton.WithCallbackData("City", "City※2"),
                            InlineKeyboardButton.WithCallbackData("Family", "Family※2")
                        },
                        new[]
                        {
                            InlineKeyboardButton.WithCallbackData("Landscape", "Landscape※2"),
                            InlineKeyboardButton.WithCallbackData("Panorama", "Panorama※2"),
                            InlineKeyboardButton.WithCallbackData("Drone", "Drone※2"),
                            InlineKeyboardButton.WithCallbackData("War", "War※2")
                        }
                    });

                await Bot.SendPhotoAsync(message.From.Id,
                                         "https://images.unsplash.com/photo-1504805572947-34fad45aed93?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80");

                await Bot.SendTextMessageAsync(message.From.Id, "Choose ganre", replyMarkup : genrekeyboard);

                break;
            }

            case "/random":
            {
                using var client = new HttpClient();
                var content = await client.GetAsync("https://api.unsplash.com/photos/random/?client_id=JGYSsjXO8ANdFCsiBrNZVmi3yXfOcSM5VD0jU8EpeY8");

                string result = content.Content.ReadAsStringAsync().Result;

                RandomResponse randomResponse = JsonConvert.DeserializeObject <RandomResponse>(result);

                var keyboardrandom = new InlineKeyboardMarkup(new[]
                    {
                        new[] { InlineKeyboardButton.WithUrl("PHOTO", randomResponse.urls.full) },
                        new[] { InlineKeyboardButton.WithCallbackData("Add to favourite", randomResponse.id + "※3") }
                    });
                await Bot.SendPhotoAsync(e.Message.Chat.Id,
                                         "https://images.unsplash.com/photo-1458419948946-19fb2cc296af?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80");

                await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Random photo", replyMarkup : keyboardrandom);

                break;
            }

            case "/favourite":
            {
                FindUser findUser = new FindUser();
                findUser.id = (int)e.Message.Chat.Id;

                var json = JsonConvert.SerializeObject(findUser);
                var data = new StringContent(json, Encoding.UTF8, "application/json");

                using var client = new HttpClient();
                var content = await client.PostAsync("https://wallpaperapi.azurewebsites.net/api/Wallpaper/getfavourite", data);

                string result = content.Content.ReadAsStringAsync().Result;

                if (result == "BAD")
                {
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Very bad");

                    break;
                }

                List <List <InlineKeyboardButton> > inlineKeyboardList = new List <List <InlineKeyboardButton> >();

                Users            users   = new Users();
                List <PhotoInfo> example = new List <PhotoInfo>();
                example      = JsonConvert.DeserializeObject <List <PhotoInfo> >(result);
                users.Images = example;

                int a = 0;


                if (users.Images.Count == 0 || users.Images.Count == null)
                {
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "No image");

                    break;
                }


                foreach (var photo in users.Images)                                                   //dynamic buttons
                {
                    List <InlineKeyboardButton> ts = new List <InlineKeyboardButton>();
                    ts.Add(InlineKeyboardButton.WithUrl(photo.Id, photo.Link));
                    ts.Add(InlineKeyboardButton.WithCallbackData("Delete", photo.Id + "※4"));
                    inlineKeyboardList.Add(ts);
                }
                var inline = new InlineKeyboardMarkup(inlineKeyboardList);


                await Bot.SendPhotoAsync(e.Message.From.Id,
                                         "https://images.unsplash.com/photo-1580571313472-5bd3de1d1ab8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60");

                await Bot.SendTextMessageAsync(e.Message.Chat.Id, "________________________________________", replyMarkup : inline);


                break;
            }

            default:
                break;
            }
        }
Example #16
0
        /// <summary>
        /// Edits text messages sent by the bot or via the bot (for inline bots).
        /// </summary>
        /// <param name="chatId">
        /// Unique identifier for the target chat or username of the target channel (in the format
        /// @channelusername). Required if <paramref name="inlineMessageId" /> is not specified.
        /// </param>
        /// <param name="messageId">
        /// Unique identifier of the sent message. Required if <paramref name="inlineMessageId" /> is not
        /// specified.
        /// </param>
        /// <param name="inlineMessageId">
        /// The identifier of the inline message. Required if <paramref name="chatId" /> and
        /// <paramref name="messageId" /> are not specified.
        /// </param>
        /// <param name="text">New text of the message</param>
        /// <param name="parseMode">
        /// A value from <see cref="ParseMode" /> enum indicates the way that the Telegram should parse the
        /// sent message. Send <see cref="ParseMode.Markdown" />, if you want Telegram apps to show bold,
        /// italic, fixed-width text or inline URLs in your bot's message.
        /// </param>
        /// <param name="disableWebPagePreview">Disables link previews for links in this message</param>
        /// <param name="replyMarkup">
        /// An <see cref="InlineKeyboardMarkup" /> object for a custom reply keyboard.
        /// </param>
        /// <param name="cancellationToken">
        /// A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for the task to
        /// complete.
        /// </param>
        /// <returns>
        /// A task that represents the asynchronous operation. The task results contains the edited
        /// <see cref="Message" /> on success.
        /// </returns>
        private Task <Message> EditMessageTextAsync(string chatId, long messageId, string inlineMessageId, [NotNull] string text, ParseMode parseMode = ParseMode.Normal, bool disableWebPagePreview = false, InlineKeyboardMarkup replyMarkup = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Contracts.EnsureNotNull(text, nameof(text));

            var parameters = new NameValueCollection();

            parameters.AddIf(!string.IsNullOrWhiteSpace(chatId), "chat_id", chatId);
            parameters.AddIf(messageId > 0, "message_id", messageId.ToString());
            parameters.AddIf(!string.IsNullOrWhiteSpace(inlineMessageId), "inline_message_id", inlineMessageId);
            parameters.Add("text", text);
            parameters.AddIf(parseMode != ParseMode.Normal, "parse_mode", parseMode.ToString());
            parameters.AddIf(disableWebPagePreview, "disable_web_page_preview", true);

            return(this.CallTelegramMethodAsync <Message>(cancellationToken, "editMessageText", parameters, replyMarkup: replyMarkup));
        }
Example #17
0
        /// <summary>
        /// Edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
        /// </summary>
        /// <param name="chatId">
        /// Unique identifier for the target chat or username of the target channel (in the format
        /// @channelusername). Required if <paramref name="inlineMessageId" /> is not specified.
        /// </param>
        /// <param name="messageId">
        /// Unique identifier of the sent message. Required if <paramref name="inlineMessageId" /> is not
        /// specified.
        /// </param>
        /// <param name="inlineMessageId">
        /// Identifier of the inline message. Required if <paramref name="chatId" /> and
        /// <paramref name="messageId" /> are not specified.
        /// </param>
        /// <param name="replyMarkup">
        /// An <see cref="InlineKeyboardMarkup" /> object for a custom reply keyboard.
        /// </param>
        /// <param name="cancellationToken">
        /// A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for the task to
        /// complete.
        /// </param>
        /// <returns>
        /// A task that represents the asynchronous operation. On success the task results contains the edited
        /// Message is returned.
        /// </returns>
        private Task <Message> EditMessageReplyMarkupAsync(string chatId, long messageId, string inlineMessageId, InlineKeyboardMarkup replyMarkup = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var parameters = new NameValueCollection();

            parameters.AddIf(!string.IsNullOrWhiteSpace(chatId), "chat_id", chatId);
            parameters.AddIf(messageId > 0, "message_id", messageId.ToString());
            parameters.AddIf(!string.IsNullOrWhiteSpace(inlineMessageId), "inline_message_id", inlineMessageId);

            return(this.CallTelegramMethodAsync <Message>(cancellationToken, "editMessageReplyMarkup", parameters, replyMarkup: replyMarkup));
        }
Example #18
0
 async Task PrintMenu(string text)
 {
     var keyboard = new[] { InlineKeyboardButton.WithCallbackData($"🔙 Назад", BackAction) };
     var markup   = new InlineKeyboardMarkup(keyboard);
     await Trail.SendTextMessageAsync(text, replyMarkup : markup);
 }
Example #19
0
 internal static Task <Message> Send(string message, long id, bool clearKeyboard = false, InlineKeyboardMarkup customMenu = null)
 {
     return(Bot.Send(message, id, clearKeyboard, customMenu));
 }
Example #20
0
 public Task EditMessageTextMarkdown(int messageMessageId, string s,
                                     InlineKeyboardMarkup inlineKeyboardButtons = null)
 => _origin.EditMarkdownMessage(messageMessageId, s, inlineKeyboardButtons);
Example #21
0
        private static async void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            var message = e.Message;

            if (message.Type != MessageType.Text || message == null)
            {
                return;
            }
            string name = $"{message.From.FirstName} {message.From.LastName}";

            Console.WriteLine($"{name} отправил сообщение6: '{message.Text}'");
            switch (message.Text)
            {
            case "/help":
                string text =
                    @"Список команд:
/inline - вывод меня
/keyboard - вывод клавиатуры";
                await Bot.SendTextMessageAsync(message.From.Id, text);

                break;

            case "/inline":
                var inlineKeyboerd = new InlineKeyboardMarkup(new[]
                {
                    new[]
                    {
                        InlineKeyboardButton.WithUrl("Мемасный телега :)", "https://t.me/darckness_reveur"),
                        InlineKeyboardButton.WithUrl("Админ телега:)", "https://t.me/darckness_reveur")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithUrl("Мемасный вк", "https://vk.com/epritula99"),
                        InlineKeyboardButton.WithUrl("Админ вк", "https://vk.com/darkness_reveur")
                    }
                });
                await Bot.SendTextMessageAsync(message.From.Id, "Выберите пункт меню",
                                               replyMarkup : inlineKeyboerd);

                break;

            case "/keyboard":
                var replyKeyboard = new ReplyKeyboardMarkup(new[]
                {
                    new KeyboardButton("Геолакация")
                    {
                        RequestLocation = true
                    },
                    new KeyboardButton("Контакты")
                    {
                        RequestContact = true
                    }
                });

                await Bot.SendTextMessageAsync(message.Chat.Id, "Если что-то не напишу, фиганёт ошибку (", replyMarkup : replyKeyboard);

                break;

            default:
                var    response = apiAi.TextRequest(message.Text);
                string answer   = response.Result.Fulfillment.Speech;
                if (answer == null || answer == "")
                {
                    answer = "Прости, я тебя не понимаю";
                }
                await Bot.SendTextMessageAsync(message.From.Id, answer);

                break;
            }
        }
Example #22
0
 internal static Task <Message> Edit(CallbackQuery query, string text, InlineKeyboardMarkup replyMarkup = null, ParseMode parsemode = ParseMode.Html, bool disableWebPagePreview = false)
 {
     return(Edit(query.Message.Chat.Id, query.Message.MessageId, text, replyMarkup, parsemode, disableWebPagePreview));
 }
Example #23
0
        public async Task Post(Update update)
        {
            if (update?.Message?.Text == "/stttart")
            {
                var chat = update.Message.Chat;

                var userDto = new UserDto()
                {
                    Id        = chat.Id,
                    FirstName = chat.FirstName,
                    LastName  = chat.LastName,
                    UserName  = chat.Username,
                    Sex       = 0
                };

                var result = _mediator.Send(new CreateUserCommand(userDto));

                var inlineKeyboardInfo = new List <(string text, string callBackValue)>();

                userDto.Sex = SexType.Female;
                var femaleDto = new CallBackDto()
                {
                    CommandQueryName = typeof(CreateUserCommand).Name,
                    Data             = JsonSerializer.Serialize(userDto),
                    DataType         = typeof(UserDto).Name
                };

                userDto.Sex = SexType.Male;
                var maleDto = new CallBackDto()
                {
                    CommandQueryName = typeof(CreateUserCommand).Name,
                    Data             = JsonSerializer.Serialize(userDto),
                    DataType         = typeof(UserDto).Name
                };

                string txt = JsonSerializer.Serialize(femaleDto);

                inlineKeyboardInfo.Add(("دختر 🚶🏻‍", JsonSerializer.Serialize(femaleDto)));
                inlineKeyboardInfo.Add(("پسر 🚶‍", JsonSerializer.Serialize(maleDto)));

                var keyboardMarkup = new InlineKeyboardMarkup(TelegramBotExtentions.GetInlineKeyboard(inlineKeyboardInfo));

                long Chat_id = _botClient.SendTextMessageAsync(update.Message.Chat.Id, StaticProvider.ChooseGender, replyMarkup: keyboardMarkup).Result.Chat.Id;

                await Task.CompletedTask;
            }
            //start

            var callBack = JsonSerializer.Deserialize <CallBackDto>(update.CallbackQuery.Data);;

            //if (!string.IsNullOrWhiteSpace(callBack.CommandQueryName))
            //{
            //    var assembly = Assembly.GetExecutingAssembly();

            //    var type = assembly.GetTypes()
            //        .First(t => t.Name == callBack.CommandQueryName);

            //    object parameter = JsonSerializer.Deserialize<object>(callBack.Data);

            //    var instance = Activator.CreateInstance(type, parameter);

            //    var result = _mediator.Send(instance);
            //}

            //TODO: set hear
        }
Example #24
0
 internal static Task <Message> Send(string message, long id, bool clearKeyboard = false, InlineKeyboardMarkup customMenu = null, ParseMode parseMode = ParseMode.Html)
 {
     //MessagesSent++;
     //message = message.Replace("`",@"\`");
     if (clearKeyboard)
     {
         //var menu = new ReplyKeyboardRemove() { RemoveKeyboard = true };
         return(Api.SendTextMessageAsync(id, message, replyMarkup: customMenu, disableWebPagePreview: true, parseMode: parseMode));
     }
     else if (customMenu != null)
     {
         return(Api.SendTextMessageAsync(id, message, replyMarkup: customMenu, disableWebPagePreview: true, parseMode: parseMode));
     }
     else
     {
         return(Api.SendTextMessageAsync(id, message, disableWebPagePreview: true, parseMode: parseMode));
     }
 }
Example #25
0
        public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
                                               CancellationToken cancellationToken)
        {
            _telegramService = new TelegramService(context);
            var msg      = context.Update.Message;
            var sendText = "Balas pesan yg mau di report";

            if (msg.Chat.Type == ChatType.Private)
            {
                await _telegramService.SendTextAsync("Report hanya untuk grup saja")
                .ConfigureAwait(false);

                return;
            }

            if (msg.ReplyToMessage != null)
            {
                var repMsg = msg.ReplyToMessage;

                if (msg.From.Id != repMsg.From.Id)
                {
                    var mentionAdmins = await _telegramService.GetMentionAdminsStr()
                                        .ConfigureAwait(false);

                    var allListAdmin = await _telegramService.GetAllAdmins()
                                       .ConfigureAwait(false);

                    var allAdminId = allListAdmin.Select(a => a.User.Id);

                    var reporterNameLink = msg.GetFromNameLink();
                    var reportedNameLink = repMsg.GetFromNameLink();
                    var repMsgLink       = repMsg.GetMessageLink();

                    sendText = $"Ada laporan nich." +
                               $"\n{reporterNameLink} melaporkan {reportedNameLink}" +
                               $"{mentionAdmins}";

                    var keyboard = new InlineKeyboardMarkup(new[]
                    {
                        new[]
                        {
                            InlineKeyboardButton.WithCallbackData("Hapus", "PONG"),
                            InlineKeyboardButton.WithCallbackData("Tendang", "PONG"),
                        },
                        new[]
                        {
                            InlineKeyboardButton.WithCallbackData("Ban", "PONG"),
                            InlineKeyboardButton.WithUrl("Ke Pesan", repMsgLink),
                        }
                    });

                    await _telegramService.SendTextAsync(sendText)
                    .ConfigureAwait(false);

                    return;
                }

                sendText = "Melaporkan diri sendiri? 🤔";
            }


            await _telegramService.SendTextAsync(sendText)
            .ConfigureAwait(false);
        }
Example #26
0
        /// <summary>
        /// Действие при нажатии на кнопку, типа UpdateType.CallbackQuery
        /// </summary>
        /// <param name="callbackQuery"></param>
        /// <returns></returns>
        async Task CallbackUpdate(CallbackQuery callbackQuery)
        {
            if (callbackQuery == null)
            {
                return;
            }

            //формирование инлайн клавиатуры
            if (callbackQuery.Data == "0")
            {
                var row = _repository.BotButtons.Where(x => x.ParentId == 0).OrderBy(x => x.Row).ThenBy(x => x.Column).GroupBy(x => x.Row).ToList();

                var inlineKeyboard = new List <List <InlineKeyboardButton> >();
                foreach (var item in row)
                {
                    var listRowButtons = new List <InlineKeyboardButton>();
                    foreach (var i in item)
                    {
                        listRowButtons.Add(InlineKeyboardButton.WithCallbackData($"{i.ButtonName}", i.Id.ToString()));
                    }
                    inlineKeyboard.Add(listRowButtons);
                }

                var inlineKeyboardMarkup = new InlineKeyboardMarkup(inlineKeyboard);
                await _botService.Client.EditMessageTextAsync(
                    callbackQuery.Message.Chat.Id,
                    callbackQuery.Message.MessageId,
                    "Основное меню",
                    replyMarkup : inlineKeyboardMarkup);
            }
            else
            {
                int id = 0;
                Int32.TryParse(callbackQuery.Data, out id);

                var row = _repository.BotButtons.Where(x => x.ParentId == id).OrderBy(x => x.Row).ThenBy(x => x.Column).GroupBy(x => x.Row).ToList();

                var inlineKeyboard = new List <List <InlineKeyboardButton> >();
                foreach (var item in row)
                {
                    var listRowButtons = new List <InlineKeyboardButton>();
                    foreach (var i in item)
                    {
                        listRowButtons.Add(InlineKeyboardButton.WithCallbackData($"{i.ButtonName}", i.Id.ToString()));
                    }
                    inlineKeyboard.Add(listRowButtons);
                }

                var parentId = _repository.BotButtons.Where(x => x.Id == id).First().ParentId;

                BotButton backButton = new BotButton();

                //Проверка для возврата в основное меню
                if (parentId != 0)
                {
                    backButton = _repository.BotButtons.Where(x => x.Id == parentId).First();
                }
                else
                {
                    backButton = new BotButton {
                        Id = 0, ParentId = 0, ButtonName = "Оснвоное меню"
                    };
                }

                inlineKeyboard.Add(new List <InlineKeyboardButton>()
                {
                    InlineKeyboardButton.WithCallbackData($"<< Назад в {backButton.ButtonName}", backButton.Id.ToString())
                });

                var inlineKeyboardMarkup = new InlineKeyboardMarkup(inlineKeyboard);
                await _botService.Client.EditMessageTextAsync(
                    callbackQuery.Message.Chat.Id,
                    callbackQuery.Message.MessageId,
                    _repository.BotButtons.Where(x => x.Id == id).First().ButtonName,
                    replyMarkup : inlineKeyboardMarkup);
            }
        }
Example #27
0
        private static async void OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message.Type == Telegram.Bot.Types.Enums.MessageType.Text && e.Message.Date.AddMinutes(1) > DateTime.UtcNow)
            {
                string messageText      = e.Message.Text;
                string lowerMessageText = messageText.ToLower();
                long   chatId           = e.Message.Chat.Id;

                // LearnedPhrases
                if (lowerMessageText.Contains("/remove") && lowerMessageText.Length > 8)
                {
                    int    position    = e.Message.Text.IndexOf("/remove") + 8;
                    string keyToRemove = lowerMessageText.Substring(position);
                    if (LearnedPhrases.ContainsKey(keyToRemove))
                    {
                        var valuesList = LearnedPhrases[keyToRemove];
                        if (valuesList.Count == 1)
                        {
                            LearnedPhrases.Remove(keyToRemove);
                            await Bot.SendTextMessageAsync(chatId, "Borrado!");
                        }
                        else
                        {
                            InlineKeyboardButton[][] buttons = new InlineKeyboardButton[valuesList.Count][];
                            for (int i = 0; i < valuesList.Count; i++)
                            {
                                var value = valuesList[i];
                                buttons[i] = new InlineKeyboardButton[] {
                                    InlineKeyboardButton.WithCallbackData(
                                        value,
                                        string.Format("{0};#!{1}", keyToRemove, value.Substring(0, value.Length < 20 ? value.Length : 20))
                                        )
                                };
                            }
                            var keyboardMarkup = new InlineKeyboardMarkup(buttons);

                            await Bot.SendTextMessageAsync(chatId, "Cual quieres eliminar?", replyMarkup : keyboardMarkup);
                        }
                    }
                    else
                    {
                        await Bot.SendTextMessageAsync(chatId, "No he encontrado esa frase para borrar");
                    }
                }
                else if (lowerMessageText.ContainsAll(new List <string>()
                {
                    "amigo", "aprende a contestar"
                }))
                {
                    int           position   = e.Message.Text.IndexOf("aprende a contestar") + 20;
                    List <string> nuevaFrase = new List <string>();
                    bool          learned    = false;

                    foreach (Match match in Regex.Matches(messageText, "\"([^\"]*)\""))
                    {
                        nuevaFrase.Add(match.ToString());
                    }

                    if (nuevaFrase.Count == 2)
                    {
                        string key   = nuevaFrase.Last().ToLower().Replace("\"", string.Empty).Trim();
                        string value = nuevaFrase.First().Replace("\"", string.Empty).Trim();

                        if (!string.IsNullOrEmpty(key) &&
                            !string.IsNullOrEmpty(value) &&
                            key.Length >= 3)
                        {
                            if (LearnedPhrases.ContainsKey(key))
                            {
                                if (LearnedPhrases[key].Contains(value))
                                {
                                    await Bot.SendTextMessageAsync(chatId, "Esta ya me la sabía!");
                                }
                                else
                                {
                                    LearnedPhrases[key].Add(value);
                                }
                            }
                            else
                            {
                                LearnedPhrases.Add(key, new List <string>()
                                {
                                    value
                                });
                            }
                            await Bot.SendTextMessageAsync(chatId, "Aprendido!");

                            System.IO.File.WriteAllText(LearnedPhrasesPath, JsonConvert.SerializeObject(LearnedPhrases));

                            learned = true;
                        }
                    }

                    if (!learned)
                    {
                        await Bot.SendTextMessageAsync(chatId, "Eso no lo he podido aprender...");
                    }
                }
                else if (lowerMessageText.ContainsAll(new List <string>()
                {
                    "amigo", "di:"
                }))
                {
                    int position = e.Message.Text.IndexOf("di:") + 3;
                    await Bot.SendTextMessageAsync(chatId, e.Message.Text.Substring(position));
                }
                else if (lowerMessageText.ContainsAny(LearnedPhrases.Keys))
                {
                    foreach (var key in lowerMessageText.GetAllContainingKeysIn(LearnedPhrases.Keys.ToList()))
                    {
                        var valuesList     = LearnedPhrases[key];
                        int randomPosition = random.Next(valuesList.Count);

                        await Bot.SendTextMessageAsync(chatId, valuesList[randomPosition]);
                    }
                }

                // SPAM
                if (lowerMessageText.Contains("/start") &&
                    (e.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Group ||
                     e.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Supergroup))
                {
                    await Bot.SendTextMessageAsync(chatId, "Quereis empezar una partida? Eso merece un buen patataspam!!");
                    await SpamAdmins(chatId);
                }
                else if (lowerMessageText.Contains("patataspa") &&
                         (e.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Group ||
                          e.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Supergroup))
                {
                    await SpamAdmins(chatId);
                }
            }
        }
Example #28
0
 IMenuAnimationReplyMarkup IReplyMarkupable <IMenuAnimationReplyMarkup> .ReplyMarkup(InlineKeyboardMarkup markup)
 {
     ReplyMarkup = markup; return(this);
 }
Example #29
0
        public override async Task Execute(Message message, TelegramBotClient botClient, Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
            settings = configuration.GetSection("Settings").Get <Settings>();

            var chatId = message.Chat.Id;
            var list   = await GetLastQuery(chatId.ToString());

            var count = 0;

            using (var db = new DbNorthwind())
            {
                count = await db.ViewsTurns
                        .Where(w => w.ChatId == chatId)
                        .CountAsync();
            }


            var countShow = settings.CountMessage;

            if (count >= countShow)
            {
                countShow = settings.CountMessage;
            }
            else
            {
                countShow = count;
            }


            if (!list.Any())
            {
                await botClient.SendTextMessageAsync(chatId, "Все результаты были показаны");
            }
            else
            {
                ReplyKeyboardMarkup keyboard4 = new[]
                {
                    new [] { "Помощь" },
                    new[] { "Поиск по категориям" }
                };
                keyboard4.ResizeKeyboard = true;


                bool isStop = false;


                var viewList = new List <UserViews>();
                foreach (var lis in list)
                {
                    viewList.Add(new UserViews
                    {
                        ChatId = (int)chatId, GroupId = lis.GroupId.ToString(), PhotoId = lis.PhotoId.ToString()
                    });
                }

                using (var db = new DbNorthwind())
                {
                    db.BulkCopy(viewList);
                }

                foreach (var lis in list)
                {
                    if (lis.Text.Length > 430)
                    {
                        lis.Text = lis.Text.Substring(0, 430);
                    }

                    lis.Text += Environment.NewLine + Environment.NewLine + $"📅 Дата публикации: {lis.StartTime:dd'/'MM'/'yyyy HH:mm:ss}";

                    await using var db = new DbNorthwind();
                    var kidal = await db.Kidals.FirstOrDefaultAsync(f => f.VkId == lis.UserId);

                    await SendPhoto(lis.Text, $"https://vk.com/photo{lis.GroupId}_{lis.PhotoId}", lis.Src, lis.UserId, (int)chatId, botClient, kidal);


                    if (list.Last() == lis)
                    {
                        ReplyKeyboardMarkup ReplyKeyboard = new[]
                        {
                            new[] { $"Показать результат ещё {countShow} (Осталось {count})", "Поиск по категориям" },
                            new [] { "Помощь", "Вкл.авто уведомление" },
                        };
                        ReplyKeyboard.ResizeKeyboard = true;

                        if (count != 0)
                        {
                            var listMarkup = new InlineKeyboardMarkup(new List <InlineKeyboardButton>()
                            {
                                InlineKeyboardButton.WithCallbackData("Показать результат", "Показать результат")
                            });
                            await botClient.SendTextMessageAsync(chatId, $"Нажмите на кнопку в меню, чтобы показать ещё {countShow}",
                                                                 replyMarkup : ReplyKeyboard);
                        }


                        else
                        {
                            ReplyKeyboard = new[]
                            {
                                new [] { "Вкл.авто уведомление", "Поиск по категориям" },
                                new[] { "Помощь" }
                            };
                            ReplyKeyboard.ResizeKeyboard = true;
                            await botClient.SendTextMessageAsync(chatId, "Все результаты были показаны, сделайте повторный запрос или включите уведомления по этому.",
                                                                 replyMarkup : ReplyKeyboard);
                        }
                    }
                    Thread.Sleep(settings.Delay);
                }
            }
        }
        public override async Task Execute(Update update, BotClient botClient)
        {
            var keyboardSuccess = new InlineKeyboardMarkup(new[]
            {
                new[]
                {
                    new InlineKeyboardButton
                    {
                        Text         = "Да",
                        CallbackData = "yes"
                    },
                    new InlineKeyboardButton
                    {
                        Text         = "Отмена",
                        CallbackData = "/back"
                    }
                }
            });
            var keyboardFail = new InlineKeyboardMarkup(new[]
            {
                new[]
                {
                    new InlineKeyboardButton
                    {
                        Text         = "Да",
                        CallbackData = "/back"
                    },
                    new InlineKeyboardButton
                    {
                        Text         = "Отмена",
                        CallbackData = "/back"
                    }
                }
            });
            var booking = botClient.Bookings[update.CallbackQuery.From.Id];

            await using var context = new DataContext(botClient.Configuration.GetConnectionString("Db"));
            var hotelRooms         = context.HotelRooms.ToList();
            var hotelRoomsFiltered = hotelRooms
                                     .Where(hotelRoom =>
                                            hotelRoom.Price >= booking.PriceFilter.Item1 &&
                                            hotelRoom.Price <= booking.PriceFilter.Item2 &&
                                            hotelRoom.RoomType == booking.RoomType)
                                     .Select(x => x.HotelId)
                                     .ToList();

            var hotelCollection = context.Hotels.Include(i => i.City).ToList();
            var hotels          = hotelCollection.Where(x => x.City.Name == booking.CityName && x.Stars == booking.HotelStarsType).ToList();

            Hotel hotel = null;

            foreach (var item in hotels)
            {
                if (hotelRoomsFiltered.Contains(item.Id))
                {
                    hotel = item;
                    break;
                }
            }

            if (hotel == null)
            {
                await _telegramBotClient.SendTextMessageAsync(update.CallbackQuery.From.Id, "Отель по вашим параметрам не найден! Попробовать снова?", replyMarkup : keyboardFail);
            }
            else
            {
                var hotelString = $"Отель: {hotel.Name}\n" +
                                  $"Адрес: {hotel.City.Name}, {hotel.Address}";
                await _telegramBotClient.SendTextMessageAsync(update.CallbackQuery.From.Id, $"Подтверждаете бронирование отеля?\n{hotelString}", replyMarkup : keyboardSuccess);
            }
        }
Example #31
0
        public async void HandleUpdate(Update update, ITelegramBotClient client)
        {
            string answer;

            //\U0000270A - Камень
            //\U0000270B - Бумага
            //\U0000270C - Ножницы
            string[] presentations = new string[] { "\U0000270A", "\U0000270B", "\U0000270C" };
            var      keyboard      = new InlineKeyboardMarkup(new InlineKeyboardButton[][]
            {
                new InlineKeyboardButton[]
                {
                    new InlineKeyboardCallbackButton(presentations[0], presentations[0]),
                    new InlineKeyboardCallbackButton(presentations[1], presentations[1]),
                    new InlineKeyboardCallbackButton(presentations[2], presentations[2])
                }
            });

            //if someone just wants to start a game
            if (update.Type == UpdateType.MessageUpdate &&
                Utils.PrettifyCommand(update.Message.Text) == "/rockpaperscissors")
            {
                answer = "Камень, ножницы, бумага:";
                Game game = new Game
                {
                    gameMessage = await client.SendTextMessageAsync(update.Message.Chat.Id, answer, replyToMessageId : update.Message.MessageId, replyMarkup : keyboard)
                };
                _logger?.LogUpdate(update, game.gameMessage);
                //adding new game to list of current games
                currentGames.Add(game);
                return;
            }

            //if someone presses the button
            if (update.Type == UpdateType.CallbackQueryUpdate)
            {
                //check if this game exist
                if (currentGames.FindAll(
                        g =>
                        (g.gameMessage.Chat.Id == update.CallbackQuery.Message.Chat.Id &&
                         g.gameMessage.MessageId == update.CallbackQuery.Message.MessageId))
                    .Count != 1)
                {
                    //if it doesn't, GTFO
                    var popup = await client.AnswerCallbackQueryAsync(update.CallbackQuery.Id, "Низзя!");

                    _logger?.LogUpdate(update, answerQuery: "Низзя!");
                    return;
                }

                //if yes then obtaining its index
                int gameIndex = currentGames.FindIndex(g =>
                                                       (g.gameMessage.Chat.Id == update.CallbackQuery.Message.Chat.Id &&
                                                        g.gameMessage.MessageId == update.CallbackQuery.Message.MessageId));

                Game game = currentGames[gameIndex];

                //if there's no one playing yet, then someone who pressed is the first player
                if (game.player1 == null)
                {
                    game.player1       = update.CallbackQuery.From;
                    game.player1Answer = Array.IndexOf(presentations, update.CallbackQuery.Data);

                    //edit game message
                    answer = "Камень, ножницы, бумага:\r\n" +
                             $"{game.player1.FirstName} {game.player1.LastName}\r\n" +
                             $"vs\r\n" +
                             $"Пока никого... Сыграй!";
                    var edit = await client.EditMessageTextAsync(game.gameMessage.Chat, game.gameMessage.MessageId, answer, replyMarkup : keyboard);

                    _logger?.LogUpdate(update, edit);
                }

                //else he is the second player
                else if (game.player2 == null)
                {
                    //if player1 and player2 are same user
                    if (game.player1.Id == update.CallbackQuery.From.Id)
                    {
                        var popup = await client.AnswerCallbackQueryAsync(update.CallbackQuery.Id, "Низзя!");

                        _logger?.LogUpdate(update, answerQuery: "Низзя!");
                        return;
                    }

                    game.player2       = update.CallbackQuery.From;
                    game.player2Answer = Array.IndexOf(presentations, update.CallbackQuery.Data);

                    //determining R-P-S outcome
                    string outcome;
                    if (game.player1Answer == game.player2Answer)
                    {
                        outcome = "Ганьба, это ничья.";
                    }
                    else if ((game.player1Answer == game.player2Answer + 1) || (game.player1Answer == 0 && game.player2Answer == 2))
                    {
                        outcome = $"{game.player1.FirstName} {game.player1.LastName}, це перемога!";
                    }
                    else
                    {
                        outcome = $"{game.player2.FirstName} {game.player2.LastName}, це перемога!";
                    }

                    //editing game message with results
                    answer = $"{game.player1.FirstName} {game.player1.LastName}: {presentations[game.player1Answer]}\r\n" +
                             $"vs\r\n" +
                             $"{game.player2.FirstName} {game.player2.LastName}: {presentations[game.player2Answer]}\r\n" +
                             $"Результат: {outcome}";

                    var edit = await client.EditMessageTextAsync(game.gameMessage.Chat, game.gameMessage.MessageId, answer);

                    _logger?.LogUpdate(update, edit);

                    //removing game from list of current games
                    currentGames.RemoveAt(gameIndex);
                }
            }
        }
Example #32
0
        public static void GetStats(Update update, string[] args)
        {
            //var reply = $"[Global Stats](werewolf.parawuff.com/Stats)\n";
            //if (update.Message.Chat.Type != ChatType.Private)
            //    reply += $"[Group Stats](werewolf.parawuff.com/Stats/Group/{update.Message.Chat.Id}) ({update.Message.Chat.Title})\n";
            //reply += $"[Player Stats](werewolf.parawuff.com/Stats/Player/{update.Message.From.Id}) ({update.Message.From.FirstName})";

            //change this to buttons
            var buttons = new List<InlineKeyboardButton[]>
            {
                new[] {new InlineKeyboardButton {Text = "Global Stats", Url = "http://werewolf.parawuff.com/Stats"}}
            };
            if (update.Message.Chat.Type != ChatType.Private)
                buttons.Add(new[] { new InlineKeyboardButton { Text = $"{update.Message.Chat.Title} Stats", Url = "http://werewolf.parawuff.com/Stats/Group/" + update.Message.Chat.Id } });
            buttons.Add(new[] { new InlineKeyboardButton { Text = $"{update.Message.From.FirstName} Stats", Url = "http://werewolf.parawuff.com/Stats/Player/" + update.Message.From.Id } });
            var menu = new InlineKeyboardMarkup(buttons.ToArray());
            Bot.Api.SendTextMessage(update.Message.Chat.Id, "Stats", replyMarkup: menu);
        }
Example #33
0
 public async Task SendTextMessageAsync(long chatId, string text, int replyToMessageId = 0, KeyboardMarkup keyboard = null)
 {
     InlineKeyboardMarkup keyboardMarkup = GetInlineKeyboardMarkup(keyboard);
     await Client.SendTextMessageAsync(chatId, text, replyToMessageId : replyToMessageId, replyMarkup : keyboardMarkup);
 }
Example #34
0
 public async Task EditTextMessageAsync(long chatId, int messageId, string messageText, KeyboardMarkup keyboard = null)
 {
     InlineKeyboardMarkup keyboardMarkup = GetInlineKeyboardMarkup(keyboard);
     await Client.EditMessageTextAsync(chatId, messageId, messageText, replyMarkup : keyboardMarkup);
 }
Example #35
0
        private static void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            //file jonatishni boshlang'ichi
            //var stream = new FileStream(@"C:\Users\User\Desktop\1.jpg", FileMode.Open);  // faylni yuklab olindi
            //var fileToSend = new FileToSend("asdasdas", stream); //filetosendga fileni tiqildi

            var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[]// bu yerda location qabul qilish ishlatilvotdi
            {
                new KeyboardButton("Location")
                {
                    RequestLocation = true
                }                                                                     //keyboard bilan locationi qabul qilinvotdi
            });
            // key board yasash
            var rkm = new ReplyKeyboardMarkup();

            rkm.Keyboard =
                new KeyboardButton[][]
            {
                new KeyboardButton[]
                {
                    new KeyboardButton("item"),
                    new KeyboardButton("item")
                },
                new KeyboardButton[]
                {
                    new KeyboardButton("item")
                }
            };
            var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[]// bu yerda location qabul qilish ishlatilvotdi
            {
                new KeyboardButton("Location")
                {
                    RequestLocation = true
                }                                                                     //keyboard bilan locationi qabul qilinvotdi
            });

            RequestReplyKeyboard.ResizeKeyboard = true;    // keyboart buttoni razmerini kichkina qiladi
            Bot.SendTextMessageAsync(e.Message.Chat.Id, "Text", ParseMode.Default, false, false, 0, rkm);
            //inline yasash
            var inlineKeyboard = new InlineKeyboardMarkup(new[] { new[] { InlineKeyboardButton.WithCallbackData("asdas") },
                                                                  new[] { InlineKeyboardButton.WithCallbackData("asdasdd") },
                                                                  new[] { InlineKeyboardButton.WithCallbackData("asdasd") } });

            Bot.SendTextMessageAsync(e.Message.Chat.Id, "-->", replyMarkup: inlineKeyboard);


            //var result = Bot.SendTextMessageAsync(e.Message.Chat.Id, "Who or Where are you?", replyMarkup: RequestReplyKeyboard);
            //Console.WriteLine(e.Message.Location.Longitude+ " :Longitude   " + e.Message.Location.Latitude+ " :Latitude"); //locationni langetud va latetudesini consolga yozilvotdi

            //Bot.SendPhotoAsync(e.Message.Chat.Id, fileToSend);// file jonatildi
            //Console.WriteLine(e.Message.Date);
            if (e.Message.Location != null)
            {
                Bot.SendLocationAsync(e.Message.Chat.Id, e.Message.Location.Latitude, e.Message.Location.Longitude);
            }
            if (e.Message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
            {
                //Bot.SendPhotoAsync(e.Message.Chat.Id, fileToSend);
                Console.WriteLine(e.Message.Chat.Id + "    " + e.Message.Text);
            }
        }
Example #36
0
        public static void ValidateLangs(Update update, string[] args)
        {
            var langs = Directory.GetFiles(Bot.LanguageDirectory)
                                                        .Select(x => XDocument.Load(x)
                                                                    .Descendants("language")
                                                                    .First()
                                                                    .Attribute("name")
                                                                    .Value
                                                        ).ToList();
            langs.Insert(0, "All");

            var buttons =
                langs.Select(x => new[] { new InlineKeyboardButton(x, $"validate|{update.Message.Chat.Id}|{x}") }).ToArray();
            var menu = new InlineKeyboardMarkup(buttons.ToArray());
            Bot.Api.SendTextMessage(update.Message.Chat.Id, "Validate which language?",
                replyToMessageId: update.Message.MessageId, replyMarkup: menu);
        }
Example #37
-1
        internal static void HandleCallback(CallbackQuery query)
        {
            using (var DB = new WWContext())
            {
                try
                {
                    string[] args = query.Data.Split('|');
                    InlineKeyboardMarkup menu;
                    Group grp;
                    List<InlineKeyboardButton> buttons = new List<InlineKeyboardButton>();
                    long groupid = 0;
                    if (args[0] == "vote")
                    {
                        var node = Bot.Nodes.FirstOrDefault(x => x.ClientId.ToString() == args[1]);
                        node?.SendReply(query);
                        return;
                    }

                    groupid = long.Parse(args[1]);
                    grp = DB.Groups.FirstOrDefault(x => x.GroupId == groupid);
                    if (grp == null && args[0] != "getlang" && args[0] != "validate")
                        return;
                    var command = args[0];
                    var choice = "";
                    if (args.Length > 2)
                        choice = args[2];
                    if (choice == "cancel")
                    {
                        Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                            $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                        return;
                    }
                    if (!nonCommandsList.Contains(command.ToLower()))
                        if (!UpdateHelper.IsGroupAdmin(query.From.Id, groupid))
                        {
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                "You do not appear to be an admin");
                            return;
                        }

                    switch (command)
                    {
                        case "validate":
                            //choice = args[1];
                            if (choice == "All")
                            {
                                Helpers.LanguageHelper.ValidateFiles(query.Message.Chat.Id, query.Message.MessageId);
                                return;
                            }
                            //var menu = new ReplyKeyboardHide { HideKeyboard = true, Selective = true };
                            //Bot.SendTextMessage(id, "", replyToMessageId: update.Message.MessageId, replyMarkup: menu);
                            var langOptions =
                                Directory.GetFiles(Bot.LanguageDirectory)
                                    .Select(
                                        x =>
                                            new
                                            {
                                                Name =
                                                    XDocument.Load(x)
                                                        .Descendants("language")
                                                        .First()
                                                        .Attribute("name")
                                                        .Value,
                                                FilePath = x
                                            });
                            var option = langOptions.First(x => x.Name == choice);
                            LanguageHelper.ValidateLanguageFile(query.Message.Chat.Id, option.FilePath, query.Message.MessageId);
                            return;
                        case "getlang":
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId, "One moment...");
                            if (choice == "All")
                                LanguageHelper.SendAllFiles(query.Message.Chat.Id);
                            else
                                LanguageHelper.SendFile(query.Message.Chat.Id, choice);

                            break;
                        case "upload":
                            Console.WriteLine(choice);
                            if (choice == "current")
                            {
                                Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId, "No action taken.");
                                return;
                            }
                            Helpers.LanguageHelper.UseNewLanguageFile(choice, query.Message.Chat.Id, query.Message.MessageId);
                            return;

                        case "vote":
                            //send it back to the game;
                            var node = Bot.Nodes.FirstOrDefault(x => x.ClientId.ToString() == args[1]);
                            node?.SendReply(query);
                            break;
                        case "lang":
                            //load up each file and get the names
                            var langs =
                                Directory.GetFiles(Bot.LanguageDirectory)
                                    .Select(
                                        x =>
                                            new
                                            {
                                                Name =
                                                        XDocument.Load(x)
                                                            .Descendants("language")
                                                            .First()
                                                            .Attribute("name")
                                                            .Value,
                                                Base = XDocument.Load(x)
                                                            .Descendants("language")
                                                            .First()
                                                            .Attribute("base")
                                                            .Value,
                                                Variant = XDocument.Load(x)
                                                            .Descendants("language")
                                                            .First()
                                                            .Attribute("variant")
                                                            .Value,
                                                FileName = Path.GetFileNameWithoutExtension(x)
                                            });

                            buttons.Clear();
                            buttons.AddRange(langs.Select(x => x.Base).Distinct().OrderBy(x => x).Select(x => new InlineKeyboardButton(x, $"setlang|{groupid}|{x}|null|base")));

                            var baseMenu = new List<InlineKeyboardButton[]>();
                            for (var i = 0; i < buttons.Count; i++)
                            {
                                if (buttons.Count - 1 == i)
                                {
                                    baseMenu.Add(new[] { buttons[i] });
                                }
                                else
                                    baseMenu.Add(new[] { buttons[i], buttons[i + 1] });
                                i++;
                            }

                            menu = new InlineKeyboardMarkup(baseMenu.ToArray());

                            var curLang = langs.First(x => x.FileName == grp.Language);
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What Language?\nCurrent: {curLang.Base}",
                                replyMarkup: menu);
                            break;
                        case "setlang":
                            //first, is this the base or variant?
                            var isBase = args[4] == "base";
                            //ok, they picked a language, let's set it.
                            var validlangs =
                                Directory.GetFiles(Bot.LanguageDirectory)
                                        .Select(
                                            x =>
                                                new
                                                {
                                                    Name =
                                                        XDocument.Load(x)
                                                            .Descendants("language")
                                                            .First()
                                                            .Attribute("name")
                                                            .Value,
                                                    Base = XDocument.Load(x)
                                                            .Descendants("language")
                                                            .First()
                                                            .Attribute("base")
                                                            .Value,
                                                    Variant = XDocument.Load(x)
                                                            .Descendants("language")
                                                            .First()
                                                            .Attribute("variant")
                                                            .Value,
                                                    FileName = Path.GetFileNameWithoutExtension(x)
                                                });
                            //ok, if base we need to check for variants....
                            var lang = validlangs.First(x => x.Base == choice);
                            if (isBase)
                            {
                                var variants = validlangs.Where(x => x.Base == choice);
                                if (variants.Count() > 1)
                                {
                                    buttons.Clear();
                                    buttons.AddRange(variants.Select(x => new InlineKeyboardButton(x.Variant, $"setlang|{groupid}|{x.Base}|{x.Variant}|v")));

                                    var twoMenu = new List<InlineKeyboardButton[]>();
                                    for (var i = 0; i < buttons.Count; i++)
                                    {
                                        if (buttons.Count - 1 == i)
                                        {
                                            twoMenu.Add(new[] { buttons[i] });
                                        }
                                        else
                                            twoMenu.Add(new[] { buttons[i], buttons[i + 1] });
                                        i++;
                                    }

                                    menu = new InlineKeyboardMarkup(twoMenu.ToArray());

                                    var curVariant = validlangs.First(x => x.FileName == grp.Language);
                                    Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                        $"What Variant?\nCurrent: {curVariant.Variant}",
                                        replyMarkup: menu);
                                    return;
                                }
                                //only one variant, move along
                            }
                            else
                            {
                                lang = validlangs.First(x => x.Base == choice && x.Variant == args[3]);
                            }

                            if (
                                Directory.GetFiles(Bot.LanguageDirectory)
                                    .Any(
                                        x =>
                                            String.Equals(Path.GetFileNameWithoutExtension(x), lang.FileName,
                                                StringComparison.InvariantCultureIgnoreCase)))
                            {
                                //now get the group

                                grp.Language = lang.FileName;
                                //check for any games running
                                var ig = GetGroupNodeAndGame(groupid);

                                ig?.LoadLanguage(lang.FileName);
                                menu = GetConfigMenu(groupid);
                                Bot.Api.AnswerCallbackQuery(query.Id, $"Language set to {lang.Base}{(String.IsNullOrWhiteSpace(lang.Variant) ? "" : ": " + lang.Variant)}");
                                Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId, $"What would you like to do?", replyMarkup: menu);
                            }
                            DB.SaveChanges();
                            break;
                        case "online":
                            buttons.Add(new InlineKeyboardButton("Yes", $"setonline|{groupid}|show"));
                            buttons.Add(new InlineKeyboardButton("No", $"setonline|{groupid}|hide"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"setonline|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"Do you want your group to be notified when the bot is online?\nCurrent: {grp.DisableNotification != false}",
                                replyMarkup: menu);
                            break;
                        case "setonline":

                            grp.DisableNotification = (choice == "hide");
                            Bot.Api.AnswerCallbackQuery(query.Id,
                                $"Notification will {(grp.DisableNotification == true ? "not " : "")}be shown on startup");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "flee":
                            buttons.Add(new InlineKeyboardButton("Yes", $"setflee|{groupid}|enable"));
                            buttons.Add(new InlineKeyboardButton("No", $"setflee|{groupid}|disable"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"setflee|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"Do you want to allow fleeing once the game has started?\nNote: players can still flee during join phase\nCurrent: Players can {(grp.DisableFlee == false ? "" : "not ")}flee",
                                replyMarkup: menu);
                            break;
                        case "setflee":

                            grp.DisableFlee = (choice == "disable");
                            Bot.Api.AnswerCallbackQuery(query.Id,
                                $"Players will {(grp.DisableFlee == true ? "not " : "")}be allowed to flee after game start");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "maxplayer":
                            buttons.Add(new InlineKeyboardButton("10", $"setmaxplayer|{groupid}|10"));
                            buttons.Add(new InlineKeyboardButton("15", $"setmaxplayer|{groupid}|15"));
                            buttons.Add(new InlineKeyboardButton("20", $"setmaxplayer|{groupid}|20"));
                            buttons.Add(new InlineKeyboardButton("25", $"setmaxplayer|{groupid}|25"));
                            buttons.Add(new InlineKeyboardButton("30", $"setmaxplayer|{groupid}|30"));
                            buttons.Add(new InlineKeyboardButton("35", $"setmaxplayer|{groupid}|35"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"setmaxplayer|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"How many players would like to set as the maximum?\nCurrent: {grp.MaxPlayers ?? Settings.MaxPlayers}",
                                replyMarkup: menu);
                            break;
                        case "setmaxplayer":

                            grp.MaxPlayers = int.Parse(choice);
                            Bot.Api.AnswerCallbackQuery(query.Id, $"Max players set to {choice}");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "roles":
                            buttons.Add(new InlineKeyboardButton("Show", $"setroles|{groupid}|show"));
                            buttons.Add(new InlineKeyboardButton("Hide", $"setroles|{groupid}|hide"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"setroles|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"Show or Hide roles on death?\nCurrent: {(grp.ShowRoles == false ? "Hidden" : "Shown")}",
                                replyMarkup: menu);
                            break;
                        case "setroles":

                            grp.ShowRoles = (choice == "show");
                            Bot.Api.AnswerCallbackQuery(query.Id,
                                $"Roles will be {(grp.ShowRoles == false ? "hidden" : "shown")} on death.");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "mode":
                            buttons.Add(new InlineKeyboardButton("Normal Only", $"setmode|{groupid}|Normal"));
                            buttons.Add(new InlineKeyboardButton("Chaos Only", $"setmode|{groupid}|Chaos"));
                            buttons.Add(new InlineKeyboardButton("Player Choice", $"setmode|{groupid}|Player"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"setmode|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What game mode will the group be?\nCurrent: {grp.Mode}", replyMarkup: menu);
                            break;
                        case "setmode":

                            grp.Mode = choice;
                            Bot.Api.AnswerCallbackQuery(query.Id, $"Game mode set to {choice}");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "endroles":
                            buttons.Add(new InlineKeyboardButton("Don't show any", $"setendroles|{groupid}|None"));
                            buttons.Add(new InlineKeyboardButton("Show only living players",
                                $"setendroles|{groupid}|Living"));
                            buttons.Add(new InlineKeyboardButton("Show all players", $"setendroles|{groupid}|All"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"setendroles|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"How do you want roles to be shown at the end?\nCurrent: {grp.ShowRolesEnd}",
                                replyMarkup: menu);
                            break;
                        case "setendroles":

                            grp.ShowRolesEnd = choice;
                            Bot.Api.AnswerCallbackQuery(query.Id, $"Roles shown at end set to: {choice}");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "day":
                            buttons.Add(new InlineKeyboardButton("30", $"setday|{groupid}|30"));
                            buttons.Add(new InlineKeyboardButton("60", $"setday|{groupid}|60"));
                            buttons.Add(new InlineKeyboardButton("90", $"setday|{groupid}|90"));
                            buttons.Add(new InlineKeyboardButton("120", $"setday|{groupid}|120"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"setday|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"Choose the base time (in seconds) for day time.   This will still be modified based on number of players.\nMinimum time added based on players is 60 seconds.  Default setting: {Settings.TimeDay}\nCurrent: {grp.DayTime ?? Settings.TimeDay}",
                                replyMarkup: menu);
                            break;
                        case "setday":

                            grp.DayTime = int.Parse(choice);
                            Bot.Api.AnswerCallbackQuery(query.Id, $"Base day time set to {choice} seconds");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "night":
                            buttons.Add(new InlineKeyboardButton("30", $"setnight|{groupid}|30"));
                            buttons.Add(new InlineKeyboardButton("60", $"setnight|{groupid}|60"));
                            buttons.Add(new InlineKeyboardButton("90", $"setnight|{groupid}|90"));
                            buttons.Add(new InlineKeyboardButton("120", $"setnight|{groupid}|120"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"setnight|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"Choose the time (in seconds) for night time. Default setting: {Settings.TimeNight}\nCurrent:{grp.NightTime ?? Settings.TimeNight}",
                                replyMarkup: menu);
                            break;
                        case "setnight":

                            grp.NightTime = int.Parse(choice);
                            Bot.Api.AnswerCallbackQuery(query.Id, $"Night time set to {choice} seconds");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "lynch":
                            buttons.Add(new InlineKeyboardButton("30", $"setlynch|{groupid}|30"));
                            buttons.Add(new InlineKeyboardButton("60", $"setlynch|{groupid}|60"));
                            buttons.Add(new InlineKeyboardButton("90", $"setlynch|{groupid}|90"));
                            buttons.Add(new InlineKeyboardButton("120", $"setlynch|{groupid}|120"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"setlynch|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"Choose the time (in seconds) for lynch voting. Default setting: {Settings.TimeLynch}\nCurrent:{grp.LynchTime ?? Settings.TimeLynch}",
                                replyMarkup: menu);
                            break;
                        case "setlynch":

                            grp.LynchTime = int.Parse(choice);
                            Bot.Api.AnswerCallbackQuery(query.Id, $"Lynch voting time set to {choice} seconds");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "fool":
                            buttons.Add(new InlineKeyboardButton("Allow", $"setfool|{groupid}|true"));
                            buttons.Add(new InlineKeyboardButton("Disallow", $"setfool|{groupid}|false"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"setfool|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"Allow fool as a role option?\nCurrent: {grp.AllowFool}", replyMarkup: menu);
                            break;
                        case "setfool":

                            grp.AllowFool = (choice == "true");
                            Bot.Api.AnswerCallbackQuery(query.Id, $"Fool as a role set to: {choice}");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "tanner":
                            buttons.Add(new InlineKeyboardButton("Allow", $"settanner|{groupid}|true"));
                            buttons.Add(new InlineKeyboardButton("Disallow", $"settanner|{groupid}|false"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"settanner|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"Allow tanner as a role option?\nCurrent: {grp.AllowTanner}", replyMarkup: menu);
                            break;
                        case "settanner":

                            grp.AllowTanner = (choice == "true");
                            Bot.Api.AnswerCallbackQuery(query.Id, $"Tanner as a role set to: {choice}");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "cult":
                            buttons.Add(new InlineKeyboardButton("Allow", $"setcult|{groupid}|true"));
                            buttons.Add(new InlineKeyboardButton("Disallow", $"setcult|{groupid}|false"));
                            buttons.Add(new InlineKeyboardButton("Cancel", $"setcult|{groupid}|cancel"));
                            menu = new InlineKeyboardMarkup(buttons.Select(x => new[] { x }).ToArray());
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"Allow cult as a role option?\nCurrent: {grp.AllowCult}", replyMarkup: menu);
                            break;
                        case "setcult":

                            grp.AllowCult = (choice == "true");
                            Bot.Api.AnswerCallbackQuery(query.Id, $"Cult as a role set to: {choice}");
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                $"What would you like to do?", replyMarkup: GetConfigMenu(groupid));
                            DB.SaveChanges();
                            break;
                        case "done":
                            Bot.Api.EditMessageText(query.Message.Chat.Id, query.Message.MessageId,
                                "Thank you, have a good day :)");
                            break;
                    }
                }
                catch (Exception ex)
                {

                }
            }
        }