避免回显 in_channel 响应的斜杠命令

Avoiding echo of slash command for in_channel responses

我现在正在为我的频道创建一个非常小的斜杠命令。我使用 HTTPS 200 将命令发送到 PHP 脚本,对其进行操作并将其作为 JSON 有效载荷发回,基本上是这样的:

<?php
header('Content-Type: application/json');

$text = $_POST['text'];

if ($text === "keyword") $answer = "Hello World";
else $answer = "Nothing in here";

$response = array(
  'response_type' => 'in_channel',
  'text' => $answer,
);

echo json_encode($response);

现在我不想 post 标题中已经提到的频道中的初始斜杠推荐,但只有服务器的答案应该对频道中的每个人可见。我找不到合适的文章,所以我问自己:这甚至可能吗?

有人有想法吗?

编辑: 我不希望这种松弛也 post 我的命令作为消息。这样频道中只有第二条消息是post: see a screenshot

更新: 我现在已经实施了 Erik Kalkoken 的建议,但是我没有从 curl 函数中得到信号。我还成功地检查了我的网络服务器是否支持 curl 功能。我的代码现在看起来像这样(代码已减少到必要的部分):

<?php
header('Content-Type: application/json');

$response = array(
  'response_type' => 'in_channel',
  'text' => "> \M2\Kunden\_Tutorial"
);

echo json_encode(array('text' => 'One moment...'));

$ch = curl_init($_POST['response_url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
$exec = curl_exec($ch);
curl_close($ch);

有效解决方案: 再次考虑了 Erik Kalkoken 的建议后,还是不行。这并不意味着他说错了什么。相反,我忘记了什么。我发现我的 $response 数组需要编码为 json 字符串。您可以在下面看到一个工作版本。感谢 Erik Kalkoken!

    <?php
    $response = array(
      'response_type' => 'in_channel',
      'text' => '> \M2\Kunden\_Tutorial'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $_POST['response_url']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
    curl_setopt($ch, CURLOPT_POST, 1);
    $headers = array();
    $headers[] = "Content-Type: application/json";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $result = curl_exec($ch);
    curl_close ($ch);

当您使用 response_type 设置为 in_channel 时,斜杠命令的标准行为会响应您的斜杠命令。这通常是有道理的,因此该频道中的人们可以在看到结果之前看到斜杠命令有问题。

没有直接的方法来关闭此回显功能,但有一个简单的解决方法。

不要直接回复 Slack 请求,而是将您的响应作为新请求发送到 response_url,这是您在初始请求中从 Slack 获得的。那么你只会在频道中得到你的回应,斜杠命令本身不会被回显。

顺便说一句。此行为也在 "Sending delayed responses":

部分的 documentation 中进行了解释

As with immediate response messages, you can include the response_type field. However, when you use a value of in_channel with this delayed method, the original text that invoked the command is not included.

我建议使用 curl 将请求发送到 Slack。

在使用 curl 调用更新问题后进行编辑

您仍在 return 直接响应 Slack 请求,这导致 Slack 回显用户命令。除了 200 OK(你的 PHP 脚本会自动执行),你不能 return 任何东西。所以请删除这一行:

echo json_encode(array('text' => 'One moment...'));

我还建议通过添加以下行在 curl 调用中包含正确的内容 header:

curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

开头的 header() php 命令不影响 curl 调用,也可以顺便删除。