Esempio n. 1
0
 def startChat(self, *participants):
     new_chat = Chat(self)
     new_chat.add_participants(*participants)
     if new_chat.participants:
         new_chat.printChat()
     else:
         print("Участники не добавлены")
Esempio n. 2
0
    def __init__(self):
        print("Shared Data initializing....", end="")
        self._online = {}
        self._players = {}
        self._all_ufos = {}
        self._all_bases = {}
        self._sessions = {}
        self._chat = Chat()
        self._map = Map(1, 1)
        self._log = Logger('XFF', 'SharedData')
        self._map_actions = {}
        self._skill_queues = []

        self._loop = GeoLoop()
        self.organizations = {}
        self.NPCs = {}
        self.havens = {}

        self.mongo_helper = mongohelper.MongoHelper()
        # Populate UFOs collection with default objects
        if config.BACKSERVER_POPULATE_MONGO:
            self.mongo_helper.add_ufo(UFOs.Probe())
            self.mongo_helper.add_ufo(UFOs.SmallScout())
            self.mongo_helper.add_ufo(UFOs.MediumScout())
            self.mongo_helper.add_ufo(UFOs.LargeScout())
            self.mongo_helper.add_site(GroundSite.BasicSectoidOperation())

        # Load Collections from Mongo
        self._ufos = self.mongo_helper.get_all_ufos()
        self._sites = self.mongo_helper.get_all_sites()

        print("OK")
Esempio n. 3
0
 def addChat_id(self, chatid, db):
     if (self.chatList.__contains__(chatid) == False):
         self.chatList.append(chatid)
         print("fatto")
         db.add_chat("chat", chatid)
         chat = Chat()
         chat.chat_id = chatid
         self.lista_chat.append(chat)
Esempio n. 4
0
 def startChat(self, *participants):
     rows = self.getContacts()
     contacts = []
     for row in rows:
         contacts.append(row[0])
     new_chat = Chat(self)
     new_chat.add_participants(contacts)
     return new_chat.id
Esempio n. 5
0
 def new_message(self, message, user_id, chat_id):
     switch_time = {
         'Понедельник': 0,
         'Вторник': 1,
         'Среда': 2,
         'Четверг': 3,
         'Пятница': 4,
         'Суббота': 5,
         'Воскресенье': 6,
     }
     if switch_time.get(self._prev_day) > switch_time.get(self._get_day()):
         self._prev_day = self._get_day()
         request = requests.get(
             'https://itmo.ru/ru/schedule/0/M3206/raspisanie_zanyatiy_M3206.htm'
         )
         self._itmo_schedule = BeautifulSoup(request.text, 'lxml')
     if message.lower() == self._commands[0]:
         return self._get_info()
     if message.lower() == self._commands[1]:
         return self._day_info(1)
     if message.lower() == self._commands[2]:
         return self._day_info(0)
     if message.lower() == self._commands[3]:
         return self._command_info()
     if message.lower() == self._commands[4] or message.lower(
     ) == self._commands[6]:
         return self._update()
     if message.lower() == self._commands[5] or message.lower(
     ) == self._commands[7]:
         self._save_state()
         return "Спасибо за понимание"
     if message == self._commands[8]:
         self._save_state()
         return "зАхАрЕвИч!"
     if message.lower() == self._commands[9]:
         return self._update_all()
     if message.lower() == self._commands[10] or message.lower(
     ) == self._commands[12]:
         self._save_state()
         return self._participation(chat_id, message.lower())
     if message.lower() == self._commands[11]:
         self._save_state()
         return "usachova.gitbook.io"
     if message.lower() == self._commands[13]:
         self._save_state()
         return "Saved"
     if message.lower() == self._commands[14]:
         self._save_state()
         return self._deadlines()
     if message.lower() == self._commands[15]:
         return self.joke()
     if message.lower() == self._commands[16]:
         return "usachova.gitbook.io - сайтик\nbars.itmo.ru - БаРС\nisu.ifmo.ru - ИСУ\nde.ifmo.ru - ЦДО"
     if self._flood.get(chat_id) is None:
         self._flood[chat_id] = Chat()
     self._flood[chat_id].plus(user_id)
     self._flood_amount[chat_id] += 1
     return "no"
Esempio n. 6
0
 def _load_state(self):
     file = open('flood.txt', 'r')
     temp_chat = ''
     for line in file:
         if line == '':
             continue
         if line.split()[0] == 'index:':
             temp_chat = int(line.split()[1])
             self._flood[temp_chat] = Chat()
             self._flood_amount[temp_chat] = int(line.split()[2])
             continue
         temp_user = int(line.split()[0])
         for _ in range(0, int(line.split()[1])):
             self._flood[temp_chat].plus(temp_user)
     file.close()
     file = open('id_to_name.txt', 'r')
     for line in file:
         if line == '':
             continue
         self._id_to_name[int(
             line.split()[0])] = line.split()[1] + " " + line.split()[2]
     file.close()
Esempio n. 7
0
 def startChat(self, *participants):
     new_chat = Chat(self)
     new_chat.add_participants(*participants)
     if new_chat.add_participants(*participants):
         all_participants = [x for x in participants]
         all_participants.append(self)
         while True:
             new_chat.printChat()
             curr_participant = 0
             curr_participant = int(
                 input("Введите номер участника: {} для {}\n".format(
                     [x for x in range(len(all_participants))],
                     [x.name for x in all_participants])))
             new_message = input(
                 "Введите сообщение от имени {} или X для выхода из чата\n".
                 format(all_participants[curr_participant].name))
             if new_message != 'X':
                 new_chat.addMessage(all_participants[curr_participant],
                                     new_message)
             else:
                 break
     else:
         print("Участники не добавлены")
Esempio n. 8
0
    def run(self):
        self.done = False
        print "Welcome! Type '/quit' to exit or '/help' for assistance."
        print "Login/sign-up below:\n"
        while True:
            tempUser = raw_input("Please enter a username: "******"InvalidUsername"] +
                                 "\n").strip()
            if tempUser == "/quit":
                self.quit()
            elif tempUser == "/help":
                print self.helpText
                continue

            tempPass = raw_input(
                "Please enter your password, if your account does not exist, you will be prompted to sign up: "
                + self.credential_errors["InvalidPassword"] + "\n").strip()
            if tempPass == "/quit":
                self.quit()
            elif tempPass == "/help":
                print self.helpText
                continue

            try:
                self.userId = self.wrapper.login(tempUser, tempPass)
                print "Login complete!"
                break
            except (invalidCredentialsException, parametersMissingException,
                    ServerWrapperException) as ex:
                if type(ex) == invalidCredentialsException:
                    print self.credential_errors["Invalid_pairing"]
                elif type(ex) == parametersMissingException:
                    print self.credential_errors["ParametersMissing"]
                else:
                    print "Error occured while trying to perform operation"

                while True:
                    response = raw_input(
                        "Press 's' to sign up as a new user with the credentials you enetered or press any key to retry login\n"
                    ).strip()
                    if response == 's':
                        print "Beginnng sign up process..."
                        try:
                            self.userId = self.wrapper.signup(
                                tempUser, tempPass)
                            print "Sign up complete, you are now logged in"
                            self.done = True
                            break
                        except (duplicateUsernameException,
                                invalidUsernameException,
                                invalidPasswordException,
                                parametersMissingException,
                                ServerWrapperException) as exx:
                            if type(ex) == duplicateUsernameException:
                                print self.credential_errors[
                                    "DuplicateUsername"]
                            elif type(ex) == invalidUsernameException:
                                print self.credential_errors["InvalidUsername"]
                            elif type(ex) == invalidPasswordException:
                                print self.credential_errors["InvalidPassword"]
                            elif type(ex) == ServerWrapperException:
                                print "Error occured while trying to perform operation"
                            else:
                                print self.credential_errors[
                                    "ParametersMissing"]
                    elif response == "/quit":
                        self.quit()
                    elif response == "/help":
                        print self.helpText
                        continue
                    else:
                        break
                if self.done:
                    break

        print self.helpText
        print "This guide can be accessed again with the /help command\n"
        self.cred = Credentials(self.userId, tempPass)
        self.chat = Chat(self.cred, self.wrapper)
        self.chat.run()
Esempio n. 9
0
def main():
    if len(sys.argv) != 2:
        print("Input format must match: python parse.py [input file]")

    filename = "./in/" + sys.argv[1]
    tree = ET.parse(filename)
    root = tree.getroot()

    addresses = {}
    chats = []

    for child in root:
        if not child.get("contact_name") in addresses:
            addresses[child.get("contact_name")] = 1
            current_chat = Chat(child.get("address"),
                                child.get("contact_name"))
            chats.append(current_chat)
        else:
            addresses[child.get("contact_name")] += 1
            current_chat = [
                chat for chat in chats
                if chat.contact_name == child.get("contact_name")
            ][0]
        if child.tag == "sms":
            current_chat.messages.append(
                SMSMessage(
                    child.get("contact_name")
                    if child.get("type") == "1" else "Me", child.get("date"),
                    child.get("readable_date"), child.get("body")))
        elif child.tag == "mms":
            if len(child[1]) == 2:
                parts = []
                for part in child[0]:
                    if part.get("seq") != "-1":
                        if part.get("ct") == "text/plain":
                            parts.append(
                                MMSPart(part.get("ct"), part.get("text"),
                                        child.get("date")))
                        elif part.get("ct")[:5] == "image":
                            parts.append(
                                MMSPart(part.get("ct"), part.get("cl"),
                                        child.get("date")))
                            f = open(
                                "./out/img/{}_{}".format(
                                    child.get("date"), part.get("cl")), 'wb')
                            f.write(base64.b64decode(part.get("data")))
                            f.close()
                        else:
                            parts.append(
                                MMSPart(part.get("ct"), part.get("cl"),
                                        child.get("date")))
                current_chat.messages.append(
                    MMSMessage(
                        child.get("contact_name")
                        if child.get("msg_box") == "1" else "Me",
                        child.get("date"), child.get("readable_date"), parts))
            else:
                print("This is a group message.")
        else:
            print("Neither SMS or MMS")

    for chat in chats:
        chat.messages.sort()

    for chat in chats:
        f = open("./out/" + chat.contact_name + ".md", 'w')
        f.write("## " + chat.contact_name)
        f.write("\n* * *\n")
        for m in chat.messages:
            f.write(str(m) + '  \n')
        f.close()
Esempio n. 10
0
 def __init__(self, appSettings: AppSettings):
     self.appSettings = appSettings
     self.chat = Chat(appSettings)
     self.database = Database(appSettings.mongoUri)
Esempio n. 11
0
class ServidorChatHandler(socketserver.BaseRequestHandler):
    chat = Chat()
    conexion = None
    """
    Método handle()
        En este método se manejara la conexion. En terminos del proyecto, se manejaran los
        diferentes eventos que se presentar según el protocolo especificado.
    """
    def handle(self):
        print("Connection from ", self.client_address)
        enchufe = self.request
        self.conexion = Conexion(enchufe)
        lock = Lock()
        self.manejaConexion(lock)

    """
    Método auxiliar manejaConexion():
        Método donde se manejara cada evento.
    """

    def manejaConexion(self, lock):
        finalizara = False
        identificado = False
        while (not finalizara):
            mensaje = self.manejaMSG()
            if (not identificado):
                if (mensaje[0] == EventoChat.UNKNWON):
                    self.eventoDesconocido()
                elif (mensaje[0] == EventoChat.DISCONNECT):
                    finalizara = True
                    self.desconectar(identificado, lock)
                elif (mensaje[0] == EventoChat.IDENT):
                    if (len(mensaje) > 1):
                        repetido = self.identificar(mensaje[1])
                        if (repetido):
                            identificado = False
                        else:
                            identificado = True
                            lock.acquire()
                            self.chat.añadirCliente(self.conexion)
                            lock.release()
                    else:
                        self.eventoDesconocido()
                else:
                    self.conexion.mandaMSG(
                        "...MUST IDENTIFY FIRST\n...TO IDENTIFY: IDENTIFY USERNAME"
                    )
            else:
                if (mensaje[0] == EventoChat.UNKNWON):
                    self.eventoDesconocido()
                if (mensaje[0] == EventoChat.IDENT):
                    if (len(mensaje) > 1):
                        lock.acquire()
                        repetido = self.identificar(mensaje[1])
                        lock.release()
                    else:
                        self.eventoDesconocido()
                elif (mensaje[0] == EventoChat.STATUS):
                    if (len(mensaje) > 1):
                        lock.acquire()
                        self.conexion.getUsuario().setState(mensaje[1])
                        self.conexion.mandaMSG(
                            self.conexion.getUsuario().getNombre() + " " +
                            mensaje[1], self.chat.getClientes(), "")
                        lock.release()
                    else:
                        self.eventoDesconocido()
                elif (mensaje[0] == EventoChat.USERS):
                    self.conexion.mandaMSG(self.mandarUSERS())
                elif (mensaje[0] == EventoChat.MSG):
                    if (len(mensaje) > 1):
                        self.mandarPrivado(mensaje[1], lock)
                    else:
                        self.eventoDesconocido()
                elif (mensaje[0] == EventoChat.PUBLICMSG):
                    if (len(mensaje) > 1):
                        self.conexion.mandaMSG("...MESSAGE SENT")
                        self.conexion.mandaMSG(
                            mensaje[1], self.chat.getClientes(),
                            self.conexion.getUsuario().getNombre(), "PUBLIC")
                    else:
                        self.eventoDesconocido()
                elif (mensaje[0] == EventoChat.CREATEROOM):
                    if (len(mensaje) > 1):
                        lock.acquire()
                        self.chat.añadirRoom(mensaje[1], [], self.conexion)
                        lock.release()
                        self.conexion.mandaMSG("...ROOM CREATED")
                    else:
                        self.eventoDesconocido()
                elif (mensaje[0] == EventoChat.ROOMSG):
                    if (len(mensaje) > 1):
                        self.mandaMSGRoom(mensaje[1])
                    else:
                        self.eventoDesconocido()
                elif (mensaje[0] == EventoChat.INVITE):
                    if (len(mensaje) > 1):
                        self.invitacion(mensaje[1], lock)
                    else:
                        self.eventoDesconocido()
                elif (mensaje[0] == EventoChat.JOINROOM):
                    if (len(mensaje) > 1):
                        self.joinRoom(mensaje[1], lock)
                    else:
                        self.eventoDesconocido()
                elif (mensaje[0] == EventoChat.DISCONNECT):
                    finalizara = True
                    self.desconectar(identificado, lock)
        self.conexion.mandaMSG("DISCONNECTING...")

    """
    Método ManejaMSG():
        Método que se encargara del input del socket del servidor.
        @return Tupla, dondé el primer elemento es el evento especificado por el protocolo.
    """

    def manejaMSG(self):
        mensaje = self.conexion.reciveMSG()
        mensaje = mensaje.strip()
        mensaje = mensaje.split(" ", 1)
        evento = EventoChat.get(EventoChat, mensaje[0])
        if (len(mensaje) == 2):
            return (evento, mensaje[1])
        return (evento, )

    """
    Método auxiliar eventoDesconocido():
        Método que se encarga de hacerle conocer al cliente que el evento no esta especificado
        en el protocolo.
    """

    def eventoDesconocido(self):
        self.conexion.mandaMSG("...INVALID MESSAGE TRY")
        self.conexion.mandaMSG("...VALID MESSAGE ARE:")
        for representacion in EventoChat.listaEventos(EventoChat):
            if (representacion is not None):
                if representacion == "IDENTIFY":
                    self.conexion.mandaMSG("..." + representacion + " NAME")
                elif representacion == "STATUS":
                    self.conexion.mandaMSG("..." + representacion +
                                           " ACTIVE/AWAY/BUSY")
                elif representacion == "USERS":
                    self.conexion.mandaMSG("..." + representacion)
                elif representacion == "MESSAGE":
                    self.conexion.mandaMSG("..." + representacion +
                                           " USERNAME messageContent")
                elif representacion == "PUBLICMESSAGE":
                    self.conexion.mandaMSG("..." + representacion +
                                           " messageContent")
                elif representacion == "CREATEROOM":
                    self.conexion.mandaMSG("..." + representacion +
                                           " roomName")
                elif representacion == "INVITE":
                    self.conexion.mandaMSG("..." + representacion +
                                           " roomName user1 user2...")
                elif representacion == "JOINROOM":
                    self.conexion.mandaMSG("..." + representacion +
                                           " roomName")
                elif representacion == "ROOMESSAGE":
                    self.conexion.mandaMSG("..." + representacion +
                                           " roomName messageContent")
                elif representacion == "DISCONNECT":
                    self.conexion.mandaMSG("..." + representacion)

    """
    Método auxiliar joinRoom():
        Método auxiliar que se encarga del evento JOINROOM especificado en el protocolo.
        @param room_name: El nombre de la sala al que el cliente se quiere unir.
               lock : Instancia de la clase Lock() del módulo threading, necesaria para
                      poder sincronizar la lista de conexiones la sala.
        
    """

    def joinRoom(self, room_name, lock):
        room = self.chat.getRoom(room_name)
        if room is None:
            self.conexion.mandaMSG("...ROOM NOT EXISTS")
            return
        if (self.conexion in room.getInvitados()
                and not (self.conexion in room.getUsers())):
            lock.acquire()
            room.agregarUser(self.conexion)
            room.eliminarInvitado(self.conexion)
            lock.release()
            self.conexion.mandaMSG("...SUCCESFULLY JOINED TO ROOM")
        elif (self.conexion in room.getInvitados()
              and (self.conexion in room.getUsers())):
            lock.acquire()
            room.eliminarInvitado(self.conexion)
            lock.release()
            self.conexion.mandaMSG("...ALREADY EXISTS IN ROOM")
        else:
            self.conexion.mandaMSG("...TOU ARE NOT INVITED TO ROOM " +
                                   room.getName())

    """
    Método auxiliar invitacion():
        Método auxiliar que se encarga del evento INVITE especificado en el protocolo.
        @param msg: Mensaje donde se sacara el nombre de la sala y el nombre del cliente
                    a quien se le esta invitando.
               lock : Instancia de la clase Lock() del módulo threading, necesaria para
                      poder sincronizar la lista de conexiones de invitados de la sala.
    """

    def invitacion(self, msg, lock):
        msg = msg.split(" ")
        room = self.chat.getRoom(msg[0])
        if (room is None):
            self.conexion.mandaMSG("...ROOM NOT EXIST")
            return
        if (room.getCreador() != self.conexion):
            self.conexion.mandaMSG("...YOU ARE NOT THE OWNER OF THE ROOM")
            return
        invitado = self.chat.getCliente(msg[1])
        if (invitado is None):
            self.conexion.mandaMSG("...USER " + msg[1] + " NOT FOUND")
            return
        lock.acquire()
        room.agregarInvitado(invitado)
        lock.release()
        nombre = self.conexion.getUsuario().getNombre()
        self.conexion.mandaMSG("...INVITATION SENT TO " + invitado.__repr__())
        self.conexion.mandaMSG(
            "...INVITATION TO JOIN ROOM " + room.getName() + " FROM BY " +
            nombre, [invitado])
        self.conexion.mandaMSG("...TO JOIN: JOINROOM " + room.getName(),
                               [invitado])

    """
    Método auxiliar identificar():
        Método auxiliar que se encarga del evento IDENTIFY especificado en el protocolo.
        Se modificara o se entrudicira el nombre del cliente.
        Si el nombre entrante es repetido, se mandara un mensaje al cliente , para que se le
        haga saber este hecho.
        @param nombre: nombre para modificar el nombre del cliente.
    """

    def identificar(self, nombre):
        nombre_repetido = False
        for cliente in self.chat.getClientes():
            if (cliente.getUsuario().getNombre() == nombre):
                nombre_repetido = True
                break
        if (nombre_repetido):
            self.conexion.mandaMSG("...NOMBRE OCUPADO...")
            return nombre_repetido
        else:
            self.conexion.setUsuario(nombre)
            self.conexion.mandaMSG("...SUCCESFUL IDENTIFICATION")
            return nombre_repetido

    """
    Método auxiliar mandarUSERS():
        Método auxiliar que se encarga del evento USERS especificado en el protocolo.
        Se envia la lista de clientes del chat.
    """

    def mandarUSERS(self):
        s = ""
        for cliente in self.chat.getClientes():
            s = s + cliente.__repr__() + "   "
        return s

    """
    Método auxiliar mandaMSG():
        Método auxiliar que se encarga del evento ROOMESSAGE especificado en el protocolo.
        Se modificara o se entrudicira el nombre del cliente.
        @param msg : mensaje en donde se sacara el nombre de la sala, y el mensaje que se
                     enviara en el room especificado.
    """

    def mandaMSGRoom(self, msg):
        msg = msg.split(" ")
        if (len(msg) < 2):
            self.eventoDesconocido()
            return
        room = self.chat.getRoom(msg[0])
        nombre = self.conexion.getUsuario().getNombre()
        if (room is None):
            self.conexion.mandaMSG("...ROOM NOT EXISTS")
            return
        self.conexion.mandaMSG("...MESSAGE SENT")
        self.conexion.mandaMSG(msg[1], room.getUsers(), nombre, msg[0])

    """
    Método auxiliar desconectar():
        Método auxiliar que se encarga del evento DISCONNECT especificado en el protocolo.
        Se eliminara de todas las listas donde este contenida la conexion que se desconectara.
        @param identificado: bool; True si la conexion ya esta indentificada, False otherwise.
               lock : Instancia de la clase Lock() del módulo threading, necesaria para
                      poder sincronizar la lista de conexiones de invitados de la sala,
                      lista de conexiones del chat y la lista de conexiones de las salas.
    """

    def desconectar(self, identificado, lock):
        if (not identificado):
            return
        if (identificado):
            self.chat.eliminarCliente(self.conexion, lock)

    """
    Método auxiliar mandarPrivado():
        Método auxiliar que se encarga del evento INVITE especificado en el protocolo.
        Se establecera la comunicación privada en una sala. Si es la primera vez que se
        establece comunicación entre los dos clientes se creara una sala, en donde se
        establecera la conversación. Sino solo se mandara  la sala privada entre los clientes.
        @param mensaje: Mensaje donde se sacara el nombre del cliente emisario y 
                        del cliente  remitente.
               lock : Instancia de la clase Lock() del módulo threading, necesaria para
                      poder sincronizar la lista de salas del chat.
    """

    def mandarPrivado(self, mensaje, lock):
        mensaje = mensaje.split(" ")
        nombre = self.conexion.getUsuario().getNombre()
        remitente = self.chat.getCliente(mensaje[0])
        if (remitente is None):
            self.conexion.mandaMSG("...USER " + mensaje[0] + " NO FOUND")
            return
        private_roomName = "$$" + nombre + "-" + mensaje[0] + "$$"
        if (private_roomName in self.chat.getRooms()):
            self.conexion.mandaMSG("...MESSAGE SENT")
            self.conexion.mandaMSG(
                mensaje[1],
                self.chat.getRoom(private_roomName).getClientes(), nombre)
        else:
            user1 = self.chat.getCliente(nombre)
            user2 = self.chat.getCliente(mensaje[0])
            lock.acquire()
            self.chat.añadirRoom(private_roomName, [user1, user2])
            lock.release()
            self.conexion.mandaMSG("...MESSAGE SENT")
            self.conexion.mandaMSG(
                mensaje[1],
                self.chat.getRoom(private_roomName).getUsers(), nombre)
Esempio n. 12
0
 def addChat_id(self, chatid):
     if (self.chatList.__contains__(chatid) == False):
         self.chatList.append(chatid)
         chat = Chat()
         chat.chat_id = chatid
         self.lista_chat.append(chat)
Esempio n. 13
0
    def disconnect(self):
        self.connection.close()

    def receive_message(self, message):
        chat.DisplayMsgToUser(message)

    def send_payload(self, data):
        # TODO: Handle sending of a payload
        sendMsg = json.dumps(data)
        rawSendMsg = sendMsg.encode()
        self.connection.send(rawSendMsg)

    def set_Chat(self, chat):
        self.Chat = chat


if __name__ == '__main__':
    """
    This is the main method and is executed when you type "python Client.py"
    in your terminal.

    No alterations are necessary
    """

    client = Client('localhost', 9998)
    chat = Chat(client)
    client.set_Chat(chat)
    chat.start()
    while True:
        pass
Esempio n. 14
0
    def __init__(self):

        __builtin__.main = self
        self.cManager = ConnectionManager()
        self.startConnection()
        self.taskMgr = taskMgr
        self.base = base

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam-left": 0,
            "cam-right": 0
        }

        self.characters = dict()
        self.cpList = dict()

        base.win.setClearColor(Vec4(0, 0, 0, 1))

        #self.environ = loader.loadModel("models/world")
        self.environ = loader.loadModel("models/land")
        """
        self.swordLeft = loader.loadModel("models/Sword_Left")
        self.swordRight = loader.loadModel("models/Sword_Right")  
        self.shieldLeft = loader.loadModel("models/Shield_Left")  
        self.shieldRight = loader.loadModel("models/Shield_Right")  
        self.money = loader.loadModel("models/Money")
        """

        self.left_atk_tower = loader.loadModel("models/attack_tower")
        self.left_def_tower = loader.loadModel("models/defense_tower")
        self.right_atk_tower = loader.loadModel("models/attack_tower")
        self.right_def_tower = loader.loadModel("models/defense_tower")
        self.money_cp = loader.loadModel("models/money_point")

        self.left_atk_tower.setPos(141.016, 0.440607, 0)
        self.left_def_tower.setPos(210.984, 115.005, 0)
        self.right_atk_tower.setPos(-149.953, 0.674369, 0)
        self.right_def_tower.setPos(-210.771, 113.753, 0)
        self.money_cp.setPos(-0.903916, 11.3765, 0)

        self.left_atk_tower.setScale(2.0)
        self.right_atk_tower.setScale(2.0)
        self.left_def_tower.setScale(2.0)
        self.right_def_tower.setScale(2.0)
        self.money_cp.setScale(2.0)

        self.left_atk_tower.reparentTo(render)
        self.right_atk_tower.reparentTo(render)
        self.left_def_tower.reparentTo(render)
        self.right_def_tower.reparentTo(render)
        self.money_cp.reparentTo(render)

        self.environ.reparentTo(render)
        """
        self.swordLeft.reparentTo(render)
        self.swordRight.reparentTo(render)
        self.shieldLeft.reparentTo(render)
        self.shieldRight.reparentTo(render)
        self.money.reparentTo(render)
        """

        self.environ.setPos(0, 0, 0)
        self.environ.setH(90)
        """
        self.swordLeft.setH(90)
        self.swordRight.setH(90)
        self.shieldLeft.setH(90)
        self.shieldRight.setH(90)
        self.money.setH(90)
        """

        mySound = loader.loadSfx("sound/Retribution.mp3")
        mySound.setLoop(True)
        mySound.play()

        fp = FilterProperties()
        #fp.addReverb(0.6, 0.5, 0.1, 0.1, 0.1)
        base.sfxManagerList[0].configureFilters(fp)

        ## swordsmanStartPos = self.environ.find("**/start_point").getPos()
        ## self.player = Swordsman("Swordsman", 0)
        ## self.player._character.reparentTo(render)
        ## self.player._character.setScale(.1)
        ## self.player._character.setPos(swordsmanStartPos)
        ## swordsmanStartPos.setY(swordsmanStartPos.getY()-10)
        ## self.player._character.setPos(swordsmanStartPos.getX(),swordsmanStartPos.getY(),swordsmanStartPos.getZ())
        ## self.initx = swordsmanStartPos.getX()

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        ## self.characters["Axeman"] = Axeman("Axeman", 1)
        ## self.characters["Axeman"]._character.reparentTo(render)
        ## self.characters["Axeman"]._character.setScale(.1)
        ## self.characters["Axeman"]._character.setPos(swordsmanStartPos)
        ## swordsmanStartPos.setY(swordsmanStartPos.getY()-10)
        ## self.characters["Axeman"]._character.setPos(swordsmanStartPos.getX(),swordsmanStartPos.getY() - 10,swordsmanStartPos.getZ())
        ## self.characters["Axeman"]._character.loop("idle")

        self.accept("a", self.setKey, ["left", 1])
        self.accept("s", self.setKey, ["backward", 1])
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("s-up", self.setKey, ["backward", 0])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("arrow_left", self.setKey, ["cam-left", 1])
        self.accept("arrow_right", self.setKey, ["cam-right", 1])
        self.accept("arrow_left-up", self.setKey, ["cam-left", 0])
        self.accept("arrow_right-up", self.setKey, ["cam-right", 0])
        self.accept("mouse1", self.attack, [3])
        self.accept("mouse3", self.attack, [4])

        self.username = str(raw_input("Username: "******"Type: ")
        faction = input("Faction: ")
        self.cManager.sendRequest(Constants.CMSG_AUTH,
                                  [self.username, type, faction])

        #taskMgr.add(self.move,"moveTask")
        taskMgr.doMethodLater(.10, self.refresh, "heartbeat")

        base.disableMouse()
        #base.camera.setPos(self.player._character.getX(),self.player._character.getY()+10,2)

        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))

        directionalLight2 = DirectionalLight("directionalLight2")
        directionalLight2.setDirection(Vec3(5, 5, 5))
        directionalLight2.setColor(Vec4(1, 1, 1, 1))
        directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1))

        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
        render.setLight(render.attachNewNode(directionalLight2))

        Chat(self.cManager)

        # Create control points
        self.cpList[1] = ControlPoint(1, 210.984, 115.005, -5, 10, RED)
        self.cpList[2] = ControlPoint(2, 141.016, 0.440607, -5, 10, RED)
        self.cpList[3] = ControlPoint(3, -0.903916, 11.3765, -2, 10, RED)
        self.cpList[4] = ControlPoint(4, -210.771, 113.753, -2, 10, BLUE)
        self.cpList[5] = ControlPoint(5, -149.953, 0.674369, -2, 10, BLUE)

        # Create the control point Bar UI
        self.cp_bar = ControlPointBar()
        # self.resource_bar = ResourceBar()

        taskMgr.doMethodLater(0.1, self.refresh, "heartbeat")
        taskMgr.doMethodLater(1, self.CPHandler, "CPHandler")
        taskMgr.doMethodLater(0.1, self.CPBarHandler, 'CPBarHandler')
        '''NPC Code Additions'''
        #self.isChased =[False,False]
        #self.npcList = [0,0]
        self.isChased = False
        self.npcList = 0
        self.controlNpc = NPCController(render)
        taskMgr.add(self.taskAIUpdate, "AIUpdate")
        taskMgr.add(self.moveNpc, "Move")
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(
            fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
                                                        ifname[:15]))[20:24])


def get_lan_ip():
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith("127.") and os.name != "nt":
        interfaces = [
            "eth0",
            "eth1",
            "eth2",
            "wlan0",
            "wlan1",
            "wifi0",
            "ath0",
            "ath1",
            "ppp0",
        ]
        for ifname in interfaces:
            try:
                ip = get_interface_ip(ifname)
                break
            except IOError:
                pass
    return ip


chat = Chat(get_lan_ip())
chat.run()
Esempio n. 16
0
from socket import *
import socket
import threading
import json
import logging
from Chat import Chat

chatserver = Chat()


class ProcessTheClient(threading.Thread):
    def __init__(self, connection, address):
        self.connection = connection
        self.address = address
        threading.Thread.__init__(self)

    def run(self):
        rcv = ""
        while True:
            data = self.connection.recv(2048)
            if data:
                d = data.decode()
                rcv = rcv + d
                # if rcv[-1:]=='.':
                # end of command, proses string
                logging.warning("data dari client: {}".format(rcv))
                hasil = json.dumps(chatserver.proses(rcv))
                hasil = hasil + "\r\n\r\n"
                logging.warning("balas ke  client: {}".format(hasil))
                self.connection.sendall(hasil.encode())
                rcv = ""
Esempio n. 17
0
	def __init__(self, parent):
		self.parent = parent
		self.update_forever = False

		# MAIN PROPERTIES

		self.settings = {
			"nick":"",
			"chan":"",
			"auth":"",
			"rate":10,
			"voic":True,
			"auto":[],
			"cmds":[]}

		self.auto_time_l = threading.Lock()
		self.auto_time = []

		self.load_settings()
		self.save_settings()

		# strip # character, it can be added when needed
		if self.settings["chan"].startswith("#"):
			self.settings["chan"] = self.settings["chan"][1:]

		print(self.settings["nick"])
		print(self.settings["chan"])
		print(self.settings["auth"])
		print(self.settings["rate"])
		print(self.settings["voic"])
		print(self.settings["auto"])
		print(self.settings["cmds"])

		if self.settings["rate"] == None:
			self.settings["rate"] = 10

		self.channel_data = {}

		# CONTROL BUTTONS FRAME

		self.frame_control		= ttk.Frame(self.parent, relief=SUNKEN, width = 50, borderwidth=15)

		self.btn_connect		= ttk.Button(self.frame_control, text = 'Connect', width = 25, command = self.core_connect)
		self.btn_goto_auth		= ttk.Button(self.frame_control, text = 'Authentication', width = 25, command = self.goto_authentication)
		self.btn_auto_msg		= ttk.Button(self.frame_control, text = 'Auto-Messages', width = 25, command = self.goto_auto_message)
		self.btn_commands		= ttk.Button(self.frame_control, text = 'Commands', width = 25, command = self.goto_commands)

		self.lab_followers_s	= StringVar()
		self.lab_followers		= ttk.Label(self.frame_control, textvariable = self.lab_followers_s, width = 25)

		self.lab_last5fol		= ttk.Label(self.frame_control, text = "Last 5 followers:", width = 25)
		self.lst_last5fol		= Listbox(self.frame_control, width = 25, height = 5, activestyle = 'none', takefocus = False, exportselection=False)

		self.lab_views_s		= StringVar()
		self.lab_views			= ttk.Label(self.frame_control, textvariable = self.lab_views_s, width = 25)

		self.lab_status_s		= StringVar()
		self.lab_status			= ttk.Label(self.frame_control, textvariable = self.lab_status_s, width = 25)

		self.lab_game_s			= StringVar()
		self.lab_game			= ttk.Label(self.frame_control, textvariable = self.lab_game_s, width = 25)

		self.lab_streams_s		= StringVar()
		self.lab_streams		= ttk.Label(self.frame_control, textvariable = self.lab_streams_s, width = 25)

		self.lab_popularity_s	= StringVar()
		self.lab_popularity		= ttk.Label(self.frame_control, textvariable = self.lab_popularity_s, width = 25)


		# CHAT AREA FRAME

		self.frame_chat			= ttk.Frame(self.parent, relief=SUNKEN, width = 50, borderwidth=15)

		self.ent_chat_input_s	= StringVar()
		self.ent_chat_input		= ttk.Entry(self.frame_chat, textvariable = self.ent_chat_input_s)
		self.txt_chat_log		= ScrolledText(self.frame_chat, wrap=WORD)

		self.chat				= Chat(self.settings["nick"], realname=self.settings["nick"])
		self.btn_chat_send		= ttk.Button(self.frame_chat, text = 'Send', width=10, command = self.chat.chat_send, state = DISABLED)
		self.chat.setup(self.ent_chat_input_s, self.txt_chat_log)


		# STATUS AREA FRAME

		self.frame_status		= ttk.Frame(self.parent, relief=SUNKEN)

		self.txt_status_s		= StringVar()
		self.txt_status			= ttk.Entry(self.frame_status, textvariable = self.txt_status_s)

		# GRID SETUP

		self.frame_control.grid	(column=0, row=0, sticky=(N, S, E, W))
		self.btn_connect.grid	(column=0, row=0, sticky=(E, W))
		self.btn_goto_auth.grid	(column=0, row=1, sticky=(E, W))
		self.btn_auto_msg.grid	(column=0, row=2, sticky=(E, W))
		self.btn_commands.grid	(column=0, row=3, sticky=(E, W))
		self.lab_followers.grid	(column=0, row=4, sticky=(E, W))
		self.lab_last5fol.grid	(column=0, row=5, sticky=(E, W))
		self.lst_last5fol.grid	(column=0, row=6, sticky=(E, W))
		self.lab_views.grid		(column=0, row=7, sticky=(E, W))
		self.lab_status.grid	(column=0, row=8, sticky=(E, W))
		self.lab_game.grid		(column=0, row=9, sticky=(E, W))
		self.lab_streams.grid	(column=0, row=10, sticky=(E, W))
		self.lab_popularity.grid(column=0, row=11, sticky=(E, W))

		self.frame_chat.grid	(column=1, row=0, sticky=(N, S, E, W))
		self.ent_chat_input.grid(column=0, row=0, sticky=(E, W), columnspan=2)
		self.btn_chat_send.grid	(column=1, row=0, sticky=E)
		self.txt_chat_log.grid	(column=0, row=1, sticky=(N, S, E, W), columnspan=2)

		self.frame_status.grid	(column=0, row=1, columnspan=2, sticky=(N, S, E, W))
		self.txt_status.pack	(fill=BOTH, expand=YES)

		# WINDOW FLAGS

		self.opened_dialog = False

		# PERFORM FIRST UPDATE MANUALLY TO POPULATE UI

		self.do_update()

		# SPEECH RECOGNITION

		if self.settings["voic"] == True:
			print("Using speech")
			self.run_speech()
Esempio n. 18
0
DATABASE_NAME = 'database.sqlite'
HOST = 'localhost'
PORT = 9000

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    server_socket.bind((HOST, PORT))
    server_socket.listen(5)
    while True:
        (clientSocket, address) = server_socket.accept()
        data_str = clientSocket.recv(5000).decode()
        js = json.loads(data_str)
        user_name = js['username']
        password = js['password']

        chat = Chat(DATABASE_NAME)
        data_to_send = {}
        if not chat.verify(user_name, password):
            data_to_send['status'] = False
            clientSocket.send(json.dumps(data_to_send).encode())
            clientSocket.close()
            continue

        data_to_send[
            'status'] = True  # TODO some awesome verification, AES keys?
        messages = chat.read_msg(2)
        messages.reverse()
        data_to_send['chats'] = messages
        clientSocket.send(json.dumps(data_to_send).encode())
        clientSocket.close()
Esempio n. 19
0
class DataBase():

    db = DBHelper()
    lista_chat = list()
    chatList = db.get_chat("chat", "ID")
    utents = db.get_chat("utenti", "ID")
    utenti = list()

    for chat_id in chatList:
        chat = Chat()
        chat.chat_id = chat_id
        mex = db.get_items("messaggi", "TESTO", chat_id)
        foto = db.get_items("foto", "TESTO", chat_id)
        chat.messaggi = mex
        chat.foto = foto
        lista_chat.append(chat)

    for utente_id in utents:
        utente = Utente()
        coin = db.get_item("utenti", "COIN", utente_id)
        first_name = db.get_item("utenti", "FIRST_NAME", utente_id)
        username_name = db.get_item("utenti", "USERNAME", utente_id)
        utente.id = utente_id
        utente.coin = coin
        utenti.append(utente)

    def addChat_id(self, chatid, db):
        if (self.chatList.__contains__(chatid) == False):
            self.chatList.append(chatid)
            print("fatto")
            db.add_chat("chat", chatid)
            chat = Chat()
            chat.chat_id = chatid
            self.lista_chat.append(chat)

    def addMex(self, chatid, utenteid, mex, db):
        for chats in self.lista_chat:
            if (chats.chat_id == chatid):
                if (chats.messaggi.__contains__(mex) == False):
                    chats.messaggi.append(mex)
                    if (len(mex) > 6):
                        chats.mex_gioco.append(mex)
                        chats.mex_utenti.append(utenteid)
                    db.add_item("messaggi", mex, chatid, utenteid)
                    print("fatto")
                    if len(chats.messaggi) >= 1000:
                        db.delete_items("messaggi", chatid)
                        nuova = chats.messaggi[len(chats.messaggi) // 2:]
                        chats.messaggi = nuova
                        break

    def addFoto(self, chatid, file_id, db, utente_id):
        for chats in self.lista_chat:
            if (chats.chat_id == chatid):
                if (chats.foto.__contains__(file_id) == False):
                    chats.foto.append(file_id)
                    db.add_item("foto", file_id, chatid, utente_id)
                    if len(chats.foto) >= 500:
                        nuova = chats.foto[len(chats.foto) // 2:]
                        chats.foto = nuova
                        break

    def addUtente(self, id_utente, db, chat_type, username, first_name):
        presente = False
        no_name = False
        for utente in self.utenti:
            if (utente.first_name == None) | (utente.first_name != first_name):
                no_name = True
            if utente.id == id_utente:
                presente = True
                utente.mex += 1
                print("mex addato")
                if (utente.mex % 10 == 0) & (chat_type == "supergroup"):
                    utente.coin += 1
                    db.add_utente_coin(id_utente, 1, "COIN")
                    break
        if presente == False:
            utente = Utente()
            utente.id = id_utente
            utente.mex += 1
            self.utenti.append(utente)
            db.add_utente(id_utente, username, first_name)
        if no_name:
            utente.first_name = first_name
            utente.username = username
            db.add_utente_name(id_utente, "FIRST_NAME", first_name)
            db.add_utente_name(id_utente, "USERNAME", username)
Esempio n. 20
0
 def __init__(self, appSettings):
     self.appSettings = appSettings
     self.name = "MusicBot"
     self.chat = Chat(appSettings)
     self.spotify = SpotifyApi(appSettings)
     self.users = Users()