• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python message.Message类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中message.Message的典型用法代码示例。如果您正苦于以下问题:Python Message类的具体用法?Python Message怎么用?Python Message使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Message类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: candidate_receive_message

    def candidate_receive_message(self, msg):
        """
        All Candidate Message Receiving
        @:param msg - the JSON message received
        @:return: Void
        """
        if msg['type'] == 'vote':
            #print str(self.id) + ": Got Vote Message----------"
            message = Message.create_message_from_json(msg)
            self.receive_vote(message)

        if msg['type'] == 'heartbeat':
            #print str(self.id) + "got ~~~HEARTBEAT~~~"
            heart_beat = Message.create_message_from_json(msg)

            if heart_beat.term >= self.current_term:
                self.current_term = heart_beat.term
                self.become_follower(heart_beat.leader)

        if msg['type'] == 'voteRequest':
            message = Message.create_message_from_json(msg)
            if message.term > self.current_term:
                self.become_follower(msg['leader'])

        if msg['type'] in ['get', 'put']:
            message = Message.create_message_from_json(msg)
            redirect_message = message.create_redirect_message("FFFF")

            self.send(redirect_message)
开发者ID:ajdcolcord,项目名称:CS3700_Project5,代码行数:29,代码来源:Server.py


示例2: startRound

	def startRound(self, connection, *args):
		game = connection.player.game
		if game.state != Game.STATE_FINISHED_ROUND:
			return
		# if game.master is connection.player:
		# game.start()
		game.startNewRound()

		# message = Message.encode(Message.SEND_GAME_MESSAGE_STARTED, '')
		# self.server.sendMessageMultiple(game.players, message)

		scores = {}
		connections = []
		for player in game.players:
			connections.append(player.connection)
			scores[player.name] = len(player.green_apples)
			red_apples = []
			for red_apple in player.red_apples:
				red_apples.append(red_apple.dictionary)
			message = Message.encode(Message.SEND_GAME_MESSAGE_PLAYER_RED_APPLES, red_apples)
			self.server.sendMessageSingle(player.connection, message)

		round_details = {}
		round_details['JUDGE'] = game.players[game.judge].name
		round_details['SCORES'] = scores
		round_details['GREEN_APPLE'] = game.active_green_apple.dictionary
		message = Message.encode(Message.SEND_GAME_MESSAGE_ROUND_DETAILS, round_details)
		self.server.sendMessageMultiple(connections, message)
开发者ID:murkymittens,项目名称:pyapples,代码行数:28,代码来源:lobby.py


示例3: test_multiple_packet_message

 def test_multiple_packet_message(self):
     body = "1a0eeb5701b202010a0101a000340034170d000208000186a0000000000000".decode('hex')
     msg = Message("1f07b1ee", 14, 0x18, body)
     packets = msg.packets()
     self.assertEqual(len(packets), 2)
     self.assertEqual(packets[0].raw_hex(), "1f07b1eeae1f07b1ee181f1a0eeb5701b202010a0101a000340034170d000208000186a019")
     self.assertEqual(packets[1].raw_hex(), "1f07b1ee900000000000000251e2")
开发者ID:openaps,项目名称:openomni,代码行数:7,代码来源:message_test.py


示例4: _parse_kexdh_gex_request

 def _parse_kexdh_gex_request(self, m):
     minbits = m.get_int()
     preferredbits = m.get_int()
     maxbits = m.get_int()
     # smoosh the user's preferred size into our own limits
     if preferredbits > self.max_bits:
         preferredbits = self.max_bits
     if preferredbits < self.min_bits:
         preferredbits = self.min_bits
     # fix min/max if they're inconsistent.  technically, we could just pout
     # and hang up, but there's no harm in giving them the benefit of the
     # doubt and just picking a bitsize for them.
     if minbits > preferredbits:
         minbits = preferredbits
     if maxbits < preferredbits:
         maxbits = preferredbits
     # now save a copy
     self.min_bits = minbits
     self.preferred_bits = preferredbits
     self.max_bits = maxbits
     # generate prime
     pack = self.transport._get_modulus_pack()
     if pack is None:
         raise SSHException('Can\'t do server-side gex with no modulus pack')
     self.transport._log(DEBUG, 'Picking p (%d <= %d <= %d bits)' % (minbits, preferredbits, maxbits))
     self.g, self.p = pack.get_modulus(minbits, preferredbits, maxbits)
     m = Message()
     m.add_byte(chr(_MSG_KEXDH_GEX_GROUP))
     m.add_mpint(self.p)
     m.add_mpint(self.g)
     self.transport._send_message(m)
     self.transport._expect_packet(_MSG_KEXDH_GEX_INIT)
开发者ID:japastor,项目名称:controlies,代码行数:32,代码来源:kex_gex.py


示例5: unicastTCP

 def unicastTCP(self, serverID, message):
     delay_time = random.uniform(self.min_delay, self.max_delay)
     m = Message(self.pid, serverID, message)
     print(m.send_str())
     print('delay unicastTCP with {0:.2f}s '.format(delay_time))
     delayed_t = threading.Timer(delay_time, self.__unicastTCP, (message,))
     delayed_t.start()
开发者ID:weiyangedward,项目名称:cs425_MP,代码行数:7,代码来源:channel.py


示例6: _keepalive_conversation

 def _keepalive_conversation(self):
     if self.state != ProtocolState.OPEN:
         return True
     message = Message()
     message.add_header("Content-Type", "text/x-keep-alive")
     self._send_command("MSG", "N", message, True)
     return True
开发者ID:hoangduit,项目名称:emesene,代码行数:7,代码来源:switchboard.py


示例7: move

    def move(self, state):
        """Use the game state to decide what action to take, and then output
           the direction to move."""
        self.game.update(state)
        message = Message()
        message.game_message(self)
        self.input_interface.append( message )

        self.action = self.decide()

        retval = 'Stay'
        if ( self.action == 'Heal' ):
            if ( None != self.game.board.taverns_list[0].path ):
                retval = self.game.board.taverns_list[0].path[0]
        elif ( self.action == 'Mine' ):
            if ( None != self.game.board.mines_list[0].path ):
                retval = self.game.board.mines_list[0].path[0]
        elif ( self.action == 'Attack' ):
            if ( None != self.game.enemies_list[0].path ):
                retval = self.game.enemies_list[0].path[0]
        elif ( self.action == 'Wait' ):
            retval = 'Stay'
        self.expected_pos = self.game.board.to( self.game.hero.pos, retval )
        self.prev_mines = self.game.hero.mines
        self.prev_gold = self.game.hero.gold
        self.prev_life = self.game.hero.life

        return retval
开发者ID:DanFritz,项目名称:vindinium-classifier-ga-bot,代码行数:28,代码来源:bot.py


示例8: unite_forest

 def unite_forest(self, msg):
     """This fuunction is called by leader process to update the component
     of all process in the current forest."""
     if msg.component_id > self.component_id:
         logging.info("Process %s is setting as non leader.",
                      str(self.process_id))
         self.update_leader(False)
     else:
         if self.level == msg.level:
             self.level += 1
         elif self.level < msg.level:
             self.level = msg.level
         msg = Message()
         msg = msg.update_component(self.level, self.component_id)
         for edge in self.mst_edges:
             edge.send_message(msg, self.process_id)
         seen_edges = []
         self.log_mst_edges()
         while len(seen_edges) != len(self.mst_edges):
             for edge in [e for e in self.mst_edges if e not in seen_edges]:
                 self.messages_lock.acquire()
                 if "ack_leader" in self.messages[edge.id] and\
                         len(self.messages[edge.id]["ack_leader"]):
                     logging.info("acknowledge received from edge: %s", edge.id)
                     msg = self.messages[edge.id]["ack_leader"].pop()
                     seen_edges.append(edge)
                 self.messages_lock.release()
         self.round_completed = True
开发者ID:praneethkits,项目名称:SynchGHS,代码行数:28,代码来源:process.py


示例9: run_round

    def run_round(self):
        """Runs the current round before rporting back."""
        self.round_completed = False
        self.merge_mwoe_received = None
        self.clear_ret_messages()
        self.get_non_mst_edges()
        if self.leader:
            logging.info("finding mwoe")
            mwoe_msg = self.find_MWOE()
            logging.info("MWOE details: edge id: %s, weight: %f",
                         mwoe_msg.edge_id, mwoe_msg.msg)
            if mwoe_msg.edge_id is None:
                self.completed = True
                self.round_completed = True
                completed_msg = Message()
                completed_msg = completed_msg.get_completed_msg()
                for edge in self.mst_edges:
                    edge.send_message(completed_msg, self.process_id)
                return

            self.merge_mwoe_received_lock.acquire()                
            self.merge_mwoe_received = mwoe_msg
            self.merge_mwoe_received_lock.release()
            # code for leader to send the mwoe request to its child
            merge_mwoe_msg = Message()
            merge_mwoe_msg = merge_mwoe_msg.merge_MWOE(mwoe_msg.edge_id,
                                                       mwoe_msg.process)
            self.log_mst_edges()
            for edge in self.mst_edges:
                edge.send_message(merge_mwoe_msg, self.process_id)

            if mwoe_msg.process == self.process_id:
                self.send_join_request(self.get_edge(mwoe_msg.edge_id))
                self.merge_mwoe(mwoe_msg)
开发者ID:praneethkits,项目名称:SynchGHS,代码行数:34,代码来源:process.py


示例10: handle

    def handle(self, message):
        if message.command == "PING":
            # respond quick before we get booted!
            m = Message()
            m.command = "PONG"
            m.params = message.params
            self.connection.send(m)
        elif message.command == "QUIT":
            # user left. Log them out if need be
            u = db.User(nick=message.sender)
            u.logout()
        elif message.command == "NICK":
            # nick updated. Chase them!
            u = db.User(nick=message.sender)
            u.change_nick(message.params[0])
        elif message.command == "PRIVMSG" and message.params[1].startswith(self.settings["command_prefix"]):
            # palm it off to the plugins
            for plugin in self.plugins:
                if plugin.handle(message):
                    break

        channel = None
        if message.params[0].startswith("#"):
            channel = message.params[0]
        db.log_message(message.command, message.sender, channel, " ".join(message.params))
开发者ID:colourblind,项目名称:BeastBot,代码行数:25,代码来源:beastbot.py


示例11: xsend

    def xsend(self):
        '''
        set appid and appkey
        使用新的线程 发送短信
        '''
        message_configs = {}
        message_configs['appid'] = self.appid
        message_configs['appkey'] = self.appkey

        '''
        set sign_type,if is set
        '''
        if self.sign_type != '':
            message_configs['sign_type'] = self.sign_type

        '''
        init mail class
        '''
        message = Message(message_configs)

        '''
        build request and send email and return the result
        '''
        result = message.xsend(self.build_request())
        # MessageThread(message).start()
        return result
开发者ID:appleface2050,项目名称:ESNS,代码行数:26,代码来源:message_xsend.py


示例12: t_one

 def t_one(self, dest_x, dest_y, self_x, self_y, self_dir, expected):
     s = "message {} {} {} {} {} aaa\\".format(
         dest_x, dest_y, self_x, self_y, self_dir.value
     )
     m = Message(s)
     action = m.action_to_join_sender()
     self.assertTrue(expected == action)
开发者ID:gbersac,项目名称:zappy_42,代码行数:7,代码来源:test_direction.py


示例13: get_messages

    def get_messages(self):
        if not self.initialized:
            self.error_message = 'Cannot get messages for non initialized Bot'
            return []

        messages = []
        updates = self.bot.get_updates(offset=self.last_update_id).wait()
        for update in updates:
            # always increase last_update_id to get only new messages next time
            self.last_update_id = update.update_id + 1
            self.chat_id = update.message.chat.id

            # skip all types of message except Message
            if not update.message or not isinstance(update.message, Message):
                continue

            m = Msg()
            ok = m.init(update)
            if not ok:
                self.errors[update.message.text] = m.get_error_message()
                continue

            messages.append(m)

        return messages
开发者ID:amaslenn,项目名称:AMWorkoutAssist,代码行数:25,代码来源:telegram.py


示例14: wiki

    def wiki(self, nick, channel, params):
        if len(params) < 1:
            return;

        replyto = nick if channel == None else channel
        qs = { 
            'action': 'query',
            'prop': 'revisions',
            'rvprop': 'content',
            'format': 'xml',
            'titles': ' '.join(params)
        }
        url = 'http://en.wikipedia.org/w/api.php?' + urllib.urlencode(qs)

        xml = ElementTree.parse(urllib.urlopen(url))
        result = xml.findtext('.//rev')

        if result is not None:
            result = self.deugly_wikimedia(result)
        else:
            result = 'Couldn\'t find it :('
            
        m = Message()
        m.command = 'PRIVMSG'
        m.params = [replyto, result]
        self.connection.send(m)
开发者ID:colourblind,项目名称:BeastBot,代码行数:26,代码来源:lookup.py


示例15: _receive_ack

    def _receive_ack(self, msg):
        """Receives an ACK and transitions message's state based on that.
        """
        self._remove_message(msg)

        idx, parent_msg = self._find_message(token=None, message_id=msg.message_id, state=MessageState.wait_for_ack)
        if parent_msg is None:
            coap_log.warning('ACK received but no matching message found - Sending RESET')
            reset_msg = Message(message_id=msg.message_id, message_type=MessageType.reset)
            self._socket.send(reset_msg.build())
            return
        if parent_msg.type != MessageType.confirmable:
            coap_log.error('ACK received for NON-CONFIRMABLE message - Ignoring')
            return

        self._transition_message(parent_msg, MessageState.wait_for_response)

        if msg.class_code == 0 and msg.class_detail == 0:
            # if this is empty message send just for ACK we are already done.
            coap_log.debug('Separate ACK received')
            return

        #coap_log.debug('Piggybacked RESPONSE {0}'.format(str(msg)))
        if msg.has_observe_option():
            self._receive_observe(parent_msg, msg)
            return

        # This message has a piggybacked response, so receive it.
        self._receive_response(parent_msg, msg)
开发者ID:samueldotj,项目名称:pycoap,代码行数:29,代码来源:coap.py


示例16: handle_request

 def handle_request(self, request):
     args = {}
     for k, v in request.args.items():
         args.update({k: v[0]},)
     
     if len(request.postpath[0]) and not args.get('callback'):
         request.setResponseCode(400)
         return HTML
     
     if 'register' in request.postpath:
         register = Register(request, args)
         return register.response()
     
     if 'login' in request.postpath:
         login = Login(request, args)
         return login.response()
     
     if 'poll' in request.postpath:
         poll = Poll(request, args)
         return poll.response()
     
     if 'message' in request.postpath:
         message = Message(request, args)
         return message.response()
     
     if 'join' in request.postpath:
         join = Join(request, args)
         return join.response()
     
     else:
         return """
开发者ID:fuzzpedal,项目名称:chatapp,代码行数:31,代码来源:tap.py


示例17: __init__

 def __init__(self):
     super(EventProcessor, self).__init__()
     self.message_handler = MessageHandler()
     #self.gps = GPS()
     Message.init(self.message_handler.plugin.address())
     Detector.start_plugins()
     Reactor.add_plugin_events()
开发者ID:flarecast,项目名称:simulation,代码行数:7,代码来源:event_processor.py


示例18: create_msg_adiumLog

    def create_msg_adiumLog(self):
        # Logs of the format:
        # (00:07:25)fetchgreebledonx:Do you know how you replace spaces in a string with nothing?
        # Logs are passed to TXTMessageParser, which returns a list of dicts with
        # timestamp, message_type, message, and sender
        # message_type will be either message or sender, and for now we ignore status

        date = self.filename.split("(")[1].split(")")[0].replace("|", "-")

        try:
            f = open(self.filename, "r")
            data = f.read()
            f.close()

            p = TXTMessageParser()

            p.parse(data)

            for msg in [f for f in p.messages if f["message_type"] in ["message"]]:
                m = Message(
                    msg["message"],
                    self.account,
                    self.contact,
                    msg["sender"],
                    self.service,
                    date + " " + msg["timestamp"],
                )
                m.insert(self.connection)
        except IOError:
            print "Error: %s" % self.filename
开发者ID:jmelloy,项目名称:sqllogger,代码行数:30,代码来源:chat.py


示例19: handle_message

 def handle_message(self, data):
     """ message handler. """
     m = Message(data)
     m.parse(self)
     if data.type == 'groupchat' and data.subject:
         logging.debug("%s - checking topic" % self.name)
         self.topiccheck(m)
         nm = Message(m)
         callbacks.check(self, nm)
         return
     if data.get('x').xmlns == 'jabber:x:delay':
         logging.warn("%s - ignoring delayed message" % self.name)
         return
     self.privwait.check(m)
     if m.isresponse:
         logging.debug("%s - message is a response" % self.name)
         return
     jid = None
     m.origjid = m.jid
     for node in m.subelements:
         try: m.jid = node.x.item.jid 
         except (AttributeError, TypeError): continue
     if self.me in m.fromm:
         logging.debug("%s - message to self .. ignoring" % self.name)
         return 0
     try:
         if m.type == 'error':
             if m.code:
                 logging.error('%s - error - %s' % (self.name, str(m)))
             self.errorwait.check(m)
             self.errorHandler(m)
     except Exception, ex:
         handle_exception()
开发者ID:melmothx,项目名称:jsonbot,代码行数:33,代码来源:bot.py


示例20: read

    def read(self):
        try:
            message = self.socket.recv(4096)
        except Exception as e:
            Log.e(getExceptionInfo(e))
            return Client.ReadError

        if len(message) == 0:
            return Client.NoMessage

        self.buf += message

        while len(self.buf) > 4:
            length = int(self.buf[0:4])
            if not len(self.buf) >= length + 4:
                break
            msg = self.buf[4: length + 4]
            self.buf = self.buf[length + 4:]
            message = Message()
            if not message.loads(msg):
                Log.w(u'Unknown Message')
            else:
                self.requests.put(message)

        return Client.NewMessage
开发者ID:RoyZeng,项目名称:ivy-webchat,代码行数:25,代码来源:network_test.py



注:本文中的message.Message类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python message.Messager类代码示例发布时间:2022-05-27
下一篇:
Python message.little_endian函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap