本文整理汇总了Python中MessageParser.MessageParser.parse方法的典型用法代码示例。如果您正苦于以下问题:Python MessageParser.parse方法的具体用法?Python MessageParser.parse怎么用?Python MessageParser.parse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MessageParser.MessageParser
的用法示例。
在下文中一共展示了MessageParser.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MessageReceiver
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class MessageReceiver(Thread):
"""
This is the message receiver class. The class inherits Thread, something that
is necessary to make the MessageReceiver start a new thread, and it allows
the chat client to both send and receive messages at the same time
"""
def __init__(self, client, connection):
super(MessageReceiver, self).__init__()
"""
This method is executed when creating a new MessageReceiver object
"""
# Flag to run thread as a deamon. A deamon is a process that runs in the background.
self.daemon = True
self.parser = MessageParser()
self.client = client
self.connection = connection
self.start()
def run(self):
while True:
received_message = self.connection.recv(4096)
try:
print self.parser.parse(received_message)
except:
pass
示例2: MessageReceiver
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class MessageReceiver(Thread):
"""
This is the message receiver class. The class inherits Thread, something that
is necessary to make the MessageReceiver start a new thread, and it allows
the chat client to both send and receive messages at the same time
"""
def __init__(self, client, connection):
"""
This method is executed when creating a new MessageReceiver object
"""
# Flag to run thread as a deamon
#self.client=client
self.connection = connection
# tODO: Finish initialization of MessageReceiver
super(MessageReceiver,self).__init__()
def run(self):
# tODO: Make MessageReceiver receive and handle payloads
self.MessageParser = MessageParser()
#s_thread = MessageParser(payload)
#s_thread.start()
while True:
payload = self.connection.recv(4096)
#print('We now listening for input from server.' + payload)
self.MessageParser.parse(payload)
示例3: run
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
def run(self):
# TODO: Make MessageReceiver receive and handle payloads
parser = MessageParser()
while True:
self.received = self.connection.recv(1024) # v2
# print self.received
print parser.parse(self.received)
示例4: __init__
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class Client:
"""
This is the chat client class
"""
def __init__(self, host, server_port):
"""
This method is run when creating a new Client object
"""
# Set up the socket connection to the server
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# TODO: Finish init process with necessary code
self.host = host
self.server_port = server_port
self.messageParser = MessageParser()
self.messageReceiver = MessageReceiver(self, self.connection)
self.run()
def run(self):
"""
Main process of the client. Waits for input from user
"""
self.connection.connect((self.host, self.server_port))
self.messageReceiver.start()
print 'Client running...\nType \'quit\' to end or \'help\' for info'
while True:
command = raw_input()
if command == 'quit':
self.disconnect()
print 'Client closing'
break
self.send_payload(self.messageParser.parse_dataToSend(command))
def disconnect(self):
"""
Close sock connection
"""
self.connection.close()
def receive_message(self, message):
"""
Prints received message after it's parsed
"""
print self.messageParser.parse(message)
def send_payload(self, data):
"""
Sends data to server
"""
self.connection.send(data)
示例5: __init__
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class Client:
"""
This is the chat client class
"""
def __init__(self, host, server_port):
"""
This method is run when creating a new Client object
"""
self.serverport = server_port
self.h = host
# Set up the socket connection to the server
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.MParser = MessageParser()
self.MReceiver = MessageReceiver(self, self.connection)
self.run()
def run(self):
# Initiate the connection to the server
self.connection.connect((self.h, self.serverport))
self.MReceiver.start()
while True:
userInput = raw_input()
try:
if userInput:
request, content = userInput.split()
if not content:
content = None
payload = {
'request': request,
'content': content
}
self.send_payload(payload)
except KeyboardInterrupt:
self.disconnect()
def handleInput(self, userInput):
message = userInput.split(' ')
def disconnect(self):
self.connection.close()
print "Server disconnected."
def receive_message(self, message):
print self.MParser.parse(message)
def send_payload(self, data):
payload = json.dumps(data)
self.connection.send(payload)
示例6: __init__
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class Client:
"""
This is the chat client class
"""
def __init__(self, host, server_port):
"""
This method is run when creating a new Client object
"""
# Set up the socket connection to the server
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.messageParser = MessageParser()
self.host = ""
self.server_port = 9998
# TODO: Finish init process with necessary code
self.run()
self.messageReceiver = MessageReceiver(self,self.connection)
self.messageReceiver.start()
def run(self):
# Initiate the connection to the server
self.connection.connect((self.host, self.server_port))
def disconnect(self):
self.messageReceiver.send_disconnect()
self.connection.close()
quit()
def receive_message(self, message):
self.messageParser.parse(self.printer, message)
def printer(self,time,sender,message_type,message):
melding = ("\n[" +
time +" : " + message_type + "] " +
sender+ ": " + message + "\n>>> ")
print melding
def send_payload(self, data):
if data == "getHistory":
self.messageReceiver.getHistory()
elif data == "getNames":
self.messageReceiver.getNames()
elif data == "getHelp":
self.messageReceiver.getHelp()
else:
self.messageReceiver.sendMessage(data)
def login(self, data):
brukerNavn = self.messageParser.parse_login(data)
self.messageReceiver.send_login(brukerNavn)
示例7: MessageReceiver
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class MessageReceiver(Thread):
"""
This is the message receiver class. The class inherits Thread, something that
is necessary to make the MessageReceiver start a new thread, and it allows
the chat client to both send and receive messages at the same time
"""
def __init__(self, client, connection):
"""
This method is executed when creating a new MessageReceiver object
"""
Thread.__init__(self)
# Flag to run thread as a deamon
self.daemon = True
self.client = client
self.connection = connection
self.msgparser = MessageParser()
# TODO: Finish initialization of MessageReceiver
def run(self):
# TODO: Make MessageReceiver receive and handle payloads
while True:
data = self.connection.recv(2048)
#print "Klient motttok: " + data
for json_msg in data.split("}"):
if len(json_msg) > 5:
self.client.receive_message(self.msgparser.parse(json_msg + "}", self))
示例8: SwankRatsWebSocketClient
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class SwankRatsWebSocketClient(WebSocketClient):
def opened(self):
self.form = RobotConfig.Config.get("robot", "form")
print("opened " + self.form)
self.parser = MessageParser()
data = '{"to":"robot", "cmd":"init", "params":{"form":"' + self.form + '"} }'
self.send(data)
def closed(self, code, reason=None):
print "Closed down", code, reason
self.parser.robot.set(0, 0)
os.system("shutdown /r")
def received_message(self, m):
print m
self.parser.parse(m.data)
示例9: __init__
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class SubredditWatcher:
MAX_ALREADY_DONE_LENGTH = 2000
def __init__(self, name, praw_reddit, triggers, username):
self.name = name
self.praw_reddit = praw_reddit
self.triggers = triggers
self.username = username
self.already_done = []
self.msg_parser = MessageParser(triggers)
def watch(self):
subreddit = self.praw_reddit.get_subreddit(self.name)
util.bot_stdout_print("Getting comments for subreddit: %s" % (self.name))
for submission in subreddit.get_comments():
if submission.id not in self.already_done:
try:
msg = submission.body
successes,failures = self.msg_parser.parse(msg)
self.already_done.append(submission.id)
reply = self.get_reply(submission, successes, failures)
if not reply is None:
util.bot_stdout_print("Reply to %s: %s\n" % (submission.id, reply))
util.handle_ratelimit(submission.reply, reply)
except:
util.bot_stdout_print("Unknown exception: %s" % sys.exc_info()[0])
print traceback.format_exc()
self.already_done.append(submission.id)
self.cleanup_already_done()
def get_reply(self, submission, successes, failures):
if len(successes) > 0:
success_msgs = []
for result in successes:
success_msgs.append("Random integer between %d and %d is %d." % (result["x"], result["y"], result["randnum"]))
reply = " \n".join(success_msgs)
return reply
elif len(failures) > 0:
failure_messages = []
for failure_msg in failures:
failure_messages.append("* %s" % failure_msg)
reply = "The following errors occurred: \n \n"
reply += " \n".join(failure_messages)
reply += " \n \nYou may be doing something incorrectly."
reply += " Please enter the following command to use this bot: "
reply += "\"/u/%s x y\" (where x and y are integers)." % self.username
return reply
def cleanup_already_done(self):
# Thought about just removing everything that is not in the current reddit comment list,
# but I'm not sure how reddit handles comment deletion. I'd hate for the bot to respond twice.
# Instead, I'm just going to keep the list at a maximum length. This will at least keep the
# bot from consuming too much memory.
if len(self.already_done) > self.MAX_ALREADY_DONE_LENGTH:
negative_length = -1 * self.MAX_ALREADY_DONE_LENGTH
self.already_done = self.already_done[negative_length:]
示例10: receive_message
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
def receive_message(self, message):
#Decode message
msg_parser = MessageParser()
#print(message)
#if message is None:
# print('oops its none')
decoded_message = msg_parser.parse(message)
#Print the "handled" response
print(decoded_message)
示例11: __init__
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class MentionsWatcher:
MAX_ALREADY_DONE_LENGTH = 2000
DELAY = 30
def __init__(self, praw_reddit, username):
self.praw_reddit = praw_reddit
self.username = username
self.already_done = []
self.last_run = None
self.msg_parser = MessageParser(username=username)
def watch(self):
now = int(time.time())
if self.last_run is None or now - self.last_run > self.DELAY:
util.bot_stdout_print("Getting mentions for user: %s" % (self.username))
mentions = self.praw_reddit.get_mentions()
self.last_run = int(time.time())
try:
for mention in mentions:
if mention.new == True and mention.id not in self.already_done:
msg = mention.body
successes,failures = self.msg_parser.parse(msg)
reply = self.get_reply(successes, failures)
self.already_done.append(mention.id)
mention.mark_as_read()
if not reply is None:
util.bot_stdout_print("Reply to %s: %s\n" % (mention.id, reply))
util.handle_ratelimit(mention.reply, reply)
except:
util.bot_stdout_print("Unknown exception: %s" % sys.exc_info()[0])
print traceback.format_exc()
self.already_done.append(mention.id)
self.cleanup_already_done()
def get_reply(self, successes, failures):
if len(successes) > 0:
success_msgs = []
for result in successes:
success_msgs.append("Random integer between %d and %d is %d." % (result["x"], result["y"], result["randnum"]))
reply = " \n".join(success_msgs)
return reply
elif len(failures) > 0:
failure_messages = []
for failure_msg in failures:
failure_messages.append("* %s" % failure_msg)
reply = "The following errors occurred: \n \n"
reply += " \n".join(failure_messages)
reply += " \n \nYou may be doing something incorrectly."
reply += " Please enter the following command to use this bot: "
reply += "\"/u/%s x y\" (where x and y are integers)." % self.username
return reply
def cleanup_already_done(self):
if len(self.already_done) > self.MAX_ALREADY_DONE_LENGTH:
negative_length = -1 * self.MAX_ALREADY_DONE_LENGTH
self.already_done = self.already_done[negative_length:]
示例12: __init__
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class Client:
"""
This is the chat client class
"""
def __init__(self, host, server_port):
"""
This method is run when creating a new Client object
"""
# Set up the socket connection to the server
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.msgParser = None
self.host = host
self.server_port = server_port
self.run()
def run(self):
# Initiate the connection to the server
self.connection.connect((self.host, self.server_port))
self.msgParser = MessageParser()
msgReceiver = MessageReceiver(self, self.connection)
msgReceiver.start()
print("INSTRUCTIONS\nUser must login first - type 'login <username>'\ntype 'help' for list over available commands\n\n")
while self.connection:
userinput = raw_input()
if userinput == 'logout':
self.disconnect()
elif userinput == 'exit':
exit()
else:
self.send_payload(userinput)
def disconnect(self):
print("Disconnecting client...")
self.send_payload('logout')
def receive_message(self, message):
print(self.msgParser.parse(message))
def send_payload(self, data):
request = None
if data.startswith("login"):
request = {'request' : 'login', 'content' : data[6:] }
elif data.startswith("logout"):
request = { 'request' : 'logout', 'content' : None}
elif data.startswith("msg"):
request = {'request' : 'message', 'content' : data[3:]}
elif data.startswith("names"):
request = {'request' : 'names', 'content' : None}
elif data.startswith("help"):
request = {'request' : 'help', 'content' : None }
else:
print("did not recognize command")
if request:
self.connection.sendall(json.dumps(request))
示例13: __init__
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class Client:
"""
This is the chat client class
"""
def __init__(self, host, server_port):
"""
This method is run when creating a new Client object
"""
# Set up the socket connection to the server
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = host
self.server_port = server_port
self.userLoggedIn = False
self.messageReceiver = MessageReceiver(self, self.connection) # is a thread by itself.
self.userInput = UserInput(self) # is a thread by itself.
self.parser = MessageParser(self)
self.run()
def run(self):
# Initiate the connection to the server
try:
self.connection.connect((self.host, self.server_port))
except:
print "No connection to the server were established. Exiting."
sys.exit()
self.messageReceiver.start() # start the thread
self.userInput.start() # start the thread
print "Client Ready. Please type command. type 'help' to view server commands."
def disconnect(self):
self.connection.close()
print "Server disconnected"
self.userInput.kill()
sys.exit()
pass
def receive_message(self, message):
parsed_message = self.parser.parse(message)
print parsed_message
def send_payload(self, data):
json = self.parser.encode(data)
self.connection.send(json)
pass
示例14: __init__
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class Client:
"""
This is the chat client class
"""
def __init__(self, host, server_port):
"""
This method is run when creating a new Client object
"""
# Set up the socket connection to the server
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = host
self.server_port = server_port
self.run()
self.messageReciever = MessageReceiver(self,self.connection)
self.messageParser = MessageParser()
self.chatClient()
def run(self):
# Initiate the connection to the server
self.connection.connect((self.host, self.server_port))
def disconnect(self):
self.connection.close()
def recieve_message(self, message):
messageAsString = self.messageParser.parse(message)
print(messageAsString)
def send_payload(self, data):
self.connection.send(data) #This assumes that "data" already is in JSON format
def messageToPayload(self, message):
# Converting user input to JSON format. Done in many steps to make the logic transparent
splitMessage = message.split(None, 1) #Separating request and content
request = splitMessage[0] if len(splitMessage) > 0 else None
content = splitMessage[1] if len(splitMessage) > 1 else None
payloadAsDictionary = {'request' : request,'content' : content}
payload = json.dumps(payloadAsDictionary)
return payload
def chatClient(self):
while True:
userInput = raw_input()
payload = self.messageToPayload(userInput)
self.send_payload(payload)
示例15: Client
# 需要导入模块: from MessageParser import MessageParser [as 别名]
# 或者: from MessageParser.MessageParser import parse [as 别名]
class Client():
def __init__(self, host, server_port):
"""
This method is run when creating a new Client object
"""
self.host = 'localhost'
self.server_Port = 1337
# Set up the socket connection to the server
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.receiver = None
self.myParser = MessageParser()
# TODO: Finish init process with necessary code
self.run()
def run(self):
self.connection.connect((self.host, self.server_Port))
self.receiver = MessageReceiver(self, self.connection)
print "Give user input to the chat client."
self.take_input()
def receive_message(self, message):
msg = (self.myParser.parse(message))
if msg is not None:
print msg
def send_payload(self, data):
self.connection.send(data)
def take_input(self):
userinput = raw_input()
words = userinput.split(' ', 1)
if len(words) == 2:
message_as_dict = {'request': words[0], 'content': words[1]}
else:
message_as_dict = {'request': words[0], 'content': None}
message_as_json = json.dumps(message_as_dict)
self.send_payload(message_as_json)
self.take_input()