def login_press(event): global canvas_instance global status global api_key global api_url global this_user global user_id7 # Create the account object which is very similar to logging in canvas_instance = can.Canvas(api_url.get(), api_key.get()) # Get the user's account object which will be saved for later and serve as confirmation login was successful # TODO implement a try-catch statement to catch login errors this_user = (canvas_instance.get_user(user_id7.get())) print("Logged in as:\t" + str(this_user)) status.set("Connected") # TODO not working/fix this # Write user info to files print("About to write user data to file...") if is_empty_file("api_key.txt"): api_key_file.write("%s" % api_key.get()) print("Wrote API Key.") api_key_file.close() if is_empty_file("api_url.txt"): api_url_file.write("%s" % api_url.get()) print("Wrote API URL.") api_url_file.close() if is_empty_file("user_id7.txt"): user_id7_file.write("%s" % user_id7.get()) print("Wrote User ID7.") user_id7_file.close() print("Data writing is complete.") return # Hopefully I don't need to return an object
def get_rubric_info(self, course_id, assignment_id): canvas = canvasapi.Canvas(self.canvas_url, self.canvas_key) course = canvas.get_course(course_id) assignment = course.get_assignment(assignment_id) criteria_id = [[ criterion["description"], criterion["points"], criterion["id"], criterion["ratings"] ] for criterion in assignment.rubric] return criteria_id
def __init__(self, *args): try: self.obj = canvasapi.Canvas(*args) log.info( f"Successfully established a connection with Canvas! ({self.obj})" ) except: raise AuthenticateException( "There was an error while logging in to StudentVUE.")
def get_students(url, token, course_id): canvas = canvasapi.Canvas(url, token) if not course_id: # prompt user to select a course they have access to (paginated) course_id = course_prompt(canvas) course = canvas.get_course(course_id) enrollments = course.get_enrollments() enrollments = [enrollment for enrollment in enrollments]
def form_teams(url, token, course_id, group_all_sections, group_category_name, strategy, total_teams, team_size, store_data, test_run): config.STORE_DATA_LOCALLY = store_data canvas = canvasapi.Canvas(url, token) (course, data) = _fetch_data(url, token, course_id) (group_category_name, group_category) = group_name_prompt(course, group_category_name) teams = None if strategy.lower() == 'random': random_teams = RandomTeams(data, group_all_sections=group_all_sections, total_teams=total_teams, team_size=team_size) teams = random_teams.form_teams() else: click.echo('Invalid strategy') import sys sys.exit() if len(teams) == 0: click.echo('No Teams could be generated') import sys sys.exit() store_teams_generated(teams) # only push new group category and teams to canvas if a real run if not test_run: if not group_category: # create new group category group_category = course.create_group_category(group_category_name) else: # remove existing groups groups = group_category.get_groups() for group in groups: group.delete() # push teams to canvas for (group_name, students_df) in teams: # create group group = group_category.create_group(name=group_name, join_level='invitation_only') # add members to group group.edit(members=students_df['id'].values)
def aplus(show: bool, token: str, base_url: str, course_id: str, code: str): colorama.init() canvas = canvasapi.Canvas(base_url, token) aplus = get_aplus(canvas, course_id) if show: show_attendance(aplus) return try: aplus.submit_code(code) except NoAvailableCodesException: print("No open codes") exit(2)
def get_csci_pepper() -> bytes: """Returns the appropriate pepper for CSCI E-29 This is similar to the salt, but defined as the UUID of the Canvas course, available from the Canvas API. This value should never be recorded or printed. :return: bytes representation of the pepper """ env = Env() canvas = canvasapi.Canvas(env.str("CANVAS_URL"), env.str("CANVAS_TOKEN")) course = canvas.get_course(env.int("CANVAS_COURSE_ID")) return base64.b64decode(course.uuid)
def create_kudo_point_giving_assignments(canvas_key: str, course_id: int, canvas_url: str, group_set_name: str, assignment_group_name: str, kudo_points: int, due_date: datetime.datetime, unlock_date: datetime.datetime, lock_date: datetime.datetime, ignore_case: bool = True): canvas_connection = canvasapi.Canvas(canvas_url, canvas_key) course = canvas_connection.get_course(course_id) group_categories = course.get_group_categories() assignment_group = locate_assignment_group(assignment_group_name, course, ignore_case)
def main(input_csv): """ Main entry point for assign_quiz.py script """ # Prompt the user for a course ID course_id = input("Enter course ID: ") canvas = canvasapi.Canvas(settings.INSTANCE, settings.TOKEN) # add_canvas_ids(input_csv, course_id) assignment_dict = process_input(canvas, input_csv) # Calls assign_quiz function once for every assignment ID for key in assignment_dict: assign_quiz(canvas, key, course_id, assignment_dict.get(key))
def main(): canvas_key = sys.argv[1] course_id = int(sys.argv[2]) canvas_url = 'https://canvas.ucdavis.edu' canvas_connection = canvasapi.Canvas(canvas_url, canvas_key) course = canvas_connection.get_course(course_id) group_categories = course.get_group_categories() for category in group_categories: if category.name == 'Kudo Point Giving Testing': print(category) for group in category.get_groups(): group = Group(group) if group.name == 'Accessible': print(f'\t{group}') for user in group.members: print(f'\t\t{user}') create_kudo_point_giving_quiz_for_user( user, group, course, 2)
def view_course_report(url, state, per_page): # ensure access token is available TOKEN = os.environ.get('CANVAS_ACCESS_TOKEN') while not TOKEN: TOKEN = click.prompt("Enter your access token", hide_input=True) # create a canvas api handler for all requests # by using a Canvas API library, we no longer need to # worry about keeping track of the authorization header # or request urls in our code canvas_api = canvasapi.Canvas(url, TOKEN) click.echo("Finding courses...") click.echo("-----------------------------") paginated_courses = canvas_api.get_courses( per_page=per_page, state=[state], include=['total_students'] ) # fetch all courses (unwrap PaginatedList) # this is a particular quirk of the canvasapi library # it will only fetch pages are they are needed so # we need to loop though it all to fetch everything # before sending the data to Pandas courses = [course.attributes for course in paginated_courses] if len(courses) == 0: click.echo("No courses found to report on.") return # from here, a simple table is printed out # using pandas for convenience click.echo("Report for "+str(len(courses)) + " courses.") click.echo("-----------------------------") courses_df = pd.DataFrame(courses) result = courses_df.to_string( columns=['id', 'name', 'course_code', 'workflow_state', 'start_at', 'end_at', 'total_students'] ) click.echo(result)
def login(self, *args): try: canvas_connection = canvasapi.Canvas(self.canvas_url.entry.get(), self.canvas_key.entry.get()) canvas_connection.get_current_user() CourseAndActionSelectionWindow(canvas_connection) self.master.destroy() except requests.exceptions.ConnectionError: messagebox.showinfo( title='Bad URL', message=f'Cannot connect to {self.canvas_url.entry.get()}.\n' f'Please check you entered the correct url.') except (canvasapi.exceptions.ResourceDoesNotExist, canvasapi.exceptions.InvalidAccessToken): messagebox.showinfo( title='Bad API Key', message=f'Cannot connect to Canvas with the given API Key.\n' f'Please check that you entered your API Key correctly.')
def __init__(self, url, token, course_id, weights_ranges_file_name, weights_ranges_file_local, weights_assignment_group_name, weights_assignment_prefix): self.url = url self.token = token self.course_id = course_id self.weights_ranges_file_name = weights_ranges_file_name self.weights_assignment_group_name = weights_assignment_group_name self.weights_assignment_prefix = weights_assignment_prefix self.canvas = canvasapi.Canvas(self.url, self.token) self.course = self.canvas.get_course(self.course_id) self.enrollments = self.course.get_enrollments() self.assignments = self.course.get_assignments() self.assignment_groups = self.course.get_assignment_groups() self.weights_ranges = self.fetch_weights_ranges_from_local( ) if weights_ranges_file_local else self.fetch_weights_ranges_from_canvas( )
def _fetch_data(url, token, course_id): canvas = canvasapi.Canvas(url, token) data = {} if not course_id: # prompt user to select a course they have access to (paginated) course_id = course_prompt(canvas) # get course by id course = canvas.get_course(course_id, include=['total_students']) data['course_df'] = process_canvas_course(course) sections = course.get_sections(include=['students'], per_page=config.PER_PAGE) data['sections_df'] = process_canvas_sections(sections) students = course.get_users(enrollment_type=['student'], enrollment_stat=['active'], per_page=config.PER_PAGE) data['students_df'] = process_canvas_students(students) return (course, data)
def pset_submission( canvas_url, canvas_token, course_id, assignment_name, quiz_name, repo, url, do_submit=True, ): """Creates and yields a canvas submission object - the recieving context is responsible for filling in the answers component of the submission, this function will then submit those answers :the first five parameters are part of the canvas api setup :the url parameter should be populated with the url of the executing device (e.g. CI/CD platform url), for providing as metadata to Canvas """ canvas = canvasapi.Canvas(canvas_url, canvas_token) course = canvas.get_course(course_id) assignment = get_assignment(course, assignment_name) quiz = get_quiz(course, quiz_name) try: qsubmission = quiz.create_submission() yield qsubmission finally: if do_submit: print("Submission to be attempted") if qsubmission is not None: print("Completing Submission") completed = qsubmission.complete() submission = assignment.submit( dict( submission_type="online_url", url=url, ), comment=dict(text_comment=json.dumps( get_submission_comments(repo, qsubmission))), ) else: print("Not submitting")
def create_module(url, token, course_id, location): canvas = canvasapi.Canvas(url, token) if not course_id: # prompt user to select a course they have access to (paginated) course_id = course_prompt(canvas) course = canvas.get_course(course_id) module = course.create_module(module={'name': 'test module'}) # create learning outcomes lo = page.create_page(course, "Learning Outcomes", location + '/Learning Outcomes.txt') # create pre-test # pret = course.create_quiz(quiz={'title':'pre-test'}) pret = quiz.create_quiz(course, 'Pre-Test', loc=location + '/Quizformat.txt') # create post-test # postt = course.create_quiz(quiz={'title':'post-test'}) postt = quiz.create_quiz(course, 'Post-Test', loc=location + '/Quizformat.txt') # create readings rea = page.create_page(course, 'Readings', loc=location + '/Readings.txt') # add videos # #add slides module.create_module_item(module_item={'title':'Learning Outcomes', 'type':'Page', \ 'content_id':None, 'page_url':lo}) module.create_module_item(module_item={'title':'Pre-Test', 'type':'Quiz', \ 'content_id':pret}) module.create_module_item(module_item={'title':'Post-Test', 'type':'Quiz', \ 'content_id':postt}) module.create_module_item(module_item={'title':'Readings', 'type':'Page', \ 'content_id':None, 'page_url':rea})
def execute(config): try: canvas = canvasapi.Canvas(config["CANVAS_API_URL"], config["CANVAS_API_KEY"]) for course in canvas.get_courses(): if config["COURSE_CODE_FILTER"] in course.course_code: for assignment in course.get_assignments(): obj = encode_assignment(course, assignment) if str(assignment.id) in config['data']['assignments']: if obj != config['data']['assignments'][str( assignment.id)]: log( config, "Assignment {} changed: {}".format( assignment.id, json.dumps(obj))) config['data']['assignments'][str( assignment.id)] = obj else: log( config, "Found new assignment {}: {}".format( assignment.id, json.dumps(obj))) config['data']['assignments'][str(assignment.id)] = obj title = assignment.name body = "[{}]({}) - {}\n\nDue {}".format( obj['name'], obj['url'], obj['course'], obj['due_at']) hub = github.Github(config["GITHUB_TOKEN"]) repo = hub.get_repo(config["GITHUB_REPO"]) # print('dry run {}: {}'.format(title, body)) issue = repo.create_issue(title, body) issue_id = issue.id log(config, "Created github issue {}".format(issue_id)) except Exception as e: log(config, 'Error: {}'.format(e), level='ERR') return config
def __init__(self, canvas_url: str, canvas_token: str): self.canvas = canvasapi.Canvas(canvas_url, canvas_token) self.zoom_placements = ZoomPlacements(self.canvas) self.db_creator: DBCreator = DBCreator(ENV['INVENTORY_DB']) self.supported_tools = self.get_supported_lti_tools()
# (date checking is working correctly for discussions and assignments) from canvasapi import Canvas import os import sys import canvasapi import dotenv import datetime from datetime import datetime from datetime import timedelta # Store your API key in a separate file with open("access_token.txt") as f: API_KEY = f.read().strip() API_URL = "https://lvc.instructure.com" canvas_api = canvasapi.Canvas(API_URL, API_KEY) # read input data for Canvas calendar and assignment entries in_file = open(sys.argv[1], 'r') Lines = in_file.readlines() in_file.close() # course id must appear on first line of input file COURSE_ID = Lines[0][Lines[0].find('<course_id>') + 11:Lines[0].find('</course_id>')] DELETE_FROM_DATE = Lines[1][Lines[1].find('<delete_from_date>') + 18:Lines[1].find('</delete_from_date>')] DELETE_TO_DATE = Lines[2][Lines[2].find('<delete_to_date>') + 16:Lines[2].find('</delete_to_date>')] delete_from_date = datetime.strptime(DELETE_FROM_DATE, '%Y-%m-%d') delete_to_date = datetime.strptime(DELETE_TO_DATE, '%Y-%m-%d')
help="Your Canavs Access Token. " "If you don't have one you can get one by following " "directions under Manual Token Generation at " "https://canvas.instructure.com/doc/api/file.oauth.html#accessing-canvas-api") parser.add_argument('--course_id', dest='course_id', required=True, type=int, help='The id of your course. You can find this right after /courses in the url ' 'of your course.\n ' 'For example, if the url of your course was https://canvas.ucdavis.edu/courses/1234 ' 'then your course id is 1234.') parser.add_argument('--url', '--canvas_url', dest='canvas_url', default='https://canvas.ucdavis.edu/', help='Your canvas url. Example: https://canvas.ucdavis.edu/' ) return parser if __name__ == '__main__': # runner() p = create_argument_parser() n = p.parse_args() canvas_connection = canvasapi.Canvas(n.canvas_url, n.canvas_key) course = canvas_connection.get_course(n.course_id) create_assignment_group('Sparta', course,True)
db = SQL("sqlite:///courses.db") # Canvas API URL API_URL = "https://canvas.harvard.edu" """ Canvas API key required for search results to appear. User must generate their own Canvas token, which can be done from a user's logged-in profile page. Application functions with Harvard student account Canvas privileges. https://canvas.instructure.com/doc/api/file.oauth.html#manual-token-generation https://canvas.harvard.edu/profile/settings """ API_KEY = "" # Initialize a new Canvas object canvas = canvasapi.Canvas(API_URL, API_KEY) # Configure application app = Flask(__name__) # Returned sites of any given search sites = [] # Home search page @app.route("/", methods=["GET", "POST"]) def index(): if request.method == "POST": del sites[:] locator_id = None
def canvas(self): if self.mock: return canvasapi_mock.Canvas(self.url, self.token) if not self._canvas: self._canvas = canvasapi.Canvas(self.url, self.token) return self._canvas
'result.txt' } GF_MARKS = {"apply": 4, "element": 5, "replace": 5, "sumLeafs": 4, "numNodes": 3, "numLevels": 3, "flip": 3, "hlint": 1} CRITERIA = {"apply": 2, "element": 2, "replace": 2, "sumLeafs": 2, "numNodes": 2, "numLevels": 2, "flip": 3, "hlint": 3} ######################################################################## # MarkUs URL = 'https://markus.utsc.utoronto.ca/{}'.format(COURSE) API = markusapi.Markus(MARKUS_API_KEY, URL) # Quercus Q_API_URL = 'https://q.utoronto.ca' CANVAS = canvasapi.Canvas(Q_API_URL, QUERCUS_API_KEY) COURSE = CANVAS.get_course(QUERCUS_COURSE_ID) # submissions info GROUPS = API.get_groups(ASSIGNMENT_ID) UTORID_TO_GROUP = markusutils.get_utorid_to_group(API, ASSIGNMENT_ID) # map function-name-in-gf-file to # (function-name-markus-criteria, gf-out-of, markus-out-of) CRITERIA_MAPS = [ {name: (name, GF_MARKS[name], CRITERIA[name]) for (name, outof) in criteria.items()} for criteria in (GF_MARKS,)] ########################################################################
from discord.ext import commands from dotenv import load_dotenv import util.canvas_handler from util.badargs import BadArgs from util.canvas_handler import CanvasHandler from util.create_file import create_file_if_not_exists from util.json import readJSON, writeJSON CANVAS_COLOR = 0xe13f2b CANVAS_THUMBNAIL_URL = "https://lh3.googleusercontent.com/2_M-EEPXb2xTMQSTZpSUefHR3TjgOCsawM3pjVG47jI-BrHoXGhKBpdEHeLElT95060B=s180" load_dotenv() CANVAS_API_URL = "https://canvas.ubc.ca" CANVAS_API_KEY = os.getenv("CANVAS_API_KEY") CANVAS_INSTANCE = canvasapi.Canvas(CANVAS_API_URL, CANVAS_API_KEY) CANVAS_FILE = "data/canvas.json" # Used for updating Canvas modules EMBED_CHAR_LIMIT = 6000 MAX_MODULE_IDENTIFIER_LENGTH = 120 class Canvas(commands.Cog): def __init__(self, bot): self.bot = bot if not isfile(CANVAS_FILE): create_file_if_not_exists(CANVAS_FILE) writeJSON({}, CANVAS_FILE)
for char in datetimeDue: if char.isnumeric(): num += char else: numList.append(int(num)) num = '' return datetime(numList[0], numList[1], numList[2], numList[3], numList[4], numList[5]) # utc and alpha time zone are both ahead of PST by 8 hours / maybe also check if assignments have started already if __name__ == '__main__': # set api necessities and create canvas object API_URL = keys.URL API_TOKEN = keys.TOKEN canvas = cv.Canvas(API_URL, API_TOKEN) # create second canvas object if user has two different Canvas accounts SEC_API_URL = keys.SECOND_URL SEC_API_TOKEN = keys.SECOND_TOKEN secondCanvas = cv.Canvas(SEC_API_URL, SEC_API_TOKEN) # gets courses & respective term. Returns dict -> course.term; 'name' is the key for the term name courses = canvas.get_courses(include=['term']) secondCourses = secondCanvas.get_courses(include=['term']) allCourses = [] # puts all courses in allCourses to only check one list for course in courses: allCourses.append(course) for course in secondCourses:
def __init__(self): self.zoom_session = requests.Session() self.canvas = canvasapi.Canvas(CANVAS_ENV.get("CANVAS_URL"), CANVAS_ENV.get("CANVAS_TOKEN"))
# These two lines enable debugging at httplib level (requests->urllib3->http.client) # You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA. # The only thing missing will be the response.body which is not logged. if LOG_LEVEL == logging.DEBUG: http.client.HTTPConnection.debuglevel = 1 # You must initialize logging, otherwise you'll not see debug output. logger = logging.getLogger(__name__) logger.setLevel(LOG_LEVEL) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(LOG_LEVEL) requests_log.propagate = True # Global variable to access Canvas CANVAS = canvasapi.Canvas(ENV.get("CANVAS_URL"), ENV.get("CANVAS_TOKEN")) class ZoomPlacements: zoom_courses = [] zoom_courses_meetings = [] def __init__(self): self.zoom_session = requests.Session() def get_zoom_json(self, page_num: int = 1) -> Dict: logger.info(f"Paging though course on page number {page_num}") # Get tab 1 (Previous Meetings) data = { 'page': page_num, 'total': 0,
#!/usr/bin/env python3 """ Downloads information about assignments from the provided course (COURSE_ID). The information is stored in a json file as data/assignments.json. """ import canvasapi import json import os BASE_URL = "https://uit.instructure.com/" # Canvas for uit.no COURSE_ID = 16497 # inf-1400 2020 COURSE_ID = 21176 # inf-1400 2021 api_key = open("api_key.txt", 'r').readline().strip() canvas = canvasapi.Canvas(BASE_URL, api_key) course = canvas.get_course(COURSE_ID) def stud_to_dict(stud): return { 'id': stud.id, 'display_name': stud.display_name, } def subm_to_dict(subm, studs): return { 'submitted_at': subm.submitted_at, 'excused': subm.excused, 'attempt': subm.attempt,
return ######################################################################################################################## # CanvasObject Screen canvas_object_screen = tk.Tk() ######################################################################################################################## ########################################################### # Global Variable (Need to be instantiated after TK object) ########################################################### status = tk.StringVar() status.set("Not Connected") api_key = tk.StringVar() api_url = tk.StringVar() canvas_instance = can.Canvas(api_url.get(), api_key.get(())) this_user = None course_id7 = tk.StringVar() user_id7 = tk.StringVar() api_key_file = open("api_key.txt", "r+") api_url_file = open("api_url.txt", "r+") user_id7_file = open("user_id7.txt", "r+") file_list = {api_key_file, api_url_file, user_id7_file} on_startup() # Perform startup tasks ########################################################### canvas_object_screen.title("CanvasObject Screen") # canvas_object_screen.geometry("{}x{}".format(460, 350))