Beispiel #1
0
        public async Task <Message> SendTestCaseNotificationAsync(string testcase, string instructions = null,
                                                                  ChatId chatid = null)
        {
            Message msg = await SendNotificationToChatAsync(false, testcase, instructions, chatid);

            return(msg);
        }
        public override void ToStream(Stream output)
        {
            output.Write(TLUtils.SignatureToBytes(Signature));

            ChatId.ToStream(output);
            AccessHash.ToStream(output);
        }
 /// <summary>
 /// Initializes a new request with chatId, messageId and new text
 /// </summary>
 /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param>
 /// <param name="messageId">Identifier of the sent message</param>
 /// <param name="text">New text of the message</param>
 public EditMessageTextRequest(ChatId chatId, int messageId, string text)
     : base("editMessageText")
 {
     ChatId    = chatId;
     MessageId = messageId;
     Text      = text;
 }
 public TelegramLogger(string categoryName, Func <string, LogLevel, bool> filter, ITelegramBotClient bot, ChatId chatId)
 {
     _categoryName = categoryName;
     _filter       = filter;
     _bot          = bot;
     _chatId       = chatId;
 }
        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
                ? (InlineKeyboardMarkup)InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Start inline query")
                : default;

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

            return(task);
        }
 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);
     }
 }
Beispiel #7
0
 public bool Equals(ChatState other)
 {
     return(ChatId.Equals(other.ChatId) &&
            ChatName == other.ChatName &&
            Messages.SequenceEqual(other.Messages) &&
            ParticipantIds.SetEquals(other.ParticipantIds));
 }
        private static Uri GetMessageUri(ChatId chatId, int messageId)
        {
            Uri    chatUri   = GetUri(chatId);
            string uriString = string.Format(ChannelMessageUriFormat, chatUri, messageId);

            return(new Uri(uriString));
        }
        private static Uri GetUri(ChatId chatId)
        {
            string username  = GetUsername(chatId);
            string uriString = string.Format(ChannelUriFormat, username);

            return(new Uri(uriString));
        }
Beispiel #10
0
        // данные курьера в массив строк
        public string[] Peek()
        {
            var status = "none";

            switch (userState)
            {
            case UserState.WaitLink:
                status = "wait";
                break;

            case UserState.Free:
                status = "free";
                break;

            default:
                break;
            }
            return(new string[]
            {
                ChatId.ToString(),
                UserName,
                PersonalLink,
                status
            });
        }
Beispiel #11
0
        public async Task OnGossipMessageAsync(ChatId chatid, SourceSignedMessage msg)
        {
            var m = msg as ChatMsg;

            if (m == null)
            {
                return;
            }

            switch (m.MsgType)
            {
            case ChatMessageType.NodeUp:
                await SendNodesInfoToGroupAsync(chatid);

                break;

            case ChatMessageType.AuthorizerPrePrepare:
            case ChatMessageType.AuthorizerPrepare:
            //case ChatMessageType.AuthorizerCommit:
            //    var typStr = string.Join(" ", Regex.Split(m.Type.ToString(), @"(?<!^)(?=[A-Z])"));
            //    var text = $"*From*: {m.From}\n*Event*: {typStr}\n*Block Number*: {m.BlockUIndex}";
            //    await SendGroupMessageAsync(text);
            //    break;
            default:
                var typStr2 = string.Join(" ", Regex.Split(m.MsgType.ToString(), @"(?<!^)(?=[A-Z])"));
                var text2   = $"*From*: {m.From}\n*Event*: {typStr2}\n*Text*: {m.Text}";
                await SendGroupMessageAsync(chatid, text2);

                break;
            }
        }
 /// <summary>
 /// Initializes a new request with chatId, question and <see cref="PollOption"/>
 /// </summary>
 /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param>
 /// <param name="question">Poll question, 1-255 characters</param>
 /// <param name="options">List of answer options, 2-10 strings 1-100 characters each</param>
 public SendPollRequest(ChatId chatId, string question, IEnumerable <string> options)
     : base("sendPoll")
 {
     ChatId   = chatId;
     Question = question;
     Options  = options;
 }
Beispiel #13
0
        private (int UserId, (string InlineMessageId, (ChatId ChatId, int MessageId))) DecodePlayerId(
            string encodedPlayerid)
        {
            encodedPlayerid = WebUtility.UrlDecode(encodedPlayerid);
            encodedPlayerid = _dataProtector.Unprotect(encodedPlayerid);

            string[] tokens = encodedPlayerid
                              .Split(Constants.PlayerIdSeparator);

            int userid = int.Parse(tokens[0]);

            if (tokens.Length == 2)
            {
                string inlineMsgId = tokens[1];
                return(userid, (inlineMsgId, default((ChatId ChatId, int MessageId))));
            }
            else if (tokens.Length == 3)
            {
                ChatId chatid = new ChatId(tokens[1]);
                int    msgId  = int.Parse(tokens[2]);
                return(userid, (null, (chatid, msgId)));
            }
            else
            {
                throw new ArgumentException();
            }
        }
Beispiel #14
0
        private string EncodePlayerId(int userid, string inlineMsgId, ChatId chatid, int msgId)
        {
            var values = new List <string> {
                userid.ToString()
            };

            if (inlineMsgId != null)
            {
                values.Add(inlineMsgId);
            }
            else if (chatid != null && msgId != default(int))
            {
                values.Add(chatid);
                values.Add(msgId.ToString());
            }
            else
            {
                throw new ArgumentException();
            }

            string playerid = string.Join(Constants.PlayerIdSeparator.ToString(), values);

            playerid = _dataProtector.Protect(playerid);
            playerid = WebUtility.UrlEncode(playerid);

            return(playerid);
        }
Beispiel #15
0
        public void Equals_Test()
        {
            //with Identifier
            var chatId = new ChatId(123);

            Assert.True(chatId.Equals(123));
            Assert.False(123.Equals(chatId)); // to be aware
            Assert.True(chatId == 123);
            Assert.True(123 == chatId);

            chatId = new ChatId("123");
            Assert.True(chatId.Equals(123));
            Assert.False(123.Equals(chatId)); // to be aware
            Assert.True(chatId == 123);
            Assert.True(123 == chatId);

            //with username
            chatId = new ChatId("@username");
            Assert.True(chatId.Equals("@username"));
            Assert.True("@username".Equals(chatId));
            Assert.True(chatId == "@username");
            Assert.True("@username" == chatId);

            //with other ChatId
            Assert.Equal(chatId, chatId);
            Assert.Equal(new ChatId(123), new ChatId(123));
        }
        public async Task PostOrUpdateWeekEventsAndScheduleAsync(ChatId chatId, bool shouldConfirm)
        {
            _weekStart = Utils.GetMonday(_bot.TimeManager);
            _weekEnd   = _weekStart.AddDays(7);

            IEnumerable <Template> templates = await LoadRelevantTemplatesAsync();

            _templates = templates.ToDictionary(t => t.Id, t => t);
            _saveManager.Load();

            ICollection <int> savedTemplateIds = _saveManager.Data.Events.Keys;

            _toPost = _templates.Values.Where(t => !savedTemplateIds.Contains(t.Id)).OrderBy(t => t.Start).ToList();

            shouldConfirm = shouldConfirm && _toPost.Any();

            _confirmationPending = !shouldConfirm;

            if (shouldConfirm)
            {
                await AskForConfirmationAsync(chatId);
            }
            else
            {
                await PostOrUpdateWeekEventsAndScheduleAsync(chatId);
            }
        }
Beispiel #17
0
        public void Check_Constructor()
        {
            var chatId = new ChatId(123);

            //check int & long
            Assert.Null(chatId.Username);
            Assert.Equal(123, chatId.Identifier);

            chatId = new ChatId(123L);
            Assert.Null(chatId.Username);
            Assert.Equal(123L, chatId.Identifier);

            // check string values
            chatId = new ChatId(123.ToString());
            Assert.Null(chatId.Username);
            Assert.Equal(123, chatId.Identifier);

            chatId = new ChatId(123L.ToString());
            Assert.Null(chatId.Username);
            Assert.Equal(123L, chatId.Identifier);

            chatId = new ChatId("@valid_username");
            Assert.Equal("@valid_username", chatId.Username);
            Assert.Equal(0, chatId.Identifier);

            Assert.Throws <ArgumentException>(() => new ChatId("username"));
        }
        public async Task PostOrUpdateWeekEventsAndScheduleAsync(ChatId chatId)
        {
            if (!_confirmationPending)
            {
                await _bot.Client.SendTextMessageAsync(chatId, "Обновлений не запланировано.");

                return;
            }

            _confirmationPending = false;

            Message statusMessage =
                await _bot.Client.SendTextMessageAsync(chatId, "_Обновляю расписание…_", ParseMode.MarkdownV2);

            await PostOrUpdateEventsAsync();
            await PostOrUpdateScheduleAsync();
            await CreateOrUpdateNotificationsAsync();

            List <int> toRemove = _saveManager.Data.Messages.Keys.Where(IsExcess).ToList();

            foreach (int id in toRemove)
            {
                _saveManager.Data.Messages.Remove(id);
            }

            _saveManager.Save();

            await _bot.Client.FinalizeStatusMessageAsync(statusMessage);
        }
 public EditMessageTextRequest(ChatId chatId, long messageId, string text)
     : base("/messages/editText", HttpMethod.Get)
 {
     ChatId    = chatId;
     MessageId = messageId;
     Text      = text;
 }
Beispiel #20
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();
Beispiel #21
0
 /// <summary>
 /// Initializes a new request with chatId, fromChatId and messageId
 /// </summary>
 public ForwardMessageRequest(ChatId chatdId, ChatId fromChatId, int messageId)
     : base("forwardMessage")
 {
     ChatId     = chatdId;
     FromChatId = fromChatId;
     MessageId  = messageId;
 }
Beispiel #22
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();
Beispiel #23
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);
        }
Beispiel #24
0
 public Task <Message> EditMessageCaptionAsync(
     ChatId chatId,
     int messageId,
     string caption,
     InlineKeyboardMarkup replyMarkup    = null,
     CancellationToken cancellationToken = new CancellationToken(),
     ParseMode parseMode = ParseMode.Default) => throw new NotImplementedException();
Beispiel #25
0
 /// <summary>
 /// Initializes a new request with chatId and location
 /// </summary>
 /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param>
 /// <param name="latitude">Latitude of the location</param>
 /// <param name="longitude">Longitude of the location</param>
 public SendLocationRequest(ChatId chatId, float latitude, float longitude)
     : base("sendLocation")
 {
     ChatId    = chatId;
     Latitude  = latitude;
     Longitude = longitude;
 }
Beispiel #26
0
 public Task <Message> EditMessageLiveLocationAsync(
     ChatId chatId,
     int messageId,
     float latitude,
     float longitude,
     InlineKeyboardMarkup replyMarkup    = null,
     CancellationToken cancellationToken = new CancellationToken()) => throw new NotImplementedException();
 /// <summary>
 /// Initializes a new request with chatId, messageId and new caption
 /// </summary>
 /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param>
 /// <param name="messageId">Identifier of the sent message</param>
 /// <param name="caption">New caption of the message</param>
 public EditMessageCaptionRequest(ChatId chatId, int messageId, string caption = default)
     : base("editMessageCaption")
 {
     ChatId    = chatId;
     MessageId = messageId;
     Caption   = caption;
 }
    public override string ToString()
    {
        var  sb      = new StringBuilder("TMessageReadRange(");
        bool __first = true;

        if (ChatId != null && __isset.chatId)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("ChatId: ");
            ChatId.ToString(sb);
        }
        if (Ranges != null && __isset.ranges)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("Ranges: ");
            Ranges.ToString(sb);
        }
        sb.Append(")");
        return(sb.ToString());
    }
Beispiel #29
0
 public override byte[] ToBytes()
 {
     return(TLUtils.Combine(
                TLUtils.SignatureToBytes(Signature),
                ChatId.ToBytes(),
                Title.ToBytes()));
 }
Beispiel #30
0
        public async void EditMessageTextAsync(ChatId chatId, int messageId, string text, ParseMode parseMode = ParseMode.Default, bool disableWebPagePreview = false, InlineKeyboardMarkup replyMarkup = null, CancellationToken cancellationToken = default)
        {
            try
            {
                //Markdown cant parse single _ symbol so we need change it  to \\_
                if (parseMode == ParseMode.Markdown || parseMode == ParseMode.MarkdownV2)
                {
                    text = text.Replace("_", "\\_");
                }

                await Bot.EditMessageTextAsync(chatId, messageId, text, parseMode, disableWebPagePreview, replyMarkup, cancellationToken);
            }
            catch (Exception ex)
            {
                if (ex is MessageIsNotModifiedException)
                {
                    return;
                }

                Log.Error(ex, "EditMessageTextAsync error");

                if (replyMarkup != null)
                {
                    var data = JsonConvert.SerializeObject(replyMarkup);
                    Log.Error(ex, $"EditMessageTextAsync error data: {data}");
                }
            }
        }