imaginaryfriend/src/domain/message.py

70 lines
1.9 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-12-11 18:41:40 +01:00
"""
Basic message entity
"""
2016-12-01 22:01:04 +01:00
def __init__(self, chance, message):
super(Message, self).__init__(message)
self.chance = chance
2016-12-09 20:45:50 +01:00
self.entities = message.entities
2016-12-11 18:41:40 +01:00
self.anchors = config.getlist('bot', 'anchors')
2016-11-10 15:21:08 +01:00
if self.has_text():
self.text = message.text
else:
self.text = ''
def has_text(self):
2016-12-11 18:41:40 +01:00
"""
Returns True if the message has text.
2016-11-10 15:21:08 +01:00
"""
2017-08-18 01:01:08 +02:00
return self.message.text is not None and self.message.text.strip() != ''
2016-11-10 15:21:08 +01:00
def is_sticker(self):
2016-12-11 18:41:40 +01:00
"""
Returns True if the message is a sticker.
2016-11-10 15:21:08 +01:00
"""
return self.message.sticker is not None
def has_entities(self):
2016-12-11 18:41:40 +01:00
"""
Returns True if the message has entities (attachments).
2016-11-10 15:21:08 +01:00
"""
2016-12-09 20:45:50 +01:00
return self.entities is not None
2016-11-10 15:21:08 +01:00
def has_anchors(self):
"""
2016-12-11 18:41:40 +01:00
Returns True if the message contains at least one anchor from anchors config.
"""
return self.has_text() and any(a in self.message.text.split(' ') for a in self.anchors)
2016-11-10 15:21:08 +01:00
def is_reply_to_bot(self):
2016-12-11 18:41:40 +01:00
"""
Returns True if the message is a reply to bot.
2016-11-10 15:21:08 +01:00
"""
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):
2016-12-11 18:41:40 +01:00
"""
Returns True if reply chance for this chat is high enough
2016-11-10 15:21:08 +01:00
"""
2016-12-01 22:01:04 +01:00
return random.randint(0, 100) < self.chance
2016-11-10 15:21:08 +01:00
2016-11-29 15:23:06 +01:00
def should_answer(self):
2016-12-11 18:41:40 +01:00
"""
Returns True if bot should answer to this message
:return: Should answer or not
"""
2016-11-29 15:23:06 +01:00
return self.has_anchors() \
or self.is_private() \
or self.is_reply_to_bot() \
or self.is_random_answer()