7

How can you find the tags created by a given user ID? I couldn't figure this query out in sede.

I'm aware that if the user has a Taxonomist badge you can find one such tag by visiting https://stackoverflow.com/help/badges/11/taxonomist?userid=1, but it's very limited because the badge can only be awarded once and the tag needs 50 questions associated.

1
  • 1
    I'm not sure you can. The Tags table has the ExerptPostID and WikiPostID values, however, the owner of those posts might not be the creator of the tag. The Badges table is present, but it doesn't tell you what tag that is related to specifically.
    – Thom A
    Oct 7, 2021 at 16:13

2 Answers 2

6

Just as Robert Longson mentioned in the other answer, getting who created a tag is a non-trivial matter. This answer supplements theirs by providing another solution via the API in an interactive manner. In contrast to the other answer, this one uses a different set of heuristics for greater accuracy (as implementing each is a bit cumbersome, please expect updates to the answer).

So, a given user is considered to be the creator of a tag itself if one of the following is true:

  1. the user posted a question tagged with the tag, the question is the earliest one with that tag and hasn't been edited since (implemented)
  2. the user made an edit adding the tag, the revision is the earliest one with that tag, and #1 is not true (not implemented yet)

A word of warning: this might get heavy depending on the activity of the user and easily eat up through a significant chunk of your daily API quota (10 000 requests with an API key). The heaviest part is requesting the earliest questions tagged with a given tag.

The following is a GUI implementing the above (the default user id is a guaranteed hit):

const API_VER = 2.3;
const API_BASE = "https://api.stackexchange.com";
const API_KEY = "zhhhBNmsqZLZ967tc2dn8w((";

const delay = (s) => new Promise((r) => setTimeout(r, s*1e3));

const searchEarlyQuestions = async ({
    key,
    site = "stackoverflow",
    ...rest
}) => {
    const url = new URL(`${API_BASE}/${API_VER}/search`);

    const params = new URLSearchParams({
        key,
        site,
        order: "asc",
        sort: "creation",
        ...rest,
    });

    url.search = params.toString();
    const res = await fetch(url.toString());
    if (!res.ok) return [];

    const { items = [], backoff } = await res.json();
    if (backoff) {
        await delay(backoff);
        return searchEarlyQuestions({
            key,
            site,
            ...rest,
        });
    }
    return items;
};

const getUserQuestions = async (userId, {
    key,
    site = "stackoverflow",
    page = 1,
    ...rest
}) => {
    const url = new URL(`${API_BASE}/${API_VER}/users/${userId}/questions`);

    const params = new URLSearchParams({
        key,
        site,
        page,
        ...rest,
    });

    url.search = params.toString();
    const res = await fetch(url.toString());
    if (!res.ok) return [];

    const { items = [], backoff, has_more } = await res.json();
    
    if (backoff) {
        await delay(backoff);
        return getUserQuestions(userId, {
            key,
            site,
            page,
            ...rest,
        });
    }
    
    if (has_more) {
        items.push(
            ...(await getUserQuestions(userId, {
                key,
                site,
                page: page + 1,
                ...rest,
            }))
        );
    }
    return items;
};

const getTags = async (names, {
    key,
    site = "stackoverflow",
    page = 1,
    ...rest
}) => {
    const url = new URL(`${API_BASE}/${API_VER}/tags/${names.join(";")}/info`);

    const params = new URLSearchParams({
        key,
        site,
        page,
        ...rest,
    });

    url.search = params.toString();
    const res = await fetch(url.toString());
    if (!res.ok) return [];

    const { items = [], has_more = false, backoff } = await res.json();
    
    if (backoff) {
        await delay(backoff);
        return getTags(names, {
            key,
            site,
            page,
            ...rest,
        });
    }

    if (has_more) {
        items.push(
            ...(await getTags(names, {
                key,
                site,
                page: page + 1,
                ...rest,
            }))
        );
    }
    return items;
};

const makeCell = (content) => {
  const td = document.createElement("td");
  td.append(content);
  return td;
};

const makeRow = (columns) => {
  const tr = document.createElement("tr");
  const cells = columns.map(makeCell);
  tr.append(...cells);
  return tr;
};

const makeLink = (url, label) => {
  const a = document.createElement("a");
  a.target = "_blank";
  a.href = url;
  a.innerText = label;
  return a;
};

const uniqify = (arr) => [...new Set(arr)];

window.addEventListener("load", () => {
  const useridInput = document.getElementById("user_id");
  const hostnameInput = document.getElementById("host");
  const progress = document.getElementById("load");

  const submit = document.getElementById("search");
  submit.addEventListener("click", async() => {
    progress.value = 0;
  
    const { value: userId } = useridInput;
    const { value: hostname } = hostnameInput;
    
    const apiSlug = hostname.slice(0, hostname.lastIndexOf("."));
    
    console.log({ apiSlug });

    const report = document.querySelector("#preview > tbody");
    
    const commonOpts = {
      key: API_KEY,
      pagesize: 100,
      site: apiSlug
    };
    
    const questions = await getUserQuestions(userId, {
        ...commonOpts,
        filter: "!.FdHWl*M9(MQSmLP_ZZzycLIeIL6j",
    });
    
    progress.value = 10;
  
    console.log({ questions });
    
    const notEditedQuestions = questions.filter(
      ({ last_edit_date }) => (!last_edit_date)
    );
    
    console.log({ notEditedQuestions });
    
    progress.value = 20;
    
    const notEditedTags = uniqify(
      notEditedQuestions
        .flatMap(({ tags = [] }) => tags)
        .filter(Boolean) // just in case
    );
    
    console.log({ notEditedTags });
    
    // since SE API treats user ids as numbers...
    const numUserId = +userId;
    
    const tagCreationStatuses = [];
    
    const step = 70 / notEditedTags.length;
    
    let simultaneousReqs = 0;
    let throttles = 0;
    for(const tagged of notEditedTags) {
      simultaneousReqs += 1;
    
      const [earliest] = await searchEarlyQuestions({
        ...commonOpts, tagged,
        filter: "!.FdHWl*M9(MQSmLP_ZZzycLIeIL6j",
      });    
      
      tagCreationStatuses.push(
        earliest.owner.user_id === numUserId
      )
      
      if(simultaneousReqs > 10) {
        throttles += 1;
        await delay(1.1);
        console.log(`${throttles} throttled for 1.1s`);
        simultaneousReqs = 0;
      }
      
      progress.value += step;
    }
    
    console.log({ tagCreationStatuses });
   
    const userCreatedTags = notEditedTags.filter((_,i) => tagCreationStatuses[i]);
    
    console.log({ userCreatedTags });
    
    const tags = userCreatedTags.length ? await getTags(userCreatedTags, commonOpts) : [];
    
    console.log({ tags });
    
    progress.value = 100;
    
    const rows = tags
      .sort((a, b) => b.count - a.count)
      .map(({
        name, count, is_required, is_moderator_only
      }) => makeRow([
        makeLink(`https://${hostname}/tags/${name}`,name),
        count,
        is_required ? "Yes": "No",
        is_moderator_only ? "Yes": "No"
      ]));

    report.querySelectorAll("tr").forEach((r) => r.remove());
    report.append(...rows);

    report.closest("table").classList.remove("hidden");
  });

});
label {
  display: block;
  font-weight: 600;
}

caption,
label {
  font-weight: 600;
  margin: 1vh 0;
}

table {
  margin-top: 4vh;
  border-collapse: collapse;
}

th,
td {
  padding: 2vh 2vw;
  border: 1px solid lightgray;
}

.hidden {
  display: none;
}
<form>
  <label for="host">Hostname</label>
  <input id="host" type="text" title="Hostname" placeholder="host.com" value="stackoverflow.com" />

  <label for="user_id">User Id</label>
  <input id="user_id" type="text" title="User Id" placeholder="12345" value="3904066" />
  <button id="search" type="button">Get Info</button>
</form>

<progress id="load" max="100" value="0"></progress>

<table id="preview" class="hidden" cellspacing="0">
  <caption>Tags created by the user</caption>
  <thead>
    <tr>
      <th>Tag</th>
      <th>Questions</th>
      <th>Required?</th>
      <th>Mod-only?</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

6
  • Does not seem to work for me (674039), the progress bar goes about 3/4 the way and then gets stuck.
    – wim
    Oct 9, 2021 at 18:26
  • @wim - I used to have a special note for you here :) Unfortunately, your case results in 191 lookup but I thought I addressed that so as the API does not start dropping requests. Worked on you yesterday, though - let me try. Oct 9, 2021 at 18:31
  • Hmm, mine got way further before getting hard-dropped (with a CORS error) but still got dropped, so I assume the API is getting fed up even with 15 simultaneous requests today (albeit promising up to 30 to be considered ok) - let me throttle that down to 10 at a time and see Oct 9, 2021 at 18:36
  • hmmm, throttling down to 10 per second did not help. CORS starts to fail today after about ~180 requests are made. There was a bug in late 2019 that caused the same error to happen at around the same number of requests no matter the code properly throttling itself. I am going to ask around and see if it resurfaced again, odd. Oct 9, 2021 at 18:46
  • @wim after some deliberation, I reported it on MSE - seems to be related to what rene, Makyen and Machavity reported before about the API. The requests intermittently succeed - sometimes they fail at around 176 successes, sometimes after 50 if restarting after a successful run. Let's see how it goes! Oct 9, 2021 at 20:21
  • For posterity: meta.stackexchange.com/questions/370711/…
    – wim
    Oct 19, 2021 at 17:39
3

The best you can do is look at the tags table. That gets you the wiki and excerpt IDs. You can then find the creators of those from the posts table i.e.

SELECT Tags.TagName, posts.ownerUserId as [User Link], posts2.ownerUserId as [User Link]
FROM Tags  
    INNER JOIN Posts ON tags.ExcerptPostId = Posts.id  
    INNER JOIN Posts as Posts2 ON tags.WikiPostId = Posts2.id  
Where Posts.ownerUserId = '##userId##' or Posts2.ownerUserId = '##userId##'

Or you can just run this.

That's often accurate but the tag might have been created without any wiki or excerpt text, if that was added later then you might need to look at the post history to find when the wiki or excerpt actually had some useful content.

3
  • Doesn't seem to work properly - no results for my userid (674039) even though I know I have created at least one tag (because I have the taxonomist badge).
    – wim
    Oct 9, 2021 at 18:25
  • Are you running the query against Stack Overflow main or here on meta? You've no tags on meta, but you do on the main site. Oct 9, 2021 at 18:53
  • 1
    Oh yeah, that was it. I had just clicked the link, which was meta. Edited the link.
    – wim
    Oct 9, 2021 at 18:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .