Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
os.environ['EFB_DATA_PATH'] = f
master_id = "tests.mocks.master.MockMasterChannel#instance1"
slave_ids = [
"tests.mocks.slave.MockSlaveChannel#instance1",
"tests.mocks.slave.MockSlaveChannel#instance2"
]
config = {
"master_channel": master_id,
"slave_channels": slave_ids
}
config = dump_and_load_config(config)
ehforwarderbot.__main__.init(config)
assert coordinator.master.channel_id == master_id
assert isinstance(coordinator.master, master.MockMasterChannel)
for i in slave_ids:
assert i in coordinator.slaves
assert isinstance(coordinator.slaves[i], slave.MockSlaveChannel)
"""Send a status 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()}__"
message = Message(
chat=chat,
author=author,
type=MsgType.Status,
target=target,
uid=uid,
text="",
attributes=status,
deliver_to=coordinator.master
)
coordinator.send_message(message)
self.messages_sent[uid] = message
return message
logger.log(99, "\x1b[0;37;42m %s \x1b[0m",
_("Slave channel {name} ({id}) # {instance_id} is initialized.")
.format(name=cls.channel_name, id=cls.channel_id,
instance_id=instance_id or _("Default profile")))
logger.log(99, "\x1b[0;37;46m %s \x1b[0m",
_("Initializing master {}...").format(conf['master_channel']))
instance_id = conf['master_channel'].split('#', 1)[1:]
instance_id = (instance_id and instance_id[0]) or None
module = utils.locate_module(conf['master_channel'], 'master')
coordinator.add_channel(module(instance_id=instance_id))
telemetry_set_metadata({conf['master_channel']: module.__version__})
logger.log(99, "\x1b[0;37;42m %s \x1b[0m",
_("Master channel {name} ({id}) # {instance_id} is initialized.")
.format(name=coordinator.master.channel_name,
id=coordinator.master.channel_id,
instance_id=instance_id or _("Default profile")))
logger.log(99, "\x1b[1;37;42m %s \x1b[0m", _("All channels initialized."))
for i in conf['middlewares']:
logger.log(99, "\x1b[0;37;46m %s \x1b[0m", _("Initializing middleware {}...").format(i))
cls = utils.locate_module(i, 'middleware')
telemetry_set_metadata({i: cls.__version__})
instance_id = i.split('#', 1)[1:]
instance_id = (instance_id and instance_id[0]) or None
coordinator.add_middleware(cls(instance_id=instance_id))
logger.log(99, "\x1b[0;37;42m %s \x1b[0m",
_("Middleware {name} ({id}) # {instance_id} is initialized.")
.format(name=cls.middleware_name, id=cls.middleware_id,
instance_id=instance_id or _("Default profile")))
logger.log(99, "\x1b[0;37;42m %s \x1b[0m",
_("Slave channel {name} ({id}) # {instance_id} is initialized.")
.format(name=cls.channel_name, id=cls.channel_id,
instance_id=instance_id or _("Default profile")))
logger.log(99, "\x1b[0;37;46m %s \x1b[0m",
_("Initializing master {}...").format(conf['master_channel']))
instance_id = conf['master_channel'].split('#', 1)[1:]
instance_id = (instance_id and instance_id[0]) or None
module = utils.locate_module(conf['master_channel'], 'master')
coordinator.add_channel(module(instance_id=instance_id))
telemetry_set_metadata({conf['master_channel']: module.__version__})
logger.log(99, "\x1b[0;37;42m %s \x1b[0m",
_("Master channel {name} ({id}) # {instance_id} is initialized.")
.format(name=coordinator.master.channel_name,
id=coordinator.master.channel_id,
instance_id=instance_id or _("Default profile")))
logger.log(99, "\x1b[1;37;42m %s \x1b[0m", _("All channels initialized."))
for i in conf['middlewares']:
logger.log(99, "\x1b[0;37;46m %s \x1b[0m", _("Initializing middleware {}...").format(i))
cls = utils.locate_module(i, 'middleware')
telemetry_set_metadata({i: cls.__version__})
instance_id = i.split('#', 1)[1:]
instance_id = (instance_id and instance_id[0]) or None
coordinator.add_middleware(cls(instance_id=instance_id))
logger.log(99, "\x1b[0;37;42m %s \x1b[0m",
_("Middleware {name} ({id}) # {instance_id} is initialized.")
.format(name=cls.middleware_name, id=cls.middleware_id,
instance_id=instance_id or _("Default profile")))
def send_efb_group_notice(self, context):
context['message_type'] = 'group'
self.logger.debug(repr(context))
chat = self.chat_manager.build_efb_chat_as_group(context)
try:
author = chat.get_member(SystemChatMember.SYSTEM_ID)
except KeyError:
author = chat.add_system_member()
msg = Message(
uid="__group_notice__.%s" % int(time.time()),
type=MsgType.Text,
chat=chat,
author=author,
text=context['message'],
deliver_to=coordinator.master
)
coordinator.send_message(msg)
def wrap_func(self: 'SlaveMessageManager', msg: wxpy.Message, *args, **kwargs):
logger = logging.getLogger(__name__)
logger.debug("[%s] Raw message: %r", msg.id, msg.raw)
efb_msg: Optional[Message] = func(self, msg, *args, **kwargs)
if efb_msg is None:
return
if getattr(coordinator, 'master', None) is None:
logger.debug("[%s] Dropping message as master channel is not ready yet.", efb_msg.uid)
return
efb_msg.deliver_to = coordinator.master
# Format message IDs as JSON of List[List[str]].
efb_msg.uid = MessageID(json.dumps(
[[str(getattr(msg, "id", constants.INVALID_MESSAGE_ID + str(uuid.uuid4())))]]
))
if not efb_msg.chat or not efb_msg.author:
chat, author = self.get_chat_and_author(msg)
# Do not override what's defined in the wrapped methods
efb_msg.chat = efb_msg.chat or chat
efb_msg.author = efb_msg.author or author
logger.debug("[%s] Chat: %s, Author: %s", efb_msg.uid, efb_msg.chat, efb_msg.author)
coordinator.send_message(efb_msg)
def _load_file(self):
if self.file_id:
# noinspection PyUnresolvedReferences
bot = coordinator.master.bot_manager
try:
file_meta = bot.get_file(self.file_id)
except BadRequest as e:
logger.exception("Bad request while trying to get file metadata: %s", e)
return
if not self.mime:
ext = os.path.splitext(file_meta.file_path)[1]
mime = mimetypes.guess_type(file_meta.file_path, strict=False)[0]
else:
ext = mimetypes.guess_extension(self.mime, strict=False)
mime = self.mime
file = tempfile.NamedTemporaryFile(suffix=ext)
file_meta.download(out=file)
file.seek(0)
def __setstate__(self, state: Dict[str, Any]):
from . import TelegramChannel
# Import inline to prevent cyclic import
self.__dict__.update(state)
with suppress(NameError, AttributeError):
if isinstance(coordinator.master, TelegramChannel):
self.db = coordinator.master.db
return None
# val = self.recall_msg_id_conversion.pop(recall_id)
# val[1] -= 1
# if val[1] > 0: # not all associated messages are recalled.
# return None
# else:
# efb_msg.uid = val[0]
else:
# Format message IDs as JSON of List[List[str]].
chat, author = self.get_chat_and_author(msg)
efb_msg = Message(
chat=chat, author=author,
uid=MessageID(json.dumps([[recall_id]]))
)
coordinator.send_status(MessageRemoval(source_channel=self.channel,
destination_channel=coordinator.master,
message=efb_msg))
return None
chat, _ = self.get_chat_and_author(msg)
try:
author = chat.get_member(SystemChatMember.SYSTEM_ID)
except KeyError:
author = chat.add_system_member()
if any(i in msg.text for i in self.NEW_CHAT_PATTERNS):
coordinator.send_status(ChatUpdates(
channel=self.channel,
new_chats=(chat.uid,)
))
elif any(i in msg.text for i in self.CHAT_AND_MEMBER_UPDATE_PATTERNS):
# TODO: detect actual member changes from message text
coordinator.send_status(ChatUpdates(
channel=self.channel,
def async_download_file(self, context, **kwargs):
res = download_file_from_qzone(**kwargs)
if isinstance(res, str):
context['message'] = self._("[Download] ") + res
self.send_efb_group_notice(context)
elif res is None:
pass
else:
data = {'file': res, 'filename': context['file']['name']}
context['message_type'] = 'group'
efb_msg = self.msg_decorator.qq_file_after_wrapper(data)
efb_msg.uid = str(context['user_id']) + '_' + str(uuid.uuid4()) + '_' + str(1)
efb_msg.text = 'Sent a file\n{}'.format(context['file']['name'])
efb_msg.chat = self.chat_manager.build_efb_chat_as_group(context)
efb_msg.author = self.chat_manager.build_or_get_efb_member(efb_msg.chat, context)
efb_msg.deliver_to = coordinator.master
async_send_messages_to_master(efb_msg)