@tsk Its very rough draft but this should do it. It grabs the user list based from the tier level/group you specify inside the api section and checks if the user is inside the group, if not it will send a POST API request to the forum and assign the group to that user. The script is in two parts, first handles the API requests (api.py).
import requests, json
Api_Key = "" # your discourse api key
groupName = "NSFW" # name of the group
tier_level = 3
url = "https://forum.0cd.xyz"
def _url(path):
return url + path
def get_group():
return requests.get(_url('/g/{}.json').format(groupName))
def get_group_members():
return requests.get(_url('/g/{}/members.json').format(groupName))
def get_tl_members():
return requests.get(_url('/g/trust_level_{}/members.json').format(tier_level))
def add_users(users, gid):
headers = {'Api-Key': Api_Key, 'content-type':'application/json'}
return requests.put(_url("/g/{}/members.json").format(gid), data=json.dumps({'usernames': ','.join(users)}), headers=headers)
and the second the main logic of the program
#!/usr/bin/env python3
import sys, requests, json, api
def main():
try:
resp = api.get_tl_members()
gid = api.get_group()
if resp.status_code != 200 or gid.status_code != 200:
raise ApiError('Cannot fetch data: tl: {} group: {}'.format(resp.status_code, gid.status_code))
member = []
for users in resp.json()['members']:
if users['username'] not in group():
member.append(users['username'])
api.add_users(member, gid.json()['group']['id'])
except(ApiError, requests.exceptions.ConnectionError) as e:
print(e)
sys.exit(0)
def group():
try:
resp = api.get_group_members()
if resp.status_code != 200:
raise ApiError('Cannot fetch data: {}'.format(resp.status_code))
member = []
for members in resp.json()['members']:
member.append(members['username'])
return member
except(ApiError, requests.exceptions.ConnectionError) as e:
print(e)
sys.exit(0)
class ApiError(Exception): pass
main()
It should work mostly fine except there’s an issue in that the proper way handle the request is broken in Discourse so I’m brute forcing it by iterating over the users and sending a separate API request for each user, this has a downside in that Discourse has a request limit so adding lots of users at once will kill the API requests., haven’t done extensive testing because the only way todo that is in production but tested code works outside of the main for loop and it works fine.
fixed most of the issues above. it now makes a single API request with a list of usernames so no chance of hitting the requests limit and its a lot more efficient. old way was to add the users from their page on the admin panel one by one but now it pushes a list using the proper Add user call to the groups API.