def playSong():
    os.system('sudo sh checkusb')
    try:
        musicList = open('musiclist', 'r')
        drivePath = open('drivepath', 'r')
        music_list = musicList.read().split('\n')
        drive_path = drivePath.read()
        drive_path = drive_path[0:len(drive_path) - 1]
        musicList.close()
        drivePath.close()
        if (len(drive_path) == 0 or len(music_list) <= 0):
            texttospeech.convert("No music file found")
            return
    except:
        print("Exception")
        return
    sharedvariable.stopFlag = True
    obj = stopomxthread.omxCheck()
    obj.start()
    sharedvariable.songFlag = False
    for a in music_list:
        song = drive_path + '/' + a
        while (sharedvariable.omxOn):
            time.sleep(1)
        sharedvariable.omxOn = True
        sharedvariable.usbFlag = True
        sharedvariable.currentSongPath = song
        os.system('omxplayer -o hdmi ' + "'" + song + "'")
        sharedvariable.omxOn = False
        sharedvariable.usbFlag = False
        time.sleep(.5)
        if (sharedvariable.songFlag):
            break
    sharedvariable.stopFlag = False
Example #2
0
def calculate(expression):
	parsedExpression=parseExpression(expression)
	try:
		print('Parsed Expression '+parsedExpression)
		result=eval(parsedExpression)
		texttospeech.convert('The value of the expression is '+str(result)+", "+str(gender.gender()))
	except Exception as e:
		print(str(e))
		randomresponse.generateResponse('calculatorfail')
def savepicture():
    try:
        cnx = mysql.connector.connect(user='******',
                                      password='******',
                                      host='127.0.0.1',
                                      database='phpmyadmin')
        cursor = cnx.cursor()
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("Something is wrong with your user name or password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("Database does not exist")
        else:
            print(err)
    else:
        count = 0
        query = ("select count(*) from pictures;")
        cursor.execute(query)
        for (x) in cursor:
            count = str(x[0] + 1)
        cursor.close()
        cnx.close()
        path = "/var/www/html/pictures/" + count + ".jpg "
        os.system("cp /var/www/html/pictures/temp.jpg " + path)
        try:
            cnx = mysql.connector.connect(user='******',
                                          password='******',
                                          host='127.0.0.1',
                                          database='phpmyadmin')
            cursor = cnx.cursor()
        except mysql.connector.Error as err:
            pass
        else:
            user = sharedvariable.currentUser
            query = ("insert into pictures (username,path) values(\'" + user +
                     "\',\'" + path + "\');")
            cursor.execute(query)
            cnx.commit()
            texttospeech.convert("The picture was saved successfully.")
            cursor.close()
            cnx.close()
            try:
                cnx = mysql.connector.connect(user='******',
                                              password='******',
                                              host='127.0.0.1',
                                              database='phpmyadmin')
                cursor = cnx.cursor()
            except mysql.connector.Error as err:
                pass
            else:
                user = sharedvariable.currentUser
                query = ("delete from temppicture where 1;")
                cursor.execute(query)
                cnx.commit()
                cursor.close()
                cnx.close()
Example #4
0
def build_date(string):
    try:
        string = string[string.rindex("is") + 3:len(string)]
    except Exception as e:
        texttospeech.convert("I am unable to understand your query")
        return "0"
    monthArray = [
        "january", "february", "march", "april", "may", "june", "july",
        "august", "september", "october", "november", "december"
    ]
    shortMonArray = [
        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sept", "oct",
        "nov", "dec"
    ]
    year = datetime.datetime.now().year
    month = datetime.datetime.now().month
    l = string.split(" ")
    if (l[0] == "today"):
        return str(datetime.datetime.now().date())
    if (l[0] == "tomorrow"):
        return str((datetime.datetime.now() + timedelta(1)).date())
    #print("l[0]=="+l[0])
    #print("l[1]=="+l[1])
    if (l[0][0].isnumeric() and l[0][1].isnumeric()):
        day = l[0][0] + l[0][1]
    elif (l[0][0].isnumeric()):
        day = "0" + l[0][0]
    else:
        print("2.1")
        return "-1"
    if (len(l) == 1):
        return str(year) + "-" + str(month) + "-" + day
    elif (len(l) >= 2):
        if (len(l) == 3):
            if (l[2].isnumeric()):
                year = l[2]
            else:
                print("2.2")
                return "-1"
        if (l[1].isnumeric()):
            return str(year) + "-" + l[1] + "-" + day
        else:
            i = 0
            while (i < len(monthArray)):
                if (l[1].lower() == monthArray[i]
                        or l[1].lower() == shortMonArray[i]):
                    if (i < 10):
                        month = "0" + str(i + 1)
                    else:
                        month = str(i + 1)
                    return str(year) + "-" + month + "-" + day
                i = i + 1
 def run(self):
     if (sharedvariable.currentUser == ""):
         return
     print(str(event))
     while (event):
         minimum = min(eventTime)
         index = eventTime.index(minimum)
         timeDifference = datetime.datetime.strptime(
             minimum + ':00', '%H:%M:%S') - datetime.datetime.strptime(
                 datetime.datetime.now().strftime('%H:%M:%S'), '%H:%M:%S')
         print(timeDifference)
         pauseTime = 1
         if ('-1' in str(timeDifference)):
             event.remove(event[index])
             eventTime.remove(eventTime[index])
         elif (str(timeDifference) <= '0:00:30'):
             pauseTime = 1
         elif (str(timeDifference) <= '0:01:00'):
             pauseTime = 30
         elif (str(timeDifference) <= '0:05:00'):
             pauseTime = 60
         elif (str(timeDifference) <= '0:10:00'):
             pauseTime = 300
         elif (str(timeDifference) <= '0:30:00'):
             pauseTime = 10 * 60
         elif (str(timeDifference) <= '1:00:00'):
             pauseTime = 30 * 60
         else:
             pauseTime = 60 * 60
         if (str(timeDifference) == '0:00:00'):
             string = "You have an event! " + event[index]
             event.remove(event[index])
             eventTime.remove(eventTime[index])
             if (sharedvariable.omxOn):
                 os.system('killall omxplayer.bin')
                 print(sharedvariable.omxOn)
                 sharedvariable.stopFlag = False
                 time.sleep(.3)
                 sharedvariable.omxOn = True
             texttospeech.convert(string)
             if (sharedvariable.playSongFlag):
                 sharedvariable.stopFlag = True
                 obj = stopomxthread.omxCheck()
                 obj.start()
         eventCondition.acquire()
         eventCondition.wait(pauseTime)
         eventCondition.release()
     sharedvariable.eventCheckerObject = None
Example #6
0
def start():
	obj=sharedvariable.loadSharedVariables()
	obj.start()
	obj.join()
	var=1
	texttospeech.convert("Hello! I am ready to talk.")
	while var==1:
		if(reloadcredentials.check()):
			credentialsloader.load();
			eventchecker.checkEvent()
			if(eventchecker.event):
				sharedvariable.eventCheckerObject=eventchecker.eventCheck()
				sharedvariable.eventCheckerObject.start()
		if(sharedvariable.doNotInterrupt==False):
			try:
				cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1',database='phpmyadmin')
				cursor = cnx.cursor()
			except mysql.connector.Error as err:
				if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
					print("Something is wrong with your user name or password")
				elif err.errno == errorcode.ER_BAD_DB_ERROR:
					print("Database does not exist")
				else:
					print(err)
			else:
				query = ("select * from buffer;")
				cursor.execute(query)
				for(v,buff,t) in cursor:
					if(v==1):
						print("Valid Value= "+str(v))
						print("Buffer Value= "+buff)
						print("Time Value is "+str(t))
						parsequery.parse(buff)
					else:
						print("talk to me")
				cursor.close()
				query = ("update buffer set valid=0 where 1;")
				cursor = cnx.cursor()
				cursor.execute(query)
				cnx.commit()
				cursor.close()
				cnx.close()
		time.sleep(2)
Example #7
0
def remove(string):
    maximum = 0
    song_index = 0
    if ("this song" in string.lower()):
        song = sharedvariable.currentSongName
        path = sharedvariable.currentSongPath
        song_index = sharedvariable.songName.index(song)
    else:

        for a in sharedvariable.songName:
            if (a in string.lower()):
                if (maximum < len(a)):
                    maximum = len(a)
                    song_index = sharedvariable.songName.index(a)
        if (maximum == 0):
            texttospeech.convert("No such song exists")
            return
        song = sharedvariable.songName[song_index]
        path = sharedvariable.songPath[song_index]
    os.system("rm '" + path + "'")
    try:
        cnx = mysql.connector.connect(user='******',
                                      password='******',
                                      host='127.0.0.1',
                                      database='phpmyadmin')
        cursor = cnx.cursor()
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("Something is wrong with your user name or password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("Database does not exist")
        else:
            print(err)
    else:
        query = ("delete from songs where name=\'" + song + "\';")
        cursor.execute(query)
        cnx.commit()
        cursor.close()
        sharedvariable.songName.remove(song)
        sharedvariable.songPath.remove(path)
        sharedvariable.songType.remove(sharedvariable.songType[song_index])
        texttospeech.convert("The song has been deleted")
def nickname(string):
	try:
		cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1',database='phpmyadmin')
		cursor = cnx.cursor()
	except mysql.connector.Error as err:
		if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
			print("Something is wrong with your user name or password")
		elif err.errno == errorcode.ER_BAD_DB_ERROR:
			print("Database does not exist")
		else:
			print(err)
	else:
		index=string.rindex(" me ")
		nickname=string[index+4:len(string)]
		query=("update users set nickname=\'"+nickname+"\' where emailid=\'"+sharedvariable.currentUser+"\';")
		cursor.execute(query)
		cnx.commit()
		cursor.close()
		cnx.close()
		texttospeech.convert("OK, "+nickname+". I will keep that in mind.")
Example #9
0
def get_day(string):
    dayArray = [
        "monday", "tuesday", "wednesday", "thursday", "friday", "saturday",
        "sunday"
    ]
    date = build_date(string)
    if (date != "-1" and date != "0"):
        try:
            req_date = datetime.datetime.strptime(date, "%Y-%m-%d")
            #print(date+" is on "+str(dayArray[req_date.weekday()]))
            texttospeech.convert(date + " is on " +
                                 str(dayArray[req_date.weekday()]))
        except Exception as e:
            texttospeech.convert("Please enter a proper date")
    elif (date == "-1" and date != "0"):
        texttospeech.convert("Please enter a proper date")
Example #10
0
def find_date(string):
    now = datetime.datetime.now()
    dayArray = [
        "monday", "tuesday", "wednesday", "thursday", "friday", "saturday",
        "sunday"
    ]
    if ("today" in string.lower()):
        texttospeech.convert("Today is " + str(now.date()))
    elif ("tomorrow" in string.lower()):
        texttospeech.convert("Tomorrow is " + str((now + timedelta(1)).date()))
    else:
        for a in dayArray:
            if (a in string.lower()):
                weekday = now.weekday()
                i = 0
                while (weekday != dayArray.index(a)):
                    weekday = (weekday + 1) % 7
                    i = i + 1
                texttospeech.convert("The day is on " +
                                     str((now + timedelta(i)).date()))
                break
def move():
    try:
        cnx = mysql.connector.connect(user='******',
                                      password='******',
                                      host='127.0.0.1',
                                      database='phpmyadmin')
        cursor = cnx.cursor()
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("Something is wrong with your user name or password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("Database does not exist")
        else:
            print(err)
    else:
        path = sharedvariable.currentSongPath
        genre = ""
        songName = ""
        query = ("update buffer set valid=0 where 1;")
        cursor.execute(query)
        cnx.commit()
        cursor.close()
        texttospeech.convert(
            "Under which category do you want me to put this song? Available categories are "
            + str(sharedvariable.songGenres))
        #print("Under which category do you want me to put this song? Available categories are "+str(sharedvariable.songGenres))
        emptyBufferFlag = True
        while (emptyBufferFlag):
            query = ("select * from buffer;")
            cnx = mysql.connector.connect(user='******',
                                          password='******',
                                          host='127.0.0.1',
                                          database='phpmyadmin')
            cursor = cnx.cursor()
            cursor.execute(query)
            for (v, buff, t) in cursor:
                if (v == 1):
                    if (buff.lower() in sharedvariable.songGenres):
                        genre = buff.lower()
                        emptyBufferFlag = False
                    elif (buff.lower() == "cancel operation"):
                        query = ("update buffer set valid=0 where 1;")
                        cnx = mysql.connector.connect(user='******',
                                                      password='******',
                                                      host='127.0.0.1',
                                                      database='phpmyadmin')
                        cursor = cnx.cursor()
                        cursor.execute(query)
                        cnx.commit()
                        cursor.close()
                        return
                    else:
                        texttospeech.convert(
                            "Please choose a genre from the available choices")
            time.sleep(1)
            cursor.close()
        query = ("update buffer set valid=0 where 1;")
        cnx = mysql.connector.connect(user='******',
                                      password='******',
                                      host='127.0.0.1',
                                      database='phpmyadmin')
        cursor = cnx.cursor()
        cursor.execute(query)
        cnx.commit()
        cursor.close()
        texttospeech.convert("What do you want to name this song?")
        emptyBufferFlag = True
        while (emptyBufferFlag):
            cnx = mysql.connector.connect(user='******',
                                          password='******',
                                          host='127.0.0.1',
                                          database='phpmyadmin')
            cursor = cnx.cursor()
            query = ("select * from buffer;")
            cursor.execute(query)
            for (v, buff, t) in cursor:
                if (v == 1 and buff.lower() == "cancel operation"):
                    query = ("update buffer set valid=0 where 1;")
                    cnx1 = mysql.connector.connect(user='******',
                                                   password='******',
                                                   host='127.0.0.1',
                                                   database='phpmyadmin')
                    cursor1 = cnx1.cursor()
                    cursor1.execute(query)
                    cnx1.commit()
                    cursor1.close()
                    return
                elif (v == 1):
                    if (buff.lower() in sharedvariable.songName):
                        query = ("update buffer set valid=0 where 1;")
                        cnx1 = mysql.connector.connect(user='******',
                                                       password='******',
                                                       host='127.0.0.1',
                                                       database='phpmyadmin')
                        cursor1 = cnx1.cursor()
                        cursor1.execute(query)
                        cnx1.commit()
                        cursor1.close()
                        texttospeech.convert(
                            "This song already exists in your playlist. Please choose another name for this song to save it."
                        )
                    else:
                        emptyBufferFlag = False
                        songName = buff.lower()
            time.sleep(1)
            cursor.close()
        try:
            destination = "/home/pi/Desktop/nanpy/Final/songs/" + songName + ".mp3"
            os.system('cp "' + path + '" ~/Desktop/nanpy/Final/songs/"' +
                      songName + '".mp3')
            query = ("insert into songs values(\'" + songName + "\',\'" +
                     destination + "\',\'" + genre + "\');")
            cnx = mysql.connector.connect(user='******',
                                          password='******',
                                          host='127.0.0.1',
                                          database='phpmyadmin')
            cursor = cnx.cursor()
            cursor.execute(query)
            cnx.commit()
            cursor.close()
            texttospeech.convert("Song was added successfully")
            sharedvariable.songName.append(songName)
            sharedvariable.songPath.append(destination)
            sharedvariable.songType.append(genre)
        except:
            texttospeech.convert(
                "I am sorry to say that this file cannot be copied")
        query = ("update buffer set valid=0 where 1;")
        cnx = mysql.connector.connect(user='******',
                                      password='******',
                                      host='127.0.0.1',
                                      database='phpmyadmin')
        cursor = cnx.cursor()
        cursor.execute(query)
        cnx.commit()
        cursor.close()
def poweroff():
    texttospeech.convert("Shutting Down. ")
    os.system("sudo poweroff")
Example #13
0
def get_time():
    texttospeech.convert(datetime.datetime.now().strftime("%H:%M"))
Example #14
0
def greet(string):
	greets=['Hello', 'Namaste', 'Hi', 'Nice to meet you']
	randomNumber=randint(0,3)
	texttospeech.convert(greets[randomNumber]+" "+string)	
def send():
    matchcount = 0  #check the number of matches in the contacts
    if (check()):
        try:
            cnx = mysql.connector.connect(user='******',
                                          password='******',
                                          host='127.0.0.1',
                                          database='phpmyadmin')
            cursor = cnx.cursor()
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                print("Something is wrong with your user name or password")
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                print("Database does not exist")
            else:
                print(err)
        else:
            gmail_user = sharedvariable.currentUserGmail
            gmail_password = sharedvariable.currentUserGmailPassword
            sent_from = gmail_user
            email_list = []
            name_list = []
            texttospeech.convert("To whom should i send this email?")
            flag = True
            sendstring = ""
            while (flag):
                try:
                    cnx = mysql.connector.connect(user='******',
                                                  password='******',
                                                  host='127.0.0.1',
                                                  database='phpmyadmin')
                    cursor = cnx.cursor()
                except:
                    texttospeech.convert(
                        "Sorry i can't process your request at this moment")
                    return
                else:
                    query = ("select * from buffer")
                    cursor.execute(query)
                    for (v, s, t) in cursor:
                        if (v == 1):
                            sendstring = s
                            flag = False
                if ("leave it" in sendstring.lower()):
                    texttospeech.convert("Cancelling Email")
                    return
                time.sleep(2)
            cursor.close()
            try:
                cnx = mysql.connector.connect(user='******',
                                              password='******',
                                              host='127.0.0.1',
                                              database='phpmyadmin')
                cursor = cnx.cursor()
            except:
                texttospeech.convert(
                    "Sorry i can't process your request at this moment")
                return
            else:
                query = ("select * from contacts where useremail=\'" +
                         sharedvariable.currentUser + "\';")
                cursor.execute(query)
                for (u, e, n) in cursor:
                    if (n.lower() in sendstring.lower().split()):
                        matchcount = matchcount + 1
                        name_list.append(n.lower())
                        email_list.append(e)
                cursor.close()
            if (matchcount != len(sendstring.lower().split())):
                texttospeech.convert(
                    "No matching contacts were found. Please add your contacts before sending an email."
                )
                return
            flag = True
            message = ""
            texttospeech.convert("What is your message?")
            while (flag):
                try:
                    cnx = mysql.connector.connect(user='******',
                                                  password='******',
                                                  host='127.0.0.1',
                                                  database='phpmyadmin')
                    cursor = cnx.cursor()
                except:
                    texttospeech.convert(
                        "Sorry i can't process your request at this moment")
                    return
                else:
                    query = ("select * from buffer")
                    cursor.execute(query)
                    for (v, s, t) in cursor:
                        if (v == 1):
                            message = s
                            flag = False
                    cursor.close()
                if ("leave it" in sendstring.lower()):
                    texttospeech.convert("Cancelling Email")
                    return
                time.sleep(2)
            #subject="OMG SUPER IMPORTANT MESSAGE".
            email_text = """\  
			From: %s  
			To: %s  

			%s
			""" % (sent_from, ", ".join(email_list), message)

            try:
                server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
                server.ehlo()
                server.login(gmail_user, gmail_password)
                server.sendmail(sent_from, email_list, email_text)
                server.close()
                texttospeech.convert('Your email has been sent successfully!')
            except Exception as e:
                texttospeech.convert(
                    "Something went wrong. I couldn't send your email." +
                    str(e))
    else:
        texttospeech.convert('Please configure your Gmail account')
Example #16
0
def parse(buff):
    answer = False
    buff = buff.lower()
    if (buff.split(" ")[0].isnumeric()):
        calculator.calculate(buff)
    else:
        try:
            cnx = mysql.connector.connect(user='******',
                                          password='******',
                                          host='127.0.0.1',
                                          database='phpmyadmin')
            cursor = cnx.cursor()
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                print("Something is wrong with your user name or password")
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                print("Database does not exist")
            else:
                print(err)
        else:
            print("1")
            query = ("select * from questions where question=\'" + buff +
                     "\';")
            cursor.execute(query)
            count = len(cursor.fetchall())
            if (count > 0):
                print("2")
                query = ("select * from questions where question=\'" + buff +
                         "\';")
                cursor.execute(query)
                for (qid, question) in cursor:
                    print("3")
                    query = (
                        "select qid,qrmap.rid,response from qrmap inner join responses on qrmap.rid=responses.rid where qid="
                        + str(qid) + ";")
                    cursor.execute(query)
                    count = len(cursor.fetchall())
                    random = randint(1, count)
                    query = (
                        "select qid,qrmap.rid,response from qrmap inner join responses on qrmap.rid=responses.rid where qid="
                        + str(qid) + ";")
                    cursor.execute(query)
                    i = 1
                    for (q, r, res) in cursor:
                        print("7")
                        if (random == i):
                            print("8")
                            answer = True
                            if ("tell me a joke" in buff):
                                texttospeech.convert(res)
                            else:
                                address = randint(0, 2)
                                if (address == 0):
                                    texttospeech.convert(res)
                                elif (address == 1):
                                    texttospeech.convert(res + " " +
                                                         gender.gender())
                                elif (address == 2):
                                    texttospeech.convert(
                                        res + " " + nickname.getNickname())
                        i = i + 1
            else:
                #First check whether functuin exists or not
                l = buff.split(" ")
                customString = ""
                query = "select * from function_keywords where keyword like "
                i = 0
                while (i < len(l)):
                    customString = customString + " " + l[i]
                    query = query + "\'%" + l[i] + "%\' or keyword like "
                    i = i + 1
                query = query[0:len(query) - 17]
                query = query + " order by length desc;"
                print(query)
                query = (query)
                cursor.execute(query)
                i = 0
                query2 = ""
                buff1 = ""
                for (kid, keyword, length, fid) in cursor:
                    if (i == 0):
                        if (keyword in buff):
                            i = 1
                            query2 = (
                                "select * from function_table where id=" +
                                str(fid) + ";")
                            buff1 = buff[buff.index(keyword):len(buff)]
                if (i == 1):
                    cursor.execute(query2)
                    for (i, m, f, a) in cursor:
                        if (str(a) == "0"):
                            getattr(eval(m), f)()
                            answer = True
                        else:
                            getattr(eval(m), f)(buff1)
                            answer = True
                else:
                    #Now check for possible responses
                    l = buff.split(" ")
                    i = 0
                    customString = ""
                    query = "select * from keywords where keyword like "
                    while (i < len(l)):
                        if (l[i] not in sharedvariable.commonWords):
                            customString = customString + l[i] + " "
                            query = query + "\'%" + l[
                                i] + "%\' or keyword like "
                        i = i + 1
                    if (len(customString) > 0):
                        customString = customString[0:len(customString) - 1]
                    query = query[0:len(query) - 17]
                    query = query + ";"
                    print(query)
                    query = (query)
                    print("f")
                    cursor.execute(query)
                    print("g")
                    returnKeyword = []
                    returnQid = []
                    percentageList = []
                    try:
                        for (kid, qid, keyword) in cursor:
                            print("a")
                            returnKeyword.append(keyword)
                            returnQid.append(qid)
                            percentageList.append(
                                matchcalculator.calculate(
                                    customString, keyword))
                        maximum = max(percentageList)
                        index = percentageList.index(maximum)
                        if (matchcalculator.checkThreshold(
                                customString, returnKeyword[index],
                                percentageList[index])):
                            print("b")
                            query = (
                                "select temp.response from keywords inner join (select qid,response from qrmap inner join responses on qrmap.rid=responses.rid ) temp on keywords.qid=temp.qid where keywords.qid="
                                + str(returnQid[index]) + ";")
                            cursor.execute(query)
                            count = len(cursor.fetchall())
                            random = randint(1, count)
                            query = (
                                "select temp.response from keywords inner join (select qid,response from qrmap inner join responses on qrmap.rid=responses.rid ) temp on keywords.qid=temp.qid where keywords.qid="
                                + str(returnQid[index]) + ";")
                            print("hochche1")
                            insertmaxmatch.insertmaxmatch(
                                buff, returnQid[index])
                            cursor.execute(query)
                            print("c")
                            i = 0
                            #print("Random number: "+str(random))
                            for (r) in cursor:
                                print("d")
                                if (i == random):
                                    answer = True
                                    print("res:" + str(r[0]))
                                    texttospeech.convert(str(r[0]))
                                i = i + 1
                            print("e")
                    except Exception as e:
                        print("I do not understand your question " + str(e))
                        return
                    cursor.close()
                    if (answer == False):
                        cursor = cnx.cursor()
                        randomresponse.generateResponse('apology')
                        query = ("insert into unanswered values(\'" + buff +
                                 "\')")
                        cursor.execute(query)
                        cnx.commit()
            cursor.close()