Newer
Older
# Given an input csv file of course participants created from moodle,
# create corresponding groups in moodle.
import re
from typing import Dict
import requests
import click
from teach_auto.common_requests import parse_repo_url, get_group_id
from teach_auto.utils import ingest_token
def invite_student_email(
student_email: str, base_url: str, group_id: int, header: Dict[str, str]
) -> None:
"""Invite student to group by email"""
response = requests.post(
f"{base_url}/api/v4/groups/{group_id}/invitations",
data={"email": student_email, "access_level": 40},
headers=header,
)
print(response.json())
def find_email(line: str) -> str:
"""Find and return email address in input string.
Raises an error if none found and only return the first
email if there are more than one.
>>> find_email('robert,smith,robert.smith@no.where,123')
'robert.smith@no.where'
>>> find_email('mike.rock@yes.no,mrock@yes.no')
'mike.rock@yes.no'
"""
regex = r"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)"
try:
email = re.search(regex, line).groups()[0]
except AttributeError:
raise ValueError(f"Missing email: {line}")
return email
@click.command()
@click.argument(
"emails_file", type=click.Path(exists=True),
)
@click.argument("group-url")
@click.option(
type=click.Path(exists=True),
help="Path to a file containing the Gitlab API token. If not provided, you will be prompted for the token.",
)
def invite_students(emails_file, group_url, token_path):
"""
Send invitations to join input gitlab group to all emails in the emails_file.
The file should have one email per line."""
header = {"PRIVATE-TOKEN": token}
# Recover the email on each line, in case there are multiple columns
emails = map(find_email, open(emails_file).read().split("\n"))
group_id = get_group_id(group_url, header)
base_url, _, _ = parse_repo_url(group_url)
for email in emails:
# Invite student to their group by email
invite_student_email(email, base_url, group_id, header)
if __name__ == "__main__":
invite_students()