Using the Moodle Web Service module - ParthBibekar/Welearn-bot GitHub Wiki

The core functions used to interact with the Moodle Web Services API have been wrapped into the moodlews.service module. This is installed on your system as part of the welearn-bot-iiserkol package when you run

pip install welearn-bot-iiserkol

The moodlews.service module gives you a client which handles authentication and server requests to any Moodle service, not just WeLearn. This may be helpful if you wish to write your own custom script to interact with a Moodle service. Following is a typical use case of the module.

from moodlews.service import MoodleClient
from moodlews.service import ServerFunctions

# The root url under which all login and server functions are available
# For reference, the WeLearn login page is at https://welearn.iiserkol.ac.in/login/index.php
baseurl = "https://welearn.iiserkol.ac.in/"

# Create the client and authenticate
moodle = MoodleClient(baseurl)
token = moodle.authenticate("username", "password")

# Empty token if login failed
if not token:
    ....

# The MoodleClient.server(function, **data) function sends a request to the server to execute a particular function
# (see https://docs.moodle.org/dev/Web_service_API_functions#Core_web_service_functions for a full list)
# with optional arguments. This is parsed into a python dictionary, which you can explore.

# Fetch site info records
site_info = moodle.server(ServerFunctions.SITE_INFO)
userfullname = site_info['fullname']
userid = site_info["userid"]

# Fetch user enrolled courses
user_courses = moodle.server(ServerFunctions.USER_COURSES, userid=userid)

# Fetch all resource records
resources = moodle.server(ServerFunctions.RESOURCES)

# For downloading a file from the server, use the MoodleClient.response(url, **data) function to get
# your binary file data. You also need to pass the token again.
fileurl = "https:// ... / ... .pdf"
filepath = "course/ ... .pdf"
response = moodle.response(fileurl, token=token)
with open(filepath, "wb") as download:
        download.write(response.content)

# Fetch all assignment records
assignments = moodle.server(ServerFunctions.ASSIGNMENTS)
...
# Iterate through all courses with assignments
for course in assignments['courses']:
    # Iterate through all assignments in a particular course
    for assignment in course['assignments']:
        assignment_id = assignment["id"]
        # Get assignment status information
        submission = moodle.server(ServerFunctions.ASSIGNMENT_STATUS, assignid=assignment_id)
        ....

# Fetch all url records
urls = moodle.server(ServerFunctions.URLS)

The source code for this module is available in the src/moodlews directory of the repository. Note that moodlews.service.ServerFunctions contains only a tiny subset of the available functions.