Using the discourse_api gem to award a badge

In my previous post I covered how to use curl to grant a user a badge in Discourse and in this post I’m going to cover how to award a badge using the discourse_api gem. If you haven’t been following along I’m working on a way to automatically check if I go to the gym and award myself a badge if I do so.

Luckily awarding a badge is already part of the discourse_api gem code base, but I do think I’ll update it a bit so that the parameters it accepts are actually mentioned.

For my ruby script I first initiate the discourse_api client, then I populate my badge hash, which I then pass into the grant_user_badge method.

require 'yaml'
require 'discourse_api'

@config = YAML.load_file('config.yml')
site = ENV['SITE']

client = DiscourseApi::Client.new(@config[site]['host'])
client.api_key = @config[site]['api_key']
client.api_username = @config[site]['api_username']

badge = {
  badge_id: 104,
  username: 'blake'
}

client.grant_user_badge(badge)

The next steps on my list to finish this little project of mine it to combine the golds_checkin code with this granting badge script and setup a cron job on my server for it to run once a day.