Example #1
0
 public Response(User user, string text, IReplyMarkup replyMarkup = null, int replyToMessageId = 0)
 {
     User             = user;
     Text             = text;
     ReplyToMessageId = replyToMessageId;
     ReplyMarkup      = replyMarkup;
 }
 private async Task SendDialog(string text, IReplyMarkup replyMarkup)
 {
     if (text.IsNotNullOrEmpty())
     {
         await Client.SendTextMessageAsync(ChatId, text, replyMarkup : replyMarkup);
     }
 }
Example #3
0
 public Response(User user, int editMessageId, string text, IReplyMarkup replyMarkup = null)
 {
     User          = user;
     Text          = text;
     ReplyMarkup   = replyMarkup;
     EditMessageId = editMessageId;
 }
Example #4
0
 public async Task SendTextMessageToBotOwnerAsync(string text, IReplyMarkup replyMarkup = null)
 {
     if (AppSettings.NotifyOwner)
     {
         await _client.SendTextMessageToBotOwnerAsync(text, replyMarkup);
     }
 }
Example #5
0
        public async Task <bool> SendMessageAsync(long chatId, ITgOutboundMessage message)
        {
            char[] toLog    = message.Message?.Take(100).ToArray();
            string msgToLog = toLog == null ? string.Empty : new string(toLog);

            Trace.TraceInformation($"SendMessage id: {chatId} msg: {msgToLog}...");

            try
            {
                IReplyMarkup replyMarkup = message.ReplyKeyboard;
                replyMarkup ??= new ReplyKeyboardRemove();

                foreach (string msg in SplitMessage(message.IsEscaped ? message.Message : message.Message.EscapeMessageForMarkupV2()))
                {
                    await Policy
                    .Handle <HttpRequestException>()
                    .WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))
                    .ExecuteAsync(async() =>
                    {
                        await _botClient.SendChatActionAsync(chatId, ChatAction.Typing);
                        await _botClient.SendTextMessageAsync(chatId, msg, parseMode: ParseMode.MarkdownV2, replyMarkup: replyMarkup);
                    });
                }
            }
            catch (Exception exception)
            {
                Trace.TraceInformation($"SendMessage: {chatId} {message} failed. Exception {exception.Message}{Environment.NewLine}{exception.StackTrace}");
                return(false);
            }

            return(true);
        }
Example #6
0
 protected BotMenu(string name, IReplyMarkup keyboard, bool resKeyb, string info)
 {
     Name           = name;
     Keyboard       = keyboard;
     ResizeKeyboard = resKeyb;
     Info           = info;
 }
        /// <summary>
        /// Sends the text message to user
        /// </summary>
        /// <param name="message">The text of the message</param>
        /// <param name="method">The method from which the message was sent.</param>
        /// <param name="keyboard">The keyboard for the user</param>
        protected async void SendMessage(string message, string method, IReplyMarkup keyboard = default)
        {
            await TelegramBotClient.SendTextMessageAsync(_chatId, message, ParseMode.Default, false, false, 0,
                                                         keyboard);

            Logger.Info(string.Format(Resources.Resources.MessageForLogger, method, message, _userName, _chatId));
        }
        public async override Task ExecuteAsync(CommandContext context)
        {
            string       message  = Localizer["EditBookshelfEnter"];
            IReplyMarkup keyboard = CommandKeyboards.GetMainMenu(Localizer);

            if (context.SelectedBookshelf == null || CheckParameters(context))
            {
                context.SelectedBookshelf = FindItem(context);
                if (context.SelectedBookshelf == null)
                {
                    message = Localizer["EditBookshelfNoExist"];
                }
            }
            else if (context.Data != null && context.SelectedBookshelf != null)
            {
                if (!context.Bookshelves.Any(b => b.Name == context.Data))
                {
                    context.SelectedBookshelf.Name = context.Data;
                    context.SelectedBookshelf      = null;

                    message = Localizer["EditBookshelfSuccess"];
                }
                else
                {
                    message = Localizer["EditBookshelfErrorName"];
                }
            }

            if (message == Localizer["EditBookshelfEnter"])
            {
                keyboard = new ReplyKeyboardRemove();
            }

            await BotClient.SendTextMessageAsync(context.Message.Chat, message, replyMarkup : keyboard);
        }
Example #9
0
        /// <summary>
        /// Use this method to send text messages. On success, the sent Message is returned.
        /// </summary>
        /// <param name="chatId">Unique identifier for the message recipient — User or GroupChat id</param>
        /// <param name="text">Text of the message to be sent</param>
        /// <param name="disableWebPagePreview">Disables link previews for links in this message</param>
        /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param>
        /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param>
        /// <returns></returns>
        public SendMessageResult SendMessage(int chatId, string text,
                                             bool?disableWebPagePreview = null,
                                             int?replyToMessageId       = null,
                                             IReplyMarkup replyMarkup   = null)
        {
            var request = new RestRequest(string.Format(sendMessageUri, Token), Method.POST);

            request.AddParameter("chat_id", chatId);
            request.AddParameter("text", text);
            if (disableWebPagePreview.HasValue)
            {
                request.AddParameter("disable_web_page_preview", disableWebPagePreview.Value);
            }
            if (replyToMessageId.HasValue)
            {
                request.AddParameter("reply_to_message_id", replyToMessageId.Value);
            }
            if (replyMarkup != null)
            {
                request.AddParameter("reply_markup", replyMarkup.GetJson());
            }
            var response = restClient.Execute(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(new SendMessageResult(response.Content));
            }
            else
            {
                throw new Exception(response.StatusDescription);
            }
        }
Example #10
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)));
     }
 }
        public LoggerRemovingCanceledMessageTemplate()
        {
            Text = "Удаление логгера отменено";

            ReplyMarkup = new InlineKeyboardMarkup()
                          .AddRow(new InlineKeyboardButton("В меню", callbackData: "menu"));
        }
Example #12
0
 public static Message Edit(long chatId, int oldMessageId, string text, IReplyMarkup replyMarkup = null, ParseMode parseMode = ParseMode.Html, bool disableWebPagePreview = true, bool disableNotification = false)
 {
     try
     {
         var t = Bot.Api.EditMessageTextAsync(chatId, oldMessageId, text, parseMode, disableWebPagePreview, replyMarkup);
         t.Wait();
         return(t.Result);
     }
     catch (Exception e)
     {
         if (e is AggregateException Agg && Agg.InnerExceptions.Any(x => x.Message.ToLower().Contains("message is not modified")))
         {
             /*
              * var m = "Messae not modified." + Environment.NewLine;
              * m += $"Chat: {chatId}" + Environment.NewLine;
              * m += $"Text: {text}" + Environment.NewLine;
              * m += $"Time: {DateTime.UtcNow.ToLongTimeString()} UTC";
              * Send(Constants.LogGroupId, m);
              */
             return(null);
         }
         e.LogError();
         return(null);
     }
 }
Example #13
0
        private Task <Message> SendNotificationToChatAsync(bool isForCollection, string name,
                                                           string instructions = default, ChatId chatid = default, bool switchInlineQuery = default)
        {
            var textFormat = isForCollection
                ? Constants.StartCollectionMessageFormat
                : Constants.StartTestCaseMessageFormat;

            string text = string.Format(textFormat, name);

            chatid = chatid ?? SupergroupChat.Id;
            if (instructions != default)
            {
                text += "\n\n" + string.Format(Constants.InstructionsMessageFormat, instructions);
            }

            IReplyMarkup replyMarkup = switchInlineQuery
                ? new InlineKeyboardMarkup(new[] {
                InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Start inline query")
            })
                : default;

            var task = BotClient.SendTextMessageAsync(chatid, text, ParseMode.Markdown,
                                                      replyMarkup: replyMarkup,
                                                      cancellationToken: CancellationToken);

            return(task);
        }
Example #14
0
        public override AnswerItem Reply(MessageItem mItem)
        {
            IReplyMarkup markup = null;

            string message;

            if (string.IsNullOrEmpty(mItem.TextOnly))
            {
                message =
                    "Type a chinese word to remove it from the dictionary. All word's score information will be removed too!";
            }
            else if (NoAnswer == mItem.TextOnly.ToLowerInvariant())
            {
                message = "Delete has been cancelled";
            }
            else if (mItem.TextOnly.ToLowerInvariant().StartsWith(YesAnswer))
            {
                try
                {
                    var wordText = mItem.TextOnly.Replace(YesAnswer, string.Empty);
                    var word     = _repository.GetWord(wordText, mItem.ChatId);

                    if (word == null)
                    {
                        message = $"Word {wordText} is not found";
                    }
                    else
                    {
                        _repository.DeleteWord(word.Id);
                        message = $"Word {word.OriginalWord} has been removed";
                    }
                }
                catch (Exception e)
                {
                    message = e.Message;
                }
            }
            else
            {
                message = $"Do you really want to remove '{mItem.TextOnly}'?";

                markup = new InlineKeyboardMarkup(new[]
                {
                    new InlineKeyboardButton {
                        Text = "✅Yes", CallbackData = $"yes{mItem.TextOnly}"
                    },
                    new InlineKeyboardButton {
                        Text = "❌No", CallbackData = "no"
                    }
                });
            }

            var answer = new AnswerItem
            {
                Message = message,
                Markup  = markup
            };

            return(answer);
        }
Example #15
0
        public RequestResult(string response, IReplyMarkup markup)
        {
            Handled = true;

            Response    = response;
            ReplyMarkup = markup;
        }
        /// <summary>
        /// Use this method to send phone contacts. See <see href="https://core.telegram.org/bots/api#sendcontact">API</see>
        /// </summary>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param>
        /// <param name="phoneNumber">Contact's phone number</param>
        /// <param name="firstName">Contact's first name</param>
        /// <param name="lastName">Contact's last name</param>
        /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param>
        /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param>
        /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard,
        /// instructions to remove keyboard or to force a reply from the user.</param>
        /// <returns>On success, the sent <see cref="MessageInfo"/> is returned.</returns>
        public SendMessageResult SendContact(object chatId, string phoneNumber, string firstName,
                                             string lastName          = null,
                                             bool?disableNotification = null,
                                             int?replyToMessageId     = null,
                                             IReplyMarkup replyMarkup = null)
        {
            RestRequest request = NewRestRequest(mSendContactUri);

            request.AddParameter("chat_id", chatId);
            request.AddParameter("phone_number", phoneNumber);
            request.AddParameter("first_name", firstName);

            if (!string.IsNullOrEmpty(lastName))
            {
                request.AddParameter("last_name", lastName);
            }
            if (disableNotification.HasValue)
            {
                request.AddParameter("disable_notification", disableNotification.Value);
            }
            if (replyToMessageId != null)
            {
                request.AddParameter("reply_to_message_id", replyToMessageId);
            }
            if (replyMarkup != null)
            {
                request.AddParameter("reply_markup", replyMarkup.GetJson());
            }

            return(ExecuteRequest <SendMessageResult>(request) as SendMessageResult);
        }
        /// <summary>
        /// Use this method to send text messages. See <see href="https://core.telegram.org/bots/api#sendmessage">API</see>
        /// </summary>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param>
        /// <param name="text">Text of the message to be sent</param>
        /// <param name="parseMode">Send Markdown or HTML, 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="disableNotification">Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound.</param>
        /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param>
        /// <param name="replyMarkup">Additional interface options.
        /// A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param>
        /// <returns>On success, the sent <see cref="SendMessageResult"/> is returned.</returns>
        public SendMessageResult SendMessage(object chatId, string text,
                                             ParseMode?parseMode        = null,
                                             bool?disableWebPagePreview = null,
                                             bool?disableNotification   = null,
                                             int?replyToMessageId       = null,
                                             IReplyMarkup replyMarkup   = null)
        {
            RestRequest request = NewRestRequest(mSendMessageUri);

            request.AddParameter("chat_id", chatId);
            request.AddParameter("text", text);
            if (parseMode != null)
            {
                request.AddParameter("parse_mode", parseMode.Value);
            }
            if (disableWebPagePreview.HasValue)
            {
                request.AddParameter("disable_web_page_preview", disableWebPagePreview.Value);
            }
            if (disableNotification.HasValue)
            {
                request.AddParameter("disable_notification", disableNotification.Value);
            }
            if (replyToMessageId.HasValue)
            {
                request.AddParameter("reply_to_message_id", replyToMessageId.Value);
            }
            if (replyMarkup != null)
            {
                request.AddParameter("reply_markup", replyMarkup.GetJson());
            }

            return(ExecuteRequest <SendMessageResult>(request) as SendMessageResult);
        }
        /// <summary>
        /// Use this method to send point on the map.
        /// See <see href="https://core.telegram.org/bots/api#sendlocation">API</see>
        /// </summary>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param>
        /// <param name="latitude">Latitude of location</param>
        /// <param name="longitude">Longitude of location</param>
        /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param>
        /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param>
        /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param>
        /// <returns>On success, the sent <see cref="MessageInfo"/> is returned.</returns>
        public SendMessageResult SendLocation(object chatId, float latitude, float longitude,
                                              bool?disableNotification = null,
                                              int?replyToMessageId     = null,
                                              IReplyMarkup replyMarkup = null)
        {
            RestRequest request = NewRestRequest(mSendLocationUri);

            request.AddParameter("chat_id", chatId);
            request.AddParameter("latitude", latitude);
            request.AddParameter("longitude", longitude);

            if (disableNotification.HasValue)
            {
                request.AddParameter("disable_notification", disableNotification.Value);
            }
            if (replyToMessageId != null)
            {
                request.AddParameter("reply_to_message_id", replyToMessageId);
            }
            if (replyMarkup != null)
            {
                request.AddParameter("reply_markup", replyMarkup.GetJson());
            }

            return(ExecuteRequest <SendMessageResult>(request) as SendMessageResult);
        }
        /// <summary>
        /// Use this method to send information about a venue.
        /// </summary>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param>
        /// <param name="latitude">Latitude of the venue</param>
        /// <param name="longitude">Longitude of the venue</param>
        /// <param name="title">Name of the venue</param>
        /// <param name="address">Address of the venue</param>
        /// <param name="foursquareId">Foursquare identifier of the venue</param>
        /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param>
        /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param>
        /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for an
        /// inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.</param>
        /// <returns>On success, the sent <see cref="SendMessageResult"/> is returned</returns>
        public SendMessageResult SendVenue(object chatId, float latitude, float longitude, string title, string address,
                                           string foursquareId      = null,
                                           bool?disableNotification = null,
                                           int?replyToMessageId     = null,
                                           IReplyMarkup replyMarkup = null)
        {
            RestRequest request = NewRestRequest(mSendVenueUri);

            request.AddParameter("chat_id", chatId);
            request.AddParameter("latitude", latitude);
            request.AddParameter("longitude", longitude);
            request.AddParameter("title", title);
            request.AddParameter("address", address);

            if (!string.IsNullOrEmpty(foursquareId))
            {
                request.AddParameter("foursquare_id", foursquareId);
            }
            if (disableNotification.HasValue)
            {
                request.AddParameter("disable_notification", disableNotification.Value);
            }
            if (replyToMessageId != null)
            {
                request.AddParameter("reply_to_message_id", replyToMessageId);
            }
            if (replyMarkup != null)
            {
                request.AddParameter("reply_markup", replyMarkup.GetJson());
            }

            return(ExecuteRequest <SendMessageResult>(request) as SendMessageResult);
        }
        /// <summary>
        /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message.
        /// For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document).
        /// On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
        /// </summary>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param>
        /// <param name="voice">Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended),
        /// pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data</param>
        /// <param name="caption">Voice message caption, 0-200 characters </param>
        /// <param name="duration">Duration of the voice message in seconds </param>
        /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param>
        /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param>
        /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard,
        /// instructions to remove reply keyboard or to force a reply from the user.</param>
        /// <returns></returns>
        public SendMessageResult SendVoice(object chatId, IFile voice,
                                           string caption           = null,
                                           int?duration             = null,
                                           bool?disableNotification = null,
                                           int?replyToMessageId     = null,
                                           IReplyMarkup replyMarkup = null)
        {
            RestRequest request = NewRestRequest(mSendVoiceUri);

            request.AddParameter("chat_id", chatId);
            request = AddFile(voice, request, "voice");

            if (!string.IsNullOrEmpty(caption))
            {
                request.AddParameter("caption", caption);
            }
            if (duration != null)
            {
                request.AddParameter("duration", duration);
            }
            if (disableNotification.HasValue)
            {
                request.AddParameter("disable_notification", disableNotification.Value);
            }
            if (replyToMessageId != null)
            {
                request.AddParameter("reply_to_message_id", replyToMessageId);
            }
            if (replyMarkup != null)
            {
                request.AddParameter("reply_markup", replyMarkup.GetJson());
            }

            return(ExecuteRequest <SendMessageResult>(request) as SendMessageResult);
        }
        /// <summary>
        /// Use this method to send .webp stickers. See <see href="https://core.telegram.org/bots/api#sendsticker">API</see>
        /// </summary>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param>
        /// <param name="sticker">Sticker to send. You can either pass a file_id as String to resend a sticker that is
        /// already on the Telegram servers, or upload a new sticker using multipart/form-data.</param>
        /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param>
        /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param>
        /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param>
        /// <returns>On success, the sent <see cref="MessageInfo"/> is returned.</returns>
        public SendMessageResult SendSticker(object chatId, IFile sticker,
                                             bool?disableNotification = null,
                                             int?replyToMessageId     = null,
                                             IReplyMarkup replyMarkup = null)
        {
            RestRequest request = NewRestRequest(mSendStickerUri);

            request.AddParameter("chat_id", chatId);
            request = AddFile(sticker, request, "sticker");

            if (disableNotification.HasValue)
            {
                request.AddParameter("disable_notification", disableNotification.Value);
            }
            if (replyToMessageId != null)
            {
                request.AddParameter("reply_to_message_id", replyToMessageId);
            }
            if (replyMarkup != null)
            {
                request.AddParameter("reply_markup", replyMarkup.GetJson());
            }

            return(ExecuteRequest <SendMessageResult>(request) as SendMessageResult);
        }
Example #22
0
        /// <summary>
        /// Use this method to send point on the map. On success, the sent Message is returned.
        /// </summary>
        /// <param name="chatId">Unique identifier for the message recipient — User or GroupChat id</param>
        /// <param name="latitude">Latitude of location</param>
        /// <param name="longitude">Longitude of location</param>
        /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param>
        /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param>
        /// <returns></returns>
        public SendMessageResult SendLocation(int chatId, float latitude, float longitude,
                                              int?replyToMessageId     = null,
                                              IReplyMarkup replyMarkup = null)
        {
            var request = new RestRequest(string.Format(sendLocationUri, Token), Method.POST);

            request.AddParameter("chat_id", chatId);
            request.AddParameter("latitude", latitude);
            request.AddParameter("longitude", longitude);
            if (replyToMessageId != null)
            {
                request.AddParameter("reply_to_message_id", replyToMessageId);
            }
            if (replyMarkup != null)
            {
                request.AddParameter("reply_markup", replyMarkup.GetJson());
            }
            var response = restClient.Execute(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(new SendMessageResult(response.Content));
            }
            else
            {
                throw new Exception(response.StatusDescription);
            }
        }
Example #23
0
 public void Init(long _userId, Vk _vkApi, UserManager _userManager)
 {
     m_vkApi         = _vkApi ?? throw new ArgumentNullException(nameof(_vkApi));
     m_userManager   = _userManager ?? throw new ArgumentNullException(nameof(_userManager));
     m_userId        = _userId;
     m_generalMarkup = KeyBoardBuilder.BuildMarkupKeyboard(new string[] { "Добавить группу", "Удалить группу" });
 }
Example #24
0
        public static async Task <Message> SendTextMessageIgnoreAPIErrorsAsync(this TelegramBotClient client,
                                                                               ChatId chatId,
                                                                               string text,
                                                                               ParseMode parseMode        = ParseMode.Default,
                                                                               bool disableWebPagePreview = false,
                                                                               bool disableNotification   = false,
                                                                               int replyToMessageId       = 0,
                                                                               IReplyMarkup
                                                                               replyMarkup = null,
                                                                               CancellationToken cancellationToken = default)
        {
            Message result = null;

            try
            {
                result = await client.SendTextMessageAsync(chatId,
                                                           text,
                                                           parseMode,
                                                           disableWebPagePreview,
                                                           disableNotification,
                                                           replyToMessageId,
                                                           replyMarkup,
                                                           cancellationToken);
            }
            catch (Exception e)
            {
                if (!(e is Telegram.Bot.Exceptions.ApiRequestException))
                {
                    throw;
                }
            }

            return(result);
        }
        public async Task <SocialResponse> SendFreeMessageAsync(string message, IReplyMarkup replyMarkup = null)
        {
            var response = new SocialResponse();

            try
            {
                if (_isFreeActive)
                {
                    var s = await _telegramFree.SendTextMessageAsync(
                        _freeChatId,
                        message,
                        parseMode : ParseMode.Markdown,
                        disableWebPagePreview : true,
                        replyMarkup : replyMarkup);
                }

                response.Success = true;
            }
            catch (Exception e)
            {
                response.Success = false;
                response.Message = e.GetFullMessage();
            }
            return(response);
        }
Example #26
0
 public Task <Message> SendDiceAsync(
     ChatId chatId,
     bool disableNotification            = false,
     int replyToMessageId                = 0,
     IReplyMarkup replyMarkup            = null,
     CancellationToken cancellationToken = new CancellationToken(),
     Emoji?emoji = null) => throw new NotImplementedException();
 public async Task <Message> SendOrUpdate(ChatId chat, string text, IReplyMarkup replyMarkup = null, int?messageId = null)
 {
     try
     {
         Message message;
         if (messageId.HasValue)
         {
             message = await _botClient.EditMessageTextAsync(
                 messageId : messageId.Value,
                 chatId : chat,
                 text : text,
                 replyMarkup : (InlineKeyboardMarkup)replyMarkup,
                 parseMode : ParseMode.Html
                 );
         }
         else
         {
             message = await _botClient.SendTextMessageAsync(
                 chat,
                 text,
                 replyMarkup : replyMarkup,
                 parseMode : ParseMode.Html
                 );
         }
         return(message);
     }
     catch (Exception ex)
     {
         Console.WriteLine($"SendOrUpdate() Error for params: chat:{chat.Identifier}:{chat.Username}, text:{text}, isUpdate:{messageId.HasValue}");
         Console.WriteLine($"{ex.Message} - \n {ex.StackTrace}");
         return(null);
     }
 }
        /// <summary>
        /// As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long.
        /// Use this method to send video messages.
        /// </summary>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param>
        /// <param name="videoNote">Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended)
        /// or upload a new video using multipart/form-data.
        /// Sending video notes by a URL is currently unsupported</param>
        /// <param name="duration">Optional. Duration of sent video in seconds</param>
        /// <param name="length">Optional. Video width and height</param>
        /// <param name="disableNotification">Optional. Sends the message silently. Users will receive a notification with no sound.</param>
        /// <param name="replyToMessageId">Optional. If the message is a reply, ID of the original message</param>
        /// <param name="replyMarkup">Optional. Additional interface options.
        /// A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.</param>
        /// <returns>On success, the sent <see cref="MessageInfo"/> is returned</returns>
        public SendMessageResult SendVideoNote(object chatId, IFile videoNote,
                                               int?duration             = null,
                                               int?length               = null,
                                               bool?disableNotification = null,
                                               int?replyToMessageId     = null,
                                               IReplyMarkup replyMarkup = null)
        {
            RestRequest request = NewRestRequest(mSendVideoNoteUri);

            request.AddParameter("chat_id", chatId);
            request = AddFile(videoNote, request, "video_note");

            if (duration != null)
            {
                request.AddParameter("duration", duration);
            }
            if (length != null)
            {
                request.AddParameter("length", length);
            }
            if (disableNotification.HasValue)
            {
                request.AddParameter("disable_notification", disableNotification.Value);
            }
            if (replyToMessageId != null)
            {
                request.AddParameter("reply_to_message_id", replyToMessageId);
            }
            if (replyMarkup != null)
            {
                request.AddParameter("reply_markup", replyMarkup.GetJson());
            }

            return(ExecuteRequest <SendMessageResult>(request) as SendMessageResult);
        }
Example #29
0
 public Task <Message> SendStickerAsync(
     ChatId chatId,
     InputOnlineFile sticker,
     bool disableNotification            = false,
     int replyToMessageId                = 0,
     IReplyMarkup replyMarkup            = null,
     CancellationToken cancellationToken = new CancellationToken()) => throw new NotImplementedException();
Example #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bot"></param>
        /// <param name="update"></param>
        /// <returns></returns>
        /// <remarks>
        /// Sends two consecutive messages so it can set both InlineButton and KeyboardButton reply markups
        /// </remarks>
        public async Task ReplyWithSetupInstructionsAsync(IBot bot, Update update)
        {
            IReplyMarkup inlineMarkup = await GetCountriesReplyMarkupAsync();

            IReplyMarkup keyboardMarkup = new ReplyKeyboardMarkup(new[]
            {
                new KeyboardButton("Share my location")
                {
                    RequestLocation = true
                },
            }, true, true);

            await bot.Client.SendTextMessageAsync(update.GetChatId(),
                                                  "Select a country and then a region to find your local transit agency",
                                                  ParseMode.Markdown,
                                                  replyMarkup : inlineMarkup);

            await bot.Client.SendTextMessageAsync(update.GetChatId(),
                                                  "or *Share your location* so I can find it for you",
                                                  ParseMode.Markdown,
                                                  replyMarkup : keyboardMarkup);

            var userChat = (UserChat)update.ToUserchat();

            var cacheContext = GetOrCreateCacheEntryFor(userChat);

            cacheContext.ProfileSetupInstructionsSent = true;
        }
        public static void SendMessage(int userId, string msg, bool? disableWebPagePreview = null, int? replyToMessageId = null, IReplyMarkup replyMarkup = null)
        {
            // Conver to UTF8 string
            var bytes = Encoding.Unicode.GetBytes (msg);
            msg = Encoding.UTF8.GetString ( Encoding.Convert (Encoding.Unicode, Encoding.UTF8, bytes) );

            botClient.SendMessage (userId, msg, disableWebPagePreview, replyToMessageId, replyMarkup );
        }
 public Task<Message> EditInlineMessageText(string inlineMessageId, string text,
     ParseMode parseMode = ParseMode.Default, bool disableWebPagePreview = false, IReplyMarkup replyMarkup = null)
     => EditInlineMessageTextAsync(inlineMessageId, text, parseMode, disableWebPagePreview, replyMarkup);
 public Task<Message> EditMessageReplyMarkup(string chatId, int messageId, IReplyMarkup replyMarkup = null)
     => EditMessageReplyMarkupAsync(chatId, messageId, replyMarkup);
 public Task<Message> EditInlineMessageCaption(string inlineMessageId, string caption, IReplyMarkup replyMarkup = null)
     => EditInlineMessageCaptionAsync(inlineMessageId, caption, replyMarkup);
 public Task<Message> EditMessageCaption(string chatId, int messageId, string caption, IReplyMarkup replyMarkup = null)
     => EditMessageCaptionAsync(chatId, messageId, caption, replyMarkup);
 public Task<Message> SendLocation(string chatId, float latitude, float longitude,
     bool disableNotification = false,
     int replyToMessageId = 0,
     IReplyMarkup replyMarkup = null)
     => SendLocationAsync(chatId, latitude, longitude, disableNotification, replyToMessageId, replyMarkup);
 public Task<Message> EditMessageText(long chatId, int messageId, string text,
     ParseMode parseMode = ParseMode.Default, bool disableWebPagePreview = false, IReplyMarkup replyMarkup = null)
     => EditMessageTextAsync(chatId, messageId, text, parseMode, disableWebPagePreview, replyMarkup);
 public Task<Message> SendVideo(string chatId, string video, int duration = 0, string caption = "",
     bool disableNotification = false,
     int replyToMessageId = 0,
     IReplyMarkup replyMarkup = null)
     => SendVideoAsync(chatId, video, duration, caption, disableNotification, replyToMessageId, replyMarkup);
 public Task<Message> SendVoice(string chatId, string audio, int duration = 0,
     bool disableNotification = false,
     int replyToMessageId = 0,
     IReplyMarkup replyMarkup = null)
     => SendVoiceAsync(chatId, audio, duration, disableNotification, replyToMessageId, replyMarkup);
 public Task<Message> SendSticker(string chatId, string sticker,
     bool disableNotification = false,
     int replyToMessageId = 0,
     IReplyMarkup replyMarkup = null)
     => SendStickerAsync(chatId, sticker, disableNotification, replyToMessageId, replyMarkup);
 public Task<Message> SendVenue(string chatId, float latitude, float longitude, string title, string address,
     string foursquareId = null,
     bool disableNotification = false,
     int replyToMessageId = 0,
     IReplyMarkup replyMarkup = null)
     => SendVenueAsync(chatId, latitude, longitude, title, address, foursquareId, disableNotification, replyToMessageId, replyMarkup);
 public Task<Message> SendContact(string chatId, string phoneNumber, string firstName, string lastName = null,
     bool disableNotification = false,
     int replyToMessageId = 0,
     IReplyMarkup replyMarkup = null)
     => SendContactAsync(chatId, phoneNumber, firstName, lastName, disableNotification, replyToMessageId, replyMarkup);
 public Task<Message> SendDocument(string chatId, string document, string caption = "",
     bool disableNotification = false,
     int replyToMessageId = 0,
     IReplyMarkup replyMarkup = null)
     => SendDocumentAsync(chatId, document, caption, disableNotification, replyToMessageId, replyMarkup);
 public Task<Message> SendPhoto(string chatId, string photo, string caption = "",
     bool disableNotification = false,
     int replyToMessageId = 0,
     IReplyMarkup replyMarkup = null)
     => SendPhotoAsync(chatId, photo, caption, disableNotification, replyToMessageId, replyMarkup);
 public Task<Message> SendAudio(string chatId, string audio, int duration, string performer, string title,
     bool disableNotification = false,
     int replyToMessageId = 0,
     IReplyMarkup replyMarkup = null)
     => SendAudioAsync(chatId, audio, duration, performer, title, disableNotification, replyToMessageId, replyMarkup);
 public Task<Message> EditInlineMessageReplyMarkup(string inlineMessageId, IReplyMarkup replyMarkup = null)
     => EditInlineMessageReplyMarkupAsync(inlineMessageId, replyMarkup);
 public Task<Message> SendTextMessage(string chatId, string text, bool disableWebPagePreview = false,
     bool disableNotification = false,
     int replyToMessageId = 0,
     IReplyMarkup replyMarkup = null,
     ParseMode parseMode = ParseMode.Default)
     => SendTextMessageAsync(chatId, text, disableWebPagePreview, disableNotification, replyToMessageId, replyMarkup, parseMode);