コード例 #1
0
        /// <summary>
        /// This extension only use only <see cref="ITelegramBotClient"/>, no middleware, so it can't prevent handling by other middlewares in your pipeline.
        /// </summary>
        public static async Task <Update> ReadUpdateAsync(
            this ITelegramBotClient bot,
            ChatId chatId,
            UpdateValidatorDelegate validatorDelegate = null
            )
        {
            var tcs = new TaskCompletionSource <Update>(TaskCreationOptions.RunContinuationsAsynchronously);
            EventHandler <Args.UpdateEventArgs> ev = null;

            ev = (s, e) =>
            {
                var upd = e.Update;
                if (upd.ExtractChatId().Identifier != chatId.Identifier)
                {
                    return;
                }

                var isValid = validatorDelegate?.Invoke(chatId, e.Update) ?? true;
                if (isValid)
                {
                    bot.OnUpdate -= ev;
                    tcs.TrySetResult(e.Update);
                }
            };
            bot.OnUpdate += ev;
            return(await tcs.Task);
        }
コード例 #2
0
 /// <summary>
 /// </summary>
 /// <param name="updateValidator">User delegate to check if Update from current context is fits.
 /// If true - current Update passed to callback result, else - will be processed by other controller actions with lower priority.</param>
 public Task <Update> ReadUpdateAsync(
     UpdateValidatorDelegate updateValidator,
     CancellationToken cancellationToken = default(CancellationToken)
     )
 {
     return(_botExtSingleton.ReadUpdateAsync(_updateContext, updateValidator, cancellationToken));
 }
コード例 #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="updateValidatorDelegate"> If null - use <see cref="DefaultUpdatesValidator"/>.</param>
        /// <returns></returns>
        public async Task ListenUpdateOnce(CancellationToken cancellationToken, UpdateValidatorDelegate updateValidatorDelegate = null)
        {
            updateValidatorDelegate = updateValidatorDelegate ?? DefaultUpdatesValidator;
            var upd = await _updateContext.BotExt.ReadUpdateAsync(updateValidatorDelegate, cancellationToken);

            await ProcessUpdate(_bot, upd);
        }
コード例 #4
0
 public async Task StartListeningUpdates(UpdateValidatorDelegate updateValidatorDelegate = null)
 {
     ThrowIfKeyboardWasntShown();
     updateValidatorDelegate = updateValidatorDelegate ?? DefaultUpdatesValidator;
     if (_listeningTokenSource != null)
     {
         throw new Exception("Listening was started before.");
     }
     _listeningTokenSource = new CancellationTokenSource();
     while (!_listeningTokenSource.Token.IsCancellationRequested)
     {
         try
         {
             await ListenUpdateOnce(_listeningTokenSource.Token, updateValidatorDelegate);
         }
         catch (TaskCanceledException ex)
         {
             if (!_listeningTokenSource.Token.IsCancellationRequested)
             {
                 throw;
             }
             break;
         }
     }
 }
コード例 #5
0
        /// <summary>
        /// </summary>
        /// <param name="updateContext">Current command context. Needed to find TaskCompletionSource of current command.</param>
        /// <param name="updateValidator">User delegate to check if Update from current context is fits.
        /// If true - current Update passed to callback result, else - will be processed by other controller actions with lower priority.</param>
        public async Task <Message> ReadMessageAsync(
            UpdateContext updateContext,
            UpdateValidatorDelegate updateValidator,
            CancellationToken cancellationToken
            )
        {
            var res = await ReadUpdateAsync(updateContext, updateValidator, cancellationToken);

            return(res.Message);
        }
コード例 #6
0
        /// <summary>
        /// </summary>
        /// <param name="updateContext">Current command context. Needed to find TaskCompletionSource of current command.</param>
        /// <param name="fromType">Used to set which members messages must be processed.</param>
        public async Task <Message> ReadMessageAsync(
            UpdateContext updateContext,
            ReadCallbackFromType fromType,
            CancellationToken cancellationToken
            )
        {
            UpdateValidatorDelegate updateValidator = async(newCtx, origCtx) =>
            {
                return(CheckFromType(newCtx, origCtx, fromType));
            };

            return(await ReadMessageAsync(updateContext, updateValidator, cancellationToken));
        }
コード例 #7
0
        public async Task <Update> ReadUpdateAsync(
            UpdateContext updateContext,
            UpdateValidatorDelegate updateValidator,
            CancellationToken cancellationToken
            )
        {
            var taskCompletionSource = new TaskCompletionSource <Update>(
                TaskContinuationOptions.RunContinuationsAsynchronously
                );

            var searchData = Add(updateContext, taskCompletionSource, updateValidator);

            //OnCanceled.
            cancellationToken.Register(() =>
            {
                SetCancelled(searchData);
            });

            var resUpdate = await taskCompletionSource.Task;

            return(resUpdate);
        }
コード例 #8
0
        UpdateContextSearchData Add(UpdateContext updateContext, TaskCompletionSource <Update> taskCompletionSource, UpdateValidatorDelegate updateValidator)
        {
            var chatId   = updateContext.ChatId.Identifier;
            var botId    = updateContext.Bot.BotId;
            var prevData = _searchBag.TryRemove(chatId, botId);

            if (prevData != null)
            {
                _logger.LogInformation(
                    "UpdateContext '{0}' cancelled while adding new context with same chatId and botId.",
                    prevData.Value.CurrentUpdateContext
                    );
                SetCancelled(prevData.Value);
            }
            var sd = new UpdateContextSearchData
            {
                CurrentUpdateContext = updateContext,
                ChatId = chatId,
                BotId  = botId,
                TaskCompletionSource = taskCompletionSource,
                UpdateValidator      = updateValidator
            };

            _searchBag.Add(sd);
            _logger.LogTrace(
                "UpdateContext '{0}' added to SearchBag of read-callbacks.",
                updateContext
                );
            return(sd);
        }
コード例 #9
0
        /// <summary>
        /// Note: Current middleware is registered automatically.
        /// </summary>
        public static void AddBotExtGlobalValidator(this IPipelineBuilder @this, UpdateValidatorDelegate updateValidator)
        {
            var botExtSingletone = @this.ServiceProvider.GetRequiredService <IBotExtSingleton>();

            botExtSingletone.GlobalValidators.Add(updateValidator);
        }