Beispiel #1
0
  def add_answer(self, question_id, source, author):
    question = Question.get_by_id(int(question_id))
    if not question or not source:
      self.set_error_code(500)
      return
    
    #TODO: if answer is added by anonymouse, author should be set to None, 
    #      real_author is always set.(eg. question_relationship = get_relationshiop(question))
    
    new_answer = Answer(
      parent = question.key, 
      summary = source[0:100], 
      question = question.key, 
      author = author.key,
      real_author = author.key,
      content = source.replace("\n", "<br />"),
      source = source) 

    new_answer.put()
    
    relation = AccountQuestionRelationService().get_relationship(author.key, question.key)
    relation.my_answer = new_answer.key
    relation.put()
    QuestionService().update_answer_num(question.key)
    return new_answer
Beispiel #2
0
 def set_no_help(self, actor, question_id, answer_id):
   question = Question.get_by_id(int(question_id))
   answer = Answer.get_by_id(parent = question.key, id = int(answer_id))
   relation = AccountQuestionRelationService().get_relationship(actor.key, question.key)
   if not answer.key in relation.no_help_answers:
     relation.no_help_answers.append(answer.key)
   
   relation.put()
Beispiel #3
0
  def remove_answer_from_question(self, question_id, answer_id):
    question = Question.get_by_id(int(question_id))
    if not question:
      return
      
    answer = Answer.get_by_id(int(answer_id), parent = question.key)
    if not answer:
      return

    answer.key.delete()
    self.update_answer_num(question.key)
    return question
Beispiel #4
0
def handle_follow(event):
    try:
        user_picture = line_bot_api.get_profile(user_id).picture_url
    except:
        user_picture = 'https://image.prntscr.com/image/t2BFLWxiRf2OJq_G4kKKtw.png'

    if user_picture == None:
        user_picture = "https://vanika.tru.io/vanikabot/tandatanya.jpg"
    else:
        user_picture = user_picture

    # INSERT DATA TO DATABASE
    """ config """
    db = Database(Config)
    """ query """
    db.run_query(Insert.userjoin(user_id, user_name, user_picture), user_name,
                 user_id)
    """ log """
    app.logger.info("Got Follow event:" + event.source.user_id)
    """ answer """
    Answer.greeting_message(event, user_name)
Beispiel #5
0
 def voteup_answer(self, actor, question_id, answer_id):
   question = Question.get_by_id(int(question_id))
   answer = Answer.get_by_id(parent = question.key, id = int(answer_id))
   relation = AccountQuestionRelationService().get_relationship(actor.key, question.key)
   if answer.key in relation.up_voted_answers:
     relation.up_voted_answers = [ a for a in relation.up_voted_answers if a != answer.key ]
     answer.up_voted_users = [ u for u in answer.up_voted_users if u != actor.key ]
   else:
     relation.up_voted_answers.append(answer.key)
     answer.up_voted_users.append(actor.key)
     
   relation.down_voted_answers = [ a for a in relation.down_voted_answers if a != answer.key ]
   answer.down_voted_users = [ u for u in answer.down_voted_users if u != actor.key ]
   answer.put()
   relation.put()
Beispiel #6
0
  def update_answer(self, question_id, answer_id, source):
    current_question = Question.get_by_id(int(question_id))
    if not current_question:
      return
      
    answer = Answer.get_by_id(int(answer_id), parent = current_question.key)
    #TODO: raise 404 error.
    if not answer:
      return
    
    #TODO: filter desc content using hlper method.
    content = source.replace("\n", "<br />")
    
    answer.content = content
    answer.source = source

    answer.put()
Beispiel #7
0
from typing import Optional
from fastapi import FastAPI
from model.answer import Answer
from model.question import Question

app = FastAPI()

db = {}
db[1] = Question(1, 'BMW', [
    Answer(1, 'England', False),
    Answer(2, 'USA', False),
    Answer(3, 'Germany', True),
    Answer(4, 'Japan', False)
])

db[2] = Question(2, 'Toyota', [
    Answer(1, 'England', False),
    Answer(2, 'USA', False),
    Answer(3, 'Germany', False),
    Answer(4, 'Japan', True)
])

db[3] = Question(3, 'Mini', [
    Answer(1, 'England', True),
    Answer(2, 'USA', False),
    Answer(3, 'Germany', False),
    Answer(4, 'Japan', False)
])

db[4] = Question(4, 'General Motors', [
    Answer(1, 'England', False),
Beispiel #8
0
def blur_ans_json():
	index = random.randint(0, len(__blur_anss)-1)
	_ans = __blur_anss[index]
	ans = Answer(_ans.get('id', 0), _ans.get('type', 0), _ans.get('seed', 0), _ans.get('deg', 0), _ans.get('content', 'oh no!我的系统出故障了!'))
	return ans.toString()
Beispiel #9
0
def default_ans_json():
	ans = Answer(-1, -1, -1, -1, '欢迎!小伙子们在火炉旁挤挤,留个位子出来~')
	return ans.toString()
Beispiel #10
0
def default_ans():
	ans = Answer(-1, -1, -1, -1, '欢迎!小伙子们在火炉旁挤挤,留个位子出来~')
	return ans
Beispiel #11
0
 def update_answer_num(self, question_key):
   question = question_key.get()
   if question:
     answers_num = Answer.query(ancestor=question_key).count()
     question.answers_num = answers_num
     question.put()
Beispiel #12
0
 def get_answers_by_question_id(self, question_id):
   #don't need call entity service for single get operation
   question = Question.get_by_id(int(question_id))
   answers = Answer.query(ancestor = question.key).fetch()
   return answers
Beispiel #13
0
 def get_answers_by_question_key(self, question_key, keys_only = True):
   answers = Answer.query(ancestor = question_key).fetch(keys_only = keys_only)
   return answers
Beispiel #14
0
 def cancel_no_help(self, actor, question_id, answer_id):
   question = Question.get_by_id(int(question_id))
   answer = Answer.get_by_id(parent = question.key, id = int(answer_id))
   relation = AccountQuestionRelationService().get_relationship(actor.key, question.key)
   relation.no_help_answers = [ a for a in relation.no_help_answers if a != answer.key ]
   relation.put() 
Beispiel #15
0
def handle_text_message(event):
    text = event.message.text
    textlow = event.message.text.lower()
    """ GET DATA FROM DATABASE """
    # Config
    db = Database(Config)
    # Query
    # This query will return array data
    userid_db_all = db.run_query(Select.userid_db_all(), user_name, user_id)
    userid_db = db.run_query(Select.userid_db(user_id), user_name, user_id)
    usertoken_db = db.run_query(Select.usertoken_db(user_id), user_name,
                                user_id)
    useremail_db = db.run_query(Select.useremail_db(user_id), user_name,
                                user_id)
    userstatusemail_db = db.run_query(Select.userstatusemail_db(user_id),
                                      user_name, user_id)
    userpasswd_db = db.run_query(Select.userpasswd_db(user_id), user_name,
                                 user_id)
    usernick_db = db.run_query(Select.usernick_db(user_id), user_name, user_id)
    userplace_db = db.run_query(Select.userplace_db(user_id), user_name,
                                user_id)
    userprivilege_db = db.run_query(Select.userprivilege_db(user_id),
                                    user_name, user_id)
    userready_db = db.run_query(Select.userready_db(user_id), user_name,
                                user_id)
    userbiro_db = db.run_query(Select.userbiro_db(user_id), user_name, user_id)
    user_statusjawab_db = db.run_query(Select.user_statusjawab_db(user_id),
                                       user_name, user_id)
    userpush_db = db.run_query(Select.userpush_db(user_id), user_name, user_id)
    """ TRAFFIC MONITOR """
    # Store data Usertext to database
    db.run_query(Insert.usertext(user_id, user_name, text, "yes"), user_name,
                 user_id)
    # Store Count Userpush to database
    try:
        db.run_query(Update.userpush(str(userpush_db[0] + 1), user_id),
                     user_name, user_id)
    except:
        pass
    """ USER ADD CONTROL """
    if userid_db == []:
        if textlow == 'add':
            db.run_query(Insert.userjoin(user_id, user_name, user_picture),
                         user_name, user_id)
        elif textlow == 'lanjutkan':
            db.run_query(Insert.userjoin(user_id, user_name, user_picture),
                         user_name, user_id)
            Answer.menu(event)
        else:
            bubble = BubbleContainer(
                direction='ltr',
                hero=BoxComponent(),
                body=BoxComponent(
                    layout='vertical',
                    contents=[
                        # Title
                        TextComponent(text="Selamat datang di Vanika",
                                      weight='bold',
                                      size='md',
                                      gravity='center',
                                      wrap=True),
                        # Info
                        TextComponent(
                            text='Hello, ' + user_name +
                            '\nSelamat datang di Vanika, tekan "Lanjutkan" untuk ngobrol dengan Vanika',
                            color="#aaaaaa",
                            size='xs',
                            gravity='center',
                            wrap=True),
                        SeparatorComponent(),
                    ],
                ),
                footer=BoxComponent(layout='horizontal',
                                    spacing='sm',
                                    contents=[
                                        ButtonComponent(
                                            style='primary',
                                            color='#11BBFF',
                                            height='sm',
                                            action=MessageAction(
                                                label='Lanjutkan',
                                                text='lanjutkan'),
                                        ),
                                    ]),
            )
            message = FlexSendMessage(alt_text="Confirm", contents=bubble)
            line_bot_api.reply_message(event.reply_token, [message])
    elif userready_db[0] == 'yes':
        if user_statusjawab_db[0] == 'none':
            if textlow == "menu":
                Answer.menu(event)
            elif ('!menumahasiswa' in text) or ('menu mahasiswa' in textlow):
                if useremail_db[0] == "none":
                    Answer.menu_login(event, user_name)
                else:
                    if userstatusemail_db[0] == "notverified":
                        db.run_query(
                            Update.userstatusemail("verified", user_id),
                            user_name, user_id)
                        Email.kirimEmail(useremail_db[0], user_name, user_id)
                        Answer.menu_mahasiswa(event, user_name)
                    else:
                        Answer.menu_mahasiswa(event, user_name)

            ############################################################
            # MENU MAHASISWA
            ############################################################
            elif ('!profile' in text) or ('profile' in textlow):
                if userstatusemail_db[0] == "verified":
                    raw_nim = useremail_db[0].replace("@student.unika.ac.id",
                                                      "")
                    nim_tahun = raw_nim[0:2]
                    nim_jurusan = raw_nim[2:4]
                    nim_noutur = raw_nim[4:8]
                    nim = nim_tahun + nim_jurusan + nim_noutur
                    ENDPOINT = "http://sintak.unika.ac.id/id/filektm/" + nim.upper(
                    ) + ".jpg"
                    my_path = "/var/www/html/vanikabot/ktmweb"
                    urllib.request.urlretrieve(
                        ENDPOINT,
                        os.path.join(my_path,
                                     os.path.basename(nim.upper() + ".jpg")))
                    data = {
                        "type": "bubble",
                        "body": {
                            "type":
                            "box",
                            "layout":
                            "vertical",
                            "contents": [{
                                "type":
                                "image",
                                "url":
                                "https://vanika.tru.io/vanikabot/ktmweb/" +
                                nim.upper() + ".jpg",
                                "size":
                                "full",
                                "aspectMode":
                                "cover",
                                "aspectRatio":
                                "20:13",
                                "gravity":
                                "center"
                            }],
                            "paddingAll":
                            "0px"
                        }
                    }
                    template_message = FlexSendMessage(alt_text='KTM',
                                                       contents=data)
                    line_bot_api.reply_message(event.reply_token,
                                               [template_message])
                else:
                    Answer.jawaban_login(event, user_name)

            elif ("ipk" in textlow) or ("ips" in textlow):
                if userstatusemail_db[0] == "verified":
                    raw_nim = useremail_db[0].replace("@student.unika.ac.id",
                                                      "")
                    nim_tahun = raw_nim[0:2]
                    nim_jurusan = raw_nim[2:4]
                    nim_noutur = raw_nim[4:8]
                    nim = nim_tahun + "." + nim_jurusan + "." + nim_noutur
                    Sintak.ipk_ips(event, user_name, nim)
                else:
                    Answer.jawaban_login(event, user_name)

            elif ("transkrip" in textlow):
                if userstatusemail_db[0] == "verified":
                    raw_nim = useremail_db[0].replace("@student.unika.ac.id",
                                                      "")
                    nim_tahun = raw_nim[0:2]
                    nim_jurusan = raw_nim[2:4]
                    nim_noutur = raw_nim[4:8]
                    nim = nim_tahun + "." + nim_jurusan + "." + nim_noutur
                    Sintak.transkrip(event, user_name, nim)
                else:
                    Answer.jawaban_login(event, user_name)

            elif ("tagihan" in textlow):
                if userstatusemail_db[0] == "verified":
                    text_split = text.split(" ")
                    if len(text_split) == 3:
                        raw_nim = useremail_db[0].replace(
                            "@student.unika.ac.id", "")
                        nim_tahun = raw_nim[0:2]
                        nim_jurusan = raw_nim[2:4]
                        nim_noutur = raw_nim[4:8]
                        nim = nim_tahun + "." + nim_jurusan + "." + nim_noutur
                        tahun = text_split[1]
                        period = text_split[2]
                        Sintak.tagihan(event, user_name, nim, tahun, period)
                    else:
                        raw_nim = useremail_db[0].replace(
                            "@student.unika.ac.id", "")
                        nim_tahun = raw_nim[0:2]
                        Answer.tagihan_input_tahun(event, "20" + nim_tahun)

                else:
                    Answer.jawaban_login(event, user_name)

            elif ("logout" in textlow):
                if userstatusemail_db[0] == "verified":
                    db.run_query(
                        Update.userstatusemail("notverified", user_id),
                        user_name, user_id)
                    db.run_query(Update.user_email("none", user_id), user_name,
                                 user_id)
                    Answer.menu(event)
                else:
                    Answer.jawaban_login(event, user_name)
            ############################################################
            # BIRO
            ############################################################
            elif ('!tanyabiro' in text) or ('tanya biro' in textlow):
                Answer.menu_biro(event)
            elif ('Mahasiswa baru' == text):
                Answer.mahasiswa_baru(event)
            elif ('Akademik' == text):
                Answer.jawaban_biro(event, 'Akademik', user_name)
            elif ('Keuangan' == text):
                Answer.jawaban_biro(event, 'Keuangan', user_name)
            elif ('Pusat karir' == text):
                Answer.jawaban_biro(event, 'Pusat Karir', user_name)
            elif ('Perpustakaan' == text):
                Answer.menu_perpustakaan(event, user_name)
            elif ("cari buku" == textlow):
                Answer.cari_buku(event)
            elif ('Kemahasiswaan' == text):
                Answer.jawaban_biro(event, 'Kemahasiswaan', user_name)
            ############################################################
            # MAHASISWA BARU
            ############################################################
            elif ('!infoprodi' in text) or ('informasi prodi' in textlow) or (
                    'info program studi' in textlow):
                Answer.info_prodi(event)
            elif ('!lokasi' in text) or ("map" in textlow):
                Answer.lokasi(event)
            elif ('!infokos' in text) or ('info kos' in textlow):
                Answer.infokos(event)
            elif ("!jadwalpendaftaran" in text) or ("jadwal pendaftaran"
                                                    in textlow):
                Answer.buku_panduan(event, "Jadwal pendaftaran", "12")
            elif ('!carapendaftaran' in text) or ('cara pendaftaran'
                                                  in textlow):
                Answer.buku_panduan(event, "Prosedur pendaftaran", "8")
            elif ("!biaya" in text) or ("biaya" in textlow):
                Answer.buku_panduan(event, "Biaya pendaftaran", "20")
            elif ("!syarat" in text) or ("syarat pendaftaran" in textlow) or (
                    'syarat kuliah di unika' in textlow):
                Answer.buku_panduan(event, "Syarat pendaftaran", "6")
            elif ('!pembayaran' in text) or ("cara pembayaran" in textlow):
                Answer.pembayaran(event)
            elif ('!pengumuman' in text) or ('pengumuman' in textlow):
                Answer.pengumuman(event)
            elif ('!daftarulang' in text) or ('daftar ulang' in textlow):
                Answer.daftar_ulang(event)
            elif ('!pmb' in text) or ('pembekalan mahasiswa baru' in textlow):
                Answer.pmb(event)
            elif ('!hotline' in text) or ('hotline'
                                          in textlow) or ("nomor" in textlow):
                Answer.hotline(event)
            elif ('!email' in text) or ('email' in textlow):
                Answer.email(event)
            elif ('!admin' in text) or ('admin' in textlow):
                Answer.admin(event)
            ############################################################
            # JURUSAN
            ############################################################
            # it's empty space
            ############################################################
            # CHAT
            ############################################################
            elif ('baik' in textlow) or ('alhamdulillah'
                                         in textlow) or ('sangat baik'
                                                         in textlow):
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(
                        text="Puji tuhan \nSemoga harinya lancar kak " +
                        user_name + " ?"))
            ############################################################
            # WEB SCRAPING
            ############################################################
            elif ('!beasiswa' in text) or ('beasiswa' in textlow):
                Beasiswa.beasiswa(event)

            elif ('!lowongan' in text) or ('lowongan' in textlow):
                Lowongan.lowongan(event)

            elif ("!news" in text) or ("news" in textlow) or ('berita'
                                                              in textlow):
                Unikanews.unikanews(event)

            elif ("!io" in text) or (textlow == "international office"):
                Internationaloffice.internationaloffice(event)

            elif ("cari buku" in textlow):
                buku = text[0:].split(" ", 2)
                try:
                    ENDPOINT = "http://lib.unika.ac.id/index.php?keywords=" + buku[
                        2].lower().replace(" ", "+") + "&search=Pencarian"
                    url = urlreq.urlopen(
                        urlreq.Request(
                            ENDPOINT,
                            headers={
                                'User-Agent':
                                "Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)"
                            }))
                    udict = url.read().decode('utf-8')
                    rawurl = re.findall(
                        '<div class="detail-list"><h4><a href="(.*?)"', udict,
                        re.DOTALL | re.IGNORECASE)
                    rawtitels = re.findall(
                        'citationLink" title="Citation for: (.*?)"', udict,
                        re.DOTALL | re.IGNORECASE)
                    my_path = "/var/www/html/vanikabot/imageperpus"

                    columns = []
                    for i in range(0, 5):
                        url = urlreq.urlopen(
                            urlreq.Request(
                                "http://lib.unika.ac.id/" + rawurl[i],
                                headers={
                                    'User-Agent':
                                    "Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)"
                                }))
                        udict = url.read().decode('utf-8')
                        rawimg = re.findall(
                            '<img itemprop="image" alt="Image of ' +
                            rawtitels[i] + '" src="(.*?)"', udict,
                            re.DOTALL | re.IGNORECASE)
                        if rawimg == []:
                            rawimg = "https://vanika.tru.io/vanikabot/tandatanya.jpg"
                        else:
                            rawimg = "http://lib.unika.ac.id" + rawimg[0]

                        img = rawimg.replace("&amp;width=200", "&width=500")

                        urllib.request.urlretrieve(
                            img,
                            os.path.join(my_path,
                                         os.path.basename(str(i) + ".png")))

                        carousel_column = BubbleContainer(
                            direction='ltr',
                            styles=BubbleStyle(footer=BlockStyle(
                                background_color="#11BBFF")),
                            header=BoxComponent(layout='vertical',
                                                contents=[
                                                    TextComponent(
                                                        text="HASIL PENCARIAN",
                                                        weight='bold',
                                                        color="#11BBFF",
                                                        size='sm',
                                                        gravity='center',
                                                        wrap=True),
                                                ]),
                            hero=ImageComponent(
                                url=
                                "https://vanika.tru.io/vanikabot/imageperpus/"
                                + str(i) + ".png",
                                size='full',
                                aspect_ratio='20:13',
                                aspect_mode='cover',
                                action=URIAction(
                                    uri=
                                    "https://vanika.tru.io/vanikabot/imageperpus/"
                                    + str(i) + ".png",
                                    label='picture')),
                            body=BoxComponent(
                                layout='vertical',
                                contents=[
                                    #titile
                                    TextComponent(text=rawtitels[i],
                                                  weight='bold',
                                                  size='md',
                                                  gravity='center',
                                                  wrap=True),
                                ],
                            ),
                            footer=BoxComponent(
                                layout='vertical',
                                spacing='sm',
                                contents=[
                                    ButtonComponent(
                                        style='primary',
                                        color="#11BBFF",
                                        height='sm',
                                        action=URIAction(
                                            label='Detail',
                                            uri="http://lib.unika.ac.id" +
                                            rawurl[i])),
                                ]),
                        )
                        columns.append(carousel_column)

                    carousel_template = CarouselContainer(contents=columns)
                    template_message = FlexSendMessage(
                        alt_text='Daftar Buku', contents=carousel_template)
                    line_bot_api.reply_message(event.reply_token, [
                        template_message,
                        TextSendMessage(
                            text="Hasil lebih lengkap bisa kunjungi " +
                            ENDPOINT)
                    ])
                except:
                    line_bot_api.reply_message(event.reply_token, [
                        TextSendMessage(
                            text="Tidak ada hasil pencarian untuk " + text +
                            "\nKunjungi situs perpustakaan di lib.unika.ac.id\n",
                            quick_reply=QuickReply(items=[
                                QuickReplyButton(action=MessageAction(
                                    label="Menu", text="Menu")),
                            ]))
                    ])
            ############################################################
            # AIML
            # GET DATA FROM aiml app and DATABASE COMMAND
            ############################################################
            elif text == text:
                inputan = textlow.replace(" ", "%20")
                #FROM DATABASE
                command_from_db = db.run_query(Select.command_db(text),
                                               user_name, user_id)
                userpush_db_command = db.run_query(
                    Select.userpush_db_command(text), user_name, user_id)
                if command_from_db == []:
                    #FROM AIML
                    try:  #prm
                        aiml_unika = urlopen(
                            "http://app.unika.ac.id/bot/chatbot/conversation_start.php?convo_id="
                            + user_id + "&format=json&bot_id=1&say=" +
                            inputan).read()
                    except:
                        bot_say = 'Semoga ke depannya akan selalu baik adanya...'
                    try:  #baa
                        aiml_unika = urlopen(
                            "http://app.unika.ac.id/bot/chatbot/conversation_start.php?convo_id="
                            + user_id + "&format=json&bot_id=3&say=" +
                            inputan).read()
                    except:
                        bot_say = 'Semoga ke depannya akan selalu baik adanya...'
                    try:  #bak
                        aiml_unika = urlopen(
                            "http://app.unika.ac.id/bot/chatbot/conversation_start.php?convo_id="
                            + user_id + "&format=json&bot_id=4&say=" +
                            inputan).read()
                    except:
                        bot_say = 'Semoga ke depannya akan selalu baik adanya...'
                    try:  #aacc
                        aiml_unika = urlopen(
                            "http://app.unika.ac.id/bot/chatbot/conversation_start.php?convo_id="
                            + user_id + "&format=json&bot_id=6&say=" +
                            inputan).read()
                    except:
                        bot_say = 'Semoga ke depannya akan selalu baik adanya...'
                    try:  #perpus
                        aiml_unika = urlopen(
                            "http://app.unika.ac.id/bot/chatbot/conversation_start.php?convo_id="
                            + user_id + "&format=json&bot_id=7&say=" +
                            inputan).read()
                    except:
                        bot_say = 'Semoga ke depannya akan selalu baik adanya...'
                    try:  #kemahaiswaan
                        aiml_unika = urlopen(
                            "http://app.unika.ac.id/bot/chatbot/conversation_start.php?convo_id="
                            + user_id + "&format=json&bot_id=5&say=" +
                            inputan).read()
                    except:
                        bot_say = 'Semoga ke depannya akan selalu baik adanya...'

                    bot_say = json.loads(aiml_unika)['botsay']
                    if ('Semoga ke depannya akan selalu baik adanya...'
                            in bot_say) or ('No answer' in bot_say):
                        Answer.else_message(event, user_name)
                        db.run_query(
                            Update.usertext_update(user_id, text, "no"),
                            user_name, user_id)
                    else:
                        line_bot_api.reply_message(
                            event.reply_token, TextSendMessage(text=bot_say))
                else:
                    bot_say = command_from_db[0]
                    db.run_query(
                        Update.userpush_command(
                            str(userpush_db_command[0] + 1), text), user_name,
                        user_id)
                    line_bot_api.reply_message(event.reply_token,
                                               TextSendMessage(text=bot_say))
            else:
                Answer.else_message(event, user_name)
                db.run_query(Update.usertext_update(user_id, text, "no"),
                             user_name, user_id)