I’ve been able to send a Python chat message to a google chat webhook by following the instructions provided by Google.
Now, my goal is to implement this solution in a C# application. Instead of using classic HttpClient
with POST
requests, I’m trying to use the official nuget packages.
How do you use the nuget library to connect with a webhook (not with credentials or API Keys) ?
using Google.Apis.HangoutsChat.v1;
using Google.Apis.HangoutsChat.v1.Data;
using Google.Apis.Services;
public class GoogleChatNotification
{
private string _key;
private string _token;
private string _space_id;
public GoogleChatNotification(string webhook)
{
if (webhook.IsNullOrWhiteSpace())
throw new Exception("Webhook can't be empty");
//Google chat webhook format : "https://chat.googleapis.com/v1/spaces/{space_id}/messages?key={key}&token={token}"
Uri webHookUri = new Uri(webhook);
var queryDictionary = System.Web.HttpUtility.ParseQueryString(webHookUri.Query);
_key = queryDictionary["key"];
_token = queryDictionary["token"];
_space_id = webHookUri.Segments[2] + webHookUri.Segments[3].Replace("/","");
}
public async Task SendMessage(string message, string? threadId)
{
var service = new HangoutsChatService(new BaseClientService.Initializer()
{
ApplicationName = "MyApp",
ApiKey = _key
}); //<= Throw an credential error ! How do you connect with a webhook URL ?
var pubSubMessage = new Message
{
Text = message,
Thread = new Google.Apis.HangoutsChat.v1.Data.Thread() { Name = threadId },
Sender = new User() { Name = "MyApp Bot", DisplayName = "MyApp Bot", Type = "BOT" }
};
SpacesResource.MessagesResource.CreateRequest req = new SpacesResource.MessagesResource(service).Create(pubSubMessage, _space_id);
await req.ExecuteAsync();
}
}
Thank for you support.