예제 #1
0
 private void CreateButton(Article article)
 {
     keyboardUrl = new InlineKeyboardMarkup(new InlineKeyboardButton[][]
     {
         new [] { InlineKeyboardButton.WithUrl("To see on original site", article.Url.ToString()), },
     });
 }
예제 #2
0
        //create 3 buttons which redirect to some sites
        public override async void Execute(Message message, TelegramBotClient client)
        {
            var chatId = message.Chat.Id;

            try
            {
                var inlineKeybord = new InlineKeyboardMarkup(new[]
                {
                    new[]
                    {
                        InlineKeyboardButton.WithUrl("Розклад", "http://desk.nuwm.edu.ua/cgi-bin/timetable.cgi")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithUrl("Moodle", "https://exam.nuwm.edu.ua/")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithUrl("Кросс-плат програмування", "https://iktmedia.moodlecloud.com/")
                    }
                });
                string msg = $"{DateTime.Now}: initials - '{message.Chat.FirstName} {message.Chat.LastName} @{message.Chat.Username}', chatId - '{message.Chat.Id}', message - \"{message.Text}\"";
                File.AppendAllText("Message.log", $"{msg}\n");
                await client.SendTextMessageAsync(chatId, "Ресурси по воднику:\n", replyMarkup : inlineKeybord);
            }
            catch (Exception e)
            {
                string errmsg = $"{DateTime.Now}: initials - '{message.Chat.FirstName} {message.Chat.LastName} @{message.Chat.Username}', chatId - '{message.Chat.Id}', message - \"{message.Text}\", error - '{e.Message}' path - '{e.StackTrace}'";
                File.AppendAllText("Error.log", $"{errmsg}\n");
                await client.SendTextMessageAsync(chatId, $"Enter Command properly '{this.Example}'");
            }
        }
예제 #3
0
        /// <summary>
        /// Метод, в котором разработано меню с кнопками, содержащими в себе некоторые ПОЛЕЗНЫЕ ССЫЛКИ
        /// </summary>
        /// <param name="e"></param>
        public static async void ShowHelpfulLinks(Telegram.Bot.Args.MessageEventArgs e, TelegramBotClient Client)
        {
            var message = e.Message;

            var menuKeyboard = new InlineKeyboardMarkup(new[]
            {
                new[]
                {
                    InlineKeyboardButton.WithUrl("Сайт Московского кампуса", "https://www.hse.ru"),
                    InlineKeyboardButton.WithUrl("Сайт Питерского кампуса", "https://spb.hse.ru")
                },
                new[]
                {
                    InlineKeyboardButton.WithUrl("Сайт Нижегородского кампуса", "https://nnov.hse.ru"),
                    InlineKeyboardButton.WithUrl("Сайт Пермского кампуса", "https://perm.hse.ru")
                },
                new[]
                {
                    InlineKeyboardButton.WithUrl("Группа для абитуриентов в VK", "https://vk.com/ba_hse")
                },
                new[]
                {
                    InlineKeyboardButton.WithUrl("Вышка в Facebook", "https://www.facebook.com/hse.ru"),
                    InlineKeyboardButton.WithUrl("Вышка в Instagram", "https://www.instagram.com/hse_ru/"),
                    InlineKeyboardButton.WithUrl("Вышка в VK", "https://vk.com/hse_university")
                }
            });

            await Client.SendTextMessageAsync(message.Chat.Id, "Выберите нужную сcылку:", replyMarkup : menuKeyboard);

            await Client.SendStickerAsync(message.Chat.Id, "CAACAgIAAxkBAAEOx1deblVYpNjC3stEpnKftOyRiZoO3gACVgEAAk-cEwJ5KHBO9mHQYBgE");
        }
예제 #4
0
        public static void Donate(Update u, string[] args)
        {
            //Bot.Api.SendTextMessageAsync(u.Message.Chat.Id,
            //    "Want to help keep Werewolf online? Please donate to:\n" +
            //    "•PayPal: PayPal.me/greywolfdevelopment\n" +
            //    "•Bitcoin: 13QvBKfAattcSxSsW274fbgnKU5ASpnK3A" +
            //    "\n\nDonations help us pay to keep the expensive servers running and the game online. Every donation you make helps to keep us going for another month. For more information please contact @werewolfsupport", ParseMode.Html, true);
            var menu = new Menu();

            if (u.Message.Chat.Type == ChatType.Private)
            {
#if RELEASE
                menu.Buttons.Add(InlineKeyboardButton.WithCallbackData("Telegram", "donatetg"));
                menu.Buttons.Add(InlineKeyboardButton.WithCallbackData("Xsolla", "xsolla"));
#else
                menu.Buttons.Add(InlineKeyboardButton.WithUrl("Telegram", $"https://t.me/werewolfbot?start=donatetg"));
                menu.Buttons.Add(InlineKeyboardButton.WithUrl("Xsolla", $"https://t.me/werewolfbot?start=xsolla"));
#endif
            }
            else
            {
                menu.Buttons.Add(InlineKeyboardButton.WithUrl("Telegram", $"https://t.me/werewolfbot?start=donatetg"));
                menu.Buttons.Add(InlineKeyboardButton.WithUrl("Xsolla", $"https://t.me/werewolfbot?start=xsolla"));
            }
            var markup = menu.CreateMarkupFromMenu();
            var txt    = $"Want to help keep Werewolf Moderator online? Donate now and gets: {"Custom gifs".ToBold()} and {"Badges".ToBold()}!\n\nClick the button below to donate!!\n\nMore Info: https://telegra.ph/Custom-Gif-Packs-and-Donation-Levels-06-27";
            Bot.Api.SendTextMessageAsync(u.Message.Chat.Id, txt, replyMarkup: markup, parseMode: ParseMode.Html, disableWebPagePreview: true);
        }
예제 #5
0
        private static async Task SendWebmAsync(IEnumerable <PostBase> posts)
        {
            foreach (var post in posts)
            {
                PostInfoLog(post);
                if (post.GetFileUrl().Contains(".webm"))
                {
                    var keyboard = new InlineKeyboardMarkup(new[]
                    {
                        InlineKeyboardButton.WithUrl("Post", post.GetPostLink())
                    });

                    try
                    {
                        LogWrite($"{DateTime.UtcNow}:Send WebM {post.GetId()}", ConsoleColor.Yellow);
                        await Bot.SendTextMessageAsync(ChatId, $"💕<a href=\"{post.GetPostLink()}\">WebM Link</a>💕\n{post.GetTags(15)}",
                                                       parseMode : Telegram.Bot.Types.Enums.ParseMode.Html, replyMarkup : keyboard, disableNotification : true);

                        LogWrite($"{DateTime.UtcNow}:WebM sended {post.GetId()}", ConsoleColor.Green);
                    }
                    catch (Exception e)
                    {
                        LogWrite($"(!) {DateTime.UtcNow}: [{e.GetType()}] {e.Source}:::{e.Message} " +
                                 $"(url: {post.GetFileUrl()})\n\t (url: {post.GetSampleUrl()})",
                                 ConsoleColor.Red, 1);
                    }
                }
            }
        }
예제 #6
0
 public override async void Execute(Message message, TelegramBotClient client)
 {
     Console.WriteLine("Executing " + Name + "Command");
     ChatId id = message.Chat.Id;
     InlineKeyboardMarkup markup = new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("Ok", "https://ru.stackoverflow.com/questions/789457/c-%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%BA%D0%B0-%D0%BD%D0%B0%D0%B6%D0%B0%D1%82%D0%B8%D1%8F-inline-%D0%B8-reply-%D0%BA%D0%BD%D0%BE%D0%BF%D0%BE%D0%BA-%D0%B4%D0%BB%D1%8F-%D0%B1%D0%BE%D1%82%D0%B0-telegram"));
     await client.SendTextMessageAsync(id, "Press OK", replyMarkup : markup);
 }
예제 #7
0
        public Profile(TelegramBotClient bot, Message message, User user)
        {
            this.bot    = bot;
            currentUser = user;
            var keyboard = new InlineKeyboardMarkup(new[] {
                new[]
                {
                    InlineKeyboardButton.WithCallbackData("Создать пароль"),
                    InlineKeyboardButton.WithCallbackData("Посмотреть все пароли")
                },
                new[]
                {
                    InlineKeyboardButton.WithCallbackData("Изменить сущ. пароль"),
                    InlineKeyboardButton.WithUrl("Написать автору какой он пусечка", "https://www.instagram.com/_yuro4ka/?hl=ru")
                },
                new[]
                {
                    InlineKeyboardButton.WithCallbackData("Сохранить свой пароль"),
                    InlineKeyboardButton.WithCallbackData("Выйти из профиля")
                }
            });

            bot.StartReceiving();
            bot.OnCallbackQuery += Bot_OnCallbackQuery;
            bot.SendTextMessageAsync(message.Chat.Id, "Что вы хотите сделать ?", replyMarkup: keyboard);
        }
예제 #8
0
파일: Helpers.cs 프로젝트: nonomal/Werewolf
        internal static void RequestPM(long groupid)
        {
            var button = InlineKeyboardButton.WithUrl("Start Me", "telegram.me/" + Bot.Me.Username);

            Send(GetLocaleString("StartMe", GetLanguage(groupid)), groupid,
                 customMenu: new InlineKeyboardMarkup(new[] { button }));
        }
예제 #9
0
    public static async Task SendAboutUsernameAsync(this TelegramService telegramService)
    {
        var urlStart = await telegramService.GetUrlStart("start=set-username");

        var usernameStr = telegramService.IsNoUsername ? "belum" : "sudah";
        var sendText    = "Tentang Username" +
                          $"\nKamu {usernameStr} mengatur Username";

        var inlineKeyboard = new InlineKeyboardMarkup(
            new[]
        {
            new[]
            {
                InlineKeyboardButton.WithUrl("Cara Pasang Username", urlStart)
            },
            new[]
            {
                InlineKeyboardButton.WithCallbackData("Verifikasi Username", "verify username-only")
            }
        }
            );

        await telegramService.SendTextMessageAsync(
            sendText : sendText,
            replyMarkup : inlineKeyboard,
            scheduleDeleteAt : DateTime.UtcNow.AddMinutes(1),
            includeSenderMessage : true,
            preventDuplicateSend : true
            );
    }
 public static InlineKeyboardButton[] EtherscanButtons(string gemId)
 => new[]
 {
     InlineKeyboardButton.WithUrl("🔎 EthScan", $"https://etherscan.io/token/{gemId}"),
     InlineKeyboardButton.WithUrl("📋 Contract", $"https://etherscan.io/address/{gemId}#code"),
     InlineKeyboardButton.WithUrl("🤑 Hodlers", $"https://etherscan.io/token/{gemId}#balances"),
 };
예제 #11
0
        /// <summary>
        /// Show Rise Price
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private async Task cmd_Price(Message message, ApplicationUser appuser)
        {
            try
            {
                await _botService.Client.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

                this.coinQuoteCol = _appdb.CoinQuotes.Where(x => x.TimeStamp >= DateTime.Now.AddDays(-7)).ToList();
                var quote = LastAllQuote();

                var strResponse = "Price (sat): <b>" + Math.Round(quote.Price * 100000000) + " [24h:" + Math.Round(PercentChange(1), 2) + "% 1W: " + Math.Round(PercentChange(7), 2) + "%]</b>" + Environment.NewLine +
                                  "Price (USD): <b>$" + Math.Round(quote.USDPrice, 5) + " (" + USDPricePercentChange(1) + "%)</b>" + Environment.NewLine +
                                  "Volume: <b>" + Math.Round(quote.Volume).ToString("N0") + " (" + VolumePercentChange(1) + "%) </b>" + Environment.NewLine +
                                  "Day Range: <b>" + Math.Round(DaysLow(1) * 100000000) + " - " + Math.Round(DaysHigh(1) * 100000000) + " sat</b>" + Environment.NewLine +
                                  "Bitcoin Price: <b>$" + Math.Round(double.Parse(CoinbaseBtcQuote.Current.amount), 2).ToString("N0") + " </b> (Coinbase)";

                await _botService.Client.SendTextMessageAsync(message.Chat.Id, strResponse, ParseMode.Html);

                var keyboard = new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("dashboard.rise.vision", "https://dashboard.rise.vision"));
                await _botService.Client.SendTextMessageAsync(message.Chat.Id, "click to open website", replyMarkup : keyboard);
            }
            catch (Exception ex)
            {
                var log = new Log();
                log.LogMessage(ex.Message + " " + ex.StackTrace + " " + ex.InnerException);
                _appdb.Logger.Add(log);
                _appdb.SaveChangesAsync().Wait();
            }
        }
예제 #12
0
        public static Tuple <IReplyMarkup, string> ForFreeTelegram(Gem gem)
        {
            var banner =
                Content(gem) +
                $"👨‍👦‍👦 Our community:\n" +
                $"Chat - @GemTrackerCommunity\n" +
                $"Info - @GemTrackerAnnouncements\n\n" +
                $"📣 Ask for premium access and get:\n" +
                $"- info about *price, liquidity, contract, holders, txns, swaps*\n" +
                $"- links to *DEXT, Astro and UniCrypt*\n" +
                $"- insights about valueable gem or shitty scam";

            var buttons = new InlineKeyboardMarkup(new[]
            {
                UniswapButtons(gem),
                SharedMessageContent.EtherscanButtons(gem.Id),
                new []
                {
                    InlineKeyboardButton.WithUrl("⚙️ How to use?", $"https://gemtracker.club/#howtouse"),
                    InlineKeyboardButton.WithUrl("💰 Premium access?", $"https://gemtracker.club/#premium")
                },
                new []
                {
                    InlineKeyboardButton.WithUrl("📧 Author", $"https://twitter.com/tomkowalczyk")
                }
            });

            return(new Tuple <IReplyMarkup, string>(buttons, banner));
        }
예제 #13
0
        internal virtual async Task Send(TelegramManager tgManager)
        {
            InlineKeyboardMarkup markup = null;
            bool?sentState = null;

            if (Ticker != null)
            {
                markup = new InlineKeyboardMarkup(
                    new[]
                {
                    new[]
                    {
                        InlineKeyboardButton.WithUrl($"Открыть {Ticker} в Инвестициях",
                                                     String.Format(TelegramManager.TinkoffInvestStocksUrl, Ticker))
                    }
                });
                var chartUrl = tgManager.GetStockChart(Ticker);
                if (chartUrl != null && AddTickerImage)
                {
                    sentState = await tgManager.ExecuteWithBot(async (bot)
                                                               => await bot.SendPhotoAsync(ChatId, new InputOnlineFile(chartUrl),
                                                                                           Text, ParseMode.Markdown, replyMarkup: markup), this);

                    if (sentState == false)
                    {
                        return;
                    }
                }
            }
            if (sentState == null)
            {
                await tgManager.ExecuteWithBot(async (bot)
                                               => await bot.SendTextMessageAsync(ChatId, Text, replyMarkup: markup, parseMode: ParseMode.Markdown), this);
            }
        }
        public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args, CancellationToken cancellationToken)
        {
            _chatProcessor = new ChatProcessor(context);

            var botName    = Bot.GlobalConfiguration["Engines:ProductName"];
            var botVer     = Bot.GlobalConfiguration["Engines:Version"];
            var botCompany = Bot.GlobalConfiguration["Engines:Company"];

            string sendText = $"🤖 {botName} {botVer}" +
                              $"\nby {botCompany}." +
                              $"\nAdalah bot debugging, manajemen grup yang di lengkapi dengan alat keamanan. " +
                              $"Agar fungsi saya bekerja dengan fitur penuh, jadikan saya admin dengan level standard. " +
                              $"\nSaran dan fitur bisa di ajukan di @WinTenGroup atau @TgBotID.";

            var urlStart = await "help".GetUrlStart();
            var keyboard = new InlineKeyboardMarkup(
                InlineKeyboardButton.WithUrl("Dapatkan bantuan", urlStart)
                );

            if (_chatProcessor.IsPrivateChat())
            {
                keyboard = new InlineKeyboardMarkup(new[]
                {
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Bantuan", "help home"),
                        InlineKeyboardButton.WithUrl("Pasang Username", "https://t.me/WinTenDev/29")
                    }
                });
            }

            await _chatProcessor.SendAsync(sendText, keyboard);
        }
        public async Task Should_set_error_unspecified()
        {
            AuthorizationRequestParameters authReq = _classFixture.AuthorizationRequestParameters;
            Message passportMessage = _classFixture.Message;

            PassportElementError[] errors =
            {
                new PassportElementErrorUnspecified(
                    PassportEnums.Scope.BankStatement,
                    passportMessage.PassportData.Data.Single().Hash,
                    "Address is NOT mentioned in this document"
                    ),
            };

            await BotClient.SetPassportDataErrorsAsync(
                passportMessage.From.Id,
                errors
                );

            await BotClient.SendTextMessageAsync(
                _fixture.SupergroupChat,
                "An error is set on the bank statement.\n" +
                "You can see error message with opening the request link again.",
                replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton.WithUrl(
                    "Passport Authorization Request",
                    $"https://telegrambots.github.io/Telegram.Bot.Extensions.Passport/redirect.html?{authReq.Query}"
                    )
                );
        }
예제 #16
0
        //Get Schedule For Day
        public void GetScheduleForDay(CallbackQueryEventArgs callbackQueryEventArgs)
        {
            var args = ArgParser.ParseCallbackData(callbackQueryEventArgs.CallbackQuery.Data);

            var directionArg = args.GetValueOrDefault(Commands.Direction);
            var direction    = directionArg == Way.ToCTIR.ToString() ? Way.ToCTIR : Way.ToRzeszow;

            DateTime selectedDay = DateTime.Parse(args.GetValueOrDefault(Commands.Date));

            //Get schedule for date
            var text = ScheduleHelper.GenerateSchedule(selectedDay, direction, User.GetLanguage);

            //Send menu to get back
            var inlineKeyboard = new InlineKeyboardMarkup(new[]
            {
                new [] // First row
                {
                    // Bus stations button
                    InlineKeyboardButton.WithCallbackData(Local.BusStations[User.GetLanguage], Commands.GetBusStation),
                },
                new [] // Second row
                {
                    // Weather button
                    InlineKeyboardButton.WithCallbackData(Local.Weather[User.GetLanguage], $"{Commands.RefreshWeather}"),
                    // Bus schedule url
                    InlineKeyboardButton.WithUrl(Local.URLSchedule[User.GetLanguage], "https://wsiz.edu.pl/studia/informator/rozklad-jazdy-uczelnianego-autobusu"),
                },
                // Third row
                TemplateModelsBuilder.WaysForBus()
            });

            SendMessageAsync(ChatId, text, ParseMode.Markdown, replyMarkup: inlineKeyboard);
            DeleteMessageAsync(ChatId, MessageId);
        }
        static async Task SendAuthorizationRequestAsync(int userId)
        {
            PassportScope scope = new PassportScope(new[]
            {
                new PassportScopeElementOne(PassportEnums.Scope.Address),
                new PassportScopeElementOne(PassportEnums.Scope.PhoneNumber),
            });
            AuthorizationRequestParameters authReq = new AuthorizationRequestParameters(
                botId: _botClient.BotId,
                publicKey: PublicKey,
                nonce: "Test nonce for this demo",
                scope: scope
                );

            await _botClient.SendTextMessageAsync(
                userId,
                "Share your *residential address* and *phone number* with bot using Telegram Passport.\n\n" +
                "1. Click inline button\n" +
                "2. Open link in browser so it redirects you to Telegram Passport\n" +
                "3. Authorize bot to access the info",
                ParseMode.Markdown,
                replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton.WithUrl(
                    "Share via Passport",
                    $"https://telegrambots.github.io/Telegram.Bot.Extensions.Passport/redirect.html?{authReq.Query}"
                    )
                );
        }
예제 #18
0
        //private readonly static Td.ClientResultHandler _defaultHandler = new DefaultHandler();
        //private static Td.Client _client = null;

        //private static string[] groups = { "@Puneites", "@Free_Zerodha_Angel_Upstox_Acct", "@AngelBroking_SMC_Upstox_Zerodha" };
        //List<string> groupIds = new List<string>(groups);
        //private long m_ReportGroupChatId = -278455237;  // Exception Reporter
        //private TelegramBotClient m_TelegramBotClient = new TelegramBotClient("replace_your_bot_token");
        //private ReplyKeyboardMarkup m_ReplyMarkupKeyboard = new ReplyKeyboardMarkup();
        //private InlineKeyboardMarkup m_GameKeyboardMarkup = new InlineKeyboardMarkup();
        //private InlineKeyboardMarkup m_AboutKeyboardMarkup = new InlineKeyboardMarkup();

        //private TelegramBotClient m_TelegramBotClient = new TelegramBotClient(botToken);

        //private ReplyKeyboardMarkup m_ReplyMarkupKeyboard = new ReplyKeyboardMarkup();

        //private InlineKeyboardMarkup m_GameKeyboardMarkup = new InlineKeyboardMarkup();
        //private InlineKeyboardMarkup m_AboutKeyboardMarkup = new InlineKeyboardMarkup();



        public static void SendTelegramMessagewithButtons(string message, string[] rowValues)
        {
            var keyboard = new InlineKeyboardMarkup(new[]
            {
                new[]
                {
                    InlineKeyboardButton.WithCallbackData("👍", "CallBackData"),
                    InlineKeyboardButton.WithCallbackData("👎🏿", "CallBackData")
                },
                new[]
                {
                    InlineKeyboardButton.WithUrl("Upstox", "https://upstox.com/upstox-pro-web/"),
                    InlineKeyboardButton.WithUrl("Zerodha", "https://drive.google.com/open?id=1ImGuf95HhZeksaNSDmBQSzq_8jHTJepo")
                }
            });

            TelegramBotClient m_TelegramBotClient = new TelegramBotClient(botToken);

            if (isInternetConnected())
            {
                foreach (var groupId in rowValues)
                {
                    m_TelegramBotClient.SendTextMessageAsync(groupId.Trim(), message, replyMarkup: keyboard);
                }
            }
        }
예제 #19
0
파일: TelegramBot.cs 프로젝트: str1py/Ducky
        public async void StreamStatusChangedAlert(object sender, MessageEventArgs messageargs, string streamer, string status, string link)
        {
            try
            {
                if (Bot != null)
                {
                    await Bot.SendChatActionAsync(Properties.Socials.Default.TelegramUserID.ToString(), ChatAction.Typing);

                    var keyboard = new InlineKeyboardMarkup(new[]
                    {
                        new[] // first row
                        {
                            InlineKeyboardButton.WithUrl("Начать просмотр на устройстве", link)
                        },
                        new [] // second row
                        {
                            InlineKeyboardButton.WithCallbackData("Начат просмотр на компьютере", link)
                        }
                    });
                    await Bot.SendTextMessageAsync(Properties.Socials.Default.TelegramUserID.ToString(), $"{streamer} {status}. {link}",
                                                   replyMarkup : keyboard);
                }
            }catch (Exception e)
            {
                log.AddLog("ERROR:", e.Message);
            }
        }
예제 #20
0
        public TelegramTextMessageWithKeyboard AddCallbackWebButton(string text, string url, bool toBottom = false)
        {
            InlineKeyboardButton keyboardButton = InlineKeyboardButton.WithUrl(text, url);

            AddButton(keyboardButton, toBottom);
            return(this);
        }
예제 #21
0
    public static IEnumerable <IEnumerable <InlineKeyboardButton> > ToInlineKeyboardButton(
        this IEnumerable <IEnumerable <Button> > lisButtonMap,
        bool validateButton = false
        )
    {
        var inlineKeyboardMarkup =
            lisButtonMap
            .Select(
                buttonRow => buttonRow
                .Select(
                    buttonCol => {
            var url = buttonCol.Url;
            if (!validateButton)
            {
                return(InlineKeyboardButton.WithUrl(buttonCol.Text, buttonCol.Url));
            }

            if (url.IsExistUrl().WaitAndUnwrapException())
            {
                return(InlineKeyboardButton.WithUrl(buttonCol.Text, buttonCol.Url));
            }

            return(InlineKeyboardButton.WithCallbackData(buttonCol.Text, $"invalid-url {url}"));
        }
                    )
                );

        return(inlineKeyboardMarkup);
    }
            private async Task HandleTopLevelCommand(Message message, IMediator mediator)
            {
                switch (message.Text)
                {
                case SpendingStatistic:
                    var(text, markup) = await mediator.Send(new PrepareWeekSpendingMessage.Command(message.Date.Date.AddDays(-6), message.Chat.Id, AverageSpending.CategoryMode.Compact));

                    await mediator.Send(new SendMessage.Command(message.Chat.Id, text, message.MessageId, ParseMode.MarkdownV2, markup));

                    break;

                case AllPurchasesGraph:
                    var targetUrl = new UriBuilder(options.Value.SiteBaseAddres)
                    {
                        Path = $"purchases/{message.Chat.Id}"
                    }.Uri.ToString();
                    var inlineMarkup = new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("Посмотреть граф", targetUrl));
                    await mediator.Send(new SendMessage.Command(message.Chat.Id, "Перейдите по ссылке для просмотра графа", message.MessageId, ParseMode.MarkdownV2, inlineMarkup));

                    break;

                default:
                    logger.LogError($"Command {message.Text} is not supported");
                    break;
                }
            }
예제 #23
0
 public async Task Should_Send_Invoice_With_Reply_Markup()
 {
     await BotClient.SendInvoiceAsync(
         chatId : (int)_classFixture.PrivateChat.Id,
         title : "Product",
         description : "product description",
         payload : "test payload",
         providerToken : _classFixture.PaymentProviderToken,
         startParameter : "start_parameter",
         currency : "USD",
         prices : new[] { new LabeledPrice("price", 150), },
         replyMarkup : new InlineKeyboardMarkup(new[]
     {
         new[]
         {
             InlineKeyboardButton.WithPayment("Pay this invoice"),
             InlineKeyboardButton.WithUrl("Repository", "https://github.com/TelegramBots/Telegram.Bot")
         },
         new[]
         {
             InlineKeyboardButton.WithCallbackData("Some other button")
         }
     })
         );
 }
예제 #24
0
        private static async void BotOnMessage(object sender, MessageEventArgs e)
        {
            var text = e?.Message?.Text;

            if (text == null || text == "/start")
            {
                return;
            }
            if (text == "/hello")
            {
                Message message = await botClient.SendTextMessageAsync(chatId : e.Message.Chat,
                                                                       text : "Приветики из ASP.NET!");
            }
            else
            {
                Message message = await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Использованы все параметры сообщений",
                    parseMode : ParseMode.Markdown,
                    disableNotification : true,
                    replyToMessageId : e.Message.MessageId,
                    replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl(
                                                               "Работаем..",
                                                               "https://github.com/jiggaaut/"
                                                               ))
                    );
            }

            Console.WriteLine($"Text: {text} in chat {e.Message.Chat.Id}");

            //await botClient.SendTextMessageAsync(chatId: e.Message.Chat, text: $"Echo: {text}").ConfigureAwait(false);
        }
예제 #25
0
        private static async Task SendMp4Async(IEnumerable <PostBase> posts)
        {
            foreach (var post in posts)
            {
                PostInfoLog(post);
                if (post.GetFileUrl().Contains(".mp4"))
                {
                    var keyboard = new InlineKeyboardMarkup(new[]
                    {
                        InlineKeyboardButton.WithUrl("Post", post.GetPostLink())
                    });

                    try
                    {
                        LogWrite($"{DateTime.UtcNow}:Send Mp4 {post.GetId()}", ConsoleColor.Yellow);
                        await Bot.SendPhotoAsync(ChatId, new InputOnlineFile(post.GetFileUrl()), caption : post.GetTags(10), replyMarkup : keyboard,
                                                 disableNotification : true);

                        LogWrite($"{DateTime.UtcNow}:Mp4 sended {post.GetId()}", ConsoleColor.Green);
                    }
                    catch (Exception e)
                    {
                        LogWrite($"(!) {DateTime.UtcNow}: [{e.GetType()}] {e.Source}:::{e.Message} " +
                                 $"(url: {post.GetFileUrl()})\n\t (url: {post.GetSampleUrl()})",
                                 ConsoleColor.Red, 1);
                    }
                }
            }
        }
예제 #26
0
 /// <summary>
 /// [ BUTTONTEXT -> ]
 /// </summary>
 /// <param name="messageId">Msg-ID des Posts im Draum</param>
 /// <param name="roomname">Chat-Name des Draums für den Link</param>
 /// <param name="buttonText">Text, der auf dem Button stehen soll</param>
 /// <returns></returns>
 internal static InlineKeyboardMarkup getPostLinkWithCustomText(long messageId, string roomname, string buttonText)
 {
     return(new InlineKeyboardMarkup(new List <InlineKeyboardButton>
     {
         InlineKeyboardButton.WithUrl(buttonText, "https://t.me/" + roomname + "/" + messageId)
     }));
 }
예제 #27
0
 public static void ReplyPM(this Message m, string[] texts, IReplyMarkup replyMarkup = null, ParseMode parseMode = ParseMode.Html, bool disableWebPagePreview = true, bool disableNotification = false)
 {
     foreach (var text in texts)
     {
         try
         {
             var r = Bot.Api.SendTextMessageAsync(m.From.Id, text, parseMode, disableWebPagePreview, disableNotification, 0, replyMarkup).Result;
             if (r == null)
             {
                 m.Reply(Commands.GetTranslation("NotStartedBot", Commands.GetLanguage(m.From.Id)), new InlineKeyboardMarkup(new InlineKeyboardButton[] {
                     InlineKeyboardButton.WithUrl("Start me!", $"https://t.me/{Bot.Me.Username}")
                 }));
                 return;
             }
         }
         catch (Exception e)
         {
             e.LogError();
         }
     }
     if (m.Chat.Type != ChatType.Private)
     {
         m.Reply(Commands.GetTranslation("SentPM", Commands.GetLanguage(m.From.Id)));
     }
 }
예제 #28
0
 /// <summary>
 /// [ Lesen und Abstimmen -> ]
 /// </summary>
 /// <param name="messageId">Msg-ID des Posts im Draum</param>
 /// <param name="roomname">Chat-Name des Draums für den Link</param>
 /// <returns></returns>
 internal static InlineKeyboardMarkup getTopPostLinkKeyboard(long messageId, string roomname)
 {
     return(new InlineKeyboardMarkup(new List <InlineKeyboardButton>
     {
         InlineKeyboardButton.WithUrl("Lesen und Abstimmen", "https://t.me/" + roomname + "/" + messageId)
     }));
 }
예제 #29
0
        public static InlineKeyboardMarkup CreateInlineKeyboardButton(Dictionary <string, string> buttonList, int columns)
        {
            int rows = (int)Math.Ceiling(buttonList.Count / (double)columns);

            InlineKeyboardButton[][] buttons = new InlineKeyboardButton[rows][];

            for (int i = 0; i < buttons.Length; i++)
            {
                buttons[i] = buttonList
                             .Skip(i * columns)
                             .Take(columns)
                             .Select(direction =>
                {
                    if (direction.Value.CheckUrlValid())
                    {
                        return(InlineKeyboardButton.WithUrl(direction.Key, direction.Value));
                    }
                    else
                    {
                        return(InlineKeyboardButton.WithCallbackData(direction.Key, direction.Value));
                    }
                })
                             .ToArray();
            }
            return(new InlineKeyboardMarkup(buttons));
        }
예제 #30
0
        /// <summary>
        /// Initializes arrays (keyboards are unique always)
        /// </summary>
        private void Init()
        {
            m_ReplyMarkupKeyboard.ResizeKeyboard = true;
            m_ReplyMarkupKeyboard.Keyboard       = new KeyboardButton[][]
            {
                new KeyboardButton[]
                {
                    new KeyboardButton("Start 2048")
                },
                new KeyboardButton[]
                {
                    new KeyboardButton("About Us")
                }
            };

            m_GameKeyboardMarkup.InlineKeyboard = new InlineKeyboardButton[][]
            {
                new InlineKeyboardButton[]
                {
                    InlineKeyboardButton.WithCallBackGame("Start Game", new CallbackGame())
                }
            };

            m_AboutKeyboardMarkup.InlineKeyboard = new InlineKeyboardButton[][]
            {
                new InlineKeyboardButton[]
                {
                    InlineKeyboardButton.WithUrl("Telegram Channel", "https://t.me/your_channel"),
                    InlineKeyboardButton.WithUrl("Instagram", "https://www.instagram.com/your_instagram/"),
                    InlineKeyboardButton.WithUrl("About Us", "http://your_domain_name.x/x/")
                }
            };
        }