In [ ]:
import os
import requests
import pandas

In [ ]:
KEY = os.getenv('DISCOURSE_KEY')
USER = os.getenv('DISCOURSE_USER')
BASE = 'https://community.lsst.org'
user_list_path = 'user-list-151016-044457-2.csv'

In [ ]:
def get_group_id(group_name, key=None, user=None, base_url=None):
    groups = requests.get(base_url + '/admin/groups.json',
                          params={'api_key': key, 'api_user': user}).json()
    group_id = None
    for group in groups:
        if group['name'] == group_name:
            group_id = group['id']
    assert group_id is not None


def update_tl_for_user(user_id, tl,
                       key=None, user=None, base_url=None):
    r = requests.put(base_url + '/admin/users/{0:d}/trust_level'.format(user_id),
                     data={'user_id': user_id, 'level': tl},
                     params={'api_key': key, 'api_user': user})
    print(r.status_code)


def update_title_for_user(user_id, title,
                          key=None, user=None, base_url=None)
    r = requests.put(base_url + '/admin/users/{0:d}/trust_level'.format(user_id),
                     data={'user_id': user_id, 'level': tl},
                     params={'api_key': key, 'api_user': user})
    print(r.status_code)

def users_in_group(group_name, excludes=None,
                    user_data_path=None,
                    key=None, user=None, base_url=None):
    with open(user_data_path) as f:
        user_table = pandas.read_csv(f)

    for i, (_id, groups) in enumerate(zip(user_table['id'], user_table['group_names'])):
        if group_name in groups:
            if excludes:
                should_skip = False
                for excluded_group in excludes:
                    if excluded_group in groups:
                        should_skip = True
            if not should_skip:
                yield {'id': _id, 'username': user_table['username'][i]}


def update_tl_for_group(group_name, tl,
                        excludes=None,
                        user_data_path=None,
                        key=None, user=None, base_url=None):
    group_id = get_group_id(group_name, key=key, user=user, base_url=base_url)
    
    for u in users_in_group(group_name,
                            user_data_path=user_data_path,
                            excludes=excludes,
                            key=key, user=user, base_url=base_url):
        user_id = u['id']
        user_name = u['username']
        print('Processing {1:d} {0}'.format(user_name, user_id))
        update_tl_for_user(_id, tl,
                           key=KEY, user=USER, base_url=BASE)

Update the trust level for all members of LSSTDM to be level 4.


In [ ]:
update_tl_for_group('LSSTDM', 4,
                    user_data_path=user_list_path,
                    key=KEY, user=USER, base_url=BASE)

In [ ]: