Пример #1
0
def gif(message, param):
    api_instance = giphy_client.DefaultApi()
    try:
        api_key = config.bot['giphy']['api_key']
        rating = config.bot['giphy']['rating']
        lang = config.bot['giphy']['lang']
    except:
        common.send_message('Failed to get giphy configurationn')

    q = param  
    limit = 1
    offset = 0 
    fmt = 'json'

    try:

      # Search Endpoint

        api_response = api_instance.gifs_search_get(
            api_key,
            q,
            limit=limit,
            offset=offset,
            rating=rating,
            lang=lang,
            fmt=fmt,
            )
        pprint(api_response.data)
        common.send_message('*' + q + '*',
                            api_response.data[0].images.original.url)
    except(ApiException, e):
        print('Exception when calling DefaultApi->gifs_search_get: %s\n' \
            % e)
Пример #2
0
def magic8ball(message, param):
    answers =   [
                "😀 It is certain", 
                "👍 It is decidedly so", 
                "👌 Without a doubt", 
                "😄 Yes definitely", 
                "😁 You may rely on it", 
                "😉 As I see it yes", 
                "🤔 Most likely", 
                "☺️  Outlook good", 
                "🙂 Yes", 
                "☝️  Signs point to yes", 
                "🕙 Reply hazy try again", 
                "🕙 Ask again later", 
                "🕙 Better not tell you now", 
                "🕙 Cannot predict now", 
                "😌 Concentrate and ask again", 
                "😔 Don't count on it", 
                "😡 My reply is no", 
                "😓 My sources say no", 
                "😟 Outlook not so good", 
                "😥 Very doubtful"
                ]
    common.send_message("🎱 *Magic 8 ball says*:\n"
                        + answers[random.randint(0, len(answers))-1])
Пример #3
0
 def kick_out(self):
     '''Kick out player
     '''
     if self.opponent is None:
         return
     msg = clientlib.make_req_kick_out(self.client_name, self.opponent)
     send_message(self.channel, msg, self.key_game, self.client_queue)
Пример #4
0
    def get_history(self, conn_id, queues):
        result = dict()
        for q in queues:
            if q in ThreadedTCPServer.HISTORY:
                result[q] = list(ThreadedTCPServer.HISTORY[q])

        send_message(self.request, conn_id, dict(response=result))
Пример #5
0
def main():
  killer = gracefulkiller.GracefulKiller()

  # setup
  config.bot = config.read()
  try:
    config.rocket = rocketapi.create_session(config.bot['server_info']['username'],
                                      config.bot['server_info']['password'],
                                      server_url = config.bot['server_info']['server'])
  except:
      sys.exit("failed to connect to rocketchat server!")

  # startup message
  common.send_message("I am up and running!")

  # start listening loop
  bot_running = True
  lastchecked = None

  while bot_running:
    time.sleep(0.100)
    lastchecked = read_messages(channel = config.bot['bot_config']['channel'], lastId=lastchecked)

    if killer.kill_now:
      break

  common.send_message("I'm shutting down NOW!")
Пример #6
0
    def broadcast(self, queue, message):
        for conn_id, d in TCPRequestHandler.connections.items():
            if conn_id == message['coremq_sender'] and queue != conn_id and d['options'].get('echo', False) is False:
                continue

            if queue in d['subscriptions']:
                send_message(d['handler'].request, queue, message)
Пример #7
0
    def get_history(self, conn_id, queues):
        result = dict()
        for q in queues:
            if q in ThreadedTCPServer.HISTORY:
                result[q] = list(ThreadedTCPServer.HISTORY[q])

        send_message(self.request, conn_id, dict(response=result))
Пример #8
0
    def broadcast(self, queue, message):
        for conn_id, d in TCPRequestHandler.connections.items():
            if conn_id == message['coremq_sender'] and queue != conn_id and d[
                    'options'].get('echo', False) is False:
                continue

            if queue in d['subscriptions']:
                send_message(d['handler'].request, queue, message)
Пример #9
0
 def add_feedback(self, user_chat_id=-1, text=None):
     if len(self.feedback) == 0:
         f_n = 0
     else:
         f_n = self.feedback[-1].self_num + 1
     self.feedback.append(Feedback(user_chat_id, text, f_n))
     self.write_feedback()
     common.send_message(text="FEEDBACK", inline_keyboard=-1)
def get_feed(url):
    rss = feedparser.parse(url)
    send_message(rss['feed']['title'].encode('utf8'))
    rank = 1
    for entry in rss['entries']:
        title = entry['title'].encode('utf8')
        message = '%d: %s' % (rank, title)
        send_message(message)
        rank = rank + 1
Пример #11
0
 def get_games_list(self):
     '''Send requests to server to get list of all game sessions.
     '''
     routing_key = common.make_key_games(self.server_name)
     # Sending request to get list of opened games
     msg = clientlib.make_req_list_opened()
     send_message(self.channel, msg, routing_key, self.client_queue)
     # Sending request to get list of closed games
     msg = clientlib.make_req_list_closed()
     send_message(self.channel, msg, routing_key, self.client_queue)
Пример #12
0
 def start_game(self):
     '''Check if all players are ready and start the game.
     '''
     if self.players.issubset(self.players_ready) and\
         self.client_name in self.players_ready:
         # Send start game request to server
         msg = clientlib.make_req_start_game(self.client_name)
         send_message(self.channel, msg, self.key_game, self.client_queue)
     else:
         tkMessageBox.showinfo('Game', 'Not all players are ready')
Пример #13
0
def keep_alive(loop: Value):
    url = 'https://huey-bot.herokuapp.com/keep_alive'

    last_time = time.time()
    while loop.value:
        if time.time() - last_time > 10:
            res = requests.post(url=url)
            # print('ping')
            last_time = time.time()

            send_message("I'm still alive")
Пример #14
0
    def change_turn(self):
        '''Change turn to next player and send event.
        '''
        next_index = self.player_order.index(self.on_turn) + 1
        if next_index >= len(self.player_order):
            next_index = 0
        self.on_turn = self.player_order[next_index]

        # Send on turn event
        msg = serverlib.make_e_on_turn(self.on_turn)
        send_message(self.channel, msg, self.key_events)
Пример #15
0
    def spectate_game(self):
        '''Send spectate game request to server.
        '''
        if self.listbox_closed.curselection() == ():
            return
        game_name = self.listbox_closed.get(self.listbox_closed.curselection())

        # Sending request to spectate game
        msg = clientlib.make_req_spectate_game(game_name, self.client_name)
        routing_key = common.make_key_games(self.server_name)
        send_message(self.channel, msg, routing_key, self.client_queue)
Пример #16
0
 def get_seed(self):
   message = self.__create_message(MessageTypes.GET_SEED, '')
   try:
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock.connect((self.server_ip, self.server_port))
     common.send_message(sock, message.serialize())
     received_message = common.recv_message(sock)
     logging.debug('received_message = {0}'.format(received_message))
   except:
     logging.error(sys.exc_info())
   finally:
     sock.close()
Пример #17
0
 def remove_game(self, name):
     '''Remove game from the dict of games.
     @param name: name of game
     '''
     try:
         del self.games[name]
         # Send event about removed game
         msg = serverlib.make_e_game_end(name)
         send_message(self.channel, msg,
                      common.make_key_game_advert(self.server_name))
     except KeyError:
         pass
Пример #18
0
def main():
    with open('config.yml') as f:
        config = yaml.safe_load(f)
    remote_name = config['remote_name']
    server_port = config['server_port']
    user_name = config['user_name']

    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sender = (remote_name, server_port)
    soc.connect(sender)

    msg = common.recv_message(soc)

    my_addr = msg.params['client_address']
    print(my_addr)

    # register
    msg = AppMessageFactory.register(user_name)
    common.send_message(soc, msg)
    msg = common.recv_message(soc)

    while True:
        cmd = input('input command:').strip().split(' ')
        if cmd[0] == 'game':
            if cmd[1] == 'create':
                gamename = cmd[2]
                msg = AppMessageFactory.create_game(gamename)
                common.send_message(soc, msg)
                msg = common.recv_message(soc)
            elif cmd[1] == 'list':
                msg = AppMessageFactory.get_game_list()
                common.send_message(soc, msg)
                msg = common.recv_message(soc)
                for g in msg.params['games']:
                    print(g)
            elif cmd[1] == 'join':
                game_name = cmd[2]
                msg = AppMessageFactory.join_game(game_name)
                common.send_message(soc, msg)
                msg = common.recv_message(soc)
                print(msg)

        elif cmd[0] == 'close':
            msg = AppMessageFactory.close()
            common.send_message(soc, msg)
            msg = common.recv_message(soc)
            break

    soc.close()
Пример #19
0
def dota_game_service(last_game_state: LastGameState):
    while True:
        if time.time() - last_game_state.last_query_time >= 10.:

            # TODO: REMOVE THIS
            print('time to check')

            if last_game_state.match_id > 0:
                try:
                    # Refresh the player's match data on OpenDota.com
                    refresh_response = requests.post(url=PLAYER_REFRESH_URL)

                    # Get the latest match data
                    match_id = requests.get(url=PLAYER_MATCHES_URL,
                                            params={
                                                'limit': 1
                                            }).json()[0]['match_id']

                    if match_id != last_game_state.match_id:
                        match_data = requests.get(url=MATCHES_URL +
                                                  str(match_id)).json()

                        # Update the last game state with the new game's information
                        update_last_game_state(last_game_state, match_data)

                        # Post to the group chat
                        send_message(
                            generate_game_notification(last_game_state))

                    else:
                        last_game_state.last_query_time = time.time()

                except:
                    pass

            else:
                # Get the latest match data
                match_id = requests.get(url=PLAYER_MATCHES_URL,
                                        params={
                                            'limit': 1
                                        }).json()[0]['match_id']
                print(f'Last match id: {match_id}')

                # Get the latest match data
                match_data = requests.get(url=MATCHES_URL +
                                          str(match_id)).json()

                # Give the last game state its data
                update_last_game_state(last_game_state, match_data)
Пример #20
0
    def connect_server(self):
        '''Send connection request to server selected in the listbox.
        '''
        if self.listbox.curselection() == ():
            return
        server_name = self.listbox.get(self.listbox.curselection())
        client_name = self.username_entry.get()
        if client_name.strip() == '':
            tkMessageBox.showinfo('Username', 'Please enter username')
            return

        # Sending connect request
        msg = clientlib.make_req_connect(client_name)
        routing_key = common.make_key_server(server_name)
        send_message(self.channel, msg, routing_key, self.client_queue)
Пример #21
0
 def get_ready(self):
     '''Confirm the ship positioning to the server.
     '''
     if self.client_name in self.players_ready:
         return
     elif self.ships_remaining != 0:
         tkMessageBox.showinfo('Game',
                               'Ships remaining: %s' % self.ships_remaining)
     else:
         # Send request to server
         ships = self.fields[self.client_name].get_all_items('ship')
         msg = clientlib.make_req_set_ready(self.client_name, ships)
         send_message(self.channel, msg, self.key_game, self.client_queue)
         # Color the button
         self.button_ready.config(bg='#68c45c', activebackground='#68c45c')
Пример #22
0
    def create_game(self):
        '''Send game creation request to server.
        '''
        game_name = self.gamename_entry.get()
        if game_name.strip() == '':
            tkMessageBox.showinfo('Name', 'Please enter name of the game')
            return
        width = self.width_entry.get()
        height = self.height_entry.get()

        # Sending request to create game
        msg = clientlib.make_req_create_game(game_name, self.client_name,
                                             width, height)
        routing_key = common.make_key_games(self.server_name)
        send_message(self.channel, msg, routing_key, self.client_queue)
Пример #23
0
def webhook():
    app.logger.debug('Got a message!')

    # Comfortable amount of time to not cause a graphical glitch in GroupMe
    time.sleep(1)

    data = request.get_json()

    if data['name'] != 'Huey':
        if oi_huey(data):
            send_message(generate_excuse())

        elif question_about_last_game(data):
            send_message(generate_old_game_notification(get_last_match_data()))

    return "ok", 200
Пример #24
0
def weather(message, param):
    if not param:
        param = config.bot['weather']['default_location']
    r = requests.get('http://wttr.in/' + param + '?1n')
    buienradar_url = \
        'https://api.buienradar.nl/image/1.0/RadarMapBE?w=500&h=512&time=' \
        + str(int(time.time()))
    if r.text:

    # we get text in ANSI, escape it

        ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
        common.send_message('```\n' + ansi_escape.sub('', r.text)
                            + '\n```', buienradar_url)
        return
    common.send_message('*Current weather in BE:*', buienradar_url)
Пример #25
0
    def add_game(self, name, owner, width, height):
        '''Add game to the dict of games.
        @param name: name of game
        @param owner: owner of game
        @param width: width of field of game
        @param height: height of field of game
        '''
        # Create game in new thread
        game = Game(self, self.server_args, name, owner, width, height)
        self.games[name] = game
        game.start()

        # Send event about added game
        msg = serverlib.make_e_game_open(name)
        send_message(self.channel, msg,
                     common.make_key_game_advert(self.server_name))

        return game
Пример #26
0
    def changes_notify():
        def gen_changes(class_id):
            changes = my_context.db.timetable.changes
            try:
                changes_cell = changes.changes[changes.ch_ind[class_id]]
            except BaseException as err:
                print(err)
                return err
            return "Свежие изменения для " + my_context.db.timetable.c_n[class_id] + " на " + \
                   my_context.db.timetable.d_n[changes.change_day] + ":```\n" + \
                   '\n'.join(c_d for c_d in changes_cell.change_data) + \
                   "```\n\nВсегда можно отказаться от этих уведомлений в настройках"

        def gen_all_changes():
            return "Свежие изменения на " + my_context.db.timetable.d_n[my_context.db.timetable.changes.change_day] + \
                   " для всех" + '\n\n'.join(
                my_context.db.timetable.c_n[changesCell.class_ind] + '\n'.join(c_d for c_d in changesCell.change_data)
                for changesCell in my_context.db.timetable.changes.changes) + \
                   "\nВсегда можно отказаться от этих уведомлений в настройках (если я их сделал)"

        is_ok = True
        for u_id in my_context.db.users:
            user = my_context.db.users[u_id]
            if (user.settings.type_name != Type.CLASS
                    or my_context.db.timetable.changes.has_changes[
                        user.settings.type_id]) and user.settings.notify:
                if user.settings.type_name == Type.CLASS:
                    text = gen_changes(user.settings.type_id)
                    is_ok = is_ok and (text is not False)
                else:
                    text = gen_all_changes()
                    is_ok = is_ok and (text is not False)
                if text is not False:
                    common.send_message(text=text,
                                        chat_id=user.user_id,
                                        inline_keyboard=-1,
                                        silent=True,
                                        markdown=True)
        return is_ok
Пример #27
0
    def player_disconnected(self, player):
        '''Actions on player leaving or disconnecting from the game
        @param player: name of player
        '''
        # Remove player's client queue
        try:
            del self.client_queues[player]
        except KeyError:
            pass

        # If noone is in the game
        if len(self.client_queues.keys()) == 0:
            # Quit game
            self.channel.stop_consuming()
            self.game_list.remove_game(self.name)

        # Else we might need to change the owner
        elif self.owner == player:
            new_owner = random.choice(self.client_queues.keys())
            self.owner = new_owner
            # Send event that owner changed
            msg = serverlib.make_e_new_owner(new_owner)
            send_message(self.channel, msg, self.key_events)
Пример #28
0
    def player_left(self, player):
        '''Actions on player leaving from the game
        @param player: name of player
        '''
        try:
            self.players.remove(player)
        except KeyError:
            pass
        try:
            del self.fields[player]
        except KeyError:
            pass
        try:
            del self.player_hits[player]
        except KeyError:
            pass
        try:
            self.spectators.remove(player)
        except KeyError:
            pass

        # Send event that player left
        msg = serverlib.make_e_player_left(player)
        send_message(self.channel, msg, self.key_events)
Пример #29
0
    def on_event(self, ch, method, properties, body):
        '''React on game event.
        @param ch: pika.BlockingChannel
        @param method: pika.spec.Basic.Deliver
        @param properties: pika.spec.BasicProperties
        @param body: str or unicode
        '''
        LOG.debug('Received event: %s', body)
        msg_parts = body.split(common.SEP)

        # New player
        if msg_parts[0] == common.E_NEW_PLAYER:
            self.add_players(msg_parts[1:])

        # Player left
        if msg_parts[0] == common.E_PLAYER_LEFT:
            self.remove_player(msg_parts[1])

        # New owner
        if msg_parts[0] == common.E_NEW_OWNER:
            if msg_parts[1] == self.client_name:
                if not self.is_owner:
                    self.become_owner()

        # Player ready
        if msg_parts[0] == common.E_PLAYER_READY:
            self.players_ready.add(msg_parts[1])

        # Game starts
        if msg_parts[0] == common.E_GAME_STARTS:
            self.at_game_start(msg_parts[1])

        # On turn
        if msg_parts[0] == common.E_ON_TURN:
            self.on_turn = msg_parts[1]
            self.turn_label.destroy()
            self.turn_label = Tkinter.Label(self.frame_player,
                                            text='Turn: %s' % self.on_turn)
            self.turn_label.grid(row=self.height + 2, columnspan=self.width)

        # Hit
        if msg_parts[0] == common.E_HIT:
            self.fields[msg_parts[2]].add_item(int(msg_parts[3]),
                                               int(msg_parts[4]),
                                               common.FIELD_HIT_SHIP)

        # Sink
        if msg_parts[0] == common.E_SINK:
            field = self.fields[msg_parts[1]]
            for sink_ship in msg_parts[2:]:
                sink_ship_pos = sink_ship.split(common.FIELD_SEP)
                field.add_item(int(sink_ship_pos[0]), int(sink_ship_pos[1]),
                               common.FIELD_SINK_SHIP)
            self.update_buttons()

        # Player end
        if msg_parts[0] == common.E_PLAYER_END:
            if msg_parts[1] == self.client_name:
                if tkMessageBox.askyesno('Game', 'You lost! Leave game?'):
                    self.leave()
                else:
                    self.spectator = True
                    msg = clientlib.make_req_get_spectator_queue(
                        self.client_name)
                    send_message(self.channel, msg, self.key_game,
                                 self.client_queue)
                    msg = clientlib.make_req_get_all_fields(self.client_name)
                    send_message(self.channel, msg, self.key_game,
                                 self.client_queue)
            else:
                self.remove_player(msg_parts[1])

        # Game end
        if msg_parts[0] == common.E_GAME_END:
            ships = self.fields[self.client_name].get_all_items(
                common.FIELD_SHIP)
            if ships != []:
                tkMessageBox.showinfo('Game', 'Congratulations, you won!')
            else:
                tkMessageBox.showinfo('Game', 'Game ended!')
            if self.is_owner:
                if tkMessageBox.askyesno('Game', 'Restart session?'):
                    msg = clientlib.make_req_restart_session()
                    send_message(self.channel, msg, self.key_game,
                                 self.client_queue)

        # Game restart
        if msg_parts[0] == common.E_GAME_RESTART:
            self.hide()
            self.show([
                self.server_name, self.client_name, self.game_name,
                self.is_owner, self.spectator, self.spectator_queue
            ])
Пример #30
0
    def button_pressed(self):
        '''Reaction on pressing the button.
        '''
        if self.game_window.spectator:
            return

        LOG.debug('Pressed button on position: %s, %s', self.row, self.column)

        # If in positioning ships phase
        if self.game_window.client_name not in self.game_window.players_ready:
            if self.parent == 'opponent':
                return

            # Add ship
            if self.color == common.FIELD_WATER and\
                self.game_window.ships_remaining != 0:
                self.change_color(common.FIELD_SHIP)
                self.game_window.ships_remaining -= 1
                # Update ready_label
                self.game_window.ready_label.destroy()
                self.game_window.ready_label = Tkinter.Label(
                    self.game_window.frame_player,
                    text='Ships remaining: %s' %\
                        self.game_window.ships_remaining)
                self.game_window.ready_label.grid(
                    row=self.game_window.height + 2,
                    columnspan=self.game_window.width)
                # Update field
                self.game_window.fields[self.game_window.client_name].add_item(
                    self.row, self.column, common.FIELD_SHIP)

            # Remove ship
            elif self.color == common.FIELD_SHIP:
                self.change_color(common.FIELD_WATER)
                self.game_window.ships_remaining += 1
                # Update ready_label
                self.game_window.ready_label.destroy()
                self.game_window.ready_label = Tkinter.Label(
                    self.game_window.frame_player,
                    text='Ships remaining: %s' %\
                        self.game_window.ships_remaining)
                self.game_window.ready_label.grid(
                    row=self.game_window.height + 2,
                    columnspan=self.game_window.width)
                # Update field
                self.game_window.fields[
                    self.game_window.client_name].remove_item(
                        self.row, self.column)

        # If game started and on turn
        if self.game_window.on_turn == self.game_window.client_name:
            if self.parent == 'player' or self.game_window.opponent is None:
                return

            # Dont allow shooting at known positions
            if self.color != 'unknown':
                return

            # Mark as shot and send request to server
            self.change_color('shot')
            msg = clientlib.make_req_shoot(self.game_window.client_name,
                                           self.game_window.opponent, self.row,
                                           self.column)
            send_message(self.game_window.channel, msg,
                         self.game_window.key_game,
                         self.game_window.client_queue)
Пример #31
0
 def respond(self, conn_id, text):
     send_message(self.request, conn_id, dict(response=text))
#!/usr/bin/python
# coding: utf-8

import sys
import urllib2
import urllib
from bs4 import BeautifulSoup
from common import send_message

send_message('Apple Dev Center System Status')

try:
    response = urllib2.urlopen('https://developer.apple.com/support/system-status/')
    html = response.read()
 
    parsed_html = BeautifulSoup(html)
    result = parsed_html.body.find('table', attrs={'class':'status-table'})
 
    for row in result.find_all('td'):
        message = '%s - %s' % (row.span.text, row['class'][0].title())
        send_message(message)
 
    send_message('https://developer.apple.com/support/system-status/')
except Exception, e:
    send_message('Error: %s' % str(sys.exc_info()))

# coding: utf-8

import sys
import feedparser
from common import send_message
 
COUNTRIES = ['jp', 'us']
LIMIT = 10
URLS = ['https://itunes.apple.com/%s/rss/topfreeapplications/limit=%d/xml',
    'https://itunes.apple.com/%s/rss/toppaidapplications/limit=%d/xml',
    'https://itunes.apple.com/%s/rss/topgrossingapplications/limit=%d/xml']
 
def get_feed(url):
    rss = feedparser.parse(url)
    send_message(rss['feed']['title'].encode('utf8'))
    rank = 1
    for entry in rss['entries']:
        title = entry['title'].encode('utf8')
        message = '%d: %s' % (rank, title)
        send_message(message)
        rank = rank + 1
 
for country in COUNTRIES:
    for url in URLS:
        try:
            url = url % (country, LIMIT)
            get_feed(url)
        except Exception, e:
            send_message('Error: %s' % str(sys.exc_info()))

Пример #34
0
 def leave(self):
     '''Leave game session.
     '''
     msg = clientlib.make_req_leave_game(self.client_name)
     send_message(self.channel, msg, self.key_game, self.client_queue)
Пример #35
0
 def disconnect(self):
     '''Disconnect from server.
     '''
     msg = clientlib.make_req_disconnect(self.client_name)
     send_message(self.channel, msg, self.key_server, self.client_queue)
     send_message(self.channel, msg, self.key_game, self.client_queue)
Пример #36
0
    def on_show(self):
        '''Bind queues, set consuming and listen.
        '''
        # Routing keys
        self.key_client = self.client_queue
        self.key_server = common.make_key_server(self.server_name)
        self.key_game = common.make_key_game(self.server_name, self.game_name)
        self.key_events = common.make_key_game_events(self.server_name,
                                                      self.game_name)
        if self.spectator:
            self.key_spectate = self.spectator_queue

        # Binding queues
        self.channel.queue_bind(exchange='direct_logs',
                                queue=self.client_queue,
                                routing_key=self.client_queue)
        self.channel.queue_bind(exchange='direct_logs',
                                queue=self.events_queue,
                                routing_key=self.key_events)
        if self.spectator:
            self.channel.queue_bind(exchange='direct_logs',
                                    queue=self.events_queue,
                                    routing_key=self.key_spectate)
        # Set consuming
        self.channel.basic_consume(self.on_response,
                                   queue=self.client_queue,
                                   no_ack=True)
        self.channel.basic_consume(self.on_event,
                                   queue=self.events_queue,
                                   no_ack=True)
        # Listening
        self.listening_thread = listen(self.channel, 'game')

        # Remove old settings and get all information from server
        self.reset_setting()

        msg = clientlib.make_req_get_dimensions()
        send_message(self.channel, msg, self.key_game, self.client_queue)
        msg = clientlib.make_req_get_players()
        send_message(self.channel, msg, self.key_game, self.client_queue)
        msg = clientlib.make_req_get_players_ready()
        send_message(self.channel, msg, self.key_game, self.client_queue)
        msg = clientlib.make_req_get_owner()
        send_message(self.channel, msg, self.key_game, self.client_queue)
        msg = clientlib.make_req_get_turn()
        send_message(self.channel, msg, self.key_game, self.client_queue)
        msg = clientlib.make_req_get_field(self.client_name)
        send_message(self.channel, msg, self.key_game, self.client_queue)
        msg = clientlib.make_req_get_spectator(self.client_name)
        send_message(self.channel, msg, self.key_game, self.client_queue)

        self.wait_for_ready()
        # If game already started
        if self.on_turn is not None:
            self.at_game_start(self.on_turn)
            msg = clientlib.make_req_get_hits(self.client_name)
            send_message(self.channel, msg, self.key_game, self.client_queue)

        if self.spectator:
            msg = clientlib.make_req_get_all_fields(self.client_name)
            send_message(self.channel, msg, self.key_game, self.client_queue)
Пример #37
0
#!/usr/bin/python
# coding: utf-8

from common import send_message

send_message('test')
Пример #38
0
    def process_request(self, msg_parts, properties):
        '''Process request about list of games.
        @param msg_parts: parsed message
        @param properties: pika.spec.BasicProperties
        @return String, response
        '''
        # Get list of games request
        if msg_parts[0] == common.REQ_LIST_OPENED:
            game_names = [game.name for game in self.get_games('opened')]
            return serverlib.make_rsp_list_opened(game_names)
        if msg_parts[0] == common.REQ_LIST_CLOSED:
            game_names = [game.name for game in self.get_games('closed')]
            return serverlib.make_rsp_list_closed(game_names)

        # Create game request
        if msg_parts[0] == common.REQ_CREATE_GAME:
            if len(msg_parts) != 5 or msg_parts[1].strip() == '' or\
                msg_parts[3].strip() == '' or msg_parts[4].strip() == '':
                return serverlib.make_rsp_invalid_request()

            game_name = msg_parts[1]
            client_name = msg_parts[2]
            width = msg_parts[3]
            height = msg_parts[4]

            if game_name in self.games:
                return serverlib.make_rsp_name_exists()
            if client_name not in self.clients.client_set:
                return serverlib.make_rsp_permission_denied()

            game = self.add_game(game_name, client_name, width, height)
            game.wait_for_ready()
            game.client_queues[client_name] = properties.reply_to
            return serverlib.make_rsp_game_entered(game_name, 1)

        # Join game request
        if msg_parts[0] == common.REQ_JOIN_GAME:
            if len(msg_parts) != 3:
                return serverlib.make_rsp_invalid_request()

            game_name = msg_parts[1]
            client_name = msg_parts[2]

            if game_name not in self.games:
                return serverlib.make_rsp_name_doesnt_exist()
            if client_name not in self.clients.client_set:
                return serverlib.make_rsp_permission_denied()
            if client_name not in self.games[game_name].players and\
                self.games[game_name].state == 'closed':
                return serverlib.make_rsp_permission_denied()

            self.games[game_name].client_queues[client_name] =\
                properties.reply_to
            if client_name not in self.games[game_name].players:
                self.games[game_name].players.add(client_name)
                # Send event that new player was added
                msg = serverlib.make_e_new_player(client_name)
                send_message(self.channel, msg,
                             common.make_key_game_events(self.server_name,
                                                         game_name))

            return serverlib.make_rsp_game_entered(game_name, 0)

        # Spectating game request
        if msg_parts[0] == common.REQ_SPECTATE_GAME:
            if len(msg_parts) != 3:
                return serverlib.make_rsp_invalid_request()

            game_name = msg_parts[1]
            client_name = msg_parts[2]

            if game_name not in self.games:
                return serverlib.make_rsp_name_doesnt_exist()
            if client_name not in self.clients.client_set:
                return serverlib.make_rsp_permission_denied()
            if client_name in self.games[game_name].players:
                return serverlib.make_rsp_permission_denied()

            game = self.games[game_name]
            game.spectators.add(client_name)
            return serverlib.make_rsp_game_spectate(game_name, 0,
                                                    game.spectator_queue)
Пример #39
0
    def send_message(self):
        message = sys.stdin.readline()[:-1]

        envelope = self.ENVELOPE_FORMAT % (self.username, message)
        log.debug("Sending the envelope %r", envelope)
        send_message(self.socket, envelope)