Skip to content

Instantly share code, notes, and snippets.

@Acapla
Last active August 29, 2015 14:02
Show Gist options
  • Save Acapla/5a4ef760463a4ddfde51 to your computer and use it in GitHub Desktop.
Save Acapla/5a4ef760463a4ddfde51 to your computer and use it in GitHub Desktop.
a message class for chat potentially support hyperlink
import yaml
class Message():
__start_mark = '{'
__end_mark = '}'
__item_tag = 'item'
__order_tag = 'order'
__hyperlink_types = [__order_tag, __item_tag]
def __init__(self):
self.content = ''
def to_yaml(self):
return yaml.dump(self.__dict__)
@staticmethod
def from_yaml(dumped):
message = Message()
for k, v in yaml.safe_load(dumped).items():
setattr(message, k, v)
return message
def add_plain_message(self, message):
for c in message:
self.content += c
if c == Message.__start_mark:
self.content += c
if c == Message.__end_mark:
self.content += c
def __add_hyperlink_message(self, message, hyperlink_type):
if hyperlink_type not in Message.__hyperlink_types:
return
self.content += Message.__start_mark
self.add_plain_message(hyperlink_type)
self.content += Message.__end_mark
attr = getattr(self, hyperlink_type, None)
if attr is None:
setattr(self, hyperlink_type, [message])
else:
attr.append(message)
def add_item_message(self, message):
self.__add_hyperlink_message(message, Message.__item_tag)
def add_order_message(self, message):
self.__add_hyperlink_message(message, Message.__order_tag)
def Test():
message = Message()
keyboard_inputs = [
'this is a message.',
'item: here is an item.',
'plus a weird me{s}}s{{a}ge.',
'item: here is another item.',
'order: here is an order.',
'exit',
]
for keyboard_input in keyboard_inputs:
if keyboard_input == "exit":
break
elif keyboard_input.find('item') >= 0:
message.add_item_message(keyboard_input)
elif keyboard_input.find('order') >= 0:
message.add_order_message(keyboard_input)
else:
message.add_plain_message(keyboard_input)
dumped = message.to_yaml()
print(dumped)
message = Message.from_yaml(dumped)
print(message.__dict__)
Test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment