# Lazy Automation

**URL:** <https://forum.0cd.xyz/t/lazy-automation/142>\
**Category:** Software and Operating Systems\
**Tags:** programming\
**Created:** [January 11, 2018, 9:08pm UTC](https://forum.0cd.xyz/t/lazy-automation/142 "2018-01-11T21:08:27Z")\
**Posts on this page:** 1\
**Showing post:** 14

<div class="post-metadata">

**Author:** ![Michael](https://forum.0cd.xyz/user_avatar/forum.0cd.xyz/michael/32/9677_2.png) [@Michael](https://forum.0cd.xyz/u/Michael)\
**Post date:** [May 22, 2019, 8:20am UTC](https://forum.0cd.xyz/t/lazy-automation/142/14 "2019-05-22T08:20:07Z")

</div>

> [@The Lounge 0001 \[From the Beginning\]](https://forum.0cd.xyz/t/the-lounge-0001-from-the-beginning/64/26075):
>
> looking around I can totally do it in the API with posts using curl and could probably write something within a day that’ll work but i’d be a bit hacky.

@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).

```auto
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

```auto
#!/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.

---

_[View the full topic](https://forum.0cd.xyz/t/lazy-automation/142)._
