Esempio n. 1
0
def create_piazza_post(title: str, content: str, folder: str) -> int:
    """Create a piazza post from the given parameters and return the post's CID."""
    EMAIL = Config.get_global().piazza_email
    PWD = Config.get_global().piazza_password
    ID = Config.get_global().piazza_id

    p = Piazza()
    p.user_login(EMAIL, PWD)
    post = p.network(ID)

    while True:
        try:
            result = post.create_post(
                title=title,
                content=content,
                nid=ID,
                folder=folder
            )
        except piazza_api.exceptions.RequestError as e:
            str_e = str(e)
            if "posting too quickly" in str_e:
                # Piazza has posting time limits, grumble grumble
                # "Sorry! It looks like you are posting too quickly--wait a second and try again."

                # Try again
                time.sleep(0.4)
                continue
            else:
                # Don't handle this
                raise e

        # All done now!
        break

    return int(result['nr'])
Esempio n. 2
0
async def send_new_posts():
    load_sent_ids()
    print('\n\nloaded')
    print(sent_ids)
    print('\n\n')

    p = Piazza()
    p.user_login("email", "pass")

    user_status = p.get_user_status()
    nid = user_status['networks'][0]['id']

    eecs2030 = p.network(nid)
    feed = eecs2030.get_feed(limit=99999)

    feed_arr = feed['feed']
    piazzaobj_arr = []

    for post in feed_arr:
        full_post = eecs2030.get_post(post['id'])
        latest_update = full_post['history'][0]
        piazzaobj_arr.append(
            PiazzaObject(post['id'], latest_update['subject'],
                         latest_update['content'], full_post['created'],
                         'https://piazza.com/class?cid=' + post['id']))

    print(sent_ids)
    for piazzaobj in piazzaobj_arr:
        if not piazzaobj.id in sent_ids:
            print(f'sending {piazzaobj.id}')
            await send_post(piazzaobj)
            sent_ids.append(piazzaobj.id)

    save_sent_ids()
Esempio n. 3
0
def post_aggregate(email, password, coursecode):
    # User credentials
    piazza = Piazza()
    # Login
    piazza.user_login(email, password)

    # get course code to hash dictionary
    coursetohash = course_hash(email, password)

    # get classroom object using the hash
    classroom = piazza.network(coursetohash[coursecode])

    # go through all the posts, aggregate them in a data-structure
    postquestions = []

    # board_posts type is generator: cannot access memory in the lazy list
    board_posts = classroom.iter_all_posts(limit=const_limit)

    # iterate through board posts
    for post in board_posts:
        # get rid of html tags in question in post
        question_string = strip_tags(post["history"][0]["content"])

        # append to questions array
        postquestions.append(question_string)

    return postquestions
def main(argv=sys.argv[1:]):
    argument_parser = argparse.ArgumentParser()
    # argument_parser.add_argument('--username', type=str,
    #         default='PiazzaBot', help='the bot\'s Keybase username')
    args = argument_parser.parse_args(argv)

    logger.info('keybase_piazza_bot starting')

    event_loop = asyncio.get_event_loop()

    piazza = Piazza()
    piazza.user_login() # login prompt
    cse220 = piazza.network(PIAZZA_NETWORK_ID)

    keybase_bot_handler = KeybaseBotHandler(piazza, cse220)
    keybase_bot = Bot(
        handler=keybase_bot_handler,
        loop=event_loop,
        # username=args.username,
    )
    future = keybase_bot.start({})

    event_loop.run_until_complete(future)
    event_loop.close()

    logger.info('keybase_piazza_bot exiting')
Esempio n. 5
0
def checkPiazza():
    client = pymongo.MongoClient(pizzapizzasecret.dbsecret)
    db = client.get_database('piazza-posts')
    table = db.posts
    existingPosts = []
    query = table.find()
    print(query)
    output = {}
    i = 0
    for x in query:
        output[i] = x
        output[i].pop('_id')
        existingPosts.append(output[i]['ID'])
        i += 1
    print(existingPosts)
    p = Piazza()
    p.user_login(pizzapizzasecret.email, pizzapizzasecret.password)
    ds = p.network(pizzapizzasecret.net)
    #print("ds", ds.iter_all_posts())
    posts = ds.iter_all_posts()
    for post in posts:
        #print("post", post)
        if post['history'][0]['subject'] not in existingPosts:
            payload = post['history'][0]['subject']
            print(payload)
            queryObject = {
                'ID': payload,
            }
            queryMongo = table.insert_one(queryObject)
            sendPayload(post)

        else:
            print("piazza channel up to date")
    return "success"
Esempio n. 6
0
    def perform_action(action,
                       course,
                       as_staff=False,
                       is_test=None,
                       kwargs=None):
        with connect_db() as db:
            if as_staff:
                user, pw = db(
                    "SELECT staff_user, staff_pw FROM piazza_config WHERE course = (%s)",
                    [course],
                ).fetchone()
            else:
                user, pw = db(
                    "SELECT student_user, student_pw FROM piazza_config WHERE course = (%s)",
                    [course],
                ).fetchone()
            if is_test:
                (course_id, ) = db(
                    "SELECT test_course_id FROM piazza_config WHERE course = (%s)",
                    [course],
                ).fetchone()
            else:
                (course_id, ) = db(
                    "SELECT course_id FROM piazza_config WHERE course = (%s)",
                    [course]).fetchone()

        p = Piazza()
        p.user_login(user, pw)
        course = p.network(course_id)
        if kwargs is None:
            kwargs = {}
        try:
            return getattr(course, action)(**kwargs)
        except Exception as e:
            return str(e), 400
Esempio n. 7
0
    def __init__(self, course_code=config.eecs281):
        self.piazza = Piazza()
        self.piazza.user_login(config.creds['email'], config.creds['password'])
        self.course = self.piazza.network(course_code)

        # rpc api to post notes
        self.piazza_rpc = PiazzaRPC(config.class_code)
        self.piazza_rpc.user_login(config.creds['email'], config.creds['password'])
 def __init__(self, days_refresh=10):
     self.piazza = Piazza()
     self.piazza.user_login(email=Config.username, password=Config.password)
     self.course = self.piazza.network(Config.courseid)
     self.engine = create_engine('sqlite:///test.db', echo=False)
     self.Session = sessionmaker(bind=self.engine)
     self.session = self.Session()
     self.days = days_refresh
 def __init__(self, course_id='xxxxxxxxxxx'):
     self.p = Piazza()
     email_id = input("Enter your Piazza email ID : ")
     password = getpass('Piazza Password:')
     # course_id = input("Enter your Course ID : ")
     self.p.user_login(email_id, password)
     user_profile = self.p.get_user_profile()
     self.comp_photo19 = self.p.network(course_id)
Esempio n. 10
0
	def __init__(self):
		self.p = Piazza()
		self.p.user_login(USER_NAME, USER_PASS)
		self.uid = self.p.get_user_profile()['user_id']

		# classes = self.p.get_user_classes()

		self.si206 = self.p.network("jlp6m1ynp9713y")
Esempio n. 11
0
def main():
    p = Piazza()
    p.user_login()
    classId = input("Enter your class id")
    classObj = p.network(classId)
    postId = input("Enter post number")
    posts = classObj.get_post(postId)
    all_users = classObj.get_all_users()

    generate_csv(all_users, posts)
Esempio n. 12
0
 def __init__(self, bot, EMAIL, PASSWORD, TARGET, NAME, ID):
     self.bot = bot
     self.p = Piazza()
     self.p.user_login(email=EMAIL, password=PASSWORD)
     self.name = NAME
     self._nid = ID
     self.cls = self.p.network(self._nid)
     self.url = f'https://piazza.com/class/{self._nid}?cid='
     self.target_channel = TARGET  # bot-commands channel
     self.sendUpdate.start()
Esempio n. 13
0
def piazza_reader(email, password, coursecode):
    # User credentials
    piazza = Piazza()
    # Login
    piazza.user_login(email, password)

    class_dictionary = piazza.get_user_classes()

    # dictionary for 'course code: hash_id'
    coursetohash = {}
    # print(len(class_dictionary))
    for i in range(len(class_dictionary)):
        coursetohash.update(
            {class_dictionary[i]['num']: class_dictionary[i]['nid']})

    print(coursetohash)

    classroom = piazza.network(coursetohash[coursecode])

    # print(coursecode)
    # print(coursetohash[coursecode])

    # go through all the posts, aggregate them in a data-structure
    postquestions = []
    postanswers = []

    # board_posts type is generator: cannot access memory in the lazy list
    board_posts = classroom.iter_all_posts(limit=const_limit)

    # iterate through board posts
    for post in board_posts:
        # get rid of html tags in question in post
        question_string = strip_tags(post["history"][0]["content"])

        # append to questions array
        postquestions.append(question_string)

        # checks if there's an answer associated to the question
        if "children" in post.keys(
        ) and post["children"] and "history" in post["children"][0]:

            # for all answers in a single post (iterate)
            for answer_index in range(len(post["children"][0]["history"])):

                # get rid of html tags for answers in the post, and check if the entry is a string
                if type(post["children"][0]["history"][answer_index]
                        ["content"]) == str:
                    answer_string = strip_tags(post["children"][0]["history"]
                                               [answer_index]["content"])

                    # append to answers array
                    postanswers.append(answer_string)

    # print(postQuestions + postAnswers)
    return " ".join(postquestions + postanswers)
Esempio n. 14
0
    def __init__(self, username, password, course_id):
        self.__username = username
        self.__password = password
        self.__course_id = course_id
        self.__path = './data/' + course_id + '.csv'

        self.__h = html2text.HTML2Text()
        self.p = Piazza()

        self.__login()
        self.__load_seen_posts()
Esempio n. 15
0
def login(email, password):
    piazza = Piazza()
    piazza.user_login(email, password)
    class_dictionary = piazza.get_user_classes()
    return class_dictionary

    courseToHash = {}
    #print(len(class_dictionary))
    for i in range(len(class_dictionary)):
        courseToHash.update(
            {class_dictionary[i]['num']: class_dictionary[i]['nid']})
Esempio n. 16
0
 def __init__(self, NAME, ID, EMAIL, PASSWORD, GUILD, FETCH_MAX=55, FETCH_MIN=30):
     self.name = NAME
     self.nid = ID
     self._guild = GUILD
     self._channels = []
     self.url = f"https://piazza.com/class/{self.nid}"
     self.p = Piazza()
     self.p.user_login(email=EMAIL, password=PASSWORD)
     self.network = self.p.network(self.nid)
     self.max = FETCH_MAX
     self.min = FETCH_MIN
Esempio n. 17
0
def main():
    """Get the cli args and start tracking."""
    args = parse_arguments()
    piazza = Piazza()
    piazza.user_login(args.email, args.password)
    # Create/load tinydb for the users and posts
    userdb = TinyDB(f'{args.class_id}.json', default_table="users")
    postdb = TinyDB(f'{args.class_id}.json', default_table="posts")
    while True:
        track(piazza, args.class_id, userdb, postdb)
        time.sleep(2)
Esempio n. 18
0
 def __init__(self, bot, TARGET, CLASS, ID, EMAIL=None, PASSWORD=None):
     self.bot = bot
     self.p = Piazza()
     self.p.user_login(email=EMAIL, password=PASSWORD)
     self._nid = ID
     self.classname = CLASS
     self.cls = self.p.network(self._nid)
     self.url = f'https://piazza.com/class/{self._nid}?cid='
     self.target_channel = TARGET  # bot-commands channel
     self.sendUpdate.start(
     )  # this error is ok, was written this way in the docs
Esempio n. 19
0
 def _connect_to_piazza(self, piazza_credentials):
     """Connect to Piazza"""
     _piazza = Piazza()
     _piazza.user_login(email=piazza_credentials['piazza_email'],
                        password=piazza_credentials['piazza_password'])
     self._myclass = _piazza.network(piazza_credentials['piazza_network'])
     # Get list of cid's from feed
     self._feed = self._myclass.get_feed(limit=999999, offset=0)
     self._instructor_ids = [
         user['id'] for user in self._myclass.get_all_users()
         if user['admin'] == True
     ]
Esempio n. 20
0
def main():
    parser = argparse.ArgumentParser(description='Retrieve Piazza posts and answers in JSON format.')
    parser.add_argument('--networkid', '-n', help='piazza network ID', required=True)
    parser.add_argument('--output', '-o', help='output filename', required=True)
    args = parser.parse_args()

    piazza = Piazza()
    print('Login to Piazza:')
    piazza.user_login()

    network = piazza.network(args.networkid)
    write_all_posts(network, args.output)
Esempio n. 21
0
    def create_piazza_bot(user_email, user_password, course_code):
        ''' Method to instantiate a Piazza Bot
    Parameters:
    user_email: Piazza user email to authenticate with
    user_password: Piazza password to authenticate with
    course_code: Class/Course code on Piazza '''

        piazza = Piazza()
        piazza.user_login(email=user_email, password=user_password)
        user_profile = piazza.get_user_profile()
        course_site = piazza.network(course_code)

        return PiazzaBot(piazza, user_profile, course_site)
Esempio n. 22
0
    def __init__(self):
        self.p = Piazza()
        self.p.user_login(PIAZZA_USER, PIAZZA_PASS)
        self.uid = self.p.get_user_profile()['user_id']

        classes = self.p.get_user_classes()
        self.classes = []

        print 'Now watching posts for the following {0} classes:'.format(len(classes))
        for c in classes:
            print '{0} ({1}, {2})'.format(c['num'], c['name'], c['term'])
            self.classes.append(self.p.network(c['nid']))

            self.filter = UnreadFilter()
Esempio n. 23
0
def main():

    parser = argparse.ArgumentParser(description='Process user input for piazza queries')
    parser.add_argument('-q', '--query', nargs="+")
    parser.add_argument('-t', '--tags', nargs="+") 
    parser.add_argument('-r', '--range', nargs=2)
    parser.add_argument('-i', '--instructor-only', action='store_true')
    parser.add_argument('-p', '--posts', action='store_true')
    parser.add_argument('-l', '--force-login', action='store_true')
    args = parser.parse_args()

    if (args.query is None): 
        raise(InputError("Query not given!"))

    queryObj = QueryObj()
    queryObj.add_query(args.query)
    queryObj.add_tags(args.tags)
    queryObj.add_time_range(args.range)
    queryObj.bool_inst_notes(args.instructor_only)
    queryObj.bool_pinned(args.posts)

    loginfile = os.path.expanduser("~") + "/.pizza"
    
    if not args.force_login: 
        try: 
            pkl = pickle.load(open(loginfile,"rb"))
            data = {'email', pkl['email'], 'password': pkl['password'].decode('rot13')}
        except IOError:
            email = raw_input('Piazza Email: ')
            password = getpass.getpass()
            data = {'email': email, 'password': password}
            pkl = {'email': email, 'password': password.encode('rot13')}
            pickle.dump(pkl, open(loginfile, "wb"))

    piazza = Piazza() 
    piazza.user_login(data['email'], data['password'])
    user_status = piazza.get_user_status()
    
    classes = user_status['networks']
    classes = sorted(classes, key=lambda k: k['status'])
    # list classes 
    print("Choose a Class")
    counter = 1
    for c in classes: 
        info = c['name']
        if c['status'] == 'inactive':
            info = '(inactive) ' + info
        print '{0:2d}: {1:s}'.format(counter, info)
        counter = counter + 1
Esempio n. 24
0
 def __init__(self,
              user,
              password,
              class_id,
              corpus=None,
              corpus_embeddings=None,
              default_bert=True):
     self.p = Piazza()
     self.p.user_login(user, password)
     self.class_id = class_id
     self.user_profile = self.p.get_user_profile()
     self.network = self.p.network(class_id)
     self.DB_manger = MongoDBManger()
     self.bert = BertSemanticSearch(corpus, corpus_embeddings, default_bert)
     self.parallel_cid_list = []
Esempio n. 25
0
def course_list(email, password):
    # User credentials
    piazza = Piazza()
    # Login
    piazza.user_login(email, password)

    # create class dictionary from user class details: we are interested in the "num" key
    class_dictionary = piazza.get_user_classes()

    course_code_list = []

    for index in range((len(class_dictionary))):
        course_code_list.append(class_dictionary[index]['num'])

    return course_code_list
Esempio n. 26
0
def course_hash(email, password):
    # User credentials
    piazza = Piazza()
    # Login
    piazza.user_login(email, password)

    class_dictionary = piazza.get_user_classes()

    # dictionary for 'course code: hash_id'
    course_to_hash = {}
    # print(len(class_dictionary))
    for i in range(len(class_dictionary)):
        course_to_hash.update(
            {class_dictionary[i]['num']: class_dictionary[i]['nid']})

    return course_to_hash
Esempio n. 27
0
def comment_post_aggregate(email, password, coursecode):
    # User credentials
    piazza = Piazza()
    # Login
    piazza.user_login(email, password)

    # get course code to hash dictionary
    coursetohash = course_hash(email, password)

    # get classroom object using the hash
    classroom = piazza.network(coursetohash[coursecode])

    # go through all the posts, aggregate them in a data-structure
    postquestions = []
    postanswers = []

    # board_posts type is generator: cannot access memory in the lazy list
    board_posts = classroom.iter_all_posts(limit=const_limit)

    # iterate through board posts
    for post in board_posts:
        # get rid of html tags in question in post
        question_string = strip_tags(post["history"][0]["content"])

        # append to questions array
        postquestions.append(question_string)

        # checks if there's an answer associated to the question
        if "children" in post.keys(
        ) and post["children"] and "history" in post["children"][0]:

            # for all answers in a single post (iterate)
            for answer_index in range(len(post["children"][0]["history"])):

                # get rid of html tags for answers in the post, and check if the entry is a string
                if type(post["children"][0]["history"][answer_index]
                        ["content"]) == str:
                    answer_string = strip_tags(post["children"][0]["history"]
                                               [answer_index]["content"])

                    # append to answers array
                    postanswers.append(answer_string)

    # print(postQuestions + postAnswers)
    return postquestions + postanswers
Esempio n. 28
0
 def __init__(self,
              name: str,
              nid: str,
              email: str,
              password: str,
              guild: discord.Guild,
              fetch_max: int = 55,
              fetch_min: int = 30):
     self._name = name
     self.nid = nid
     self._guild = guild
     self._channels = []
     self.url = f"https://piazza.com/class/{self.nid}"
     self.p = Piazza()
     self.p.user_login(email=email, password=password)
     self.network = self.p.network(self.nid)
     self.fetch_max = fetch_max
     self.fetch_min = fetch_min
Esempio n. 29
0
def try_login():
    '''
    Tries to login to Piazza using the username/password specified in
    config.yml
    '''
    yaml_config = get_config()

    print 'Attempting to login to Piazza as %s.....' % yaml_config['username'],
    piazza = Piazza()

    try:
        piazza.user_login(email=yaml_config['username'],
                          password=yaml_config['password'])
    except BaseException:
        print 'failed, check username/password'

    print 'success'
    return piazza
Esempio n. 30
0
def pubish_to_piazza(message_contents):
    # Get the meeting URL + meeting password
    message_body = base64.urlsafe_b64decode(
        message_contents["payload"]["body"]["data"]).decode("utf-8").replace(
            "&", "&")
    meeting_url = re.findall('(https?://[^\s]+)', message_body)[2]
    meeting_password = re.findall(r'Access Password: (.{8})', message_body)[0]

    # Post them to Piazza
    piazza_message_content = f"Recording URL: {meeting_url}\nMeeting Password: {meeting_password}"
    piazza_client = Piazza()
    piazza_client.user_login(email=PIAZZA_EMAIL, password=PIAZZA_PASSWORD)
    piazza_class = piazza_client.network(PIAZZA_CLASS_NETWORK_ID)
    piazza_class.create_post(post_type="note",
                             post_folders=["logistics"],
                             post_subject="New Recording Available",
                             post_content=piazza_message_content)

    print("Uploaded new recording to Piazza!")