Exemplo n.º 1
0
        private async void OnDirectMessageReceived(DirectMessageEvent obj)
        {
            _logger.LogInformation(
                $"Direct Message from {obj.Sender.Name} (@{obj.Sender.ScreenName}): {obj.MessageText}");

            // Important: Ignore messages originating from the bot else recursion happens
            if (obj.Sender.ScreenName == _options.BotUsername)
            {
                return;
            }

            if (_options.AllowedUsernamesConfigured() &&
                _options.AllowedUsernames.Contains(obj.Sender.ScreenName) ||
                !_options.AllowedUsernamesConfigured())
            {
                // Only respond if sender is different than the bot
                await _bot.OnTurnAsync(new TurnContext(_adapter, new Activity
                {
                    Text = obj.MessageText,
                    Type = "message",
                    From = new ChannelAccount(obj.Sender.Id, obj.Sender.ScreenName),
                    Recipient = new ChannelAccount(obj.Recipient.Id, obj.Recipient.ScreenName),
                    Conversation = new ConversationAccount {
                        Id = obj.Sender.Id
                    },
                    ChannelId = "twitter"
                }));
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Intercept incoming requests to the server to handle them according to Twitter Documentation, Currently:
        ///     - Challenge Response Check.
        ///     - Incoming DirectMessage.
        /// </summary>
        /// <param name="requestMessage">Thr request message object you recieved.</param>
        /// <param name="OnDirectMessageRecieved">If this is an incoming direct message, this callback will be fired along with the message object <see cref="DirectMessageEvent"/>.</param>
        /// <returns>
        /// <see cref="InterceptionResult"/> Interception result.
        /// </returns>
        public async Task <InterceptionResult> InterceptIncomingRequest(HttpRequestMessage requestMessage, Action <DirectMessageEvent> OnDirectMessageRecieved)
        {
            if (string.IsNullOrEmpty(ConsumerSecret))
            {
                throw new TweetyException("Consumer Secret can't be null.");
            }

            if (requestMessage.Method == HttpMethod.Get)
            {
                Dictionary <string, string> requestParams = requestMessage.RequestUri.GetParams();
                if (!requestParams.ContainsKey("crc_token"))
                {
                    goto Finally;
                }

                // Challenge Response Check Request:
                string crcToken = requestParams["crc_token"];
                HttpResponseMessage response = AcceptChallenge(crcToken);

                return(InterceptionResult.CreateHandled(response, requestMessage));
            }
            else if (requestMessage.Method == HttpMethod.Post)
            {
                if (!requestMessage.Headers.Contains("x-twitter-webhooks-signature"))
                {
                    goto Finally;
                }

                string payloadSignature = requestMessage.Headers.GetValues("x-twitter-webhooks-signature").First();
                string payload          = await requestMessage.Content.ReadAsStringAsync();


                bool signatureMatch = IsValidTwitterPostRequest(payloadSignature, payload);
                if (!signatureMatch)
                {
                    //This is interseting, a twitter signature key 'x-twitter-webhooks-signature' is there but it's wrong..!
                    return(InterceptionResult.CreateHandled(new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest), requestMessage));
                }

                try
                {
                    WebhookDMResult    dmResult    = JsonConvert.DeserializeObject <WebhookDMResult>(payload);
                    DirectMessageEvent eventResult = dmResult;
                    eventResult.JsonSource = payload;

                    OnDirectMessageRecieved?.Invoke(eventResult);
                }
                catch
                {
                    //Failed to deserialize twitter direct message,
                    //TODO: Handle in a better way.. perhaps send the json?
                }
            }

Finally:
            return(InterceptionResult.CreateUnhandled(OK(), requestMessage));
        }
        /// <summary>
        /// Intercept incoming requests to the server to handle them according to Twitter Documentation, Currently:
        ///     - Challenge Response Check.
        ///     - Incoming DirectMessage.
        /// </summary>
        /// <param name="requestMessage">Thr request message object you received.</param>
        /// <param name="OnDirectMessageRecieved">If this is an incoming direct message, this callback will be fired along with the message object <see cref="DirectMessageEvent"/>.</param>
        /// <returns>
        /// <see cref="InterceptionResult"/> Interception result.
        /// </returns>
        public async Task <InterceptionResult> InterceptIncomingRequest(HttpRequest requestMessage, Action <DirectMessageEvent> OnDirectMessageRecieved)
        {
            if (string.IsNullOrEmpty(ConsumerSecret))
            {
                throw new TwitterException("Consumer Secret can't be null.");
            }

            if (HttpMethods.IsGet(requestMessage.Method))
            {
                if (!requestMessage.Query.TryGetValue("crc_token", out var values))
                {
                    return(InterceptionResult.CreateUnhandled());
                }

                // Challenge Response Check Request:
                var crcToken = values.First();
                var response = AcceptChallenge(crcToken);
                return(InterceptionResult.CreateHandled(response));
            }
            else if (HttpMethods.IsPost(requestMessage.Method))
            {
                if (!requestMessage.Headers.TryGetValue("x-twitter-webhooks-signature", out var header))
                {
                    return(InterceptionResult.CreateUnhandled());
                }

                var payloadSignature = header.First();
                var streamReader     = new StreamReader(requestMessage.Body);
                var payload          = await streamReader.ReadToEndAsync();


                var signatureMatch = IsValidTwitterPostRequest(payloadSignature, payload);
                if (!signatureMatch)
                {
                    //This is intersecting, a twitter signature key 'x-twitter-webhooks-signature' is there but it's wrong..!
                    //return InterceptionResult.CreateHandled(new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest), requestMessage);
                    throw new TwitterException("Invalid signature");
                }

                try
                {
                    var dmResult = JsonConvert.DeserializeObject <WebhookDMResult>(payload);
                    DirectMessageEvent eventResult = dmResult;
                    eventResult.JsonSource = payload;

                    OnDirectMessageRecieved?.Invoke(eventResult);
                    return(InterceptionResult.CreateHandled(string.Empty));
                }
                catch
                {
                    return(InterceptionResult.CreateHandled(string.Empty));
                    //Failed to deserialize twitter direct message,
                    //TODO: Handle in a better way.. perhaps send the json?
                }
            }
            return(InterceptionResult.CreateUnhandled());
        }
 private Activity RequestToActivity(DirectMessageEvent obj)
 {
     return(new Activity
     {
         Text = obj.MessageText,
         Type = "message",
         From = new ChannelAccount(obj.Sender.Id, obj.Sender.ScreenName),
         Recipient = new ChannelAccount(obj.Recipient.Id, obj.Recipient.ScreenName),
         Conversation = new ConversationAccount {
             Id = obj.Sender.Id
         },
         ChannelId = "twitter"
     });
 }
        public async Task ProcessActivityShouldSucceed()
        {
            var adapter            = new TwitterAdapter(_testOptions.Object);
            var directMessageEvent = new DirectMessageEvent();
            var bot = new Mock <IBot>();

            directMessageEvent.MessageText          = "test message text";
            directMessageEvent.Sender               = new TwitterUser();
            directMessageEvent.Recipient            = new TwitterUser();
            directMessageEvent.Sender.Id            = string.Empty;
            directMessageEvent.Sender.ScreenName    = string.Empty;
            directMessageEvent.Recipient.Id         = string.Empty;
            directMessageEvent.Recipient.ScreenName = string.Empty;
            bot.SetupAllProperties();

            await adapter.ProcessActivity(directMessageEvent, bot.Object.OnTurnAsync);

            bot.Verify(b => b.OnTurnAsync(It.IsAny <TurnContext>(), It.IsAny <CancellationToken>()), Times.Once);
        }
Exemplo n.º 6
0
        private async void OnDirectMessageReceived(DirectMessageEvent obj)
        {
            _logger.LogInformation(
                $"Direct Message from {obj.Sender.Name} (@{obj.Sender.ScreenName}): {obj.MessageText}");

            // Important: Ignore messages originating from the bot else recursion happens
            if (obj.Sender.ScreenName == _options.BotUsername)
            {
                return;
            }

            if (_options.AllowedUsernamesConfigured() &&
                _options.AllowedUsernames.Contains(obj.Sender.ScreenName) ||
                !_options.AllowedUsernamesConfigured())
            {
                // Only respond if sender is different than the bot
                await _adapter.ProcessActivity(obj, _bot.OnTurnAsync);
            }
        }
        public async Task ProcessActivity(DirectMessageEvent obj, BotCallbackHandler callback)
        {
            TurnContext context = null;

            try
            {
                var activity = RequestToActivity(obj);
                BotAssert.ActivityNotNull(activity);

                context = new TurnContext(this, activity);

                await RunPipelineAsync(context, callback, default).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await OnTurnError(context, ex);

                throw;
            }
        }