API call to watch categories and tags


(Robert) #1

Hello,

I added a new watch-by-default category and have to add it to the watching list of all existing accounts. I have not found a correponding API call in our How-to: Discourse API Documentation

I am also looking for an API call to add given tags to the watch list for a given account.

All the best,
Robert


(Tobias Eigen) #2

You might want to take a look at this:


(Robert) #3

Based on the plugin, I wrote a ruby snippet to execute in the rails console (get a shell in your docker using ./launcher enter app and then rails c).

# based on https://github.com/discourse/discourse-watch-category-mcneel/blob/master/plugin.rb

# let a group watch or watch_first_post a category

group_name = "trust_level_0"
category_slug = "news"

group = Group.find_by_name(group_name)
category = Category.find_by_slug(category_slug)

unless category.nil? || group.nil?
  group.users.each do |user|
    # levels: :watching :watching_first_post
    level = :watching_first_post
    watched_categories = CategoryUser.lookup(user, level).pluck(:category_id)
    CategoryUser.set_notification_level_for_category(user, CategoryUser.notification_levels[level], category.id) unless watched_categories.include?(category.id)
  end
end

I had some troubles when I pasted the code into the console due to less that displays the results of the query for the group and category and consumes apparently some following code lines.


(Robert) #4

The same for tags, but yet untested:

# based on https://github.com/discourse/discourse-watch-category-mcneel/blob/master/plugin.rb

# watch tag

group_name = "trust_level_0"
tag_name = "newstag"

group = Group.find_by_name(group_name)
tag = Tag.find_by_name(tag_name)

unless tag.nil? || group.nil?
  group.users.each do |user|
    # levels: :watching :watching_first_post
    level = :watching_first_post
    watched_tags = TagUser.lookup(user, level).pluck(:tag_id)
    TagUser.change(user.id, tag.id, TagUser.notification_levels[level]) unless watched_tags.include?(tag.id)
  end
end