Badge Granting in bulk or for a group of users

(Marcus Baw) #1

So far as I can see there is no facility for granting Badges in bulk except for via the SQL query in the Badge Edit / New Badge page at /admin/badges/

In my Discourse instances we award Badges to people for accolades or for attendance at certain events.

Quite often I find myself wanting to grant badges to a number of users. The group is otherwise arbitrary, ie there is nothing in Discourse’s database that could be used to decide if they should get the badge or not, so a SQL query can’t be used.

I can appreciate this is going to be a low priority feature request (as I reckon it’s maybe a bit of an edge case, and I’m not one of Discourse’s paying customers :slight_smile: ) but I thought I’d ask anyway.

A ‘grant badges’ UI which would let me add a number of users via CSV file would be awesome - something a bit like the Bulk Invite functionality would do the job.

For the time being, and to help anyone else who has the same problem, I currently grant bulk badges in the Rails console using this code:

# start with a list of emails as an array
# I prepare the list from a CSV list I am given of event attendees
# then I use Sublime Text to get it right, before pasting into the rails console)
emails = ["", "", "" ..... etc ]

# initialize blank array for User objects you're going to collect
userlist = [] 

# find emails from the list where there is a matching User in Discourse
emails.each { |e| userlist << User.try(:where, email: e) } # the use of try avoids errors when no match is found

userlist.reject!(:&empty) # get rid of any non-matches which are an empty entry in the array
userlist.flatten! # flatten the array by one level

# BadgeGranter requires the Badge object and the User object to be passed in as parameters
# In our case we were assigning the Badge with the id number 108
userlist.each {|u| BadgeGranter.grant ( Badge.find(108), u ) }

It seems to work and so far hasn’t caused any ‘undocumented features’ or killed the DB



Sounds like a nice feature. Thanks for the code, and we’re also interested in having a similar feature.

(Erlend Sogge Heggen) #3

Another workaround would be to create a group dedicated to a single badge, and use the “badge for all members of a group” query to give these members a badge.

(Marcus Baw) #4

Note to self: the above code should be userlist.reject!(&:empty?)