imaginaryfriend/src/domain/message.py

76 lines
2.5 KiB
Python
Raw Normal View History

2016-11-10 15:21:08 +01:00
import random
2016-11-12 23:55:48 +01:00
from .abstract_entity import AbstractEntity
2016-11-10 15:21:08 +01:00
from src.utils import deep_get_attr
2016-11-12 16:36:23 +01:00
from src.config import config
2016-11-10 15:21:08 +01:00
2016-11-12 23:55:48 +01:00
class Message(AbstractEntity):
2016-11-12 14:56:42 +01:00
def __init__(self, chat, message):
2016-11-13 12:55:23 +01:00
super(Message, self).__init__(chat=chat, message=message)
2016-11-10 15:21:08 +01:00
if self.has_text():
self.text = message.text
self.words = self.__get_words()
else:
self.text = ''
def has_text(self):
"""Returns True if the message has text.
"""
2016-11-12 18:57:37 +01:00
return self.message.text.strip() != ''
2016-11-10 15:21:08 +01:00
def is_sticker(self):
"""Returns True if the message is a sticker.
"""
return self.message.sticker is not None
def is_editing(self):
"""Returns True if the message was edited.
"""
return self.message.edit_date is not None
def has_entities(self):
"""Returns True if the message has entities (attachments).
"""
return self.message.entities is not None
def has_anchors(self):
"""Returns True if the message contains at least one anchor from anchors config.
"""
2016-11-12 14:56:42 +01:00
anchors = config['bot']['anchors'].split(',')
2016-11-12 19:31:40 +01:00
return self.has_text() and any(a in self.message.text.split(' ') for a in anchors)
2016-11-10 15:21:08 +01:00
def is_private(self):
"""Returns True if the message is private.
"""
return self.message.chat.type == 'private'
def is_reply_to_bot(self):
"""Returns True if the message is a reply to bot.
"""
user_name = deep_get_attr(self.message, 'reply_to_message.from_user.username')
2016-11-12 14:56:42 +01:00
return user_name == config['bot']['name']
2016-11-10 15:21:08 +01:00
def is_random_answer(self):
"""Returns True if reply chance for this chat is high enough
"""
2016-11-12 14:56:42 +01:00
return random.randint(0, 100) < getattr(self.chat, 'random_chance', config['bot']['default_chance'])
2016-11-10 15:21:08 +01:00
def __get_words(self):
2016-11-12 19:53:34 +01:00
symbols = list(self.text)
2016-11-10 15:21:08 +01:00
2016-11-12 18:57:37 +01:00
def prettify(word):
lowercase_word = word.lower().strip()
2016-11-12 19:53:34 +01:00
last_symbol = lowercase_word[-1:]
if last_symbol not in config['grammar']['end_sentence']:
last_symbol = ''
pretty_word = lowercase_word.strip(config['grammar']['all']) + last_symbol
2016-11-12 18:57:37 +01:00
return pretty_word if pretty_word != '' and len(pretty_word) > 2 else lowercase_word
2016-11-10 15:21:08 +01:00
for entity in self.message.entities:
2016-11-12 19:53:34 +01:00
symbols[entity.offset:entity.length] = ' ' * entity.length
2016-11-10 15:21:08 +01:00
2016-11-12 19:53:34 +01:00
return list(filter(None, map(prettify, ''.join(symbols).split(' '))))