Lookup user id from username or email address

I have the archive of our old news feed as JSON, which I want to use to populate the News category of our new forum; all the posts in the feed were made by users who already have forum accounts. The most straightforward way to do this seems to be to modify the generic JSON importer to lookup existing users (either by username or email address) rather than create new users.

It looks as though I could supply an empty users list in my input JSON to avoid creating any new users, and then change the line in /srcipts/import_scripts/json_generic.rb which sets the user id for each post:

user_id: user_id_from_imported_user_id(username_for(first_post["author"])) || -1

So I need to replace the value of this key-value pair with something that gets the existing user id, rather than looking up the id of a user created earlier by the importer.

How do I look up the id of an existing user, either from the username or email address?

It can be done with the API.

I’m aware I can lookup users vai the JSON API, but as I’m doing this from Ruby that Discourse is running itself, wouldn’t it be more straightforward to call the function I need directly rather than mess with a call to the JSON API? Is that really the recommended way to do this? I see no use of the JSON API anywhere else in the importers I’ve looked at.

It has been a long time since I imported into Discourse, so I’m not sure, but maybe someone else knows. I sometimes have to look up users by email and ID in bulk, so I’ve been using the API.

What I was looking for turned out to be this:

User.find_by_username(username)&.id