Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from logging import getLogger
from ehforwarderbot import EFBChannel, EFBMsg, EFBStatus, ChannelType, MsgType, coordinator, EFBChat
from ehforwarderbot.message import EFBMsgLinkAttribute, EFBMsgLocationAttribute
from ehforwarderbot.status import EFBMessageRemoval
from ehforwarderbot.types import ModuleID, MessageID
from ehforwarderbot.types import ChatID
class MockMasterChannel(EFBChannel):
channel_name: str = "Mock Master"
channel_emoji: str = "➕"
channel_id: ModuleID = ModuleID("tests.mocks.master.MockMasterChannel")
channel_type: ChannelType = ChannelType.Master
supported_message_types: Set[MsgType] = {MsgType.Text, MsgType.Link}
__version__: str = '0.0.1'
logger = getLogger(channel_id)
polling = threading.Event()
def poll(self):
self.polling.wait()
def send_status(self, status: EFBStatus):
self.logger.debug("Received status: %r", status)
def send_message(self, msg: EFBMsg) -> EFBMsg:
self.logger.debug("Received message: %r", msg)
return msg
from ehforwarderbot.status import MessageRemoval, ReactToMessage, MessageReactionsUpdate, ChatUpdates, \
MemberUpdates
from ehforwarderbot.types import ModuleID, ChatID, MessageID, ReactionName, Reactions
from ehforwarderbot.utils import extra
_T = TypeVar("_T")
ChatTypeName = Literal['PrivateChat', 'GroupChat', 'SystemChat']
class MockSlaveChannel(SlaveChannel):
channel_name: str = "Mock Slave"
channel_emoji: str = "➖"
channel_id: ModuleID = ModuleID("tests.mocks.slave")
supported_message_types: Set[MsgType] = {
MsgType.Text, MsgType.Image, MsgType.Voice, MsgType.Animation,
MsgType.Video, MsgType.File, MsgType.Location, MsgType.Link,
MsgType.Sticker, MsgType.Status, MsgType.Unsupported
}
__version__: str = '0.0.2'
logger = getLogger(channel_id)
CHAT_ID_FORMAT = "__chat_{hash}__"
polling = threading.Event()
__picture_dict: Dict[str, str] = {}
suggested_reactions: List[ReactionName] = [
ReactionName("R0"),
ReactionName("R1"),
def compare_message(self, tg_msg: Message, efb_msg: EFBMessage) -> None:
assert efb_msg.type == MsgType.Text
media = tg_msg.media
assert isinstance(media, MessageMediaDice)
assert str(media.emoticon) in efb_msg.text
assert str(media.value) in efb_msg.text
def send_text_message(self, chat: Chat,
author: Optional[ChatMember] = None,
target: Optional[Message] = None,
reactions: bool = False,
commands: bool = False,
substitution: bool = False,
unsupported: bool = False) -> Message:
"""Send a text message to master channel.
Leave author blank to use “self” of the chat.
Returns the message sent.
"""
author = author or chat.self
uid = f"__msg_id_{uuid4()}__"
msg_type = MsgType.Unsupported if unsupported else MsgType.Text
message = Message(
chat=chat,
author=author,
type=msg_type,
target=target,
uid=uid,
text=f"Content of {msg_type.name} message with ID {uid}",
deliver_to=coordinator.master
)
message = self.attach_message_properties(message, reactions, commands, substitution)
coordinator.send_message(message)
self.messages_sent[uid] = message
return message
self.bot.edit_message_text(text=txt,
chat_id=tg_chat_id,
message_id=tg_msg_id)
update.callback_query.answer()
return ConversationHandler.END
callback_idx = int(callback_uid.split()[1])
chat: ETMChatType = self.msg_storage[(tg_chat_id, tg_msg_id)].chats[callback_idx]
chat_display_name = chat.full_name
self.msg_storage.pop((tg_chat_id, tg_msg_id), None)
txt = self._("Reply to this message to chat with {0}.").format(chat_display_name)
chat_head_etm = ETMMsg()
chat_head_etm.chat = chat
chat_head_etm.author = chat.self or chat.add_self()
chat_head_etm.uid = MessageID("__chathead__")
chat_head_etm.type = MsgType.Text
chat_head_etm.text = txt
chat_head_etm.type_telegram = TGMsgType.Text
chat_head_etm.deliver_to = self.channel
self.db.add_or_update_message_log(chat_head_etm, update.effective_message)
self.bot.edit_message_text(text=txt, chat_id=tg_chat_id, message_id=tg_msg_id)
update.callback_query.answer()
return ConversationHandler.END
def qq_text_simple_wrapper(self, text: str, ats: dict): # This cute function only accepts string!
efb_msg = Message()
efb_msg.type = MsgType.Text
efb_msg.text = text
if ats: # This is used to replace specific text with @blahblah
# And Milkice really requires a brain check
efb_msg.substitutions = Substitutions(ats)
return efb_msg
def send_msg_to_master(self, context):
self.logger.debug(repr(context))
if not getattr(coordinator, 'master', None): # Master Channel not initialized
raise Exception(context['message'])
chat = self.chat_manager.build_efb_chat_as_system_user(context)
try:
author = chat.get_member(SystemChatMember.SYSTEM_ID)
except KeyError:
author = chat.add_system_member()
msg = Message(
uid="__{context[uid_prefix]}__.{uni_id}".format(context=context,
uni_id=str(int(time.time()))),
type=MsgType.Text,
chat=chat,
author=author,
deliver_to=coordinator.master
)
if 'message' in context:
msg.text = context['message']
if 'commands' in context:
msg.commands = MessageCommands(context['commands'])
coordinator.send_message(msg)
url: str, suffix: str = "") -> Message:
if url:
efb_msg = Message(
type=MsgType.Link,
text=suffix,
attributes=LinkAttribute(
title=title,
description=description,
image=image,
url=url
)
)
else:
efb_msg = Message(
type=MsgType.Text,
text=f"{title}\n{description}",
)
if suffix:
efb_msg.text += f"\n{suffix}"
if image:
efb_msg.text += f"\n\n{image}"
return efb_msg
def wechat_video_msg(self, msg: wxpy.Message) -> Message:
efb_msg = Message(type=MsgType.Video)
try:
if msg.file_size == 0:
raise EOFError
efb_msg.path, efb_msg.mime, efb_msg.file = self.save_file(msg)
efb_msg.filename = msg.file_name
efb_msg.text = ""
except EOFError:
efb_msg.type = MsgType.Text
efb_msg.text += self._("[Failed to download the video message, please check your phone.]")
return efb_msg
class WeChatChannel(SlaveChannel):
"""
EFB Channel - WeChat Slave Channel
Based on wxpy (itchat), WeChat Web Client
Author: Eana Hufwe
"""
channel_name = "WeChat Slave"
channel_emoji = "💬"
channel_id = ModuleID('blueset.wechat')
__version__ = __version__
supported_message_types = {MsgType.Text, MsgType.Sticker, MsgType.Image,
MsgType.File, MsgType.Video, MsgType.Link, MsgType.Voice,
MsgType.Animation}
logger: logging.Logger = logging.getLogger(
"plugins.%s.WeChatChannel" % channel_id)
done_reauth: threading.Event = threading.Event()
_stop_polling_event: threading.Event = threading.Event()
config: Dict[str, Any] = dict()
bot: wxpy.Bot
# GNU Gettext Translator
translator = translation("efb_wechat_slave",
resource_filename('efb_wechat_slave', 'locale'),
fallback=True)