Example #1
0
    def test_chat_match_alternative(self):
        search_str = 'Zebra'
        res = {
            'count': 1,
            'similarity': 1,
            'value': {
                'subject': ('eels', 'Zebra Moray'),
                'keywords':
                (('eel', 'snake-like'), ('zebra', 'strip', 'moray')),
                'phrase': ('Zebra Moray', ),
                'info': ({
                    'name': 'Diet',
                    'value': 'Sea urchins, mollusks, and crustaceans.'
                }, ),
                'isLeaf':
                True
            },
            'lastCount': 1,
            'lastSimilarity': 1,
            'matching': ('zebra', ),
            'certainty': 2
        }

        thisChat = Chat(flatten(resources), ['fishes', 'nothingthere'])
        self.assertEqual(thisChat.match(search_str), res)
def start_client():

    connected = True
    client = Chat.create_client()
    client.connect(('localhost', 1024))
    msg = Chat.receive_message(client)
    print(msg)

    def receiver_thread(client):
        try:
            while connected:
                msg = Chat.receive_message(client)
                print(msg)
            print('Disconnected From Server.')
        except ConnectionResetError as e:
            print(f'Error: Server Closed Connection.')
            return

    threading.Thread(target=receiver_thread, args=[client],
                     daemon=True).start()

    while connected:
        try:
            msg = input('>')
            Chat.send_message(client, msg)
            if msg == '\exit()':
                connected = False
        except ConnectionResetError as e:
            print(f'Error: Server Closed Connection.')
            connected = False
Example #3
0
 def __init__(self, slack_client, channel, players):
     self.last_message = None
     self.slack_client = slack_client
     self.channel = channel
     self.players = players
     self.chat = Chat(slack_client, channel)
     print str(channel)
Example #4
0
    def enter(self):
        self.login = self.LoginLineEdit.text()
        self.password = self.PasswordLineEdit.text()

        self.con = sqlite3.connect("dollars.db")
        cur = self.con.cursor()
        result = cur.execute(
            """SELECT login, password FROM users 
                        WHERE login == ? AND password == ?""",
            (self.login, self.password)).fetchall()
        if len(result) > 0:
            result = result[0]
            if result[0] == self.login and str(result[1]) == self.password:
                self.name = self.login
                self.chat = Chat(self.name)
                self.chat.show()
                self.close()
            else:
                self.error.setText("login or password isn't correct")
                self.LoginLineEdit.setText('')
                self.PasswordLineEdit.setText('')
        else:
            self.error.setText("login or password isn't correct")
            self.LoginLineEdit.setText('')
            self.PasswordLineEdit.setText('')
Example #5
0
    def __init__(self, parent, width, height):
        super(GameFrame, self).__init__(parent)
        self.width = width
        self.height = height
        self.resize(self.width, self.height)

        #Input
        self.keys = {}

        #Chat
        self.chatMode = False
        self.chat = Chat(10, self.height - 210, 600, 200)

        #World (holds map size, entities, characters/players)
        self.world = World()

        #Character
        character = Character()
        character.setName("Macke")
        character.setPos(300, 300)
        self.world.setCharacter(character)

        #Server connection
        self.threadHandler = ClientThread(self.world.getCharacter(),
                                          self.world.getOtherPlayers())
        self.threadHandler.start()
Example #6
0
 def __init__(self,
              host=None,
              port=None,
              commander_name=None,
              bot_name=None):
     self.server_host = host
     self.server_port = port
     self.config = config
     self.eventregister = EventRegister(self)
     self.eventregister.setup()
     self.commander = Commander(commander_name)
     self.chat = Chat(self)
     self.stats = Statistics()
     self.bot = BotEntity(self, bot_name)
     self.game_ticks = 0
     self.connected = False
     self.logged_in = False
     self.protocol = None
     self.factory = None
     self.entities = None
     self.inventories = inventory.InvetoryContainer(self)
     self.grid = None
     self.sign_waypoints = None
     self.dimension = None
     self.dimensions = [Dimension(self), Dimension(self), Dimension(self)]
     self.spawn_position = None
     self.game_mode = None
     self.difficulty = None
     self.players = defaultdict(int)
     self.last_tick_time = datetime.now()
     self.period_time_estimation = config.TIME_STEP
     utils.do_later(config.TIME_STEP, self.tick)
Example #7
0
   def __init__(self, parent, width, height):
      super(GameFrame, self).__init__(parent)
      self.width = width
      self.height = height
      self.resize(self.width, self.height)

      #Chat
      self.chatMode = False
      self.chat = Chat(10,self.height - 210, 600, 200)

      #Entities
      self.entities = []
      #self.entities.append(Entity())

      #e = Entity()
      #e.setPos(200,200)
      #self.entities.append(e)
      
      self.character = Character()
      self.character.setPos(300,300)

      self.otherPlayers = []

      #Server connection
      self.offline = False
      self.sock = socket.socket()
      self.sock.connect(('127.0.0.1', 1338))
      self.updatesPerServerSync = 5
      self.serverSyncCounter = 0
Example #8
0
class Player:
    IN_STATE = "IN"
    FOLD_STATE = "FOLD"
    ALL_IN_STATE = "ALL IN"

    CALL_ACTION = "CALL"
    RAISE_ACTION = "RAISE"
    CHECK_ACTION = "CHECK"
    BET_ACTION = "BET"

    def __init__(self, slack_id, slack_client):
        self.slack_id = slack_id
        self.money = 200
        self.cards = []
        self.state = Player.IN_STATE
        self.action = ''
        self.bet = 0
        self.slack_client = slack_client
        self.chat = Chat(
            slack_client,
            Player.get_im_channel(self.slack_client, self.slack_id))

    @staticmethod
    def get_im_channel(slack_client, slack_id):
        ims = json.loads(slack_client.api_call('im.list'))['ims']
        for im in ims:
            if im['user'] == slack_id:
                return im['id']

        print str(ims)
        raise "IM Channel not found!"

    def get_username(self):
        user_api = json.loads(
            self.slack_client.api_call('users.info',
                                       user=self.slack_id))['user']
        return user_api['name']

    def card_str(self):
        return '{}, {}'.format(Card.int_to_pretty_str(self.cards[0]),
                               Card.int_to_pretty_str(self.cards[1]))

    def deal(self, cards):
        self.bet = 0
        self.cards = cards
        self.state = Player.IN_STATE
        self.chat.message('Your hand: {}'.format(self.card_str()))

    def __hash__(self):
        return hash(self.slack_id)

    def __eq__(self, other):
        try:
            return hash(self) == hash(other)
        except:
            return False

    def __str__(self):
        return self.get_username()
Example #9
0
def hello_world():
    if request.method == 'PUT':
        print(request.json)
        errorStatement = request.json["errorstat"]

        bot = Chat()
        ans = bot.chatbot_response(errorStatement)
        return jsonify(ans)
Example #10
0
class Round(object):
    def __init__(self, word, player_drawing, game):
        """
        init object
        :param word: str
        :param player_drawing: Player
        :param game: Game object
        """
        self.word = word
        self.player_drawing = player_drawing
        self.player_guessed = []
        self.skips = 0
        self.time = 60
        self.game = game
        self.player_scores = {player: 0 for player in self.game.players}
        self.chat = Chat()
        start_new_thread(self.time_thread, ())

    def skip(self):
        """
        Returns bool deciding whether skipping round or not
        :return: bool
        """
        self.skips += 1
        if self.skips > len(self.game.players) - 2:
            return True
        return False

    def time_thread(self):
        """
        Runs in different thread to keep track of time
        :return: None
        """
        while self.time > 0:
            t.sleep(1)
            self.time -= 1
        self.end_round()

    def guess(self, player, wrd):
        """
        :returns whether the player guessed right
        :param player: Player
        :param wrd: str
        :return: bool
        """
        if wrd.lower() == self.word.lower():
            self.player_guessed.append(player)
            self.chat.update_chat(f"g{player.name} guessed correctly")
            return True
        self.chat.update_chat(f"r{player.name}: {wrd}")
        return False

    def end_round(self):
        for player in self.game.players:
            player.has_guessed = False
            if player in self.player_scores:
                player.update_score(self.player_scores[player])
        self.game.end_round()
Example #11
0
 def login(self):
     " События, когда пользователь заходит в онлайн "
     log_debug(self.name + " login")
     self.session["channel"] = None
     msg, p = self.get_welcome_message()
     Chat.announce(msg, p)
     msg_online = self.get_other_online_message()
     self.private_message(msg_online)
     Loc.enter(self)
Example #12
0
    def __init__(self, client):
        self.client = client
        self.state = 'main'
        # state main
        self.title_main = TextBox(DIM_TITLE, C.WHITE, POS_TITLE,'SocketGame', font=Font.f100)

        self.button_login = Button(DIM_MAIN_B, C.LIGHT_BLUE,
                                POS_BLOG,'Log in')


        self.button_signup = Button(DIM_MAIN_B, C.LIGHT_BLUE,
                                POS_BSIGN,'Sign up') 

        self.button_credits = Button(DIM_LI_MAIN_B, C.LIGHT_BLUE, (LMARGE, LMARGE),'Credits',font=Font.f30)

        # state login
        self.title_login = TextBox(DIM_TITLE, C.WHITE, POS_TITLE,'Log in', font=Font.f100)

        self.text_logusername = TextBox(DIM_TEXTBL,C.WHITE,
                                (X_POS_TEXTBL, Y_POS_TEXTBL), 'Username:'******'Password:'******'Done', font=Font.f30)
        self.button_back = Button(DIM_NB, C.LIGHT_BLUE, POS_BBACK,'Back', font=Font.f30)
        # state signup
        self.title_signup = TextBox(DIM_TITLE, C.WHITE, POS_TITLE,'Sign up', font=Font.f100) 
        # state fail log
        self.text_faillog = TextBox(DIM_FAILT, C.WHITE, (X_POS_TEXTBL2, Y_POS_FAILT),
                                'Invalid username or password', font=Font.f25, TEXT_COLOR=C.RED)  
        # state fail sign
        self.text_failsign = TextBox(DIM_FAILT, C.WHITE, (X_POS_TEXTBL2, Y_POS_FAILT),
                                'Username already taken', font=Font.f25, TEXT_COLOR=C.RED)  
        # state logged
        self.title_logged = TextBox(DIM_TITLE, C.WHITE, POS_TITLE,'Welcome', font=Font.f100)
        self.text_username = TextBox(DIM_LOGINP, C.WHITE, (LMARGE, LMARGE),'',marge=True)
        self.button_play = Button(DIM_MAIN_B, C.LIGHT_BLUE, 
                    POS_BPLAY, 'Play') 
        self.chat_logged = Chat(DIM_CHAT, (MARGE,dim.y-DIM_CHAT[1]-MARGE), self.client)
        self.friends = Friends(DIM_FR, (dim.x-DIM_FR[0]-MARGE, E(250)), self.client)
        self.button_disconn = Button(DIM_LI_MAIN_B, C.LIGHT_BLUE, (LMARGE + E(250), MARGE+DIM_LOGINP[1])
                        ,'Disconnect',font=Font.f30)
        self.button_account = Button(DIM_LI_MAIN_B, C.LIGHT_BLUE, (LMARGE, MARGE+DIM_LOGINP[1]),'Account',font=Font.f30)
        # state env
        self.title_env = TextBox(DIM_TITLE, C.WHITE, POS_TITLE,'Env', font=Font.f100)
        self.text_wating = TextBox(DIM_TWAIT,C.WHITE, POS_TWAIT,
                             'Waiting for the other players...', font=Font.f30)
        self.button_exit = Button(DIM_BEXIT, C.LIGHT_BLUE, POS_BEXIT, 'Exit', font=Font.f30)
        self.teams = Teams
        self.teams.init(POS_TEAMS,DIM_TEAMS, client)
        # state account
        self.title_account = TextBox(DIM_TITLE, C.WHITE, (POS_TITLE[0], POS_TITLE[1] + E(100)),'', font=Font.f100)
        Stats.init(client, POS_STATSY)
        self.Stats = Stats
Example #13
0
    def from_json(self, json):
        chat = Chat(json['id'])
        for jFeed in json['feeds']:
            feed: Feed = Feed(jFeed['key'], jFeed['url'])
            feed.lastUpdate = jFeed['lastUpdate']
            feed.addFilterBy(jFeed['filterBy'])

            chat.addfeed(feed)
        return chat
Example #14
0
 def logout(self):
     " События, когда пользователь выходит из онлайна "
     log_debug(self.name + " logout")
     f = self.fighter()
     if f != None:
         f.slowpoke = True
         self.leave_fight()
     Loc.leave(self)
     Chat.unsubscribe(self.name)
Example #15
0
 def __init__(self, word, player_drawing, game):
     self.word = word
     self.player_drawing = player_drawing
     self.player_guessed = []
     self.skips = 0
     self.time = 75
     self.game = game
     self.player_scores = {player: 0 for player in self.game.players}
     self.chat = Chat(self)
     start_new_thread(self.time_thread, ())
Example #16
0
def loop():
    twitch = Chat()
    twitch.connect()
    time.sleep(3)
    while True:
        try:
            response = twitch.get_message()
            #DEBUG
            #print("Reponse:"+response)
            if response == "PING :tmi.twitch.tv\r\n":
                twitch.pong()
            elif response:
                evaluate_message(response)
        except socket.timeout:
            debug_event = True
            #print("Socket Timed Out!")

        except socket.error:
            print("Socket Error, Connection closed!")
            time.sleep(1)
            twitch.connect()
        except Exception as e:
            print("Unknown error")
            print(e)
        #TODO: Find a better sleep cycle. Rate limiting already in place
        time.sleep(1 / cfg.RATE)
Example #17
0
 def join_chats(self, channel_url=None):
     if self.validate_join_chats():
         sleep(SLEEP_TIME_BETWEEN_COMPONENTS)
         if self.open_joining_channel():
             sleep(SLEEP_TIME_BETWEEN_COMPONENTS)
             # The bot update to have a link on the chats as well
             if self.controller.click_ok_popup_button():
                 sleep(SLEEP_TIME_BETWEEN_COMPONENTS)
                 # Get current url. It would be something like that https://t.me/Jizzax_Zomin_bozor
                 if len(self.driver.window_handles) < 2:
                     self.skip_channel()
                     sleep(SLEEP_TIME_BETWEEN_COMPONENTS)
                     self.refresh()
                 else:
                     self.driver.switch_to.window(
                         self.driver.window_handles[1])
                     print("Bot::Current url is ", self.driver.current_url)
                     chatUrlNameParts = self.driver.current_url.split("/")
                     print("Bot::URL parts are", chatUrlNameParts)
                     chatUrlName = chatUrlNameParts[len(chatUrlNameParts) -
                                                    1].strip()
                     print("Bot::Extracted chat name", chatUrlName)
                     self.close_tab()
                     sleep(SLEEP_TIME_BETWEEN_COMPONENTS)
                     self.open_channel(OPEN_CHAT_LINK_PART + chatUrlName)
                     sleep(SLEEP_TIME_BETWEEN_COMPONENTS)
                     channel_url = OPEN_CHAT_LINK_PART + chatUrlName
                     if self.join_openned_channel():
                         sleep(SLEEP_TIME_BETWEEN_COMPONENTS)
             else:
                 channel_url = self.driver.current_url
                 if self.join_openned_channel():
                     sleep(SLEEP_TIME_BETWEEN_COMPONENTS)
             self.open_channel(BOT_LINK)
             sleep(SLEEP_TIME_BETWEEN_COMPONENTS)
             if self.click_button_by_name(["Joined"]):
                 sleep(SLEEP_TIME_BETWEEN_COMPONENTS)
                 if self.is_bot_joined_success() and channel_url != None:
                     hoursUntillReward = self.get_hours_untill_reward()
                     if hoursUntillReward != None:
                         print("Bot::Hours untill reward '",
                               hoursUntillReward, "'")
                         joinDate = datetime.now()
                         leaveDate = joinDate + timedelta(
                             hours=hoursUntillReward)
                         chat = Chat(channel_url, joinDate, leaveDate)
                         self.chatsJoined.append(chat)
                         print("Bot::Joined channel: ", chat.get_info())
                         self.joinedChatsCount += 1
                         print("Bot::You have joined ",
                               self.joinedChatsCount, " chats in total")
                         if self.joinedChatsCount % self.joinLimit == 0:
                             self.change_operation(Operation.VISIT)
                     else:
                         self.change_operation(Operation.VISIT)
Example #18
0
 def __init__(self):
     self.app = QtWidgets.QApplication(sys.argv)
     MainWindow = QtWidgets.QMainWindow()
     self.setupUi(MainWindow)
     self.tickertimer = QTimer()
     self.chat = Chat()
     self.clientlist = []
     self.tickertimer.timeout.connect(lambda: self.update_server())
     self.delay = 1000  #ms (1s = 1000ms)
     MainWindow.show()
     sys.exit(self.app.exec_())
Example #19
0
 def onOpen(self):
     if debug:
         print("[Connection] Connection established!")
     self.block_chat = False  # It will block chat when question are shown
     self.chat = Chat()
     self.solver = Solver()
     """ Game Summary """
     self.gs_enable = readFromConfig("GameSummary", "enable")
     self.gs_prize = readFromConfig("GameSummary", "show_prize")
     self.gs_userids = readFromConfig("GameSummary", "show_userids")
     self.gs_usernames = readFromConfig("GameSummary", "show_usernames")
Example #20
0
class Player:
    IN_STATE = "IN"
    FOLD_STATE = "FOLD"
    ALL_IN_STATE = "ALL IN"

    CALL_ACTION = "CALL"
    RAISE_ACTION = "RAISE"
    CHECK_ACTION = "CHECK"
    BET_ACTION = "BET"

    def __init__(self, slack_id, slack_client):
        self.slack_id = slack_id
        self.money = 200
        self.cards = []
        self.state = Player.IN_STATE
        self.action = ''
        self.bet = 0
        self.slack_client = slack_client
        self.chat = Chat(slack_client, Player.get_im_channel(self.slack_client, self.slack_id))

    @staticmethod
    def get_im_channel(slack_client, slack_id):
        ims = json.loads(slack_client.api_call('im.list'))['ims']
        for im in ims:
            if im['user'] == slack_id:
                return im['id']

        print str(ims)
        raise "IM Channel not found!"

    def get_username(self):
        user_api = json.loads(self.slack_client.api_call('users.info', user=self.slack_id))['user']
        return user_api['name']

    def card_str(self):
        return '{}, {}'.format(Card.int_to_pretty_str(self.cards[0]), Card.int_to_pretty_str(self.cards[1]))

    def deal(self, cards):
        self.bet = 0
        self.cards = cards
        self.state = Player.IN_STATE
        self.chat.message('Your hand: {}'.format(self.card_str()))

    def __hash__(self):
        return hash(self.slack_id)

    def __eq__(self, other):
        try:
            return hash(self) == hash(other)
        except:
            return False

    def __str__(self):
        return self.get_username()
Example #21
0
 def enter_fight(self, fight, team_id):
     """ Вход в битву.
         Не изменяет саму битву, только изменяет параметры пользователя.
     """
     self["fight"] = {"id": fight.id, "team_id": team_id}
     self["prev_loc"] = self["loc"]
     anim_key = "anim_" + self.id
     app.data[anim_key] = 0  # сбрасываем анимацию
     self.go("fight")
     Chat.unsubscribe_special(self.name, "$fight$")
     Chat.subscribe(self.name, fight.channel())
Example #22
0
 def __init__(self, slack_id, slack_client):
     self.slack_id = slack_id
     self.money = 200
     self.cards = []
     self.state = Player.IN_STATE
     self.action = ''
     self.bet = 0
     self.slack_client = slack_client
     self.chat = Chat(
         slack_client,
         Player.get_im_channel(self.slack_client, self.slack_id))
Example #23
0
 def kick_user(self, uid, tid, time_removed, time_to_rejoin=0):
     if uid not in self.users:
         self.track_new_user(uid)
     user = self.users[uid]
     if time_to_rejoin != 0:
         chat = Chat(tid, time_removed, rejoin_time=time_to_rejoin)
         user.add_chat(chat, timed=True)
     else:
         chat = Chat(tid, time_removed)
         user.add_chat(chat)
     self.removeUserFromGroup(uid, thread_id=tid)
     self.save_to_file()
Example #24
0
    def __init__(self, haslo, rysujacy, gra):

        self.haslo = haslo
        self.rysujacy = rysujacy
        self.gracz_zgadujacy = []
        self.gracze_pomijajacy = []
        self.liczba_pominiec = 0
        self.czas = 75  #czas trfania rundy
        self.gra = gra
        self.wyniki_gracza = {gracz: 0 for gracz in self.gra.gracze}
        self.chat = Chat(self)
        start_new_thread(self.czas_thread, ())  #uruchomienie nowego wątki
Example #25
0
    def log_in(self):

        db = Database()

        if (not db._log_in(self.lineEdit_username.text(),
                           self.lineEdit_password.text())):
            msg = QMessageBox()
            msg.setText('Incorrect credientals')
            msg.exec_()
        else:
            chat = Chat(self.lineEdit_username.text())
            self.dialogs.append(chat)
            chat.show()
Example #26
0
    def __init__(self, time, queue, t):

        # 时间
        self.time = time

        # 队列
        self.queue = queue

        # 聊天语句,从网络获取句子(数据源类型)
        self.chat = Chat(t)

        # 键盘控制器
        self.k = Controller()
Example #27
0
 def __init__(self, win, conn: Network=None):
     pygame.font.init()
     self.win = win
     self.conn = conn
     self.leader_board = LeaderBoard(50, 125)
     self.board = Board(310, 125)
     self.top_bar = TopBar(10, 10, 1280, 100)
     self.top_bar.change_round(1)
     self.players = []
     self.skip_button = TextButton(90, 800, 125, 50, (255, 255, 0), "Skip")
     self.bottom_bar = BottomBar(310, 880, self)
     self.chat = Chat(1050, 120)
     self.draw_color = (0, 0, 0)
Example #28
0
 def receivedMessage(self, data):
     message = Message()
     message.fromJson(str(data))
     user = message.getUser()
     if user in self.chats:
         chat = self.chats[user]
         chat.receiveMessage(message)
     else:
         self.refreshUsers()
         ip = self.userList[user]
         chat = Chat(self.username, user, ip, self.ciphers)
         self.chats[user] = chat
         chat.receiveMessage(message)
Example #29
0
 def receivedMessage(self, data):
     message = Message()
     message.fromJson(str(data))
     user = message.getUser()
     if user in self.chats:
         chat = self.chats[user]
         chat.receiveMessage(message)
     else:
         self.refreshUsers()
         ip = self.userList[user]
         chat = Chat(self.username, user, ip, self.ciphers)
         self.chats[user] = chat
         chat.receiveMessage(message)
Example #30
0
 def __init__(self, win, connection=None):
     pygame.font.init()
     self.connection = connection
     self.win = win
     self.leaderboard = Leaderboard(50, 125)
     self.board = Board(305, 125)
     self.top_bar = TopBar(10, 10, 1280, 100)
     self.top_bar.change_round(1)
     self.players = []
     self.skip_button = TextButton(85, 830, 125, 60, (255, 255, 0), "Skip")
     self.bottom_bar = BottomBar(305, 880, self)
     self.chat = Chat(1050, 125)
     self.draw_color = (0, 0, 0)
     self.drawing = False
Example #31
0
 def __init__(self, win, connection=None):
     pygame.font.init()
     self.connection = connection
     self.win = win
     self.leaderboard = Leaderboard(30, 95)
     self.board = Board(200, 100)
     self.top_bar = TopBar(10, 10, 1080, 80)
     self.bottom_bar = BottomBar(200, 714, self)
     self.top_bar.change_round(1)
     self.players = []
     self.chat = Chat(860, 95)
     self.skip_button = TextButton(70, 700, 100, 45, (255, 255, 0), "Skip")
     self.draw_color = (0, 0, 0)
     self.drawing = False
Example #32
0
def start_server():
    clients = []
    server = Chat.create_server()

    def remove_client(client):
        for clt, addrs in clients:
            if client[0] == clt:
                index = clients.index(client)
                clients.pop(index)
                print(f'Client {addrs} disconnected.')
                return

    def start_thread(client):
        clt, addrs = client
        print(f'Thread started for {addrs}')
        
        while True:
            try:
                msg = Chat.receive_message(clt)
                print(f'Client:{addrs}: {msg}', end='\n')

                if msg == '\exit()':
                    clt.close()
                    remove_client(client)
                    return
                broadcast(client, msg)
            except Exception as e:
                print(f'{e.with_traceback}')
                remove_client(client)
                clt.close()
                break
        
    def broadcast(client, msg):
        for clt, addrs in clients:
            if client[0] == clt:
                continue
            print(f'{addrs}')
            Chat.send_message(clt, f'{client[1]}: {msg}')


    server.listen(2)
    while True:
        print('Waiting for connection...')
        clt, addrs = server.accept()
        clients.append((clt, addrs))
        print(f'Connection Established with {addrs}')
        Chat.send_message(clt, 'Welcome, You are now connected to the server.')
        
        threading.Thread(target=start_thread, args=[(clt, addrs)], daemon=True).start()
Example #33
0
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.forbidden()

    # validate body
    body = json.loads(event["body"])
    senior_executive = body.get('senior_executive')
    chats_new = body.get('chats')
    if not senior_executive or not chats_new:
        return http_status.bad_request("invalid parameter(s): 'senior_executive, chats'")

    session = Session()
    for chat_new in chats_new:
        if not chat_new.get('chat_type') or chat_new['chat_type'] not in ChatType.__members__:
            session.close()
            return http_status.bad_request("invalid parameter(s): 'chat_type'")

        chat_type = ChatType[chat_new['chat_type']]
        description = chat_new.get('description')
        tags = chat_new.get('tags')
        fixed_date = chat_new.get('fixed_date')
        if chat_type in mandatory_date and not fixed_date:
            session.rollback()
            session.close()
            return http_status.bad_request("missing body attribute { fixed_date } with chat_type { %s }" % (chat_type.name))

        chat = Chat(
            chat_type=chat_type, description=description,
            chat_status=ChatStatus.PENDING, tags=tags,
            senior_executive=senior_executive
        )

        admin_update_declared_chats_frequency(senior_executive, 1)
        if fixed_date:
            chat.fixed_date = datetime.fromtimestamp(fixed_date).replace(hour=0, minute=0,second=0, microsecond=0)
            chat.chat_status = ChatStatus.ACTIVE
        else:
            admin_update_remaining_chats_frequency(senior_executive, 1)
        session.add(chat)

    session.commit()
    session.close()

    return http_status.success()
Example #34
0
    def start(self, channel):
        self.state = START_STATE
        self.timer = WAIT
        self.players = []
        self.deck = Deck()
        self.current_player = 0
        self.chat = Chat(self.slack_client, channel)
        self.pot_manager = PotManager(self.chat)
        self.join_manager = JoinManager(self.slack_client, channel,
                                        self.players)

        self.bet_manager = BetManager(self.pot_manager, self.players)
        self.board = []
        self.last_message = None
        self.board_message = None
Example #35
0
 def __init__(self, win, connection=None):
     pygame.font.init()
     self.connection = connection
     self.win = win  # okno do wyswietlania
     # inicjalizacja parametrow
     self.ranking = Ranking(50, 125)
     self.tablica = Tablica(305, 125)
     self.pasek_gorny = PasekGorny(50, 10, 990, 100)
     self.pasek_gorny.zmiana_rundy(1)
     self.gracze = []
     self.pomin_button = PrzyciskTekstowy(810, 555, 225, 50, (255, 255, 0), "Pomin")
     self.pasek_dolny = PasekDolny(305, 880, self)
     self.chat = Chat(810, 125)
     self.kolor_rysowania = (0, 0, 0)
     self.rysujacy = False
Example #36
0
 def __init__(self, host=None, port=None, commander_name=None, bot_name=None):
     self.server_host = host
     self.server_port = port
     self.config = config
     self.eventregister = EventRegister(self)
     self.eventregister.setup()
     self.commander = Commander(commander_name)
     self.chat = Chat(self)
     self.stats = Statistics()
     self.bot = BotEntity(self, bot_name)
     self.game_ticks = 0
     self.connected = False
     self.logged_in = False
     self.protocol = None
     self.factory = None
     self.entities = None
     self.inventories = inventory.InvetoryContainer(self)
     self.grid = None
     self.sign_waypoints = None
     self.dimension = None
     self.dimensions = [Dimension(self), Dimension(self), Dimension(self)]
     self.spawn_position = None
     self.game_mode = None
     self.difficulty = None
     self.players = defaultdict(int)
     self.last_tick_time = datetime.now()
     self.period_time_estimation = config.TIME_STEP
     utils.do_later(config.TIME_STEP, self.tick)
Example #37
0
 def __init__(self, host=None, port=None, commander_name=None, bot_name=None, to_bot_q=None, to_gui_q=None):
     self._to_bot = DummyQueue() if to_bot_q is None else to_bot_q
     self._to_gui = DummyQueue() if to_gui_q is None else to_gui_q
     self.to_gui("name", bot_name)
     self.server_host = host
     self.server_port = port
     self.commander = Commander(commander_name)
     # Users who can give the bot non-administrative commands
     self.managers = set(config.MANAGERS)  # names as given from server
     self.chat = Chat(self)
     self.bot = BotEntity(self, bot_name)
     self.inventories = inventory.Inventories(self.bot)
     self.stats = Statistics()
     self.game_ticks = 0
     self.connected = False
     self.logged_in = False
     self.protocol = None
     self.factory = None
     self.entities = None
     self.grid = None
     self.sign_waypoints = None
     self.dimension = None
     self.dimensions = [Dimension(self), Dimension(self), Dimension(self)]
     self.spawn_position = None
     self.game_mode = None
     self.difficulty = None
     self.players = defaultdict(int)
     self.last_tick_time = datetime.now()
     self.period_time_estimation = config.TIME_STEP
     utils.do_later(config.TIME_STEP, self.tick)
     self.shutdown_reason = ""
Example #38
0
 def __init__(self, slack_id, slack_client):
     self.slack_id = slack_id
     self.money = 200
     self.cards = []
     self.state = Player.IN_STATE
     self.action = ''
     self.bet = 0
     self.slack_client = slack_client
     self.chat = Chat(slack_client, Player.get_im_channel(self.slack_client, self.slack_id))
Example #39
0
 def sycnData(self):
     for item in os.listdir(p):
         d = item[0:8]
         
         itemsrc = os.path.join(p, item)
         
         conn = ConnFactorty.getConn()
         chat = Chat(conn);
         user = chat.saveReport(itemsrc);
         conn.close();
         
         conn = ConnFactorty.getConn()
         chat = Chat(conn);
         chat.total(user, d);   
         conn.close();
         
         if True:
             if user == '大副':
                 item = item.replace('_zlm', '').replace('.mht', '_zlm.mht')
             elif user == '船长':
                 item = item.replace('_slp', '').replace('.mht', '_slp.mht')
             elif user == '舵手':
                 item = item.replace('_panlb', '').replace('.mht', '_panlb.mht')
             #拷贝文件
             if user != '':
                 shutil.copy(itemsrc, pCopy + '/' + item);
                 print itemsrc + '处理完成'
                 #删除一个月前数据
                 conn = ConnFactorty.getConn()
                 chat = Chat(conn);
                 #chat.deleteData();
             if os.path.isfile(itemsrc): 
                 os.remove(itemsrc)
Example #40
0
	def __init__(self,usr,ip1,ip2):
		self.usr = usr
		self.ip1 = ip1
		self.ip2 = ip2
		self.alice = xmlrpclib.ServerProxy("http://"+self.ip2+":8000",allow_none=True) 
		self.tem = threading.Event()
		self.chat = Chat(self.tem)
		self.chat.show()
		self.chat.boton_send.clicked.connect(self.enviar)
		self.hilo_Bob = threading.Thread(target=self.escucha)
		self.hilo_Bob.start()
		self.chat.boton_call.clicked.connect(self.iniciaLlamada)
		self.chat.boton_callVideo.clicked.connect(self.terminarLlamada)
Example #41
0
    def start(self, channel):
        self.state = START_STATE
        self.timer = WAIT
        self.players = []
        self.deck = Deck()
        self.current_player = 0
        self.chat = Chat(self.slack_client, channel)
        self.pot_manager = PotManager(self.chat)
        self.join_manager = JoinManager(self.slack_client, channel, self.players)

        self.bet_manager = BetManager(self.pot_manager, self.players)
        self.board = []
        self.last_message = None
        self.board_message = None
Example #42
0
 def handle(self, q):
     if "msg" in q and q["msg"]:
         msg = q["msg"]
         if msg.startswith("/w "):
             msg = msg[3:].split(':', 2)
             if len(msg) >= 2:
                 message = Chat.validate(unicode(msg[1]).lstrip())
                 self.current_user.private_message(u"{to:}" + message, {"to": u'<span class="chat_line_channel channel_private" style="cursor:pointer" onclick="chat.insert_func(\'/w {0}: \')();">[Для {0}] </span>'.format(msg[0])})
                 Chat.add(self.current_user.name, message, Chat.private_channel(msg[0]))
         elif self.current_user.is_admin and msg.startswith("/"):
             log_warning('!ADMIN! ' + msg)
             msg = msg[1:].split()
             AdminAction(self.current_user, {"action": msg[0], "params": msg[1:]})
         else:
             message = Chat.validate(unicode(msg))
             Chat.add(self.current_user.name, message)
     from_time = q.get("_t", 0)
     res = {"chat": Chat.js(self.current_user.name, from_time)}
     if self.current_user.need_update():
         res["user"] = self.current_user.js()
     self.save_users()
     return res
Example #43
0
def process(chat_id, message, date):
	chat = Chat(chat_id)

	if chat.is_exist() == False:
		chat.create()
		channels = config.get("channels");
		for channel in channels:
			chat.subscribe(channel["name"], Type.Auto)
		bot.broadcast_message(chat_id, str(config.get("hello_message")));
		return;
		
	try:
		command = bot.decode_command(message)
		args = message.split()
		args.pop(0)
		bot.execute(command, chat_id, args, date)
	except KeyError:
		print "Nothing to command"
	
	return chat
Example #44
0
#!/usr/bin/python

from chat import Chat

chat = Chat()
chat.show()
Example #45
0
        user_pass = {
            'card_id': user_card['id'],
            'identity': user_card['identity']['value'],
            'identity_type': user_card['identity']['type'],
            'private_key': user_key_pair['private_key'],
            'public_key': user_key_pair['public_key']
        }

        # save a Private Key with information about Virgil Card
        # to the file on the disk.

        save_virgil_pass(VIRGIL_PRIVATE_KEY_PATH, user_pass)

    # create and join to the chat channel DEMO.

    chat_channel = Chat(CHAT_API_URL, 'DEMO', user_pass['identity'])

    # get and display all previous messages from channel history.

    messages = chat_channel.get_messages(None)

    if messages:
        print("Messages({})".format(len(messages)))
        for chat_message in messages:

            # verify the message and decrypt it in case if massage
            # signature is valid.

            message_text = decrypt_then_verify_message(chat_message,
                                                       user_pass['card_id'],
                                                       user_pass['private_key'],
Example #46
0
 def private_channel(self):
     return Chat.private_channel(self.name)
Example #47
0
class Game:
    def __init__(self, slack_client):
        self.state = DEAD_STATE
        self.timer = WAIT

        self.players = []
        self.deck = None
        self.current_player = 0
        self.pot_manager = None
        self.slack_client = slack_client
        self.join_manager = None
        self.chat = None
        self.dealer_id = 0
        self.bet_manager = None
        self.board = []
        self.evaluator = Evaluator()
        self.last_message = None
        self.board_message = None

    def start(self, channel):
        self.state = START_STATE
        self.timer = WAIT
        self.players = []
        self.deck = Deck()
        self.current_player = 0
        self.chat = Chat(self.slack_client, channel)
        self.pot_manager = PotManager(self.chat)
        self.join_manager = JoinManager(self.slack_client, channel, self.players)

        self.bet_manager = BetManager(self.pot_manager, self.players)
        self.board = []
        self.last_message = None
        self.board_message = None

    def process(self, data):
        if 'text' in data:
            text = data['text']
            quit_text = '{}: quit'.format(bot_name)

            if quit_text.lower() in text.lower():
                if PAUSE_BETWEEN_GAME_STATE == self.state:
                    player_to_remove = None
                    for player in self.players:
                        if player.slack_id == data['user']:
                            player_to_remove = player

                    self.players.remove(player_to_remove)
                    self.chat.message("{} has quit.".format(player_to_remove))
                else:
                    self.chat.message("You can't quit now, wait between games.")

        if DEAD_STATE == self.state:
            self.process_dead(data)

        if START_STATE == self.state:
            self.process_start(data)

        if BET_STATE == self.state:
            self.bet_manager.process(data)

    def process_dead(self, data):
        text = data['text']
        deal_text = '{}: deal'.format(bot_name)

        if deal_text.lower() in text.lower():
            self.start(data['channel'])

    def process_start(self, data):
        self.join_manager.process_message(data)

    def set_state(self, state):
        self.state = state
        self.timer = WAIT
        self.last_message = None
        self.board_message = None

    def enough_players(self):
        if len(self.players) < 2:
            self.chat.message("Not enough players.")
            self.set_state(DEAD_STATE)
            return False
        return True

    def deal_state(self):
        self.current_player = 0

        if not self.enough_players():
            return

        # burn card
        self.deck.draw(1)

        for player in self.players:
            player.deal(self.deck.draw(2))

        self.set_state(BLIND_STATE)

    def post_blind(self, blind_func):
        while True:
            player = self.players[self.current_player % len(self.players)]
            can_post = blind_func(player)
            if not can_post:
                self.players.pop(0)
                if not self.enough_players():
                    return False
            self.current_player += 1
            return True

    def blind_state(self):
        if not self.post_blind(self.pot_manager.post_small_blind):
            return

        if not self.post_blind(self.pot_manager.post_big_blind):
            return

        self.pot_manager.add_other_players(self.players)

        self.dealer_id = self.current_player

        self.display_board()
        flop_callback = partial(self.set_state, FLOP_STATE)
        fold_win_callback = partial(self.set_state, FOLD_WIN_STATE)
        self.bet_manager.request_bets(self.dealer_id, flop_callback, fold_win_callback, self.display_board)
        self.set_state(BET_STATE)

    def display_board(self):
        board_str = '```'
        for i, player in enumerate(self.players):
            if i == self.current_player % len(self.players):
                board_str += '->'
            else:
                board_str += '  '

            board_str += '<@{}>\t\t\t${}\t{}\t{} {}\n'.format(player.slack_id,
                                                              player.money,
                                                              player.state,
                                                              player.action,
                                                              player.bet)
        board_str += '```\n'
        board_str += self.pot_manager.get_pot_string()
        board_str += "\n{}".format(Game.board_to_string(self.board))

        self.board_message = self.chat.message(board_str, self.board_message)

    @staticmethod
    def board_to_string(board):
        result = ""
        for card in board:
            result += "{} ".format(Card.int_to_pretty_str(card))

        return result

    def flop_state(self):
        # burn card
        self.deck.draw(1)

        self.board.extend(self.deck.draw(3))
        self.chat.message("*Dealing the flop:*\n{}".format(Game.board_to_string(self.board)))
        turn_callback = partial(self.set_state, TURN_STATE)
        fold_win_callback = partial(self.set_state, FOLD_WIN_STATE)
        self.bet_manager.request_bets(0, turn_callback, fold_win_callback, self.display_board)
        self.set_state(BET_STATE)

    def turn_state(self):
        # burn card
        self.deck.draw(1)

        self.board.append(self.deck.draw(1))
        self.chat.message("*Dealing the turn:*\n{}".format(Game.board_to_string(self.board)))
        turn_callback = partial(self.set_state, RIVER_STATE)
        fold_win_callback = partial(self.set_state, FOLD_WIN_STATE)
        self.bet_manager.request_bets(0, turn_callback, fold_win_callback, self.display_board)
        self.set_state(BET_STATE)

    def river_state(self):
        # burn card
        self.deck.draw(1)

        self.board.append(self.deck.draw(1))
        self.chat.message("*Dealing the river:*\n{}".format(Game.board_to_string(self.board)))
        self.set_state(SHOW_HANDS_STATE)

    def count_down(self, new_state):
        self.timer -= 1
        if self.timer < 0:
            self.set_state(new_state)
            return

    def show_hands_state(self):
        for player in self.players:
            if player.state == Player.FOLD_STATE:
                continue

            card_score = self.evaluator.evaluate(self.board, player.cards)
            card_class = self.evaluator.get_rank_class(card_score)
            self.chat.message('{} had: {} {}'.format(player, player.card_str(), card_class))

        self.set_state(DETERMINE_WINNER_STATE)

    def determine_winner_state(self):

        for pot in reversed(self.pot_manager.pots):
            pot_score = 9999
            pot_winners = []
            if len(pot.players) == 1:
                self.chat.message(SINGLE_WINNER_MESSAGE.format(pot.players[0], pot.amount, pot.name))
                pot.players[0].money += pot.amount
            else:
                for player in pot.players:
                    card_score = self.evaluator.evaluate(self.board, player.cards)
                    if card_score == pot_score:
                        pot_winners.append(player)

                    if card_score < pot_score:
                        pot_winners = [player]
                        pot_score = card_score

                if len(pot_winners) == 1:
                    self.chat.message(SINGLE_WINNER_MESSAGE.format(pot_winners[0], pot.amount, pot.name))
                    pot_winners[0].money += pot.amount
                else:
                    self.chat.message(SPLIT_WINNER_MESSAGE.format(pot_winners, pot.amount, pot.name))
                    for pot_winner in pot_winners:
                        pot_winner.money += (pot.amount / len(pot_winners))

        self.set_state(PREPARE_NEW_GAME_STATE)

    def prepare_new_game_state(self):
        # rotate players
        self.players.append(self.players.pop(0))
        self.set_state(PAUSE_BETWEEN_GAME_STATE)

    def pause_between_game_state(self):
        self.last_message = self.chat.message(PAUSE_MESSAGE.format(self.timer), self.last_message)
        self.timer = NEW_GAME_WAIT
        self.count_down(DEAL_STATE)

    def tick(self):
        if START_STATE == self.state:
            self.join_manager.tick(self.timer)
            self.count_down(DEAL_STATE)

        if DEAL_STATE == self.state:
            self.deal_state()

        if BLIND_STATE == self.state:
            self.blind_state()

        if BET_STATE == self.state:
            self.bet_manager.tick()

        if FLOP_STATE == self.state:
            self.flop_state()

        if TURN_STATE == self.state:
            self.turn_state()

        if RIVER_STATE == self.state:
            self.river_state()

        if FOLD_WIN_STATE == self.state:
            self.set_state(DETERMINE_WINNER_STATE)

        if SHOW_HANDS_STATE == self.state:
            self.show_hands_state()

        if DETERMINE_WINNER_STATE == self.state:
            self.determine_winner_state()

        if PREPARE_NEW_GAME_STATE == self.state:
            self.prepare_new_game_state()

        if PAUSE_BETWEEN_GAME_STATE == self.state:
            self.pause_between_game_state()
Example #48
0
 def log(self, message, params = None):
     ''' Добавляет сообщение в чат для всех участников битвы '''
     Chat.addsys(message, self.channel(), params)
Example #49
0
class World(object):
    def __init__(self, host=None, port=None, commander_name=None, bot_name=None):
        self.server_host = host
        self.server_port = port
        self.commander = Commander(commander_name)
        self.chat = Chat(self)
        self.bot = BotEntity(self, bot_name)
        self.stats = Statistics()
        self.game_ticks = 0
        self.connected = False
        self.logged_in = False
        self.protocol = None
        self.factory = None
        self.entities = None
        self.grid = None
        self.sign_waypoints = None
        self.dimension = None
        self.dimensions = [Dimension(self), Dimension(self), Dimension(self)]
        self.spawn_position = None
        self.game_mode = None
        self.difficulty = None
        self.players = defaultdict(int)
        self.last_tick_time = datetime.now()
        self.period_time_estimation = config.TIME_STEP
        utils.do_later(config.TIME_STEP, self.tick)

    def predict_next_ticktime(self, tick_start):
        tick_end = datetime.now()
        d_run = (tick_end - tick_start).total_seconds()  # time this step took
        t = config.TIME_STEP - d_run  # decreased by computation in tick
        d_iter = (tick_start - self.last_tick_time).total_seconds()  # real tick period
        r_over = d_iter - self.period_time_estimation  # diff from scheduled by
        t -= r_over
        t = max(0, t)  # cannot delay into past
        self.period_time_estimation = t + d_run
        self.last_tick_time = tick_start
        return t

    def tick(self):
        tick_start = datetime.now()
        if self.logged_in:
            self.bot.tick()
            self.chat.tick()
            self.every_n_ticks()
        utils.do_later(self.predict_next_ticktime(tick_start), self.tick)

    def every_n_ticks(self, n=100):
        self.game_ticks += 1

    def on_connection_lost(self):
        self.connected = False
        self.logged_in = False
        self.protocol = None
        self.bot.on_connection_lost()

    def connection_made(self):
        self.connected = True

    def on_shutdown(self):
        log.msg("Shutdown")
        self.factory.log_connection_lost = False

    def send_packet(self, name, payload):
        if self.protocol is not None:
            self.protocol.send_packet(name, payload)
        else:
            log.msg("Trying to send %s while disconnected" % name)

    def dimension_change(self, dimension):
        dim = dimension + 1  # to index from 0
        d = self.dimensions[dim]
        self.dimension = d
        self.entities, self.grid, self.sign_waypoints = d.entities, d.grid, d.sign_waypoints
        if not self.entities.has_entity(self.bot.eid):
            self.entities.new_bot(self.bot.eid)

    def on_login(self, bot_eid=None, game_mode=None, dimension=None, difficulty=None):
        self.bot.eid = bot_eid
        self.logged_in = True
        self.dimension_change(dimension)
        self.game_mode = game_mode
        self.difficulty = difficulty

    def on_spawn_position(self, x, y, z):
        self.spawn_position = (x, y, z)
        self.bot.spawn_point_received = True

    def on_respawn(self, game_mode=None, dimension=None, difficulty=None):
        self.dimension_change(dimension)
        self.game_mode = game_mode
        self.difficulty = difficulty
        self.bot.location_received = False
        self.bot.spawn_point_received = False
        self.bot.i_am_dead = False

    def on_time_update(self, timestamp=None, daytime=None):
        self.timestamp = timestamp
        self.daytime = daytime
Example #50
0
 def js_all(self, max_time=0):
     """ Описание пользователя и сообщения чата.
     """
     return {"user": self.js(), "chat": Chat.js(self.name, max_time)}
Example #51
0
tank = Tank(width/2, height - 20)
enemy = Tank(width/2, 20, rotate = False)

# estabilish connect, have to receive
# 'conn' to be in the game
client = client.Client(sys.argv[1], int(sys.argv[2]))
print 'Conectando ao servidor...'
if client.connected():
	print 'OK!'
else:
	print 'Nao ha espaco livre no servidor'
	sys.exit()


# initialize chat
chat = Chat(client)

print 'Sincronizando...'
if client.synced():
	client.listen(tank, enemy, chat)

# init and show screen
pygame.init()
screen = pygame.display.set_mode(size)


# load object
heart = pygame.transform.scale(pygame.image.load("images/heart-icon.png"), (20, 20))


while True:
Example #52
0
class Model(object):
    def __init__(self):
        self.email_to_number = {} 
        self.number_to_email = {}
        self.email_to_most_recent_time_used = {}
        self.email_to_alias = {} # TODO: import buddy list to get alias (priority: low)
        self.emails = []
        self.receiver_list = []
        self.random_counter = -1
        self.receiver_index = -1
    
    def addUI(self, ui):
        self.ui = ui
        
    def addBot(self):
        self.bot = Chat(USER, PD)
        self.bot.addModel(self)
        self.bot.run()
    
    def handleIncomingMessage(self, message):
        from_field = message["from"]
        body_field = message["body"]
        email = from_field.bare 
        alias = from_field.user
        if email not in self.receiver_list:
            self.receiver_list.append(email)
        
        self.__register_email(email, alias)
        buddy_number = self.email_to_number[email]
        message_to_show = beautify_incoming_message(alias, buddy_number, body_field)
        # TODO: need to refactor alias, buddy_number, body_field to a class or something (priority: low)
        self.ui.showMessage(message_to_show)
        self.ui.set_current_receiver()
        self.show_composing_message(self.ui.bufferMessage)
        
    def __register_email(self, email, alias):
        if email not in self.email_to_alias:
            self.email_to_alias[email] = alias
            self.emails.append(email)
        self.__register_buddy_number(email)
        self.email_to_most_recent_time_used[email] = time.time()
        
    def __register_buddy_number(self, email):
        if email in self.email_to_number:
            return
        for number in NUMBER_RANGE:
            if not number in self.number_to_email:
                break
        if number in self.number_to_email:
            number = self.__pop_oldest_used_indexnumber()
        self.email_to_number[email] = number
        self.number_to_email[number] = email
    
    def __pop_oldest_used_indexnumber(self): # untested
        number, min_last_used_time = 0, 1e10
        for i in NUMBER_RANGE:
            last_used_time = self.email_to_most_recent_time_used[self.number_to_email[i]]
            if  last_used_time < min_last_used_time:
                number, min_last_used_time = i, last_used_time
        email = self.number_to_email[number]
        del self.number_to_email[number]
        del self.email_to_number[email]

    def get_receiver(self, up_or_down):
        self.receiver_index += up_or_down
        if self.receiver_index < 0: 
            self.receiver_index = 0
        if len(self.receiver_list) <= self.receiver_index:
            self.receiver_list.append(self.get_any_receiver())
        self.__clean_receiver_list()
        return self.receiver_list[self.receiver_index]
    
    def insert_receiver(self, email):
        if self.receiver_list[self.receiver_index] != email:
            self.receiver_index +=1
            self.receiver_list = self.receiver_list[:self.receiver_index] + [email] + \
                                 self.receiver_list[self.receiver_index:]
        self.__clean_receiver_list()
        
    def __clean_receiver_list(self):
        if self.receiver_index > MAX_RECIEVER_LIST_LEN:
            self.receiver_index -= MAX_RECIEVER_LIST_LEN/2
            self.receiver_list = self.receiver_list[MAX_RECIEVER_LIST_LEN/2:]

    def get_any_receiver(self):
        if not self.emails:
            return ''
        self.random_counter += 1
        return self.emails[self.random_counter % len(self.emails)]
    
    def send_message(self, bufferMessage):
        email = bufferMessage.get_receiver()
        self.__register_email(email, default_alias_from_email(email))
        buddy_number = self.email_to_number[email]
        alias = self.email_to_alias[email]
        body_field = bufferMessage.get_body()
        message_to_show = beautify_outgoing_message(alias, buddy_number, body_field)
        self.ui.showMessage(message_to_show)
        self.bot.sendChat(bufferMessage)
        
    def get_email_from_number(self, number):
        if number in self.number_to_email:
            return self.number_to_email[number]
        return self.get_any_receiver()
    
    def show_composing_message(self, bufferMessage):
        email = bufferMessage.get_receiver()
        buddy_number = self.email_to_number.get(email, 0)
        body_field = bufferMessage.get_body()
        message_to_show = beautify_composing_message(email, buddy_number, body_field)
        self.ui.showMessage(message_to_show)
        
    def show_help_message(self):
        self.ui.showMessage(HELP_MESSAGE)
        self.show_composing_message(self.ui.bufferMessage)
        # still need to think about this, the updation of bufferMessage
Example #53
0
class World(object):
    def __init__(self, host=None, port=None, commander_name=None, bot_name=None, to_bot_q=None, to_gui_q=None):
        self._to_bot = DummyQueue() if to_bot_q is None else to_bot_q
        self._to_gui = DummyQueue() if to_gui_q is None else to_gui_q
        self.to_gui("name", bot_name)
        self.server_host = host
        self.server_port = port
        self.commander = Commander(commander_name)
        # Users who can give the bot non-administrative commands
        self.managers = set(config.MANAGERS)  # names as given from server
        self.chat = Chat(self)
        self.bot = BotEntity(self, bot_name)
        self.inventories = inventory.Inventories(self.bot)
        self.stats = Statistics()
        self.game_ticks = 0
        self.connected = False
        self.logged_in = False
        self.protocol = None
        self.factory = None
        self.entities = None
        self.grid = None
        self.sign_waypoints = None
        self.dimension = None
        self.dimensions = [Dimension(self), Dimension(self), Dimension(self)]
        self.spawn_position = None
        self.game_mode = None
        self.difficulty = None
        self.players = defaultdict(int)
        self.last_tick_time = datetime.now()
        self.period_time_estimation = config.TIME_STEP
        utils.do_later(config.TIME_STEP, self.tick)
        self.shutdown_reason = ""

    def predict_next_ticktime(self, tick_start):
        tick_end = datetime.now()
        # time this step took
        d_run = (tick_end - tick_start).total_seconds()
        # decreased by computation in tick
        t = config.TIME_STEP - d_run
        # real tick period
        d_iter = (tick_start - self.last_tick_time).total_seconds()
        # diff from scheduled by
        r_over = d_iter - self.period_time_estimation
        t -= r_over
        t = max(0, t)  # cannot delay into past
        self.period_time_estimation = t + d_run
        self.last_tick_time = tick_start
        return t

    def tick(self):
        tick_start = datetime.now()
        if self.logged_in:
            self.bot.tick()
            self.chat.tick()
            self.every_n_ticks()
        utils.do_later(self.predict_next_ticktime(tick_start), self.tick)

    def every_n_ticks(self, n=100):
        self.game_ticks += 1

    def on_connection_lost(self):
        self.connected = False
        self.logged_in = False
        self.protocol = None
        self.bot.on_connection_lost()

    def connection_made(self):
        self.connected = True

    def on_shutdown(self):
        reason = self.shutdown_reason
        reason = reason if reason else "(no reason given)"
        log.msg("Shutting Down: " + reason)
        if self.protocol._transactions and len(self.protocol._transactions) > 5:
            log.msg("Possible memory leak: %s" % self.factory._transactions)
        self.to_gui("shutting down", reason)
        self._to_gui.close()
        self._to_bot.close()
        self.factory.log_connection_lost = False

    def send_packet(self, name, *payload, **kwpayload):
        if payload and not kwpayload:
            kwpayload = payload[0]
        elif kwpayload and payload:
            raise ValueError("Received both payload and kwpayload.")
        if self.protocol is not None:
            self.protocol.send_packet(name, kwpayload)
        else:
            log.msg("Trying to send %s while disconnected" % name)

    def dimension_change(self, dimension):
        dim = dimension + 1  # to index from 0
        d = self.dimensions[dim]
        self.dimension = d
        self.entities, self.grid = d.entities, d.grid
        self.sign_waypoints = d.sign_waypoints
        if self.bot.eid not in self.entities:
            # no etype given as EntityBot has no server-side corollary
            new_bot = entities.EntityBot(eid=self.bot.eid, x=0, y=0, z=0)
            self.entities[new_bot.eid] = new_bot

    def on_entity_equipment(self, slot, slotdata, eid):
        entity = self.entities.get(eid, None)
        if entity is None:
            msg = "Equipment for unkown entity %s, slot %s:  %s"
            log.msg((msg % eid, slot, Item(slotdata)))
            return
        entity.equipment[slot] = Item.from_slotdata(slotdata)

    def on_login(self, bot_eid=None, game_mode=None, dimension=None, difficulty=None):
        self.bot.eid = bot_eid
        self.logged_in = True
        self.dimension_change(dimension)
        self.game_mode = game_mode
        self.difficulty = difficulty

    def on_spawn_position(self, x, y, z):
        self.spawn_position = (x, y, z)
        self.bot.spawn_point_received = True

    def on_respawn(self, game_mode=None, dimension=None, difficulty=None):
        self.dimension_change(dimension)
        self.game_mode = game_mode
        self.difficulty = difficulty
        self.bot.location_received = False
        self.bot.spawn_point_received = False
        self.bot.i_am_dead = False

    def on_time_update(self, age_of_world=None, daytime=None):
        self.age_of_world = age_of_world
        self.daytime = daytime

    def to_bot(self):
        """Convenience method for getting data from the _to_bot queue.
        Returns data if there is data, else returns None
        :rtype: Message
        """
        return None if self._to_bot.empty() else self._to_bot.get()

    def to_gui(self, name, data):
        """world.to_gui('foo', 'stuff') -> send Message 'foo' w/data to gui.
        This is just a convenience method to turn:
            world._to_gui.put(Message('foo', data))
            into:
            world.to_gui('foo', data)
        :rtype: Message
        """
        self._to_gui.put(utils.Message(name, data))

    def update_gui_inventory(self):
        inventory = self.bot.interface.inventory
        items = [item for item in inventory.general if item]
        items = items + [item for item in inventory.ready if item]
        self.to_gui("update items", items)
Example #54
0
 def addBot(self):
     self.bot = Chat(USER, PD)
     self.bot.addModel(self)
     self.bot.run()
Example #55
0
class Bob():

	def __init__(self,usr,ip1,ip2):
		self.usr = usr
		self.ip1 = ip1
		self.ip2 = ip2
		self.alice = xmlrpclib.ServerProxy("http://"+self.ip2+":8000",allow_none=True) 
		self.tem = threading.Event()
		self.chat = Chat(self.tem)
		self.chat.show()
		self.chat.boton_send.clicked.connect(self.enviar)
		self.hilo_Bob = threading.Thread(target=self.escucha)
		self.hilo_Bob.start()
		self.chat.boton_call.clicked.connect(self.iniciaLlamada)
		self.chat.boton_callVideo.clicked.connect(self.terminarLlamada)
		#self.stopVideo = 0
				
		
	def escucha(self):
		while True:
			time.sleep(1)
			server = xmlrpclib.ServerProxy("http://"+self.ip1+":8000",allow_none=True) 
			msj = server.vaciaBuffer()
			if(len(msj)!=0):
				self.chat.setTexto(msj)
				print 'MI mensaje es :'+msj
		
 
	def enviar(self):
		print 'Mando mensaje'
		if(self.alice.ping()):
			print 'Entramos'
			msj = self.usr+' : '+str(self.chat.text_send.toPlainText())+'\n'
			self.alice.enviarMensaje(msj)
			self.chat.setTexto(msj)
			print 'se hizo ping con exito'
		
	
	def iniciaLlamada(self):
		import multiprocessing
		self.stack = multiprocessing.Queue(10000)
		self.hiloManda = ThreadEx(targetp=self.enviaAudio,namep='hiloManda')
		self.hiloManda.start()
		self.hiloEscucha = ThreadEx(targetp=self.reprodAudio,namep='hiloEscucha')
		self.hiloEscucha.start()
		

	def reprodAudio(self):
		CHUNK = 1024
		WIDTH = 2
		CHANNELS = 2
		RATE = 44100
		p = pyaudio.PyAudio()
		FORMAT = p.get_format_from_width(WIDTH)
		
		stream = p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK)

		while True:
			if self.hiloManda.isStopEx():
				return 1
			n = 50
			frame = []
			for i in range(0,n):
				frame.append(stream.read(CHUNK))

			audioBinario = numpy.fromstring(''.join(frame), dtype=numpy.uint8)

			if self.stack.full():
				self.stack.get_nowait()
			self.stack.put(audioBinario)

	def enviaAudio(self):
		while True:
			if self.hiloManda.isStopEx():
				return 1
			d = self.stack.get()
			data = xmlrpclib.Binary(d)
			self.alice.recibeAudio(data)

	def terminarLlamada(self):
		self.hiloEscucha.stopEx()
		self.hiloManda.stopEx()	
	
	def video(self):
		'''
		if(self.stopVideo!=0):
			self.hilo_video.stop()	
		self.stopVideo = 1
		#self.alice.creaHiloVideo()
		'''
		self.hilo_video = threading.Thread(target=self.iniciaVideo)
		self.hilo_video.start()

		
	def iniciaVideo(self):
		self.video = VideoLLamada(self.ip2)
Example #56
0
 def test_send(self):
     sock = Chat(self.sock, line_term = "\r\n")
     sock.rexpect(ur"^220")
     sock.send("HELO unittesting")
     sock.rexpect(ur"^250")
     sock.send("MAIL FROM: <*****@*****.**>")
     sock.rexpect(ur"^250")
     sock.send("RCPT TO: <*****@*****.**>")
     sock.rexpect(ur"^250")
     sock.send("DATA")
     sock.rexpect(ur"^354")
     sock.send('From: "John Smith" <*****@*****.**>')
     sock.send('To: "Jane Doe" <*****@*****.**>')
     sock.send('Subject: test message sent from manual telnet session')
     sock.send('Date: Wed, 11 May 2011 16:19:57 -0400\r\n')
     sock.send('Hello World,')
     sock.send('This is a test message sent from a manual telnet session.\r\n')
     sock.send('Yours truly,')
     sock.send('SMTP administrator')
     sock.send('.')
     sock.rexpect(ur"^250")
     sock.send("QUIT")
     sock.rexpect(ur"^221")
     self.assertIsNotNone(self.beanstalk.reserve(timeout = 30))
Example #57
0
class World(object):
    def __init__(self, host=None, port=None, commander_name=None, bot_name=None):
        self.server_host = host
        self.server_port = port
        self.config = config
        self.eventregister = EventRegister(self)
        self.eventregister.setup()
        self.commander = Commander(commander_name)
        self.chat = Chat(self)
        self.stats = Statistics()
        self.bot = BotEntity(self, bot_name)
        self.game_ticks = 0
        self.connected = False
        self.logged_in = False
        self.protocol = None
        self.factory = None
        self.entities = None
        self.inventories = inventory.InvetoryContainer(self)
        self.grid = None
        self.sign_waypoints = None
        self.dimension = None
        self.dimensions = [Dimension(self), Dimension(self), Dimension(self)]
        self.spawn_position = None
        self.game_mode = None
        self.difficulty = None
        self.players = defaultdict(int)
        self.last_tick_time = datetime.now()
        self.period_time_estimation = config.TIME_STEP
        utils.do_later(config.TIME_STEP, self.tick)

    def predict_next_ticktime(self, tick_start):
        tick_end = datetime.now()
        d_run = (tick_end - tick_start).total_seconds()  # time this step took
        t = config.TIME_STEP - d_run  # decreased by computation in tick
        d_iter = (tick_start - self.last_tick_time).total_seconds()  # real tick period
        r_over = d_iter - self.period_time_estimation  # diff from scheduled by
        t -= r_over
        t = max(0, t)  # cannot delay into past
        self.period_time_estimation = t + d_run
        self.last_tick_time = tick_start
        return t

    def tick(self):
        tick_start = datetime.now()
        if self.logged_in:
            self.bot.tick()
            self.chat.tick()
            self.every_n_ticks()
            self.game_ticks += 1
        utils.do_later(self.predict_next_ticktime(tick_start), self.tick)

    def every_n_ticks(self, n=100):
        pass

    def on_shutdown(self):
        log.msg("Shutdown")
        self.factory.log_connection_lost = False

    def send_packet(self, name, payload):
        if self.protocol is not None:
            self.protocol.send_packet(name, payload)
        else:
            log.err("Trying to send %s while disconnected" % name)

    def dimension_change(self, dimension):
        dim = dimension + 1  # to index from 0
        d = self.dimensions[dim]
        self.dimension = d
        self.entities, self.grid, self.sign_waypoints = d.entities, d.grid, d.sign_waypoints
        if not self.entities.has_entity_eid(self.bot.eid):
            self.entities.new_bot(self.bot.eid)
        log.msg("NEW DIMENSION %d" % dim)

    @property
    def server_lag(self):
        return self.players[config.USERNAME]
Example #58
0
 def private_message(self, msg, params=None, sender="$system"):
     Chat.add(sender, msg, self.private_channel(), params)
Example #59
0
  for the next coffee (mug + pod)
* Get technical state of machine from Slack: ready, default, heating
* Produce a video of a typical day at Equisense with the Eqs Coffee Machine.
"""
import time
from senseo import Senseo
from brewer import Brewer
from chat import Chat
from tank import Tank
brewer = None
tank = None

print('Listening to Slack...')
try:
	while True:
		for notification in Chat.getNotifications():
			Chat.processNotification(notification)
		while True:
			action = Chat.getNextAction()
			if action is None:
				break
			if brewer and brewer.isAlive():
				Chat.talk('Oh I\'m kind of busy now! Please wait a bit and I\'ll take your order @{0}.'
					.format(action['user']['name']),
					channel=action['notification']['channel'])
				continue
			# Spam a brewing process.
			brewer = Brewer(action['isShort'], action['notification']['channel'],
				action['user'])
			brewer.start()
		if not tank or not tank.isAlive() and not Chat.isDisabled():
Example #60
0
def main():
    chat = Chat()
    chat.hello_message()
    chat.main_loop()