How to get invite URL from Telegram bot invite link creation

I’m working with a Telegram bot and I can successfully call the createChatInviteLink method, but I’m having trouble getting the actual invite URL from the response. Here’s my current code:

function generateInviteLink(groupId){
  groupId = 'group_id';
  memberLimit = 1;
  var apiCall = botApiUrl + '/createChatInviteLink?chat_id=' + groupId + '&member_limit=' + memberLimit;
  return UrlFetchApp.fetch(apiCall);
}

The function runs without errors, but I can’t figure out how to parse the response and get the invite link that I need to send back to users. What’s the correct way to extract the generated invitation URL from the API response?

Your problem is that UrlFetchApp.fetch() gives you an HTTPResponse object, not the JSON data you want. You need to call getContentText() on the response first, then parse it as JSON to get the invite URL. Right now your code fetches the data but doesn’t actually process it. After you get the response, use JSON.parse(response.getContentText()) to turn it into a usable object, then grab data.result.invite_link for the URL. I hit this same issue building something similar - wasted hours wondering why my function wasn’t returning URLs before realizing I was trying to use the raw response instead of extracting the JSON first.

The Problem:

You’re attempting to extract the invite link from the response of Telegram’s createChatInviteLink method, but your JavaScript code is not correctly parsing the JSON response to retrieve the URL. Your current code fetches the response but doesn’t process the JSON data contained within.

TL;DR: The Quick Fix:

Add JSON parsing to your generateInviteLink function to extract the invite_link from the response data.

function generateInviteLink(groupId){
  groupId = 'group_id'; //Consider making groupId a parameter instead of hardcoding.
  memberLimit = 1;
  var apiCall = botApiUrl + '/createChatInviteLink?chat_id=' + groupId + '&member_limit=' + memberLimit;
  var response = UrlFetchApp.fetch(apiCall);
  var data = JSON.parse(response.getContentText());
  if (data.ok) {
    return data.result.invite_link;
  } else {
    //Handle errors appropriately. Log the error or throw an exception.  Example:
    console.error("Telegram API error:", data.description);  //Access error description if available.
    return null; //Or throw an error: throw new Error("Telegram API error: " + data.description);
  }
}

:thinking: Understanding the “Why” (The Root Cause):

The UrlFetchApp.fetch() method in Google Apps Script returns an HTTPResponse object. This object contains the raw response data, which in this case is a JSON string representing the Telegram API’s response. Your original code was attempting to use the HTTPResponse object directly as if it were already the parsed JSON data, leading to an inability to extract the invite_link. The JSON needs to be parsed into a JavaScript object before you can access the nested properties like result.invite_link.

:gear: Step-by-Step Guide:

  1. Fetch the API Response: Your existing UrlFetchApp.fetch(apiCall) call correctly retrieves the response from the Telegram API. Store this response in a variable: var response = UrlFetchApp.fetch(apiCall);

  2. Parse the JSON Response: Use the JSON.parse() method to convert the response’s text content into a JavaScript object. Note that response.getContentText() extracts the raw response text as a string. Ensure that this step is performed after the UrlFetchApp.fetch() call to avoid errors: var data = JSON.parse(response.getContentText());

  3. Check for Errors: The Telegram API response will typically have an ok field. Check this field to ensure the request was successful. If ok is false, handle the error appropriately. The response might include an error description in a field like description. Log the error, throw an exception, or return a default value.

  4. Extract the Invite Link: If the request was successful (data.ok === true), extract the invite link from the nested result object: return data.result.invite_link;

  5. Return the Invite Link or Handle Errors: Return the extracted invite link or an appropriate value (like null) if an error occurred.

:mag: Common Pitfalls & What to Check Next:

  • Error Handling: Always include comprehensive error handling when interacting with external APIs. Check the ok field of the JSON response and handle errors gracefully. Log the error details for debugging. Ensure the botApiUrl is correctly configured.

  • Authentication: Verify that your bot has the necessary permissions (admin rights) to create invite links for the specified group.

  • Group ID: Double-check that the groupId is correct and in the proper format. Incorrect group IDs will result in API errors.

  • Rate Limits: Be mindful of Telegram’s API rate limits. Excessive requests might temporarily block your bot.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

You’re missing the JSON parsing step. Telegram’s API returns JSON, so you need to extract the invite_link field from the response.

Here’s the fix:

function generateInviteLink(groupId){
  groupId = 'group_id';
  memberLimit = 1;
  var apiCall = botApiUrl + '/createChatInviteLink?chat_id=' + groupId + '&member_limit=' + memberLimit;
  var response = UrlFetchApp.fetch(apiCall);
  var data = JSON.parse(response.getContentText());
  return data.result.invite_link;
}

The response looks like this:

{
  "ok": true,
  "result": {
    "invite_link": "https://t.me/+abc123def456",
    "creator": {...},
    "member_limit": 1
  }
}

That said, handling all these API calls manually gets messy quick. I just automate this whole thing with Latenode instead. You can set up the Telegram bot integration, it handles JSON parsing automatically, and you can trigger invite creation based on different conditions.

With Latenode, you drag and drop the Telegram node, add your bot token, and it parses all responses for you. Way cleaner than writing custom JavaScript.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.