0

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

我的问题是,我如何以 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();
        }
    }
}

4

1 回答 1

0

对于您的要求,请参考以下代码:

#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);
    });
}

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

于 2019-11-15T06:23:52.913 回答