def __init__(self, channel: 'WeChatChannel'): self.channel: 'WeChatChannel' = channel self.logger: logging.Logger = logging.getLogger(__name__) # noinspection PyProtectedMember self._ = self.channel._ self.MISSING_GROUP: GroupChat = GroupChat( channel=self.channel, uid=ChatID("__error_group__"), name=self._("Group Missing") ) self.MISSING_CHAT: PrivateChat = PrivateChat( channel=self.channel, uid=ChatID("__error_chat__"), name=self._("Chat Missing") ) self.efb_chat_objs: Dict[str, Chat] = {} # Cached Chat objects. Key: tuple(chat PUID, group PUID or None) # Load system chats self.system_chats: List[Chat] = [] for i in channel.flag('system_chats_to_include'): self.system_chats.append( self.wxpy_chat_to_efb_chat( wxpy.Chat( wxpy.utils.wrap_user_name(i), self.bot ) ) )
def test_chat_manager_update_chat_obj(chat_manager, slave): chat = PrivateChat(channel=slave, uid="unique_id", name="Chat name") chat_manager.compound_enrol(chat) chat.alias = "Alias" assert chat_manager.get_chat(chat.module_id, chat.uid).alias != chat.alias chat_manager.update_chat_obj(chat) assert chat_manager.get_chat(chat.module_id, chat.uid).alias == chat.alias
def __init__(self, instance_id=None): super().__init__(instance_id) self.alice = PrivateChat(channel=self, name="Alice", uid="alice") self.bob = PrivateChat(channel=self, name="Bob", alias="Little bobby", uid="bob") self.wonderland = GroupChat(channel=self, name="Wonderland", uid="wonderland001") self.wonderland.add_member(name="bob", alias="Bob James", uid="bob") self.carol = self.wonderland.add_member(name="Carol", uid="carol") self.dave = self.wonderland.add_member( name="デブ", uid="dave") # Nah, that's a joke self.chats: List[Chat] = [self.alice, self.bob, self.wonderland]
def test_verify_valid_chat_middleware(middleware): chat = PrivateChat( middleware=middleware, uid="00001", name="Chat", alias="chaT" ) chat.verify()
def test_verify_valid_chat(slave_channel): chat = PrivateChat( channel=slave_channel, uid="00001", name="Chat", alias="chaT" ) chat.verify()
def test_private_other(slave_channel): chat = PrivateChat(channel=slave_channel, name="__name__", alias="__alias__", uid="__id__") assert isinstance(chat.other, ChatMember) assert not isinstance(chat.other, SelfChatMember) assert not isinstance(chat.other, SystemChatMember) assert chat.other in chat.members assert chat.name == chat.other.name assert chat.alias == chat.other.alias assert chat.uid == chat.other.uid
def build_efb_chat_as_private(private: EFBPrivateChat) -> PrivateChat: """ Build EFB PrivateChat object from EFBPrivateChat :return: GroupChat from group_id :param private: EFBPrivateChat object, see CustomTypes.py """ efb_chat: PrivateChat = PrivateChat(channel=ChatMgr.slave_channel, **private) return efb_chat
def test_copy(slave_channel): chat = PrivateChat( channel=slave_channel, uid="00001", name="Chat", alias="chaT" ) copy = chat.copy() assert chat == copy assert chat is not copy
def test_pickle(slave_channel): chat = PrivateChat( channel=slave_channel, uid="00001", name="Chat", alias="chaT" ) chat_dup = pickle.loads(pickle.dumps(chat)) for attr in ("module_name", "module_id", "channel_emoji", "name", "alias", "uid"): assert getattr(chat, attr) == getattr(chat_dup, attr)
def make_efb_chat_obj(self, diag) -> Chat: if isinstance(diag.entity, TgUser): return PrivateChat(channel=self, name=diag.name, uid=str(diag.entity.id), other_is_self=diag.entity.is_self) if isinstance(diag.entity, TgChat) or isinstance( diag.entity, TgChannel): return GroupChat(channel=self, name=diag.name, uid=str(diag.entity.id))
def test_properties(slave_channel): chat = PrivateChat( channel=slave_channel, uid="__id__", name="__name__" ) assert chat.display_name == chat.name assert chat.long_name == chat.name chat.alias = "__alias__" assert chat.display_name == chat.alias assert chat.name in chat.long_name assert chat.alias in chat.long_name
def __init__(self, channel: 'QQMessengerChannel'): self.channel: 'QQMessengerChannel' = channel self.logger: logging.Logger = logging.getLogger(__name__) self.MISSING_GROUP: GroupChat = GroupChat( channel=self.channel, uid=ChatID("__error_group__"), name="Group Missing") self.MISSING_CHAT: PrivateChat = PrivateChat( channel=self.channel, uid=ChatID("__error_chat__"), name="Chat Missing")
def build_efb_chat_as_private(self, context): uid = context['user_id'] if 'nickname' not in context: i: dict = self.channel.QQClient.get_stranger_info(uid) chat_name = "" if i: chat_name = i['nickname'] else: chat_name = context['nickname'] efb_chat = PrivateChat( channel=self.channel, uid='private' + '_' + str(uid), name=str(chat_name), alias=None if 'alias' not in context else str(context['alias'])) return efb_chat
def build_chat_by_thread_obj(self, thread: Thread) -> Chat: vendor_specific = { "chat_type": thread.type.name.capitalize(), "profile_picture_url": thread.photo, } chat: Chat if thread.uid == self.client.uid: chat = PrivateChat(channel=self.channel, uid=thread.uid, other_is_self=True) chat.name = chat.self.name # type: ignore elif isinstance(thread, User): chat = PrivateChat(channel=self.channel, name=thread.name, uid=ChatID(thread.uid), alias=thread.own_nickname or thread.nickname, vendor_specific=vendor_specific) elif isinstance(thread, Page): desc = self._("{subtitle}\n{category} in {city}\n" "Likes: {likes}\n{url}").format( subtitle=thread.sub_title, category=thread.category, city=thread.city, likes=thread.likes, url=thread.url) chat = PrivateChat(channel=self.channel, name=thread.name, uid=ChatID(thread.uid), description=desc, vendor_specific=vendor_specific) elif isinstance(thread, Group): name = thread.name or "" group = GroupChat(channel=self.channel, name=name, uid=ChatID(thread.uid), vendor_specific=vendor_specific) participant_ids = thread.participants - {self.client.uid} try: participants: Dict[ThreadID, User] = self.client.fetchThreadInfo( *participant_ids) for i in participant_ids: member = participants[i] alias = member.own_nickname or member.nickname or None if thread.nicknames and i in thread.nicknames: alias = thread.nicknames[str(i)] or None group.add_member(name=member.name, alias=alias, uid=ChatID(i)) except FBchatException: self.logger.exception( "Error occurred while building chat members.") for i in participant_ids: group.add_member(name=str(i), uid=ChatID(i)) if thread.name is None: names = sorted(i.name for i in group.members) # TRANSLATORS: separation symbol between member names when group name is not provided. name = self._(", ").join(names[:3]) if len(names) > 3: extras = len(names) - 3 name += self.ngettext(", and {number} more", ", and {number} more", extras).format(number=extras) group.name = name chat = group else: chat = SystemChat(channel=self.channel, name=thread.name, uid=ChatID(thread.uid), vendor_specific=vendor_specific) if chat.self: chat.self.uid = self.client.uid return chat
def test_generate_with_channel(slave_channel): chat = PrivateChat(channel=slave_channel, uid="chat_id") assert chat.module_id == slave_channel.channel_id assert chat.module_name == slave_channel.channel_name assert chat.channel_emoji == slave_channel.channel_emoji
def wxpy_chat_to_efb_chat(self, chat: wxpy.Chat) -> Chat: # self.logger.debug("Converting WXPY chat %r, %sin recursive mode", chat, '' if recursive else 'not ') # self.logger.debug("WXPY chat with ID: %s, name: %s, alias: %s;", chat.puid, chat.nick_name, chat.alias) if chat is None: return self.MISSING_USER cache_key = chat.puid chat_name, chat_alias = self.get_name_alias(chat) cached_obj: Optional[Chat] = None if cache_key in self.efb_chat_objs: cached_obj = self.efb_chat_objs[cache_key] if chat_name == cached_obj.name and chat_alias == cached_obj.alias: return cached_obj # if chat name or alias changes, update cache efb_chat: Chat chat_id = ChatID(chat.puid or f"__invalid_{uuid4()}__") if cached_obj: efb_chat = cached_obj efb_chat.uid = chat_id efb_chat.name = chat_name efb_chat.alias = chat_alias efb_chat.vendor_specific = {'is_mp': isinstance(chat, wxpy.MP)} if isinstance(chat, wxpy.Group): # Update members if necessary remote_puids = {i.puid for i in chat.members} local_ids = {i.uid for i in efb_chat.members if not isinstance(i, SelfChatMember)} # Add missing members missing_puids = remote_puids - local_ids for member in chat.members: if member.puid in missing_puids: member_name, member_alias = self.get_name_alias(member) efb_chat.add_member(name=member_name, alias=member_alias, uid=member.puid, vendor_specific={'is_mp': False}) elif chat == chat.bot.self: efb_chat = PrivateChat(channel=self.channel, uid=chat_id, name=chat_name, alias=chat_alias, vendor_specific={'is_mp': True}, other_is_self=True) elif isinstance(chat, wxpy.Group): efb_chat = GroupChat(channel=self.channel, uid=chat_id, name=chat_name, alias=chat_alias, vendor_specific={'is_mp': False}) for i in chat.members: if i.user_name == self.bot.self.user_name: continue member_name, member_alias = self.get_name_alias(i) efb_chat.add_member(name=member_name, alias=member_alias, uid=i.puid, vendor_specific={'is_mp': False}) elif isinstance(chat, wxpy.MP): efb_chat = PrivateChat(channel=self.channel, uid=chat_id, name=chat_name, alias=chat_alias, vendor_specific={'is_mp': True}) elif isinstance(chat, wxpy.User): efb_chat = PrivateChat(channel=self.channel, uid=chat_id, name=chat_name, alias=chat_alias, vendor_specific={'is_mp': False}) else: efb_chat = SystemChat(channel=self.channel, uid=chat_id, name=chat_name, alias=chat_alias, vendor_specific={'is_mp': False}) efb_chat.vendor_specific.update(self.generate_vendor_specific(chat)) if efb_chat.vendor_specific.get('is_muted', False): efb_chat.notification = ChatNotificationState.MENTIONS self.efb_chat_objs[cache_key] = efb_chat return efb_chat
def test_generate_with_middleware(middleware): chat = PrivateChat(middleware=middleware, uid="chat_id") assert chat.module_id == middleware.middleware_id assert chat.module_name == middleware.middleware_name
def test_verify_missing_uid(slave_channel): with pytest.raises(AssertionError): chat = PrivateChat( channel=slave_channel, name="Chat") chat.verify()
def __init__(self, instance_id: InstanceID = None): super().__init__(instance_id) # For test self.chat: PrivateChat = PrivateChat( channel=self, name='Echo Message', uid=ChatID('echo_chat')) self.condition: Optional[Condition] = None
def generate_chats(self): """Generate a list of chats per the chat templates, and categorise them accordingly. """ self.chats: List[Chat] = [] self.chats_by_chat_type: Dict[ChatTypeName, List[Chat]] = { 'PrivateChat': [], 'GroupChat': [], 'SystemChat': [], } self.chats_by_notification_state: Dict[ ChatNotificationState, List[Chat]] = { ChatNotificationState.ALL: [], ChatNotificationState.MENTIONS: [], ChatNotificationState.NONE: [], } self.chats_by_profile_picture: Dict[bool, List[Chat]] = { True: [], False: [] } self.chats_by_alias: Dict[bool, List[Chat]] = {True: [], False: []} for name, chat_type, notification, avatar, alias in self.__chat_templates: chat = chat_type(channel=self, name=name, alias=alias, uid=ChatID( self.CHAT_ID_FORMAT.format(hash=hash(name))), notification=notification) self.__picture_dict[chat.uid] = avatar if chat_type == GroupChat: self.fill_group(chat) self.chats_by_chat_type[chat_type.__name__].append(chat) self.chats_by_notification_state[notification].append(chat) self.chats_by_profile_picture[avatar is not None].append(chat) self.chats_by_alias[alias is not None].append(chat) self.chats.append(chat) name = "Unknown Chat" self.unknown_chat: PrivateChat = PrivateChat( channel=self, name=name, alias="不知道", uid=ChatID(self.CHAT_ID_FORMAT.format(hash=hash(name))), notification=ChatNotificationState.ALL) name = "Unknown Chat @ unknown channel" self.unknown_channel: PrivateChat = PrivateChat( module_id="__this_is_not_a_channel__", module_name="Unknown Channel", channel_emoji="‼️", name=name, alias="知らんでぇ", uid=ChatID(self.CHAT_ID_FORMAT.format(hash=hash(name))), notification=ChatNotificationState.ALL) name = "backup_chat" self.backup_chat: PrivateChat = PrivateChat( channel=self, name=name, uid=ChatID(self.CHAT_ID_FORMAT.format(hash=hash(name))), notification=ChatNotificationState.ALL) name = "backup_member" self.backup_member: ChatMember = ChatMember( self.chats_by_chat_type['GroupChat'][0], name=name, uid=ChatID(self.CHAT_ID_FORMAT.format(hash=hash(name))))