Create a direct link to open a conversation with a user at chat.google.com
Asked Answered
N

1

7

I have a list of contacts on my site, each of whom has a valid google account / email address. I want to create a link for each person which, when clicked, will take the user to chat.google.com (not hangouts) and open a conversation with that person.

Looking at the URLs which appear when I open conversations with users in the Google Hangouts chat web app, the format seems to be the following:

https://chat.google.com/u/1/dm/

Is there a way of retrieving this user id for a given google user? If this is possible, will a link of constructed in this way solve the issue, or is there more to consider?

Many thanks in advance.

Nunn answered 4/7, 2019 at 15:52 Comment(1)
For years we tried to do that and never could. We even discarded Hangouts as a contact channel for our clients because of the lack of such a basic feature. After a couple years in which even Whatsapp solved this, we haven't heard of such a solution for Hangouts, I hope you get answered soon. Even making a fast search in developers.google.com/hangouts/chat gave no direct answer for that. I believe this has been a very heavy reason for many developers to discard the use of Hangouts, there are many easier resources for connecting unknown people together, and that seems CRUCIAL for us.Bursary
P
3

I had exactly the same problem (this answer is a bit late, but hopefully helps somebody).

This answer assumes you're in a Google Workspace environment ...

The little token you're looking for is the chat space ID for the two connected users (or however many may be in the chat space). So it's not an ID for the user, rather the users in the chat. If the users in question have not messaged eachother before .. then there is no token to find - but you can create it for them.

If you're looking to get the URL required for UserA to message UserB then you'll need to use a service account to impersonate one or other user.

The service account needs the https://www.googleapis.com/auth/chat.spaces scope and in your workspace admin you'll need to enable Domain-Wide delegation for the service account with that scope.

Then something like this will get you towards a security token you can impersonate a user with:

        
   var service = OAuth2.createService('Chat: ' + email)
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')
      .setPrivateKey('REDACTED') // Key from the .json you get with the service account
      .setIssuer('REDACTED')     // email address of the service account
      .setSubject(email)         // email of the user to impersonate
      .setPropertyStore(PropertiesService.getScriptProperties())
      .setScope("https://www.googleapis.com/auth/chat.spaces");

By adding the Authorization header to the REST calls you can impersonate the first user. You'll then need the ID for the user to connect to. It's a 20 digit number you can find in the Admin Directory.

This will get the ID and primary email for everyone in your organisation

   let pageToken;
   let page;
   do {
      page = AdminDirectory.Users.list({
         customer: 'my_customer',  // this is literally 'my_customer'
         orderBy: 'primaryEmail',
         maxResults: 500,
         projection: 'users(id,primaryEmail)',
         pageToken: pageToken
      });
      const users = page.users;
      for (const user of users) {
         console.log('%s (%s)', user.id, user.primaryEmail);
      }
      pageToken = page.nextPageToken;
   } while (pageToken);

While impersonating the first user we search for a direct message to the second user using the ID for the second user

   var ID = "1XXXXXXXXXXXXXXXXXXXX";
   var requestBody = {};
    // Add the previously fetched service access token
      requestBody.headers = {'Authorization': 'Bearer ' + service.getAccessToken()};
      requestBody.contentType = "application/json";
      requestBody.method = "GET";

   var url = "https://chat.googleapis.com/v1/spaces:findDirectMessage?name=users/" + ID;
   var response = UrlFetchApp.fetch(url, requestBody)

   var HTTPCode = response.getResponseCode();

If that returns 200 in the HTTP response code then you have what you need in the response. If you get a 404 returned it means those two users do not have a direct message between them, so you need to create one.

We only add one user in the memberships as the calling user is implicitly added to the created chat space.

   var postBody = `{
      space: {spaceType: "DIRECT_MESSAGE"},
      memberships: [{member: {name : "users/${ID}", type: "HUMAN"}}]
   }`;
   var requestBody = {};
      requestBody.headers = {'Authorization': 'Bearer ' + service.getAccessToken()};
      requestBody.contentType = "application/json";
      requestBody.method = "POST";
      requestBody.payload = postBody;

   url = 'https://chat.googleapis.com/v1/spaces:setup'
   response = UrlFetchApp.fetch(url, requestBody);

   HTTPCode = response.getResponseCode();

In the successful reponse you can find the name of the space in the form 'spaces/1234567' - strip out the number and you can constuct your URL:

    content = JSON.parse(response.getContentText());
    var token = content.name.split('/')[1]
    var url = "https://chat.google.com/dm/" + token

Note that if you create a direct message chat like this neither user sees anything until a message is added, so it's non-intrusive.

Pedicel answered 15/2 at 16:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.