Exemplo n.º 1
0
def Wait_And_Send_And_Receive_Aut_Msg(enc_sec_message, sec_message, DEBUG,
                                      DEBUG_NO_CARD):
    print "TCPServer Waiting for client on port %d" % PORT
    client_socket, address = server_socket.accept()
    print "I got a connection from ", address
    if DEBUG:
        print('I send autentification message. LEN: %d' %
              (len(enc_sec_message)))
    client_socket.send(enc_sec_message)

    print "Wait for recepient message"
    data = client_socket.recv(4096)
    if (len(data) != 0):
        print('Number of recv char %d' % (len(data)))
        #print "DATA RECEIVED: %s" % data
        ret_con_msg = msgo.Confirm_Message(data, sec_message, DEBUG,
                                           DEBUG_NO_CARD)
        if ret_con_msg == 111:
            print "communication error"
        elif ret_con_msg == 1:
            print "ALL right"
            chat.chat(client_socket, sec_message, SENDER_NAME)
        else:
            print "Intruder"
    else:
        print "ERROR, communication FAILED"
        return 0
    return data
Exemplo n.º 2
0
def Wait_And_Send_And_Receive_Aut_Msg(enc_sec_message, sec_message, DEBUG, DEBUG_NO_CARD):
    print "TCPServer Waiting for client on port %d" % PORT
    client_socket, address = server_socket.accept()
    print "I got a connection from ", address
    if DEBUG:
      print('I send autentification message. LEN: %d' % (len(enc_sec_message)))
    client_socket.send(enc_sec_message)
    
    print "Wait for recepient message"
    data = client_socket.recv(4096)
    if (len(data) != 0):
	print('Number of recv char %d' % (len(data)))
	#print "DATA RECEIVED: %s" % data
	ret_con_msg = msgo.Confirm_Message(data, sec_message, DEBUG, DEBUG_NO_CARD)
	if ret_con_msg == 111:
	    print "communication error"
	elif ret_con_msg == 1:
	    print "ALL right"
	    chat.chat(client_socket, sec_message, SENDER_NAME);
	else:
	    print "Intruder"
    else:
	print "ERROR, communication FAILED"
	return 0
    return data 
    
Exemplo n.º 3
0
def main(_):
    args = params_setup()
    print("[args]: ", args)
    if args.mode == 'train':
        train(args)
    elif args.mode == 'test':
        predict(args)
    elif args.mode == 'chat':
        chat(args)
Exemplo n.º 4
0
def fb_webhook():
    """This handler deals with incoming Facebook Messages.

    In this example implementation, we handle the initial handshake mechanism,
    then just echo all incoming messages back to the sender. Not exactly Skynet
    level AI, but we had to keep it short...

    """
    # Handle the initial handshake request.
    if flask.request.method == 'GET':
        if (flask.request.args.get('hub.mode') == 'subscribe' and
            flask.request.args.get('hub.verify_token') ==
            app.config['FACEBOOK_WEBHOOK_VERIFY_TOKEN']):
            challenge = flask.request.args.get('hub.challenge')
            return challenge
        else:
            print 'Received invalid GET request'
            return ''  # Still return a 200, otherwise FB gets upset.

    # Get the request body as a dict, parsed from JSON.
    payload = flask.request.json

    # TODO: Validate app ID and other parts of the payload to make sure we're
    # not accidentally processing data that wasn't intended for us.

    # Handle an incoming message.
    # TODO: Improve error handling in case of unexpected payloads.
    for entry in payload['entry']:
        for event in entry['messaging']:
            if 'message' not in event:
                continue
            message = event['message']
            # Ignore messages sent by us.
            if message.get('is_echo', False):
                continue
            # Ignore messages with non-text content.
            if 'text' not in message:
                continue
            sender_id = event['sender']['id']
            
            request_url = FACEBOOK_API_MESSAGE_SEND_URL % (
                app.config['FACEBOOK_PAGE_ACCESS_TOKEN'])
            
            chat.chat(message['text'], request_url, sender_id)
            '''requests.post(request_url,
                          headers={'Content-Type': 'application/json'},
                          json={'recipient': {'id': sender_id},
                                'sender_action': "typing_on"})
            #time.sleep(1) # sleep for one second
            requests.post(request_url,
                          headers={'Content-Type': 'application/json'},
                          json={'recipient': {'id': sender_id},
                                'message': {'text': message_text}})'''

    # Return an empty response.
    return ''
Exemplo n.º 5
0
  def Send_Encrypted_Msg_To_Server(self, dec_message, DEBUG, DEBUG_NO_CARD):
      if DEBUG_NO_CARD:
	  enc_msg = dec_message
      else:
	  enc_msg = commands.getoutput('echo \'%s\' | gpg --encrypt --armor -r \'%s\'' %(dec_message,SERVER_PUBLIC))
      print "I send message to server"
      self.client_socket.send(enc_msg) 
         
      chat.chat(self.client_socket, dec_message, SENDER_NAME)
      return 0
Exemplo n.º 6
0
    def Send_Encrypted_Msg_To_Server(self, dec_message, DEBUG, DEBUG_NO_CARD):
        if DEBUG_NO_CARD:
            enc_msg = dec_message
        else:
            enc_msg = commands.getoutput(
                'echo \'%s\' | gpg --encrypt --armor -r \'%s\'' %
                (dec_message, SERVER_PUBLIC))
        print "I send message to server"
        self.client_socket.send(enc_msg)

        chat.chat(self.client_socket, dec_message, SENDER_NAME)
        return 0
Exemplo n.º 7
0
    def do_POST(self):

        #chat = chat(s.bot)

        #msg = ret['message']

        #ret = c.process(msg)

        #if ret:
        #   b.send_answer(ret[0], ret[1])

        self.send_response(200)
        self.end_headers()

        print "Income form: "

        print self.headers
        ctype, pdict = cgi.parse_header(self.headers['content-type'])
        length = int(self.headers['content-length'])

        if ctype == 'application/json':
            postvars = json.loads(self.rfile.read(length))
            c = chat(self.bot)
            msg = postvars['message']
            ret = c.process(msg)
             
            if ret:
                self.bot.send_answer(ret[0], ret[1])

        print postvars

        return
Exemplo n.º 8
0
def index_route():
    if not request.is_json:
        print('Input not json')
        return ''
    json = request.get_json()
    [input_type, result, topic] = chat.chat(json['text'], json['topic'])
    return jsonify({'type': input_type, 'content': result, 'topic': topic})
Exemplo n.º 9
0
    def run(self):
        print("开启线程.....")
        try:
            while True:
                print("等待接受消息")
                msg = ''
                while True:
                    # 读取recvsize个字节
                    rec = self._socket.recv(self._recvsize)
                    # 解码
                    msg += rec.decode(self._encoding)
                    # 文本接受是否完毕,因为python socket不能自己判断接收数据是否完毕,
                    # 所以需要自定义协议标志数据接受完毕
                    if msg.strip().endswith('over'):
                        msg = msg[:-4]
                        break
                print("收到消息:", msg)
                # 调用神经网络模型处理请求
                res = "AI@ALL@" + cb.chat(msg)
                sendmsg = json.dumps(res) + "\n"
                # 发送数据
                self._socket.send(("%s" % sendmsg).encode(self._encoding))
                print(sendmsg + " 已发送!")
        except Exception as identifier:
            self._socket.send("500".encode(self._encoding))
            print(identifier)
            pass
        finally:
            self._socket.close()
        print("任务结束.....")

        pass
Exemplo n.º 10
0
    def do_POST(self):

        #chat = chat(s.bot)

        #msg = ret['message']

        #ret = c.process(msg)

        #if ret:
        #   b.send_answer(ret[0], ret[1])

        self.send_response(200)
        self.end_headers()

        print "Income form: "

        print self.headers
        ctype, pdict = cgi.parse_header(self.headers['content-type'])
        length = int(self.headers['content-length'])

        if ctype == 'application/json':
            postvars = json.loads(self.rfile.read(length))
            c = chat(self.bot)
            msg = postvars['message']
            ret = c.process(msg)

            if ret:
                self.bot.send_answer(ret[0], ret[1])

        print postvars

        return
Exemplo n.º 11
0
def post(request):
    msg = ''
    if request.POST:
        msg = request.POST['question']
        answer = chat.chat(msg)

        return render(request, 'chatbot/response.html', {
            'question': msg,
            'answer': answer
        })
Exemplo n.º 12
0
    def on_button_Send_clicked(self):
        self.question = self.lineedit.text()
        self.lineedit.clear()

        self.textedit.setAlignment(Qt.AlignRight)
        self.textedit.append("Me\n" + self.question + '\n')

        reply = chat.chat(self.question)
        self.textedit.setAlignment(Qt.AlignLeft)
        self.textedit.append("Chatboat\n" + reply)
Exemplo n.º 13
0
def dochat():
    wc_path, user_path, time_path, ls_str = chat(group_id)
    if wc_path != None:
        itchat.send_image(wc_path, group_id)
    if user_path != None:
        itchat.send_image(user_path, group_id)
    if time_path != None:
        itchat.send_image(time_path, group_id)
    if ls_str != None:
        itchat.send(ls_str, group_id)
Exemplo n.º 14
0
def main(_):
    config = flags.FLAGS
    if config.mode == "train":
        train(config)
    elif config.mode == "prepro":
        prepro(config)
    elif config.mode == "debug":
        config.num_steps = 2
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        train(config)
    elif config.mode == "test":
        test(config)
    elif config.mode == "chat":
        chat(config)
    else:
        print("Unknown mode")
        exit(0)
Exemplo n.º 15
0
    def OnEnter(self, event):

        input = self.txt.GetValue()
        input = input.lower()

        from chat import chat
        chat(input)

        from operations import oper
        oper(input)

        from mathOper import math
        math(input)

        from lookup import lookup
        lookup(input)

        from translate import translate
        translate(input)

        if 'help' in input:
            with open('help.txt', 'r') as fin:
                print fin.read()

        #-----------Speech Recognition----------#
        if input == '':
            import speech_recognition as sr
            r = sr.Recognizer()
            with sr.Microphone(
            ) as source:  # use the default microphone as the audio source
                audio = r.listen(
                    source
                )  # listen for the first phrase and extract it into audio data

            try:
                self.txt.SetValue(r.recognize_google(audio))

            except LookupError:  # speech is unintelligible
                print("Could not understand audio")
Exemplo n.º 16
0
def massage():

    for input in massages():

        b_user(input['from'], input['body'], ulist)
        barr(input['from'], input['body'], ulist)
        if ulist[input['from']].ready == 'True':
            if '///' in input['body']:
                user_control(input['from'], input['body'])
        #print (str(input) + ulist [input ['from']].name)

        it = ulist[input['from']]
        if ulist[input['from']].mode == 'block':

            send_message({
                'type': 'TEXT',
                'body': 'برو کار دارم',
                'to': input['from']
            })

        elif input['body'] == 'admin' or "admin" in it.mode:

            if it.id == dmn():

                it.lmsg = input['body']
                admin2(ulist)

            else:

                try:
                    it.wait()
                except:
                    pass

                send_message({'body': 'چی میگی؟؟', 'to': input['from']})

        elif it.mode == 'chat':

            it.lmsg = input['body']
            moe = chat(it, ulist[it.chat])

            if moe == '//End':

                it.lmsg = input['body']
                admin2(ulist)

        else:

            yield ((input['from'], input['body']))
Exemplo n.º 17
0
    def btn_clk(self):
        sender = self.sender()
        if sender.text() == 'মুছুন':
            self.inputText.clear()
        elif sender.text() == 'পাঠান':
            if self.inputText.text() == '':
                pass
            else:
                text = self.inputText.text()
                self.inputText.clear()
                self.conversation.setAlignment(Qt.AlignRight)
                self.conversation.append(text + '\n')

                reply = chat.chat(text)
                self.conversation.setAlignment(Qt.AlignLeft)
                self.conversation.append(reply)
Exemplo n.º 18
0
 def update(self):
     chats = []
     messages = json.loads((requests.get(self.site + "/getupdates")).text)
     if messages["result"] != []:
         requests.get(self.site + "/getupdates?offset=" +
                      str(messages["result"][len(messages["result"]) -
                                             1]["update_id"] + 1))
         while (messages["result"] != []):
             temp_message = messages["result"].pop(0)
             for obj in chats:
                 if obj.id == temp_message["message"]["chat"]["id"]:
                     obj.append(temp_message)
                     temp_message = 1
                     break
             if temp_message != 1:
                 chats.append(chat(temp_message))
     self.chats = chats
    def __init__(self):
        G.player = self
        self.inventory = playerinventory.PlayerInventory()
        self.dimension = None
        self.name = "mcpython_test_player"
        self.chat = chat.chat()
        G.inventoryhandler.show_inventory(self.inventory.id)
        self.gamemode = config.DEFAULT_GAMEMODE
        self.selectedinventoryslot = 0
        self.movingslot = None
        self.movingslotstart = None
        self.entity = PlayerEntity()
        self.tooltip = tooltip.ToolTip()
        self.active_tooltip = False
        self.tooltipslot = None
        self.checkinventorysforslots = [self.inventory.inventorys[0]]
        self.harts = 20
        self.__oldharts = None
        self.hartsprites = []
        self.hartimages = [
            pyglet.image.load(
                G.local +
                "/assets/minecraft/textures/gui/icons/hards_full.png"),
            pyglet.image.load(
                G.local +
                "/assets/minecraft/textures/gui/icons/hards_half.png"),
        ]
        self.drawn_sprites = 0
        for i in range(10):
            self.hartsprites.append(pyglet.sprite.Sprite(self.hartimages[0]))
            self.hartsprites[-1].position = (
                self.inventory.inventorys[0].getBasePosition()[0] + i * 17,
                70,
            )
        self.updateHarts()

        for k in config.AdvancedVanilla.START_INVENTORY.keys():
            self.addToInventory(k, config.AdvancedVanilla.START_INVENTORY[k])
Exemplo n.º 20
0
 def get(self):
     self.session = session.TornadoSession(self.application.session_manager, self)
     _get_c = self.get_arguments('c')
     _get_redirect = self.get_arguments('redirect')
     _get_close  = self.get_arguments('close')
     _post_logout = self.get_arguments('logout')
     _made_of_chars = '^\w+$'
     _valid_url = '((mailto\:|(news|(ht|f)tp(s?))\:\/\/){1}\S+)'
     _user_agent = self.request.headers["User-Agent"]
     _browser = 'style'
     _mobile_browsers = ['iPhone', 'iPod', 'BlackBerry', 'Windows Phone', 'Fennec', 'Opera Mini', 'Opera Mobi', 'MeeGo']
     for b in _mobile_browsers:
         if _user_agent.find(b) > -1:
             _browser = 'mobile'
     if _get_redirect and re.findall(_valid_url,_get_redirect[0]):
         self.render('redirect.html', redirect=_get_redirect[0])
         return
     if ''.join(_get_close):
         self.render('close.html')
         return
     if _get_c:
         if re.findall(_made_of_chars, _get_c[0]):
             if len(_get_c) <= 32:
                 responseList = chat(_get_c)
                 self.render(responseList[0],browser='style',install=responseList[1], nick=responseList[2] , name=responseList[3], maxinput=responseList[4]) 
             else:
                 self.render('welcome.html',browser='style',install=config.INSTALL,name='chat name too large')
         else:
             self.render('welcome.html',browser='style',install=config.INSTALL,name='letters and numbers only')
     elif _post_logout and  re.findall(_made_of_chars, _post_logout):
             self.session['name'] ='s' + _post_logout
             self.session.save()
             logout(_post_logout, self.session['nick'], 0)
             self.render('welcome.html',browser='style',install=config.INSTALL,name='name your chat')
     else:
             self.render('welcome.html',browser='style',install=config.INSTALL,name='name your chat')
Exemplo n.º 21
0
if token:
    print token
    
    tbot = bot.bot(token, adminuser)

    if args.w and ssl_public_cert and webhook_url:
        print "Webhook mode enabled"
        s = bot.httpserver('127.0.0.1', 9090, tbot, ssl_public_cert, webhook_url)
    else:
        print "Webhook mode disabled"
        print "Reseting exists webhook... " + str(tbot.resetWebhook())
        
        from chat import chat

        c = chat(tbot)

        print "Processing... "

        while True:
            print '...'
            
            for ret in tbot.get_next_message():
                print ret

                msg = ret['message'] 
                ret = c.process(msg)
    
                if ret:
                    tbot.send_answer(ret[0], ret[1])
            
Exemplo n.º 22
0
 def send_receive(self, request, context):
     response = chat_pb2.ChatReply()
     response.message = chat.chat(str(request.src), str(request.dst),
                                  str(request.msg))
     return response
Exemplo n.º 23
0
def main():

    phase = {"train": {"pairs": []}, "test": {"pairs": []}}

    if run_mode == 'train':
        with open(datafiles["qr_train"], "r") as file_obj:
            for line in file_obj:
                phase["train"]["pairs"].append(line.split("\n")[0].split("\t"))
        with open(f"{os.path.join(split_path, 'voc.pickle')}", "rb") as f:
            phase["train"]["voc"] = pickle.load(f)

        # Shuffle both sets ONCE before the entire training
        random.seed(1)  # seed can be any number
        random.shuffle(phase["train"]["pairs"])

        print('Building training set encoder and decoder ...')
        # Initialize word embeddings for both encoder and decoder
        embedding = nn.Embedding(phase["train"]["voc"].num_words,
                                 HIDDEN_SIZE).to(device)

        # Initialize encoder & decoder models
        encoder = EncoderRNN(HIDDEN_SIZE,
                             embedding,
                             ENCODER_N_LAYERS,
                             DROPOUT,
                             gate=encoder_name,
                             bidirectional=BIDIRECTION)
        decoder = LuongAttnDecoderRNN(attn_model,
                                      embedding,
                                      HIDDEN_SIZE,
                                      phase["train"]["voc"].num_words,
                                      DECODER_N_LAYERS,
                                      DROPOUT,
                                      gate=decoder_name)

        # Use appropriate device
        encoder = encoder.to(device)
        decoder = decoder.to(device)
        encoder.train()
        decoder.train()
        print('Models built and ready to go!')

        # Initialize optimizers
        print('Building optimizers ...')
        if args.get('optimizer') == "ADAM":
            encoder_optimizer = optim.Adam(encoder.parameters(),
                                           lr=LR,
                                           weight_decay=WD)
            decoder_optimizer = optim.Adam(decoder.parameters(),
                                           lr=LR,
                                           weight_decay=WD)
        elif args.get('optimizer') == "SGD":
            encoder_optimizer = optim.SGD(encoder.parameters(), lr=LR)
            decoder_optimizer = optim.SGD(decoder.parameters(), lr=LR)
        else:
            raise ValueError(
                "Wrong optimizer type has been given as an argument.")

        # If you have cuda, configure cuda to call
        for optimizer in [encoder_optimizer, decoder_optimizer]:
            for state in optimizer.state.values():
                for k, v in state.items():
                    if isinstance(v, torch.Tensor):
                        state[k] = v.cuda()

        print("Starting Training!")
        save_model = run(encoder,
                         decoder,
                         encoder_optimizer,
                         decoder_optimizer,
                         EPOCH_NUM,
                         BATCH_SIZE,
                         CLIP,
                         phase,
                         evaluation=True)
        if save_model:
            try:
                save_seq2seq(encoder, decoder, encoder_name, decoder_name,
                             encoder_optimizer, decoder_optimizer,
                             phase["train"]["losses"], phase["train"]["bleu"],
                             phase["train"]["voc"], embedding, DROPOUT, CLIP,
                             WD)
                print("Model has been saved successfully.")
            except Exception as error:
                print("Saving the model has caused an exception:", error)

        write_results("loss", "train", encoder, encoder_name, decoder_name,
                      DROPOUT, CLIP, WD, phase["train"]["losses"])
        write_results("bleu", "train", encoder, encoder_name, decoder_name,
                      DROPOUT, CLIP, WD, phase["train"]["bleu"])

    else:
        # Loading basic objects needed for all 3 of validation, testing and chatting
        checkpoint = torch.load(args.get('model_path'))
        embedding = load_embedding(checkpoint, HIDDEN_SIZE)
        encoder = load_encoder(checkpoint, EncoderRNN, HIDDEN_SIZE, embedding,
                               ENCODER_N_LAYERS, DROPOUT, encoder_name,
                               BIDIRECTION)
        voc = load_voc(checkpoint)
        decoder = load_decoder(checkpoint, LuongAttnDecoderRNN, attn_model,
                               embedding, HIDDEN_SIZE, voc.num_words,
                               DECODER_N_LAYERS, DROPOUT, decoder_name)
        encoder = encoder.to(device)
        decoder = decoder.to(device)

        if run_mode == "test":
            with open(datafiles["qr_train"], "r") as file_obj:
                for line in file_obj:
                    phase["train"]["pairs"].append(
                        line.split("\n")[0].split("\t"))
            with open(datafiles["qr_test"], "r") as file_obj:
                for line in file_obj:
                    phase["test"]["pairs"].append(
                        line.split("\n")[0].split("\t"))
            with open(f"{os.path.join(split_path, 'voc.pickle')}", "rb") as f:
                phase["train"]["voc"] = pickle.load(f)
            _ = run(encoder,
                    decoder,
                    None,
                    None,
                    EPOCH_NUM,
                    BATCH_SIZE,
                    CLIP,
                    phase,
                    evaluation=True)
            write_results("loss", "train", encoder, encoder_name, decoder_name,
                          DROPOUT, CLIP, WD, phase["train"]["losses"])
            write_results("bleu", "train", encoder, encoder_name, decoder_name,
                          DROPOUT, CLIP, WD, phase["train"]["bleu"])

            write_results("loss", "test", encoder, encoder_name, decoder_name,
                          DROPOUT, CLIP, WD, phase["test"]["losses"])
            write_results("bleu", "test", encoder, encoder_name, decoder_name,
                          DROPOUT, CLIP, WD, phase["test"]["bleu"])

        elif run_mode == "chat":
            # Initialize search module
            searcher = GreedySearchDecoder(encoder, decoder)
            chat(searcher, voc)

        else:
            raise ValueError(
                "Wrong run_mode has been given, options: ['train', 'test', 'chat']"
            )
Exemplo n.º 24
0
def main():
    for arg in sys.argv[1:]:
	process(arg)
    select_lang()
    global panel
    global chat_screen
    global level_setting
    global message_thread
    cursor = pygame.cursors.load_xbm(os.path.join('art', 'ff2_cursor.xbm'),os.path.join('art', 'ff2_cursor-mask.xbm'))
    #print cursor
    pygame.mouse.set_cursor(cursor[0],cursor[1],cursor[2],cursor[3])
    # Displaying the WFP logo
    intro_thread = threading.Thread(target = load_images.load_images, args=[])
    intro_thread.start()
    # Loading and starting the sound play
    threades.audio.play_music(False,'soundtrack')
    
    threades.check_saved_game_level()
    model.game_controller.reset_time()
    gui_buttons.initialize_gui()
    pause_screen()
    intro_thread.join()
    
    proceduralFlow.storyboard_level = threades.current_level
    if threades.current_level != 1:
        load_resume_game()
    else:
	threades.load_initial_facilities()
        data_file = os.path.join('storyboards',str(model.storyboard_file),'data','data1.pkl')
        model.init_cons(data_file)
        model.init_obj()
        threades.initialize_facilities(True)
        proceduralFlow.openStoryBoardFile() 

     
    # loading the correct data file

    #gui_buttons.initialize_gui()

    threades.screen.fill((0,0,0))
    #panel = display_panel.display_panel()
    panel.change_labels()
    animation_obj = threades.Animation()
    animation_obj.update()
    # Starting of the threads
    #print update_thread
    message_thread = threading.Thread(target = message_window, args=[])
    message_thread.start()
    mouse_flag = False
    chat_screen=chat.chat()
    #print 'i was here'
    clock = pygame.time.Clock()
    threades.total_update_flag = True
    # The main infinite loop
    while True:
        time_passed = clock.tick()
        model.game_controller.update_level_time(threades.update_thread_pause)
        threades.update_turn(time_passed)
        animation_obj.update()

        mouse_flag = False
            
        (x,y) = (0,0)
        x,y = pygame.mouse.get_pos()
        
        if not gui_buttons.gui_obj.get_win_flag():
            if len(threades.buildFacilityPlacementFlag):
                facility_placement()               
            if (x > (threades.resize_pt_x(890)) and x < threades.resize_pt_x(930)) and y< threades.resize_pt_y(600):
                threades.transform_obj.move_free((-10,0))
                
            if x < threades.resize_pt_x(60) and y< threades.resize_pt_y(600):
                threades.transform_obj.move_free((10,0))
                
            if  y > threades.resize_pt_y(560) and y< threades.resize_pt_y(600) and x < threades.resize_pt_x(930):
                threades.transform_obj.move_free((0,-10))
                
            if y < threades.resize_pt_y(60) and x < threades.resize_pt_x(930) and x < threades.resize_pt_x(930):
                threades.transform_obj.move_free((0,10))
                
            if (x > threades.resize_pt_x(0)) and (x < threades.resize_pt_x(600)) and (y > threades.resize_pt_y(845)) and (y < threades.resize_pt_y(900)):
                mouse_flag = True
                
        pygame.display.set_caption('FoodForce2')

        for e in gui.setEvents(pygame.event.get()):
            event_handling(e)

        
        

        # Calculate the values of the indicators
        threades.calculate_indicators_starting()
        
               

        
        rects_list = get_update_region()
        panel.update()
        
        if (threades.total_update_flag or threades.map_update_flag or threades.facilities_update_flag or threades.panel_update_flag or panel.res.money_flag):
            threades.desktop.update()
            threades.desktop.draw()
        
        pygame.display.update(rects_list)

        model.iteration_time = time_passed
        model.global_time += model.iteration_time
        storyboardObj.flow()
        gui_buttons.instruction_off_flag = False
Exemplo n.º 25
0
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from account import login
from chat import chat

driver = webdriver.Firefox()
driver.get("http://localhost:8000")

login(driver)
chat(driver)
Exemplo n.º 26
0
def response():
    query = dict(request.form)['query']
    print(query)
    res = chat(query)
    return jsonify({"response" : res})
Exemplo n.º 27
0
def reply(update, context):
    """Reply"""
    message = update.message.text
    # This is where the magic happens
    answer = chat(message)
    context.bot.send_message(chat_id=update.effective_chat.id, text=answer)
Exemplo n.º 28
0
from flask import Flask, render_template, request

import chat as ch
import global_var as gv
app = Flask(__name__)
c = ch.chat()
c.model_load()
image = gv.global_var()


@app.route("/")
def home():
    return render_template("home.html")


@app.route("/img")
def img():
    return render_template('image.html',
                           name='Graph Plot',
                           url='/static/graph' + image.get_img() + '.jpeg')


@app.route("/get")
def chatter():
    userText = request.args.get('msg')
    print(userText)
    m = str(c.chatter(userText.lower())).split('</a>')
    print("app.py", m)
    if len(m) > 1:
        image.set_img(m[1])
    return m[0]
Exemplo n.º 29
0
        elif arg == "--gui={}".format(c.TEXT_DISABLE):
            useChatGui = False

        elif re.compile(r"^--dataLimit=\d+$").match(arg):
            dataLimit = int(arg[12:])

            if dataLimit < c.MIN_DATA_SIZE:
                printErrorAndExit(c.ERROR_MIN_DATA_SIZE)

        elif re.compile(r"^--testDataLimit=\d+$").match(arg):
            testDataLimit = int(arg[16:])

            if testDataLimit < c.MIN_TEST_DATA_SIZE:
                printErrorAndExit(c.ERROR_MIN_TEST_DATA_SIZE)

        elif re.compile(r"^--model=\d+$").match(arg):
            modelNumber = int(arg[8:])

            if modelNumber > c.NUMBER_OF_MODELS:
                printErrorAndExit(c.ERROR_ARGUMENTS)

        else:
            printErrorAndExit(c.ERROR_ARGUMENTS)

    if mode == c.MODE_CHAT:
        chat(modelNumber, useChatGui)
    elif mode == c.MODE_TEST:
        test(modelNumber, testDataLimit)
    else:
        train(modelNumber, dataLimit, useSavedWeights, testing)
Exemplo n.º 30
0
def message_control(messaging_event, sender_id):
    if ("text" in messaging_event["message"]):
        message_text = messaging_event["message"]["text"]  # the message's text
        print(sender_id)  # test
        if message_text == u'寵物顧問':
            upload_flag(1, sender_id)
            json_message(sender_id, "我懂很多寵物知識喔\n你可以問我有關寵物領養 寵物健康 寵物食品的各種問題~")
        elif message_text == u'交換明信片':
            upload_flag(20, sender_id)
            json_message(sender_id,
                         "這是交換寵物明信片的小遊戲,藉由本汪這個郵差,讓您可以藉由明信片認識愛寵物的新朋友")
            json_message(sender_id, "返回上一頁,點擊傳送訊息,然後傳送一張照片")
        elif message_text == u'可愛寵物影片推播':
            upload_flag(3, sender_id)
            videos = get_video()
            deal_video(sender_id, videos)
            if first_use(sender_id, 3) == 1:
                json_subscription(sender_id)
        elif message_text == u'領養資訊搜尋':
            upload_flag(4, sender_id)
            json_location(sender_id)
        elif message_text == u'民間送養資訊搜尋':
            upload_flag(5, sender_id)
            json_choosedogcat2(sender_id)
        elif (get_flag(sender_id) == 1):
            chat(sender_id, message_text)
        elif (get_flag(sender_id) == 21):
            upload_flag(22, sender_id)
            upload_db_intro(message_text, sender_id)
            json_message(sender_id, "已收到,請輸入暱稱")
        elif (get_flag(sender_id) == 22):
            upload_db_nickname(message_text, sender_id)
            json_message(sender_id, "已完成,請耐心等待神秘的明信片")
            upload_flag(0, sender_id)
            match(sender_id)
        elif (get_flag(sender_id) == 4 or get_flag(sender_id) == 5):
            '''
        use payload to save the data which user send
        領養資訊搜尋:location->city->kind->body->start crawler
        民間送養資訊:kind->location->city-> start crawler
            '''
            if (message_text == u"北部地區" or message_text == u"中部地區"
                    or message_text == u"南部地區" or message_text == u"東部地區"):
                payload = messaging_event["message"]["quick_reply"]["payload"]
                print "payload={a}".format(a=payload)
                if (payload == "1" or payload == "2" or payload == "3"
                        or payload == "4"):
                    json_city(sender_id, payload)
                else:
                    json_city2(sender_id, payload)
            elif (u"縣" in message_text or u"市" in message_text
                  or message_text == u"北北基宜全部" or message_text == u"桃竹苗全部"
                  or message_text == u"中彰投全部" or message_text == u"雲嘉南全部"
                  or message_text == u"高屏全部" or message_text == u"花東全部"):
                payload = messaging_event["message"]["quick_reply"]["payload"]
                if (len(payload) <= 5):
                    json_searchdogcat(sender_id, payload)
                else:
                    typingon_json(sender_id)
                    crawler2(sender_id, payload)
            elif (message_text == u"全部種類" or message_text == u"狗"
                  or message_text == u"貓"):
                payload = messaging_event["message"]["quick_reply"]["payload"]
                if (payload == "dog " or payload == "cat "):
                    json_location2(sender_id, payload)
                else:
                    json_searchbodytype(sender_id, payload)
            elif message_text == u"全部體型" or message_text == u"迷你型" or message_text == u"小型" or message_text == u"中型" or message_text == u"大型":
                typingon_json(sender_id)
                searchlist = messaging_event["message"]["quick_reply"][
                    "payload"]
                crawler(sender_id, searchlist)

        elif get_flag(sender_id) == 6:
            reci_id = get_reci_id(sender_id)
            if reci_id == 'None':
                json_message(sender_id, '目前沒有配對到的好友喔,若要交朋友,請按功能表的交換新明信片')
            else:
                nickname = get_nickname(sender_id)
                message_text = nickname + ':'.decode('utf-8') + message_text
                json_message(reci_id, message_text.encode('utf-8'))

    elif "attachments" in messaging_event["message"]:
        if get_flag(sender_id) == 20:
            for attachment in messaging_event["message"]["attachments"]:
                url = attachment["payload"]["url"]
            url = upload_photo(url)
            upload_db_photo_url(url, sender_id)
            upload_flag(21, sender_id)
            json_message(sender_id, "已收到圖片")
            json_message(sender_id, "請輸入簡單的明信片內容,給未知的寵物愛好者吧\n 例如")
            json_message(sender_id, "這是我家的可愛小狗,叫作蛋黃,他的尾巴超可愛的 對吧~")
            # 待補
        elif get_flag(sender_id) == 6:
            for attachment in messaging_event["message"]["attachments"]:
                url = attachment["payload"]["url"]
            url = upload_photo(url)
            reci_id = get_reci_id(sender_id)
            nickname = get_nickname(sender_id)
            json_message(reci_id,
                         (nickname + ':'.decode('utf-8')).encode('utf-8'))
            json_photo(reci_id, url)
Exemplo n.º 31
0
def do_hello():
    input_text = request.forms.input_text
    output_text = chat(input_text)
    return template('chatbot.html',
                    input_text=input_text,
                    output_text=output_text)
Exemplo n.º 32
0
async def on_message(mensaje):
    if mensaje.author == cliente.user:
        return
    await mensaje.channel.send(chat(mensaje.content))
Exemplo n.º 33
0
def main():

    global panel
    global chat_screen
    global level_setting
    
    # Displaying the WFP logo
    intro_thread = threading.Thread(target = load_images.load_images, args=[])
    intro_thread.start()
    # Loading and starting the sound play
    GameSounds.objMusic.start_music()
    
    level_setting=level_change.change_level()
    pause_screen()

    intro_thread.join()
    threades.initialize_facilities()

    #surface_middle = pygame.transform.scale(surface3,threades.resize_pos((1200,560)))
    
    # Processing regarding the storyboard
    proceduralFlow.openStoryBoardFile()
    storyboardObj = proceduralFlow.storyboardFlow()
    proceduralFlow.openStoryBoardFile()

    gui_buttons.initialize_gui()

    threades.screen.fill((0,0,0))
    panel = display_panel.display_panel()
    animation_obj = threades.Animation()
    animation_obj.update()
    # Starting of the threads
    update_thread = threading.Thread(target = threades.update_turn, args=[]).start()
    message_thread = threading.Thread(target = message_window, args=[]).start()
    mouse_flag = False
    chat_screen=chat.chat()
        
    model.game_controller.reset_time()
    # The main infinite loop
    while True:
        #clock.tick()
        model.game_controller.update_level_time()
        

        mouse_flag = False
            
        (x,y) = (0,0)
        x,y = pygame.mouse.get_pos()
        
        if ((x < threades.new_screen_size[0]) and (x > (threades.new_screen_size[0]-60))):
            threades.transform_obj.move_free((0,0))
            
        if (x < 60 and x > 0):
            threades.transform_obj.move_free((0,0))
            
        if (y < threades.resize_pt_y(900)) and (y > threades.resize_pt_y(840)):
            threades.transform_obj.move_free((0,0))
            
        if ((y < threades.resize_pt_y(60)) and (y > threades.resize_pt_y(0))):
            threades.transform_obj.move_free((0,0))
            
        if (x > threades.resize_pt_x(0)) and (x < threades.resize_pt_x(600)) and (y > threades.resize_pt_y(845)) and (y < threades.resize_pt_y(900)):
            mouse_flag = True
            
        pygame.display.set_caption('FoodForce2')

        for e in gui.setEvents(pygame.event.get()):
            event_handling(e)

        
        #pygame.draw.rect(threades.screen,(209,169,106),threades.resize_rect((0,40,1200,560)))
        animation_obj.update()


        # Claculate indicators again
        threades.calculate_indicators_starting()
        
        #For middle surface
        #surface_middle = pygame.transform.scale(surface3,threades.resize_pos((1200,560)))
        #threades.screen.blit(surface_middle,threades.resize_pos((0,40)))

        

        
        rects_list = get_update_region()
        panel.update()
        
        if (threades.total_update_flag or threades.map_update_flag or threades.facilities_update_flag or threades.panel_update_flag or panel.res.money_flag):
            threades.desktop.update()
            threades.desktop.draw()
        
        pygame.display.update(rects_list)

        model.iteration_time = clock.tick()
        model.global_time += model.iteration_time
        storyboardObj.flow()
Exemplo n.º 34
0
import chat as cb
import sys
while True:
    print("YOU>", end="")
    sentence = sys.stdin.readline()
    print("AI>", cb.chat(sentence))
Exemplo n.º 35
0
def chat_bot(msg):
    return chat(msg)
Exemplo n.º 36
0
 def CrearChat(self):
     self.Chat = chat(self.posX_chat + 5, self.posY_chat,self.width,self.heigth)
     self.Chat.SetCliente(self.Cliente)
     self.Cliente.setChat(self.Chat)        
Exemplo n.º 37
0
    def clientConnectionFailed(self, connector, reason):
        print "connection failed:", reason
        reactor.stop()


def runReactor(reactor):
    reactor.run()
    return


if __name__ == "__main__":
    channel = raw_input("Enter channel name: ")
    pygame.init()
    twitchFont = pygame.font.SysFont("helvetica", 24, bold=True)
    twitchChat = chat(twitchFont)
    # create factory protocol and application
    f = MonitorFactory(channel, twitchChat)

    # connect factory to this host and port
    reactor.connectTCP("irc.twitch.tv", 6667, f)

    # run bot
    reactorThread = Thread(target=runReactor, args=(reactor,))
    reactorThread.daemon = True
    reactorThread.start()
    # reactor.run()

    # Set the height and width of the screen
    SIZE = [1184, 500]
Exemplo n.º 38
0
def main():

    global panel
    global chat_screen
    global level_setting
    global update_thread
    global message_thread
    
    cursor = pygame.cursors.load_xbm(os.path.join('art', 'ff2_cursor.xbm'),os.path.join('art', 'ff2_cursor-mask.xbm'))
    #print cursor
    pygame.mouse.set_cursor(cursor[0],cursor[1],cursor[2],cursor[3])
    # Displaying the WFP logo
    intro_thread = threading.Thread(target = load_images.load_images, args=[])
    intro_thread.start()
    # Loading and starting the sound play
    #level_setting=level_change.change_level()
    
    #Checks the level on which 	he user is
    threades.current_level = threades.check_saved_game_level()
    
    
    #Resets the time
    model.game_controller.reset_time()
    
    #Initialises and creates the starting screen and pauses the game until the user gives an input
    pause_screen()
    #Lets the initial thread started to get completed
    intro_thread.join()
    
    
        
    
    proceduralFlow.storyboard_level = threades.current_level
    
     #Takes action according to the level
    if threades.current_level != 1:
        load_resume_game()
    else:
        threades.initialize_facilities(True)
        proceduralFlow.openStoryBoardFile()

     
    # Processing regarding the storyboard
    
    storyboardObj = proceduralFlow.storyboardFlow()
    
    gui_buttons.initialize_gui()

    threades.screen.fill((0,0,0))
    panel = display_panel.display_panel()
    animation_obj = threades.Animation()
    animation_obj.update()
    # Starting of the threads
    update_thread = threading.Thread(target = threades.update_turn, args=[])
    update_thread.start()
    #print update_thread
    message_thread = threading.Thread(target = message_window, args=[])
    message_thread.start()
    mouse_flag = False
    chat_screen=chat.chat()
        
    
    # The main infinite loop
    while True:
        #clock.tick()
        model.game_controller.update_level_time(threades.update_thread_pause)
        
        animation_obj.update()


        mouse_flag = False
            
        (x,y) = (0,0)
        x,y = pygame.mouse.get_pos()
        
        if len(threades.buildFacilityPlacementFlag):
            facility_placement()               
        if (x > (threades.resize_pt_x(890)) and x < threades.resize_pt_x(930)):
            threades.transform_obj.move_free((-10,0))
            
        if x < threades.resize_pt_x(60) :
            threades.transform_obj.move_free((10,0))
            
        if  y > threades.resize_pt_y(560) and y< threades.resize_pt_y(600):
            threades.transform_obj.move_free((0,-10))
            
        if y < threades.resize_pt_y(60):
            threades.transform_obj.move_free((0,10))
            
        if (x > threades.resize_pt_x(0)) and (x < threades.resize_pt_x(600)) and (y > threades.resize_pt_y(845)) and (y < threades.resize_pt_y(900)):
            mouse_flag = True
            
        pygame.display.set_caption('FoodForce2')

        for e in gui.setEvents(pygame.event.get()):
            event_handling(e)

        
        

        # Calculate the values of the indicators
        threades.calculate_indicators_starting()
        
               

        #updating the region
        rects_list = get_update_region()
        panel.update()
        
        if (threades.total_update_flag or threades.map_update_flag or threades.facilities_update_flag or threades.panel_update_flag or panel.res.money_flag):
            threades.desktop.update()
            threades.desktop.draw()
        
        pygame.display.update(rects_list)

        #updates the time
        model.iteration_time = clock.tick()
        model.global_time += model.iteration_time
        
        #Calls the function which decides which action to be taken
        storyboardObj.flow()