Example #1
0
 def regenerate_auth(self):
     token = self.tokens[self.count]
     if self.tokens.index(token) == len(self.tokens) - 1:
         self.count = 0
     else:
         self.count += 1
     self.jotform_api = JotformAPIClient(token)
Example #2
0
class JotformMonitor:
    def __init__(self):
        self.latest = None
        self.entrance_webhook = 'https://discordapp.com/api/webhooks/721531220479049868/9AaNPBSNi3fYt0sL-AJ8M_UGqmS0dRHx_ZEiWDUYOPj8XtfHK8k4ZC0P0ok6eLCz1aP6'
        self.count = 0
        self.tokens = [
            '17df4208b37eb80324e68805b6bce15a',
            '83285c23f180db2702c30f7eaba34382',
            '985a737612e7cdcb5edeae88a5b66c67',
            'be70837a6313c19b28226e18a4c2e258',
            '5834536ae379568cb112b78ef92ca208'
        ]
        self.jotform_api = JotformAPIClient(random.choice(self.tokens))

    def load_data(self):
        with open('keys.json', 'r') as f:
            return json.load(f)

    def dump_data(self, data):
        with open('keys.json', 'w') as f:
            return json.dump(data, f)

    def regenerate_auth(self):
        token = self.tokens[self.count]
        if self.tokens.index(token) == len(self.tokens) - 1:
            self.count = 0
        else:
            self.count += 1
        self.jotform_api = JotformAPIClient(token)

    def monitor_keys(self, *, seconds=0, minutes=0, hours=0):
        self.latest = self.jotform_api.get_form_submissions('201360640153038')

        # loop
        while True:
            newest = self.jotform_api.get_form_submissions('201360640153038')
            if newest != self.latest:
                data = self.load_data()
                new_submissions = [
                    submission for submission in newest
                    if submission not in self.latest
                ]
                self.latest = newest
                for submission in new_submissions:
                    if submission['form_id'] == '201360640153038':
                        username = submission['answers']['5']['answer']
                        key = submission['answers']['24']['answer']
                        data[username] = key
                        self.dump_data(data)
                        requests.post(self.entrance_webhook,
                                      json={
                                          'content':
                                          f'username: {username}\nkey: {key}'
                                      })
            self.regenerate_auth()
            time.sleep(seconds + minutes * 60 + hours * 3600)
Example #3
0
 def __init__(self):
     self.latest = None
     self.entrance_webhook = 'https://discordapp.com/api/webhooks/721531220479049868/9AaNPBSNi3fYt0sL-AJ8M_UGqmS0dRHx_ZEiWDUYOPj8XtfHK8k4ZC0P0ok6eLCz1aP6'
     self.count = 0
     self.tokens = [
         '17df4208b37eb80324e68805b6bce15a',
         '83285c23f180db2702c30f7eaba34382',
         '985a737612e7cdcb5edeae88a5b66c67',
         'be70837a6313c19b28226e18a4c2e258',
         '5834536ae379568cb112b78ef92ca208'
     ]
     self.jotform_api = JotformAPIClient(random.choice(self.tokens))
Example #4
0
    def login(self, force_new=False):
        """Read API key from file or request one from user, create API-client."""
        from jotform import JotformAPIClient
        print "Creating client... ",
        user = self.user
        try:
            assert (force_new == False)
            with open(".%s_jotform_API_key.txt" % user, "r") as f:
                api_key = f.readline()
            print "sucsessfully read API key from file"

        except:
            print "failed to find API key. Please generate one at http://www." \
                  "jotform.com/myaccount/api and paste it here."
            api_key = raw_input("API_key: ")

            # Write API key to file for future use
            with open(".%s_jotform_API_key.txt" % user, "w") as f:
                f.write(api_key)
            print "API key has been saved to file for future use."

        self.client = JotformAPIClient(api_key, debug=True)
Example #5
0
class JotformQuizMaker(QuizMaker):
    """
    Uses the Jotform service. Register a user at jotform.com.
    Get the python 2.7 API from https://github.com/jotform/jotform-api-python
    Get an API key from http://www.jotform.com/myaccount/api.
    """
    def __init__(self, user, force_new=False):
        self.user = user
        # Creates an API client using the API key
        self.login(force_new)

    def login(self, force_new=False):
        """Read API key from file or request one from user, create API-client."""
        from jotform import JotformAPIClient
        print "Creating client... ",
        user = self.user
        try:
            assert (force_new == False)
            with open(".%s_jotform_API_key.txt" % user, "r") as f:
                api_key = f.readline()
            print "sucsessfully read API key from file"

        except:
            print "failed to find API key. Please generate one at http://www." \
                  "jotform.com/myaccount/api and paste it here."
            api_key = raw_input("API_key: ")

            # Write API key to file for future use
            with open(".%s_jotform_API_key.txt" % user, "w") as f:
                f.write(api_key)
            print "API key has been saved to file for future use."

        self.client = JotformAPIClient(api_key, debug=True)

    def upload_quiz(self, form):
        """
        Take a JotForm form-object and upload it, return the id assigned
        to the form and the url where it can be located.
        For more information on the JotForm form-object, see the JotForm 
        syntax guide.
        """
        print "Uploading quiz to JotForm... ",

        # Uses the JotForm API
        r = self.client.create_form(form)

        print "success!"
        return r['id'], r['url']

    def get_quiz(self, form_id):
        """Fetch a given quiz belonging to the user, returns dictionary."""
        print "Fetching given quiz from JotForm...",

        # Note: client.get_form() only gets basic information about a form

        properties = self.client.get_form_properties(form_id)
        questions = self.client.get_form_questions(form_id)

        print "success!"

        return {"properties": properties, "questions": questions}

    def get_all_quizzes(self):
        """Fetch all forms belonging to user from server, return as list."""
        print "Fetching all quizzes from JotForm... ",

        # Note, client.get_forms() only returns basic information about forms
        form_filter = {"status:ne": "DELETED"}
        forms = self.client.get_forms(None, None, form_filter, None)
        quizzes = [self.get_quiz(f[u'id']) for f in forms]

        print "success!"
        return quizzes

    def delete_quiz(self, quiz_id):
        """Delete form of given id."""
        print "Deleting JotForm form... ",
        self.client.delete_form(quiz_id)
        print "success!"

    def delete_all_quizzes(self):
        """Delete all forms of user."""
        print "Deleting all JotForm forms... ",
        for quiz_id in [f[u'id'] for f in self.client.get_forms()]:
            self.delete_quiz(quiz_id)
        print "success!"

    def make_quiz(self, questions, **kwargs):
        """
        Take a list of dictionaries of the format given by reading 
        a .quiz-file. Return the corresponding JotForm quiz-object.
        """
        print "Turning questions into a JotForm quiz-object."

        form = \
        {
            'properties':
            {
                'title': 'Quiztools test quiz!',
                #'sendpostdata': u'No',
                #'activeRedirect': u'thanktext'
            },
            'questions': {}
        }

        # Add form properties
        for k in kwargs:
            form['properties'][k] = kwargs[k]

        # Add header to the quiz
        form['questions']['1'] = \
        {
            'headerType': 'Large',
            'name': 'titleHeader',
            'order': '1',
            'type': 'control_head',
            'text': 'Quiztools test quiz!',
            'subHeader': 'Made using quiztools',
        }

        default_question = \
        {
            'name': '',
            'special': 'None',
            'spreadCols': '1',
            'required': 'No',
            'labelAlign': 'Top',
            'allowOther': 'No',
            'otherTest': 'Other',
        }

        for q in questions:
            question = default_question.copy()
            question['name'] = str(len(form['questions']) + 1)
            question['text'] = q['question']
            question['order'] = str(len(form['questions']) + 1)
            question['options'] = "|".join(c[1] for c in q['choices'])
            #nc = sum([c[0]=='right' for c in q['choices']])
            question['type'] = 'control_radio'  #if (nc == 1) \
            #else 'control_checkbox'
            question['calcVales'] = "|".join(
                [str(1 * (c[0] == 'right')) for c in q["choices"]])
            form['questions'][str(len(form['questions']) + 1)] = question

        # Add a submit button to quiz
        form['questions'][str(len(form['questions'])+1)] = \
        {
            'name': 'submitButton',
            'type': 'control_button',
            'buttonAlign': 'Auto',
            'order': str(len(form['questions'])+1),
            'clear': 'No',
            'print': 'No',
            'text': 'Complete Quiz',
            'buttonStyle': 'simple_blue'
        }

        return form
Example #6
0
import unicodedata
import sys
import os
import re

reload(sys)  
sys.setdefaultencoding('utf8')

"""
Jotform API call, submission ids, etc.
"""
FORM_1 = "62355313880152" # Interfaz de usuario
FORM_2 = "62357176330151" # Generar análisis por empresa
form_list  = [FORM_1,FORM_2]
jotFormKey = '33dcf578e3523959b282e1bebff1f581'
jotformAPIClient = JotformAPIClient(jotFormKey)


def update_submissions():
    """
    Creates a log on the last submission for each of the forms and alerts new submissions.
    """
    n = 1
    bool_dict = {} # Stores truth values to indicate new submissions in any of the forms
    for form_op in form_list:
        submission = jotformAPIClient.get_form_submissions(form_op,limit=5,order_by="created_at")
        log_file_name = str('logs/form'+str(n)+'.log')
        with open("logs/temp.txt", "w") as text_file:
            for sub in submission:            
                text_file.write('Timestamp : {}'.format(sub['updated_at']))
                if form_op == FORM_1:
Example #7
0
class JotformQuizMaker(QuizMaker):
    """
    Uses the Jotform service. Register a user at jotform.com.
    Get the python 2.7 API from https://github.com/jotform/jotform-api-python
    Get an API key from http://www.jotform.com/myaccount/api.
    """

    def __init__(self, user, force_new=False):
        self.user = user
        # Creates an API client using the API key
        self.login(force_new)

    def login(self, force_new=False):
        """Read API key from file or request one from user, create API-client."""
        from jotform import JotformAPIClient

        print "Creating client... ",
        user = self.user
        try:
            assert force_new == False
            with open(".%s_jotform_API_key.txt" % user, "r") as f:
                api_key = f.readline()
            print "sucsessfully read API key from file"

        except:
            print "failed to find API key. Please generate one at http://www." "jotform.com/myaccount/api and paste it here."
            api_key = raw_input("API_key: ")

            # Write API key to file for future use
            with open(".%s_jotform_API_key.txt" % user, "w") as f:
                f.write(api_key)
            print "API key has been saved to file for future use."

        self.client = JotformAPIClient(api_key, debug=True)

    def upload_quiz(self, form):
        """
        Take a JotForm form-object and upload it, return the id assigned
        to the form and the url where it can be located.
        For more information on the JotForm form-object, see the JotForm 
        syntax guide.
        """
        print "Uploading quiz to JotForm... ",

        # Uses the JotForm API
        r = self.client.create_form(form)

        print "success!"
        return r["id"], r["url"]

    def get_quiz(self, form_id):
        """Fetch a given quiz belonging to the user, returns dictionary."""
        print "Fetching given quiz from JotForm...",

        # Note: client.get_form() only gets basic information about a form

        properties = self.client.get_form_properties(form_id)
        questions = self.client.get_form_questions(form_id)

        print "success!"

        return {"properties": properties, "questions": questions}

    def get_all_quizzes(self):
        """Fetch all forms belonging to user from server, return as list."""
        print "Fetching all quizzes from JotForm... ",

        # Note, client.get_forms() only returns basic information about forms
        form_filter = {"status:ne": "DELETED"}
        forms = self.client.get_forms(None, None, form_filter, None)
        quizzes = [self.get_quiz(f[u"id"]) for f in forms]

        print "success!"
        return quizzes

    def delete_quiz(self, quiz_id):
        """Delete form of given id."""
        print "Deleting JotForm form... ",
        self.client.delete_form(quiz_id)
        print "success!"

    def delete_all_quizzes(self):
        """Delete all forms of user."""
        print "Deleting all JotForm forms... ",
        for quiz_id in [f[u"id"] for f in self.client.get_forms()]:
            self.delete_quiz(quiz_id)
        print "success!"

    def make_quiz(self, questions, **kwargs):
        """
        Take a list of dictionaries of the format given by reading 
        a .quiz-file. Return the corresponding JotForm quiz-object.
        """
        print "Turning questions into a JotForm quiz-object."

        form = {
            "properties": {
                "title": "Quiztools test quiz!",
                #'sendpostdata': u'No',
                #'activeRedirect': u'thanktext'
            },
            "questions": {},
        }

        # Add form properties
        for k in kwargs:
            form["properties"][k] = kwargs[k]

        # Add header to the quiz
        form["questions"]["1"] = {
            "headerType": "Large",
            "name": "titleHeader",
            "order": "1",
            "type": "control_head",
            "text": "Quiztools test quiz!",
            "subHeader": "Made using quiztools",
        }

        default_question = {
            "name": "",
            "special": "None",
            "spreadCols": "1",
            "required": "No",
            "labelAlign": "Top",
            "allowOther": "No",
            "otherTest": "Other",
        }

        for q in questions:
            question = default_question.copy()
            question["name"] = str(len(form["questions"]) + 1)
            question["text"] = q["question"]
            question["order"] = str(len(form["questions"]) + 1)
            question["options"] = "|".join(c[1] for c in q["choices"])
            # nc = sum([c[0]=='right' for c in q['choices']])
            question["type"] = "control_radio"  # if (nc == 1) \
            # else 'control_checkbox'
            question["calcVales"] = "|".join([str(1 * (c[0] == "right")) for c in q["choices"]])
            form["questions"][str(len(form["questions"]) + 1)] = question

        # Add a submit button to quiz
        form["questions"][str(len(form["questions"]) + 1)] = {
            "name": "submitButton",
            "type": "control_button",
            "buttonAlign": "Auto",
            "order": str(len(form["questions"]) + 1),
            "clear": "No",
            "print": "No",
            "text": "Complete Quiz",
            "buttonStyle": "simple_blue",
        }

        return form
Example #8
-1
    def login(self, force_new=False):
        """Read API key from file or request one from user, create API-client."""
        from jotform import JotformAPIClient

        print "Creating client... ",
        user = self.user
        try:
            assert force_new == False
            with open(".%s_jotform_API_key.txt" % user, "r") as f:
                api_key = f.readline()
            print "sucsessfully read API key from file"

        except:
            print "failed to find API key. Please generate one at http://www." "jotform.com/myaccount/api and paste it here."
            api_key = raw_input("API_key: ")

            # Write API key to file for future use
            with open(".%s_jotform_API_key.txt" % user, "w") as f:
                f.write(api_key)
            print "API key has been saved to file for future use."

        self.client = JotformAPIClient(api_key, debug=True)