自定义 Slack 命令到 return 状态 200 并触发另一个作业

Custom Slack Command to return status 200 and trigger another job

我正在构建一个使用 Azure Functions 的自定义松弛命令,问题是该作业需要超过 3 秒才能完成,这将触发自定义松弛命令超时。

我的问题是,我怎样才能用 200 状态响应 Slack 并触发我的工作来获得一些很酷的东西。

我正在使用 "Slack.Webhooks" 以便能够向 slack 发送一条包含所有酷数据的单独消息。

这是我的代码:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Slack.Webhooks;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace WinRatio
{
    public class GetMachines
    {
        [FunctionName("GetMachines")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req,
            ILogger log)
        {
            var formData = await req.Content.ReadAsFormDataAsync();
            req.CreateResponse(HttpStatusCode.OK);

            Console.WriteLine(formData["text"]);
            Console.WriteLine($"Response URL: '{formData["response_url"]}'");

            MachineInstructions machineInstructions = new MachineInstructions();
            machineInstructions.doCoolStuff(); 

            var slackResponseHook = formData["response_url"];
            var slackClient = new SlackClient(slackResponseHook);

            var slackMessage = new SlackMessage
            {
                Text = "We found some Machines for you",
            };

            var slackAttachment = new SlackAttachment
            {
                Fallback = "Place down the street",
                Text = $"Machine: {machineInstructions.Rooms[0]}",
            };

            slackMessage.Attachments = new List<SlackAttachment> { slackAttachment };
            slackClient.Post(slackMessage);

            return new OkResult();
        }
    }
}

您的需求请参考以下代码:

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Threading;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("do what you want before the job");

    DoYourJob(log);  //do your job in this method

    return new OkResult();  //return 200 status to slack
}

public static async void DoYourJob(ILogger log)
{
    await Task.Run(() =>
    {
        log.LogInformation("do your job, it can be completed more than 3 seconds");
        //Thread.Sleep(3000);
    });
}

希望对您的需求有所帮助~