def assignments(): sc = schoolopy.Schoology( schoolopy.Auth(getenv('SCHOOLOGY_KEY'), getenv('SCHOOLOGY_SECRET'))) classes = loads(getenv('CLASSES')) sc.limit = 100000 * 10000 data = [] for day in days: day_data = [] for class_name in classes: for assignment in sc.get_assignments(classes[class_name]): due_time = assignment['due'] try: due_day = due_time[:due_time.index(' ')] except: continue if str(day) == due_day: due_time = due_time[:-3][due_time.index(' '):].replace( ' ', '') due_hour = int(due_time[:2].replace('0', '')) if due_hour > 12: due = str(due_hour - 12) + ' pm' else: due = str(due_hour) + ' am' day_data.append({ 'title': assignment['title'], 'link': getenv('SCHOOLOGY_URL') + '/assignment/' + str(assignment['id']), 'due': due }) data.append({'date': day, 'assignments': day_data}) return (data)
def __init__(self): self.schoolopyAuth = schoolopy.Auth( getenv('SCHOOLOGY_KEY'), getenv('SCHOOLOGY_SECRET'), three_legged=True, domain='https://schoology.harker.org/') self.schoolopyUrl = self.schoolopyAuth.request_authorization( callback_url=host + '/authorized')
def __init__(self, user): my_user = User.query.filter_by(username=user).first() access_token = decrypt_message(my_user.token) access_token_secret = decrypt_message(my_user.token_secret) self.schoolopyAuth = schoolopy.Auth( getenv('SCHOOLOGY_KEY'), getenv('SCHOOLOGY_SECRET'), domain='https://schoology.harker.org/', access_token=access_token, access_token_secret=access_token_secret, three_legged=True) self.schoolopyAuth.oauth.token = { 'oauth_token': access_token, 'oauth_token_secret': access_token_secret } self.schoolopyUrl = self.schoolopyAuth.request_authorization( callback_url=host + '/authorized')
def sendEmailUser(user, ms): access_token = decrypt_message(user[4]) access_token_secret = decrypt_message(user[5]) auth = schoolopy.Auth(os.getenv('SCHOOLOGY_KEY'), os.getenv('SCHOOLOGY_SECRET'), domain='https://schoology.harker.org/', access_token=access_token, access_token_secret=access_token_secret, three_legged=True) auth.oauth.token = { 'oauth_token': access_token, 'oauth_token_secret': access_token_secret } sc = schoolopy.Schoology(auth) me = sc.get_me() print(me.username) crs = getUserCourse(user[3]) retDict = {} for course in crs: retList = [] try: sec = sc.get_section(course).section_title assignments = sc.get_assignments(section_id=course) except Exception as e: print(e) assignments = [] for assignment in assignments: try: due = assignment.due due = datetime.strptime(due, "%Y-%m-%d %H:%M:%S") now = datetime.now() #-timedelta(hours=8) #pst if (7 > (due - now).days > -2): retList.append(assignment.title) except Exception: pass if len(retList) > 0: retDict[sec] = retList try: sendEmailCourses(retDict, me.primary_email, ms) except Exception as e: print(e)
#!/usr/bin/python3 import schoolopy from os import environ import pytz import flask from datetime import datetime app = flask.Flask(__name__) sc = schoolopy.Schoology( schoolopy.Auth(environ.get('SCHOOLOGY_KEY'), environ.get('SCHOOLOGY_SECRET'))) sc.limit = 13 def updates(): updates = sc.get_group_updates(402741151) ls = [] for update in updates: sender = sc.get_user(update['uid'])['name_display'].replace( ' (Admin)', '') ls.append({ 'from': sender, 'body': update['body'].replace('\n', '<br>'), 'time': str( datetime.fromtimestamp( update['created'], pytz.timezone('America/Los_Angeles')))[:-9].replace(
""" Retrieves a list of school grading periods in the school. """ import os from dotenv import load_dotenv import pandas as pd import schoolopy # TODO: find a better way. This value is set for Ed-Fi/MSDF users # because of an internal network issue. Necessary for running PIP. But # it messes with the commands below, so needs to be unset. os.environ["REQUESTS_CA_BUNDLE"] = "" load_dotenv() api_key = os.getenv("SCHOOLOGY_KEY") api_secret = os.getenv("SCHOOLOGY_SECRET") sc_client = schoolopy.Schoology(schoolopy.Auth(api_key, api_secret)) df = pd.DataFrame([{ "grading_period_id": gp.id, "title": gp.title } for gp in sc_client.get_grading_periods()]) print(df.to_string())
import schoolopy import yaml with open("example_config.yml", "r") as f: cfg = yaml.load(f) print(cfg, type(cfg)) sc = schoolopy.Schoology(schoolopy.Auth(cfg["key"], cfg["secret"])) sc.limit = 10 # Only retrieve 10 objects max userinfo = { "school_uid": "538118791", "name_first": "This_user_should_not_exist", "name_last": "null", "primary_email": "*****@*****.**", "role_id": "318927", "additional_buildings": "" } school = 538118791 print( sc._post( "users", { "school_uid": "538118791", "name_first": "This_user_should_not_exist", "name_last": "null", "primary_email": "*****@*****.**", "role_id": "318927", "additional_buildings": "" })) #print(sc.update_user({school_id': 538118791, 'name_first': 'Daniel', 'primary_email': '*****@*****.**', 'picture_url': 'https://cdn3-6.cdn.schoology.com/system/files/imagecache/profile_reg/sites/all/themes/schoology_theme/images/user-default.gif'},54473338))
def main(limit): """ Likes all the posts & comments in your most recent feed (20 posts). Args: limit: How many posts to like. Returns: A message of the number of posts & comments that were newly liked. """ with open('config.yaml', 'r') as file: config = yaml.load(file, Loader=yaml.FullLoader) sc = schoolopy.Schoology(schoolopy.Auth(config['key'], config['secret'])) post_liked = 0 comments_liked = 0 # Set the number of posts to check try: sc.limit = int(limit) except ValueError: err("The 'limit' argument must be a number") # Get updates try: updates = sc.get_feed() except KeyError: err("The key or secret is incorrect") print("Liking posts...") # Go through all most recent 20 posts for update in updates: # Like post try: sc.like(update.id) post_liked += 1 except schoolopy.NoDifferenceError: pass # Get comments if post is in a group if update.realm == "group": comments = sc.get_group_update_comments(update.id, update.group_id) # Else get comments if post is in a course elif update.realm == "section": comments = sc.get_section_update_comments(update.id, update.section_id) else: continue # Go through the comments inside the group for comment in comments: # Like each comment try: sc.like_comment(update.id, comment.id) comments_liked += 1 except schoolopy.NoDifferenceError: continue return ("---------------\n" f"Liked {post_liked} posts and {comments_liked} comments")
# Requires Schoolopy. Could I had used requests? yes, but this guy already did it. import schoolopy from modules.settings import schoology as settings from modules.dbModels import importedUsers from flask import session from sqlalchemy import exc #auth = False auth = schoolopy.Auth(settings['apiKey'], settings['apiSecret'], three_legged=True, domain=settings['instanceUrl']) def authUrl(baseUrl): # Makes the URL to give to the user to authorize Celery to access Schoology. try: # Creates the URL that redirects back to celery url = "https://" + auth.request_authorization() urlsep = "oauth_callback=" url = url.split(urlsep)[0] + 'oauth_callback=' + baseUrl return url except: #If we are authorized or something is wrong. return connectionCheck() def connectionCheck(userAccessToken=None, userAccessTokenSecret=None): # Checks to make sure we have authorization, and if we don't, checks to see if we can use # preexisting schoology oauth credentials in a cookie (we probably cannot) global sc
def _initialize_connection(self): self.sc_client = schoolopy.Schoology( schoolopy.Auth(self.api_key, self.api_secret))
import pretty_errors import datetime from json import loads import pickle from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import schoolopy sc_conf = loads(open('schoology.json', 'r').read()) sc = schoolopy.Schoology(schoolopy.Auth(sc_conf['key'], sc_conf['secret'])) sc.limit = 10*10*10 me = sc.get_me() assignments = [] for class_ in sc_conf['classes']: assignments.extend(sc.get_assignments(section_id=class_)) today=datetime.datetime.today() recentAssignments=[] for i in assignments: if i['due'] == '': continue assignmentTime = datetime.datetime.strptime(i['due'], '%Y-%m-%d %H:%M:%S') tDelta=(assignmentTime-today).days if (0 <= tDelta <= 15): recentAssignments.append(i) me['tz_offset'] = str(me['tz_offset'])
#!/usr/bin/python3 import logging import discord import schoolopy import asyncio import os from time import sleep from json import loads from datetime import datetime sc = schoolopy.Schoology(schoolopy.Auth(os.environ.get('SCHOOLOGY_KEY'), os.environ.get('SCHOOLOGY_SECRET'))) sc.limit = 1 def get_updates(): return(sc.get_group_updates(402741151)[0]) class bot(discord.Client): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.bg_task = self.loop.create_task(self.push_update()) async def on_ready(self): print('Logged in as') print(self.user.name) print(self.user.id) print('------') await self.change_presence(activity=discord.Game(name='#schoology-updates'))
import schoolopy import yaml import webbrowser as wb with open('example_config.yml', 'r') as f: cfg = yaml.load(f) # Instantiate with 'three_legged' set to True for three_legged oauth. # Make sure to replace 'https://www.schoology.com' with your school's domain. DOMAIN = 'https://www.schoology.com' auth = schoolopy.Auth(cfg['key'], cfg['secret'], three_legged=True, domain=DOMAIN) # Request authorization URL to open in another window. url = auth.request_authorization() # Open OAuth authorization webpage. Give time to authorize. if url is not None: wb.open(url, new=2) # Wait for user to accept or deny the request. input('Press enter when ready.') # Authorize the Auth instance as the user has either accepted or not accepted the request. # Returns False if failed. if not auth.authorize(): raise SystemExit('Account was not authorized.') # Create a Schoology instance with Auth as a parameter. sc = schoolopy.Schoology(auth) sc.limit = 10 # Only retrieve 10 objects max
def devConnect(): # Uses two-leg authentication and the keys we have in settings to connect a REPL to schoology. sc = schoolopy.Schoology( schoolopy.Auth(settings['apiKey'], settings['apiSecret'])) return sc
import schoolopy import yaml with open('example_config.yml', 'r') as f: cfg = yaml.load(f) sc = schoolopy.Schoology(schoolopy.Auth(cfg['key'], cfg['secret'])) sc.limit = 10 # Only retrieve 10 objects max print('Your name is %s' % sc.get_me().name_display) for update in sc.get_feed(): user = sc.get_user(update.uid) print('By: ' + user.name_display) print(update.body[:40].replace('\r\n', ' ').replace('\n', ' ') + '...') print('%d likes\n' % update.likes)
def sc_login(key, sec): ''' returns a Schoology object''' sc_obj = MySchoology(schoolopy.Auth(key, sec)) me = sc_obj.get_me() # print("Logged in as:", me.name_display) return sc_obj
from typing import Dict, List, Optional BASE_URL = 'https://api.schoology.com/v1' save_file = 'saved.yml' building_id = 10704963 # Load staff names from file with open('staff.yml') as file: # STAFF is a list of lists containing first and last names. Decoding as tuples might require extra effort # E.x. [['First', 'Last']] STAFF = yaml.load(file, Loader=yaml.FullLoader) with open('keys.yml', 'r') as f: keys = yaml.load(f, Loader=yaml.FullLoader) sc = schoolopy.Schoology(schoolopy.Auth(keys['public'], keys['secret'])) def schoology_req(endpoint: str, data: Optional[Dict] = None) -> Response: if data is not None: res = sc.schoology_auth.oauth.post( endpoint, headers=sc.schoology_auth._request_header(), auth=sc.schoology_auth.oauth.auth, json=data) else: res = sc.schoology_auth.oauth.get( endpoint, headers=sc.schoology_auth._request_header(), auth=sc.schoology_auth.oauth.auth) return res
import logging import discord import schoolopy import asyncio import os from time import sleep from json import loads from datetime import datetime sc = schoolopy.Schoology( schoolopy.Auth(os.environ.get('SCHOOLOGY_KEY'), os.environ.get('SCHOOLOGY_SECRET'))) sc.limit = 1 def get_updates(): return (sc.get_group_updates(402741151)[0]) class bot(discord.Client): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.bg_task = self.loop.create_task(self.push_update()) async def on_ready(self): print('Logged in as') print(self.user.name) print(self.user.id) print('------') await self.change_presence(activity=discord.Game( name='#schoology-updates')) async def push_update(self): await self.wait_until_ready() print('ready')