from flask import Flask, request
import telegram
import telebot
import asyncio
import json
from rasa.core.agent import Agent
from rasa.core.interpreter import RasaNLUInterpreter

async def process(msg):
    agent = Agent.load("./models/20200512-195339.tar.gz")
    output = await agent.handle_text(msg)
    print(msg)
    print(output)
    return output

def normalisasi(msg):
    dictionary={'saya':["aku","aq","saya","sy","sya"],
                'pendaftaran':["pendaftaran","pndaftaran","pdnftrn","pendaftrn","pendftran"],
                'bisa': ["bisa","bs","bsa","isa"],
                'waktu':["waktu","wktu","wkt","saat"],
                'jurusan': ["jurusan","jrusan","jrsn","jurusn","jursn","jrusn"],
                'daftar':["daftar","daftr","dftar","dftr"],
                'yang':["yang","yg","yagn"]}
    for x, y in dictionary.items():
        if msg in y:
           msg=x
           break
    return msg

bot = telegram.Bot('1117975097:AAEc_9wuS0fBl7KeYg7zqRLfSmRHAM19m6s')

#bot.remove_webhook()
#bot.set_webhook(url="https://YOURURL{}".format(secret))

app = Flask(__name__)
@app.route('/', methods=["POST"])
def lololo():
 
 update = request.get_json()
 text = update["message"]["text"]
 chat_id = update["message"]["chat"]["id"]
 doc = text.split()
 out=""
 for t in doc:
     out=out+" "+normalisasi(t)
 data_json=asyncio.run(process(out))
 teks=""
 for element in data_json:
    teks+= element['text']+"\n"
    f = open("teks.txt", "a")
    f.write(update["message"]["text"]+"\n")
    f.close()
 bot.send_message(chat_id=chat_id, text=teks)
 return "ok"

# run the app
if __name__ == '__main__':
  app.run()
