API Filter users by emails, including secondary emails

AI-generated summary

The original poster, oca, is attempting to use the API to filter users by email, including secondary emails. They want to add users with matching emails to a group and remove those without matches. However, the get(/admin/users/list/all.json?email={email}) command only returns users with the specified email as their primary address.

Arkshine suggests using the Data Explorer plugin, which allows creating custom queries. oca successfully implements this solution by creating a query to join the users and user_emails tables and filter by email. They share their query and Python script to execute it using the Discourse API.

Hello,

I would like to match users from a list of email addresses coming from an other app, in order to add all the users to one group, and remove members that are not in the . I’ve got a script doing that from the API.

The removing part is easy. For each member, I extract all their emails with:
get(/u/{username}/emails.json)
and I try to match each one against the list. If there is none, the member is excluded.

The including one is trickier. For each email address, I want to see if there is a user with that address. If there is, I add it to the group. If there is not, I don’t want to send an invite. I use the command:
get(/admin/users/list/all.json?email={email})
but this command returns a list of users with that address as primary, an not the ones with that address as secondary, nor unconfirmed_emails, nor associated_accounts. Is there a way to filter from every possible email addresses, or should I export the list of all users and do that by hand externally ? I would prefer doing it internally so there would be less risks of data leaks.

Thanks !

Hello, welcome back! :wave:

The Data Explorer plugin might be suitable for your use case.

You can use it as an API and create your query based on initial inputs.

Thank you.
I managed to do it with this plugin, using this query:

--[params]
-- string :q_email

SELECT u.username FROM users u JOIN user_emails e ON u.id=e.user_id WHERE e.email = :q_email

And calling it with the python script:

import pydiscourse
client = DiscourseClient('https://forum.com', api_username='system', api_key='1234')
params = '{"q_email":"' + str(email) + '"}'
response = client._request('POST', '/admin/plugins/explorer/queries/{number}/run', params={"params":params})  # Yes, there are 3 params, each one representing something different. Good hacking practice !
username=response["rows"]