使用pub / sub时,交互式按钮无法正常工作

时间:2018-04-11 22:52:46

标签: hangouts-chat

我在C#中编写了一个使用pub / sub的环聊聊天机器人,因此我可以在防火墙一侧托管机器人。除了卡片内的交互式按钮外,一切似乎都运行良好。如果我创建一个具有特定操作方法名称的按钮,则bot会收到带有相应操作方法名称的CARD_CLICKED消息。但是,环聊聊天应用中的卡片似乎不知道是否发送了响应,因为在环聊聊天应用最终说“#34;无法联系Bot”之前,机器人最终获得了三次CARD_CLICKED消息。稍后再试一次"。我一直在使用NuGet的Google.Apis.HangoutsChat.v1和Google.Cloud.PubSub.V1软件包。

这是猜测,但似乎问题可能是交互式按钮无法通过pub / sub正常工作。任何帮助将不胜感激。

以下是我的代码片段:

SubscriptionName subscriptionName = new SubscriptionName(PROJECT_ID, SUBSCRIPTION_ID);
SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();

GoogleCredential credential = GoogleCredential.FromFile(CREDENTIALS_PATH_ENV_PROPERTY).CreateScoped(HANGOUTS_CHAT_API_SCOPE);
HangoutsChatService chatService = new HangoutsChatService(new BaseClientService.Initializer
{
    ApplicationName = "My Bot",
    HttpClientInitializer = credential
});

while (true)
{
    PullResponse response = client.Pull(subscriptionName, false, 3, CallSettings.FromCallTiming(CallTiming.FromExpiration(Expiration.FromTimeout(TimeSpan.FromSeconds(90)))));

    if ((response.ReceivedMessages == null) || (response.ReceivedMessages.Count == 0))
        Console.WriteLine("Pulled no messages.");
    else
    {
        foreach (ReceivedMessage message in response.ReceivedMessages)
        {
            try
            {
                byte[] jsonBytes = message.Message.Data.ToByteArray();
                JObject json = JObject.Parse(Encoding.UTF8.GetString(jsonBytes));

                string messageType = (string)json["type"];
                switch (messageType)
                {
                    case "MESSAGE":
                    {
                        // Get text
                        string messageText = (string)json["message"]["text"];
                        Console.WriteLine($"[{messageType}] {messageText}");

                        // Send response
                        string spaceName = (string)json["space"]["name"];
                        SpacesResource.MessagesResource.CreateRequest request = chatService.Spaces.Messages.Create(new Message
                        {
                            Cards = new[]
                            {
                                new Card
                                {
                                    Header = new CardHeader
                                    {
                                        Title = "Message Received!"
                                    },
                                    Sections = new[]
                                    {
                                        new Section
                                        {
                                            Widgets = new[]
                                            {
                                                new WidgetMarkup
                                                {
                                                    Buttons = new[]
                                                    {
                                                        new Button
                                                        {
                                                            TextButton = new TextButton
                                                            {
                                                                Text = "Click Me!",
                                                                OnClick = new OnClick
                                                                {
                                                                    Action = new FormAction
                                                                    {
                                                                        ActionMethodName = "ClickedAction"
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            },
                            Thread = new Thread
                            {
                                Name = (string)json["message"]["thread"]["name"]
                            }
                        }, spaceName);
                        Message responseMsg = request.Execute();

                        break;
                    }
                    case "CARD_CLICKED":
                    {
                        string actionMethodName = (string)json["action"]["actionMethodName"];
                        Console.WriteLine($"[{messageType}] {actionMethodName} at {((DateTime)json["message"]["createTime"]).ToString()}");

                        // Send response
                        string spaceName = (string)json["space"]["name"];
                        SpacesResource.MessagesResource.CreateRequest request = chatService.Spaces.Messages.Create(new Message
                        {
                            ActionResponse = new ActionResponse
                            {
                                Type = "UPDATE_MESSAGE"
                            },
                            Text = $"You clicked on '{actionMethodName}'.",
                            Thread = new Thread
                            {
                                Name = (string)json["message"]["thread"]["name"]
                            }
                        }, spaceName);
                        Message responseMsg = request.Execute();

                        break;
                    }
                    default:
                    {
                        Console.WriteLine($"[{messageType}]");
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing message: {ex}");
            }
        }

        // Acknowledge the message so we don't see it again.
        string[] ackIds = new string[response.ReceivedMessages.Count];
        for (int i = 0; i < response.ReceivedMessages.Count; ++i)
            ackIds[i] = response.ReceivedMessages[i].AckId;
        client.Acknowledge(subscriptionName, ackIds);
    }
}

1 个答案:

答案 0 :(得分:0)

在环聊聊天API中使用按钮需要自定义答案,包括:

{
    'thread': {
        'name': thread_id
    },
    'actionResponse': {
        'type': 'UPDATE_MESSAGE'
    }
}

我建议将环聊聊天API与机器人网址一起使用。