def delete(self):
        try:
            payload = json.loads(request.data.decode())
            user_name = payload["user_name"]

            database.deleteUser(user_name)
            return make_response(
                jsonify({
                    'title': "User Deleted Successfully",
                    "status": HTTPStatus.OK
                }),
                HTTPStatus.OK,
            )

        except Exception as e:
            return make_response(
                jsonify({
                    'title': "Unsuccessful from user deletion",
                    "status": HTTPStatus.BAD_REQUEST,
                    "error": {
                        "message": str(e)
                    }
                }),
                HTTPStatus.BAD_REQUEST,
            )
	def voiceCommand(self):
		#restricts guests from using this function
		if self.ww.name == None:
			self.label.setText('You must be logged in to use this function.')
			return

		self.label.setText('Please say a command.')

		#turns on microphone and returns audio as a string
		self.r = sr.Recognizer()
		with sr.Microphone() as source:
			audio = self.r.listen(source)

		#defines the logic for each type of voice command
		if 'go to' in self.r.recognize_google(audio):
			self.textbox.setText('')
			items = self.r.recognize_google(audio).split()
			self.goto(items[2].lower())
		elif 'clear data' in self.r.recognize_google(audio):
			self.textbox.setText('')
			database.deleteUser(self.ww.name)
			database.addUser(self.ww.name)
			self.ww.websites = ['google https://www.google.com/']
			self.ww.websitesDictionary = {'google': 'https://www.google.com/'}
			self.ww.homeScreen()
		elif 'add site' in self.r.recognize_google(audio):
			self.textbox.setText('')
			self.ww.addSite()
			self.label.setText('Done')
		elif 'go home' in self.r.recognize_google(audio):
			self.ww.homeScreen()
			self.label.setText('')
Beispiel #3
0
    def deleteUser(self,data):
        # Initialize response
        response = responses.Responses()

        MAC = data["MAC"]
        dbFunction = database.getMAC(MAC)

        if dbFunction.count() == 0:
            response.setResponse("response",False)
        else:
            database.deleteUser(MAC)
            response.setResponse("response",True)

        return response
Beispiel #4
0
def speak(request, userID, userInfo="", msg="", answ="", attach=""):
    # Специальные команды бота
    # #Учим бота новым словам
    if msg[:6] == "/teach":
        pos = msg.find("?")
        newMsg = msg[7:pos].replace(" ", "")
        newAnsw = msg[pos + 1:]
        database.insert("answer", ["msg", "answ"], [newMsg, newAnsw])
        answ = "Я добавил новый запрос '{0}', давай попробуй =)".format(newMsg)
    # #Вывести список всех команд
    elif msg == "/list":
        answ = database.get("answer", ["msg"])
    # #Узнать в какой я группе
    elif msg == "/whoAmI":
        answ = """Вы относитесь к группе {0}""".format(
            database.getGroup(str(userID))[0]["groupName"])
    # #Посмотреть список пользователей
    elif msg == "/whoAreThey":
        answ = """Пользователи:\n"""
        for i in database.getGroup():
            answ += """id: {0}, group: {1}\n""".format(i["id"], i["groupName"])
    elif msg == "/changeMe":
        # 1) Удалить пользователя из базы
        database.deleteUser(userID)
        # 2) Вызвать клавиатуру
        keyboardStart(request, userID)
        return 1

    # Поиск ответа в базе
    if answ == "":
        for i in database.get("answer"):
            if msg == i["msg"]:
                answ = i["answ"]
                break
            else:
                answ = "Я не знаю такой команды. Можешь научить меня используя команду /teach ЗАПРОС ? ОТВЕТ"

    sendAnswer(userID, answ, attach)
def del_user(id):
    # Check if specified ID is an integer
    if not function.isInt(id):
        return jsonify({"error": "id is not an integer"}), 400

    # Check if token identity corresponds to the user being deleted
    if not (int(id) == get_jwt_identity()):
        return jsonify({"error": "Not allowed to delete this user"}), 403

    # Check if user actually exists
    user = database.getUserByID(id)
    if user is None:
        return jsonify({"error": "Specified user does not exist"})

    # Delete user
    if database.deleteUser(id):
        return jsonify({"Info": "User deleted successfully"}), 200
    else:
        return jsonify({"erorr": "Something went wrong deleting user"}), 500
Beispiel #6
0
    def callMenuZalogowane(self): # po pomyślnym zalogowaniu tudzież rejestracji odpala się to menu

        print() # dla lepszej przejrzystości

        while True: # nieskończona pętla po to aby użytkownik cały czas miał menu przed sobą, żeby wyjść z niego
                    # trzeba wybrać odpowiedni numer

            wyborUzytkownika = int(input(self.menuZalogowanegoUzytkownika)) # wybor użytkownika co chce robić

            if wyborUzytkownika == 1: # szukanie piosenki (zapytanie do bazy wyswietla piosenkę i jej szczegóły)
                                      # otherwise error
                wybor = input("Wyszukiwana fraza: ") # album, artysta, nazwa piosenki trzeba dobrze napisac
                                                     # ponieważ inczej nie znajdzie DO POPRAWY
                print("\n"*50)                       # czyszczenie command prompta DO POPRAWY
                sprawdzCzyBylJakisOdzew = 0
                for song in database.searchForSongs(wybor):
                    print("Znaleziono utwor nalezacy do playlisty " + song['genre.name'])
                    print("wykonawca: " + song['name'])
                    self.aktualnieOdtwarzanaPiosenka = song['song_id']
                    self.aktualnaPlaylista = song['genre.name']
                    print("tytul: " + song['title'])
                    print("album: " + song['album.name'])
                    print("rok wydania: " + str(song['year']))
                    print("liczba polubien: " + str(song['likes_count']))
                    sprawdzCzyBylJakisOdzew = 1
                    break
                if sprawdzCzyBylJakisOdzew == 0:
                    print(colored("Brak wynikow", 'red'))

                print("Co chcialbys zrobic z piosenka? 1 - SLUCHAJ, 2 - KONTYNUUJ")
                wybor = input("Twoj wybor: ")

                if wyborUzytkownika == 1: # Słuchanie danej piosenki z opcja polubienia
                    print("\n" * 50)
                    print("Aktualnie odtwarzana piosenka: ")
                    playingSong = database.getSongById(self.aktualnieOdtwarzanaPiosenka)
                    print("wykonawca: " + playingSong['name'])
                    print("tytul: " + playingSong['title'])
                    print("liczba polubien: " + str(playingSong['likes_count']))
                    print()
                    print("Pozostale piosenki w playliscie:")
                    print("id\twykonawca\ttytul")
                    for playlistSongs in database.getAllPlaylistSongs(self.aktualnaPlaylista, self.aktualnieOdtwarzanaPiosenka):
                        print(str(playlistSongs['song_id']) + "\t" + playlistSongs['name'] + "\t" + playlistSongs['title'])

                    print("Co chcesz zrobic? 1 - DODANIE PIOSENKI DO ULUBIONYCH, 2 - PRZEJSCIE DO SLUCHANIA KOLEJNEJ PIOSENKI, 3 - WYJSCIE")
                    wybor = int(input("Twoja decyzja: "))

                    if wybor == 1: # dodanie do ulubionych
                        database.addToLikedSongs(str(self.aktualnieOdtwarzanaPiosenka), self.loginZalogowanegoUzytkownika)
                        print("Dodano utwor do ulubionych")
                        print("\n" * 50) # wyczyszczenie okna po dodaniu do ulubionych

                        ###############################################################

                        print("Aktualnie odtwarzana piosenka: ")
                        playingSong = database.getSongById(self.aktualnieOdtwarzanaPiosenka)
                        print("wykonawca: " + playingSong['name'])
                        print("tytul: " + playingSong['title'])
                        print("liczba polubien: " + str(playingSong['likes_count']))
                        print()
                        print("Pozostale piosenki w playliscie:")
                        print("id\twykonawca\ttytul")
                        for playlistSongs in database.getAllPlaylistSongs(self.aktualnaPlaylista, self.aktualnieOdtwarzanaPiosenka):
                            print(str(playlistSongs['song_id']) + "\t" + playlistSongs['name'] + "\t" + playlistSongs[
                                'title'])

                        print("Co chcesz zrobic? 1 - PRZEJSCIE DO SLUCHANIA KOLEJNEJ PIOSENKI, 2 - WYJSCIE")
                        wybor = input("Twoja decyzja to 2: ")
                        wybor = 2 # XD

                elif wybor == 2: # powrot do menu
                    print("\tPowrot do menu...")
                else:
                    print("\tNiepoprawny wybor")
                #if piosenke_znaleziono
                    #kolejny if co chcesz z nia zrobic albo posluchac, albo dodac do ulubionych
                    #dodanie do ulubionych
                    #sluchanie (emulacja sluchania piosenki, wyjscie z niej, pauza)
                    #usuniecie z ulubionych
                    #dodanie artysty do plubionych
            elif wyborUzytkownika == 2: # wyświetlenie polubionych piosenek
                print("\n" * 50)
                print("LISTA ULUBIONYCH PIOSENEK")
                print()
                print("id\twykonawca\ttytul\tliczba polubien")
                for likedSong in database.getAllLikedSongs(self.loginZalogowanegoUzytkownika):
                    print(likedSong['song_id'], "\t", likedSong['name'], "\t", likedSong['title'], "\t",
                        likedSong['album.name'], "\t", likedSong['year'], "\t", likedSong['genre.name'])
                    #wylistowanie polubionych piosenek, sluchanie ich, usuniecie z polubionych
                    #wyjscie do menu

                print("Czy chcesz usunac jakiegos piosenke z listy polubionych? 1 - TAK, 2 - NIE")
                wybor = int(input("Twoj wybor: "))

                if wybor == 1:  # usuwamy z listy
                    piosenkaDoUsunieciaID = int(input("ID piosenki do usuniecia: "))
                    database.deleteFromLikedSongs(str(piosenkaDoUsunieciaID), self.loginZalogowanegoUzytkownika)
                    print(colored("Usunieto wybrana piosenke z ulubionych", 'green'))
                elif wybor == 2:
                    print("\n" * 50)
                    pass
                else:
                    print(colored("Niepoprawny wybor", 'red'))

            elif wyborUzytkownika == 3: # wyswietlnie ulubionych artystów użytkownika
                print("\n"*50)
                print("LISTA ULUBIONYCH ARTYSTOW")
                print()
                print("id\twykonawca")

                for artist in database.getAllLikedArtists(self.loginZalogowanegoUzytkownika):
                    print(artist['artist_id'], "\t", artist['name'])

                print("Czy chcesz usunac jakiegos artyste z listy polubionych? 1 - TAK, 2 - NIE")
                wybor = int(input("Twoj wybor: "))

                if wybor == 1: # usuwamy z listy
                    artystaDoUsunieciaID = int(input("ID artysty do usuniecia: "))
                    database.deleteFromLikedArtist(artystaDoUsunieciaID, self.loginZalogowanegoUzytkownika)
                elif wybor == 2:
                    print("\n" * 50)
                    pass
                else:
                    print(colored("Niepoprawny wybor", 'red'))

                #tutaj przeniesienie opcji: usun z listy ulubionych artystow
            elif wyborUzytkownika == 4: # wyjscie z programu (biblioteka muzyczna)
                print("\tWychodzenie z programu...")
                exit()
            elif wyborUzytkownika == 5: # usuniecie konta

                wybor = int(input("\tCzy na pewno chcesz usunac uzytkownika? 1 - TAK, 2 - NIE: "))

                if wybor == 1: # chce usunac konto
                    print("\tUsuwanie uzytkownika...")
                    database.deleteUser(self.loginZalogowanegoUzytkownika)
                    self.callMenu(self)
                elif wybor == 2: # nie chce usuwac
                    print("\tWracanie do menu")
                    break
                else:
                    print("\tNiepoprawny wybor")

            elif wyborUzytkownika == 6: # zmiana uzytkownika
                print("\tPodaj login oraz haslo uzytkownika")
                login = input("\tLogin: "******"\tHaslo: ")

                # sprawdzenie czy uzytkownik o podanym loginie istnieje i czy haslo jest poprawne
                for uzytkownik in database.getAllLogins():
                    if login == uzytkownik["login"]:
                        print(colored("\tPodany uzytkownik istnieje, zmienianie konta...", 'green'))
                        self.loginZalogowanegoUzytkownika = login  # do ewentualnego usuniecia konta
                        break
                    print(colored("\tUzytkownik o podanej nazwie nie istnieje", 'red'))
            else: # wybranie niewlasciwej opcji i powrot
                print(colored("\tWybrales niewlasciwa opcje", 'red'))
Beispiel #7
0
def deleteUser(username):
    with database.connect() as conn:
        database.deleteUser(conn, username)
    return redirect("/manage")
	def devGo(self):

		#this boolean is used to restrict guests from using certain features
		cantUse = False
		if self.ww.name == None:
			cantUse = True

		self.label.setText('')

		#lists the different commands
		if self.textbox.text() == 'help':
			self.textbox.setText('')
			self.label.setText('Commands: addSite, addUser(name), clearData, deleteUser, clear')

		#Adds site to the current user's list of sites
		elif self.textbox.text() == 'addSite':
			if cantUse:
				self.textbox.setText('')
				self.label.setText('You must be logged in to use this function.')
				return
			self.textbox.setText('')
			self.ww.addSite()

		#clears user preferences 
		elif self.textbox.text() == 'clearData':
			if cantUse:
				self.textbox.setText('')
				self.label.setText('You must be logged in to use this function.')
				return
			self.textbox.setText('')
			database.deleteUser(self.ww.name)
			database.addUser(self.ww.name)
			self.ww.websites = ['google https://www.google.com/']
			self.ww.websitesDictionary = {'google': 'https://www.google.com/'}
			self.ww.homeScreen()

		#adds a new user to the database and takes images to use for recognition
		elif self.textbox.text()[0:7] == 'addUser':
			name = self.textbox.text()[8:-1]
			_thread.start_new_thread(face_recognize.addUser, (name, ))
			self.ww.name = name.title()
			database.addUser(name.title())
			self.textbox.setText('')
			self.ww.homeScreen()

		#removes user from image database and websites database
		elif self.textbox.text() == 'deleteUser':
			if cantUse:
				self.textbox.setText('')
				self.label.setText('You must be logged in to use this function.')
				return
			self.textbox.setText('')
			database.deleteUser(self.ww.name)
			self.ww.websites = ['google https://www.google.com/']
			self.ww.websitesDictionary = {'google': 'https://www.google.com/'}
			create_database.deleteUser(self.ww.name)
			self.ww.name = None
			self.ww.homeScreen()

		#tool used for debuggin in development
		elif self.textbox.text()[0:15] == 'deleteUserAdmin':
			tempName = self.textbox.text()[16:-1]
			database.deleteUser(tempName)
			create_database.deleteUser(tempName)
			self.ww.homeScreen()

		#clears the label
		elif self.textbox.text() == 'clear':
			self.textbox.setText('')
			self.label.setText('')
Beispiel #9
0
def bot(request):
    body = json.loads(request.body)

    def SendAnswer(userID, msg, keyboard=""):
        vkAPI.messages.send(user_id=userID,
                            message=msg,
                            keyboard=keyboard,
                            random_id=random.randint(1, 99999999999999),
                            v=5.103)

    print(body)
    if body == {"type": "confirmation", "group_id": 194135917}:
        return HttpResponse('5ba3cbbe')
    if body["type"] == "message_new":
        msg = body["object"]["message"]["text"]
        userID = body["object"]["message"]["from_id"]
        name_us = vkAPI.users.get(user_ids=userID, v=5.103)
        name_user = name_us[0]["first_name"]
        tag_rep = (msg).split(" ", maxsplit=1)
        answ = ""
        gpid = -1
        gpname = ""
        if "payload" in body["object"]["message"]:
            payload = body["object"]["message"]["payload"]

        def keyboardStart(request, userID):
            answ = "Привет! Выбери свою группу пользователя!"
            keyboard = json.dumps({
                "one_time":
                True,
                "buttons": [[{
                    "action": {
                        "type": "text",
                        "label": "Администратор",
                        "payload": """{"command":"admin"}"""
                    },
                    "color": "negative"
                }],
                            [{
                                "action": {
                                    "type": "text",
                                    "label": "Программист",
                                    "payload": """{"command":"program"}"""
                                },
                                "color": "positive"
                            }],
                            [{
                                "action": {
                                    "type": "text",
                                    "label": "Труп",
                                    "payload": """{"command":"person"}"""
                                },
                                "color": "primary"
                            }]]
            })
            SendAnswer(userID, answ, keyboard)

        if msg == "Привет":
            name_us = vkAPI.users.get(user_ids=userID, v=5.103)
            answ = "Привет " + name_user + ", я Твой самый лучший друг, я сниму с тебя скальп 💀 💀 💀 :)"
            SendAnswer(userID, answ)
        elif msg == "/whoAmI":
            answ = """Вы относитесь к группе {0}""".format(
                database.getGroup(str(userID))[0]["GroupName"])
            SendAnswer(userID, answ)
        elif msg == "/changeMeNow":
            database.deleteUser(userID)
            keyboardStart(request, userID)
            return 1

        elif tag_rep[0] == "/say":
            answ = tag_rep[1]
            SendAnswer(userID, answ)
        elif payload == """{"command":"start"}""":
            keyboardStart(request, userID)
        elif payload == """{"command":"admin"}""":
            gpid = str(1)
            gpname = "Администратор"
            database.insert("user", ["id, groupId"], [str(userID), gpid])
            answ = "Вы были добавлены в группу {0}".format(gpname)
            SendAnswer(userID, answ)
        elif payload == """{"command":"program"}""":
            gpid = str(2)
            gpname = "Программист"
            database.insert("user", ["id, groupId"], [str(userID), gpid])
            answ = "Вы были добавлены в группу {0}".format(gpname)
        elif payload == """{"command":"person"}""":
            gpid = str(3)
            gpname = "Труп"
            database.insert("user", ["id, groupId"], [str(userID), gpid])
            answ = "Вы были добавлены в группу {0}".format(gpname)
        else:
            conn = sqlite3.connect("db.sqlite")
            cur = conn.cursor()
            query = """ SELECT * FROM answers """
            cur.execute(query)
            answer = cur.fetchall()
            conn.close()
            for i in range(len(answer)):
                if answer[i][1] == msg:
                    answ = answer[i][2]
                    SendAnswer(userID, answ)

        # elif body ["object"]["message"]["text"]=="Какой сейчас час?":
        #     msg = "Час убивать!!!"
        #     vkAPI.messages.send(user_id=userID, message=msg, random_id=random.randint(1, 99999999999999), v=5.103)
        # elif body ["object"]["message"]["text"]=="Почему ты злой?":
        #     msg = "Я не злой, это ты просто скоро будешь мёртвым"
        #     vkAPI.messages.send(user_id=userID, message=msg, random_id=random.randint(1, 99999999999999), v=5.103)
        # elif body ["object"]["message"]["text"]=="Я ухожу":
        #     msg = " Беги, беги, далеко не убежишь."
        #     vkAPI.messages.send(user_id=userID, message=msg, random_id=random.randint(1, 99999999999999), v=5.103)
        # elif body ["object"]["message"]["text"]=="/help":
        #     msg = "Я тебе не Сири, чтобы показывать что у меня внутри."
        #     vkAPI.messages.send(user_id=userID, message=msg, random_id=random.randint(1, 99999999999999), v=5.103)
        # if msg=="/help":
        #     conn = sqlite3.connect("db.sqlite")
        #     cur = conn.cursor()
        #     query =""" SELECT * FROM answers """
        #     cur.execute(query)
        #     answer = cur.fetchall()
        #     conn.close()
        #     for i in range(len(answer)):
        #         if answer[i][1]==msg:
        #             answ=answer[i][2]
        #             SendAnswer(userID, answ)
        # elif msg=="Какой сейчас час?":
        #     conn = sqlite3.connect("db.sqlite")
        #     cur = conn.cursor()
        #     query =""" SELECT * FROM answers """
        #     cur.execute(query)
        #     answer = cur.fetchall()
        #     conn.close()
        #     for i in range(len(answer)):
        #         if answer[i][1]==msg:
        #             answ=answer[i][2]
        #             SendAnswer(userID, answ)

        #name_us = vkAPI.users.get(access_token = token, user_ids = userID, v=5.103)
        #name_us=json.loads(vkAPI.users.get(userID))
        #print(name_us[0]["first_name"])

    return HttpResponse("ok")
Beispiel #10
0
 def deleteUser(self):
     database.deleteUser(self.user['key'])
     return REDIRECT % {'title': "User Delete", 'text': "User has been Deleted"}
Beispiel #11
0
    def render_GET(self, request):
	database.deleteUser(self.user['key'])
	return REDIRECT % {'title': "User Delete", 'text': "User has been Deleted"}
Beispiel #12
0
#import database.py
from database import userExists, deleteUser, insertUser, getMainPage

print('userExists("adducin")=' + str(userExists('adducin')))
print('userExists("test2")=' + str(userExists('test2')))
print('trying to delete user "test2"')
deleteUser('test2')
print('userExists("test2")=' + str(userExists('test2')))
print('trying to insert user "test2"')
insertUser('test2', 'test2Pass', 'Test', '2', 'Test User 2 Desc',
           'Hello World.pdf')
print('userExists("test2")=' + str(userExists('test2')))
print('Database contents:')
getMainPage()
Beispiel #13
0
 def deleteUser(self):
     database.deleteUser(self.user['key'])
     return REDIRECT % {
         'title': "User Delete",
         'text': "User has been Deleted"
     }
Beispiel #14
0
 def render_GET(self, request):
     database.deleteUser(self.user['key'])
     return REDIRECT % {
         'title': "User Delete",
         'text': "User has been Deleted"
     }