Skip to content

Commit cd169db

Browse files
committed
Framework updates
- Return EFBMsg object with message UID when message is sent - Channel property: `supported_message_type` - New exception: `EFBMessageError`
1 parent e7cf414 commit cd169db

File tree

8 files changed

+70
-18
lines changed

8 files changed

+70
-18
lines changed

channel.py

+1
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ class EFBChannel:
3838
channel_id = "emptyChannel"
3939
channel_type = ChannelType.Slave
4040
queue = None
41+
supported_message_types = set()
4142

4243
def __init__(self, queue):
4344
self.queue = queue

channelExceptions.py

+4
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,7 @@ class EFBMessageNotFound(Exception):
88

99
class EFBMessageTypeNotSupported(Exception):
1010
pass
11+
12+
13+
class EFBMessageError(Exception):
14+
pass

docs/channel.md

+7
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ Type of the channel, choose between
2323
* `ChannelType.Master`
2424
* `ChannelType.Slave`
2525

26+
**supported_message_types** (`set` of `MsgType` constant)
27+
A list of supported message types to send **to** the channel.
28+
2629
**queue** (queue.Queue)
2730
Global message queue initialized by the parental `__init__` method. This queue is used to deliver messages from slave channels to the master channel.
2831

@@ -58,6 +61,10 @@ Raises:
5861
* `EFBChatNotFound`
5962
* `EFBMessageNotFound`
6063
* `EFBMessageTypeNotSupported`
64+
* `EFBMessageError`
65+
66+
Returns:
67+
The original EFBMsg object `msg` with `uid` property defined.
6168

6269
**get_chats(self)** _(for slave channels)_
6370
Returns a `list` of `dict`s for available chats in the channel. Each `dict` should be like:

docs/exceptions.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,7 @@ Raised by a slave channel when the recipient channel is not found when a message
99
Raised when an incoming message is in a type not supported by the recipient channel. Applicable to both master and slave channels.
1010

1111
## `EFBMessageNotFound`
12-
Raised when a message is trying to "direct reply" to another message which couldn't be found.
12+
Raised when a message is trying to "direct reply" to another message which couldn't be found.
13+
14+
## `EFBMessageError`
15+
Raised when a message is failed to send for any other reason.

main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
if sys.version_info.major < 3:
99
raise Exception("Python 3.x is required. Your version is %s." % sys.version)
1010

11-
__version__ = "1.2 build 20170114"
11+
__version__ = "1.2 build 20170115"
1212

1313
parser = argparse.ArgumentParser(description="EH Forwarder Bot is an extensible chat tunnel framework which allows "
1414
"users to contact people from other chat platforms, and ultimately "

plugins/eh_telegram_master/__init__.py

+35-8
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from . import db, speech
1919
from .whitelisthandler import WhitelistHandler
2020
from channel import EFBChannel, EFBMsg, MsgType, MsgSource, TargetType, ChannelType
21-
from channelExceptions import EFBChatNotFound, EFBMessageTypeNotSupported
21+
from channelExceptions import EFBChatNotFound, EFBMessageTypeNotSupported, EFBMessageError
2222
from .msgType import get_msg_type, TGMsgType
2323
from moviepy.editor import VideoFileClip
2424

@@ -65,6 +65,9 @@ class TelegramChannel(EFBChannel):
6565
channel_emoji = "✈"
6666
channel_id = "eh_telegram_master"
6767
channel_type = ChannelType.Master
68+
supported_message_types = {MsgType.Text, MsgType.File, MsgType.Audio,
69+
MsgType.Command, MsgType.Image, MsgType.Link, MsgType.Location,
70+
MsgType.Sticker, MsgType.Video}
6871

6972
# Data
7073
slaves = None
@@ -73,6 +76,19 @@ class TelegramChannel(EFBChannel):
7376
msg_storage = {}
7477
me = None
7578

79+
# Constants
80+
TYPE_DICT = {
81+
TGMsgType.Text: MsgType.Text,
82+
TGMsgType.Audio: MsgType.Audio,
83+
TGMsgType.Document: MsgType.File,
84+
TGMsgType.Photo: MsgType.Image,
85+
TGMsgType.Sticker: MsgType.Sticker,
86+
TGMsgType.Video: MsgType.Video,
87+
TGMsgType.Voice: MsgType.Audio,
88+
TGMsgType.Location: MsgType.Location,
89+
TGMsgType.Venue: MsgType.Location,
90+
}
91+
7692
def __init__(self, queue, slaves):
7793
"""
7894
Initialization.
@@ -269,7 +285,7 @@ def process_msg(self, msg):
269285
os.remove(msg.path)
270286
return self.bot.bot.sendMessage(tg_dest, msg_template % ("Error: Empty %s received. (MS01)" % msg.type))
271287
if not msg.text:
272-
if MsgType.Image:
288+
if msg.type == MsgType.Image:
273289
msg.text = "sent a picture."
274290
elif msg.type == MsgType.Sticker:
275291
msg.text = "sent a sticker."
@@ -342,7 +358,8 @@ def process_msg(self, msg):
342358
"slave_origin_uid": "%s.%s" % (msg.channel_id, msg.origin['uid']),
343359
"slave_origin_display_name": msg.origin['alias'],
344360
"slave_member_uid": msg.member['uid'],
345-
"slave_member_display_name": msg.member['alias']}
361+
"slave_member_display_name": msg.member['alias'],
362+
"slave_message_uid": msg.uid}
346363
if tg_chat_assoced and append_last_msg:
347364
msg_log['update'] = True
348365
db.add_msg_log(**msg_log)
@@ -801,6 +818,14 @@ def msg(self, bot, update):
801818
# Type specific stuff
802819
self.logger.debug("Msg type: %s", mtype)
803820

821+
if self.TYPE_DICT.get(mtype, None):
822+
m.type = self.TYPE_DICT[mtype]
823+
else:
824+
raise EFBMessageTypeNotSupported()
825+
826+
if m.type not in self.slaves[channel].supported_message_types:
827+
raise EFBMessageTypeNotSupported()
828+
804829
if mtype == TGMsgType.Text:
805830
m.type = MsgType.Text
806831
m.text = update.message.text
@@ -812,12 +837,12 @@ def msg(self, bot, update):
812837
m.file = open(m.path, "rb")
813838
elif mtype == TGMsgType.Sticker:
814839
m.type = MsgType.Sticker
815-
m.text = update.message.sticker.emoji
840+
m.text = ""
816841
tg_file_id = update.message.sticker.file_id
817842
m.path, m.mime = self._download_file(update.message, tg_file_id, m.type)
818843
m.file = open(m.path, "rb")
819844
elif mtype == TGMsgType.Document:
820-
m.text = update.message.document.file_name
845+
m.text = update.message.document.file_name + "\n" + update.message.caption
821846
tg_file_id = update.message.document.file_id
822847
self.logger.debug("tg: Document file received")
823848
if update.message.document.mime_type == "video/mp4":
@@ -830,18 +855,18 @@ def msg(self, bot, update):
830855
m.file = open(m.path, "rb")
831856
elif mtype == TGMsgType.Video:
832857
m.type = MsgType.Video
833-
m.text = update.message.document.file_name
858+
m.text = update.message.caption
834859
tg_file_id = update.message.document.file_id
835860
m.path, m.mime = self._download_file(update.message, tg_file_id, m.type)
836861
m.file = open(m.path, "rb")
837862
elif mtype == TGMsgType.Audio:
838863
m.type = MsgType.Audio
839-
m.text = "%s - %s" % (update.message.audio.title, update.message.audio.perfomer)
864+
m.text = "%s - %s\n%s" % (update.message.audio.title, update.message.audio.perfomer, update.message.caption)
840865
tg_file_id = update.message.audio.file_id
841866
m.path, m.mime = self._download_file(update.message, tg_file_id, m.type)
842867
elif mtype == TGMsgType.Voice:
843868
m.type = MsgType.Audio
844-
m.text = ""
869+
m.text = update.message.caption
845870
tg_file_id = update.message.voice.file_id
846871
m.path, m.mime = self._download_file(update.message, tg_file_id, m.type)
847872
elif mtype == TGMsgType.Location:
@@ -866,6 +891,8 @@ def msg(self, bot, update):
866891
return self._reply_error(bot, update, "Internal error: Chat not found in channel. (CN01)")
867892
except EFBMessageTypeNotSupported:
868893
return self._reply_error(bot, update, "Message type not supported. (MN01)")
894+
except EFBMessageError as e:
895+
return self._reply_error(bot, update, "Message is not sent. (MN01)\n\n%s" % str(e))
869896

870897
def _download_file(self, tg_msg, file_id, msg_type):
871898
"""

plugins/eh_telegram_master/db.py

+3
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ def add_msg_log(**kwargs):
163163
slave_origin_display_name = kwargs.get('slave_origin_display_name', None)
164164
slave_member_uid = kwargs.get('slave_member_uid', None)
165165
slave_member_display_name = kwargs.get('slave_member_display_name', None)
166+
slave_message_uid = kwargs.get('slave_message_uid', None)
166167
update = kwargs.get('update', False)
167168
if update:
168169
msg_log = MsgLog.get(MsgLog.master_msg_id == master_msg_id)
@@ -173,10 +174,12 @@ def add_msg_log(**kwargs):
173174
msg_log.slave_origin_display_name = slave_origin_display_name
174175
msg_log.slave_member_uid = slave_member_uid
175176
msg_log.slave_member_display_name = slave_member_display_name
177+
# msg_log.slave_message_uid = slave_message_uid
176178
msg_log.save()
177179
return msg_log
178180
else:
179181
return MsgLog.create(master_msg_id=master_msg_id,
182+
# slave_message_uid=slave_message_uid
180183
text=text,
181184
slave_origin_uid=slave_origin_uid,
182185
msg_type=msg_type,

plugins/eh_wechat_slave.py

+15-8
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
import config
1515
from channel import EFBChannel, EFBMsg, MsgType, MsgSource, TargetType, ChannelType
16-
from channelExceptions import EFBMessageTypeNotSupported
16+
from channelExceptions import EFBMessageTypeNotSupported, EFBMessageError
1717
from utils import extra
1818

1919

@@ -94,6 +94,7 @@ class WeChatChannel(EFBChannel):
9494
channel_emoji = "💬"
9595
channel_id = "eh_wechat_slave"
9696
channel_type = ChannelType.Slave
97+
supported_message_types = {MsgType.Text, MsgType.Sticker, MsgType.Image, MsgType.File, MsgType.Video, MsgType.Link}
9798
users = {}
9899
logger = logging.getLogger("plugins.eh_wechat_slave.WeChatChannel")
99100

@@ -575,20 +576,18 @@ def send_message(self, msg):
575576
"Type: %s\n"
576577
"Text: %s"
577578
% (msg.destination['uid'], UserName, msg.destination['name'], msg.type, msg.text))
578-
if msg.type == MsgType.Text:
579+
if msg.type in [MsgType.Text, MsgType.Link]:
579580
if msg.target:
580581
if msg.target['type'] == TargetType.Member:
581582
msg.text = "@%s\u2005 %s" % (msg.target['target'].member['alias'], msg.text)
582583
elif msg.target['type'] == TargetType.Message:
583584
msg.text = "@%s\u2005 「%s」\n\n%s" % (msg.target['target'].member['alias'], msg.target['target'].text, msg.text)
584585
r = itchat.send(msg.text, UserName)
585-
return r
586586
elif msg.type in [MsgType.Image, MsgType.Sticker]:
587587
self.logger.info("Image/Sticker %s", msg.type)
588588
if msg.mime in ["image/gif", "image/jpeg"]:
589589
r = itchat.send_image(msg.path, UserName)
590590
os.remove(msg.path)
591-
return r
592591
else: # Convert Image format
593592
img = Image.open(msg.path)
594593
try:
@@ -601,21 +600,29 @@ def send_message(self, msg):
601600
img.save("%s.gif" % msg.path, transparency=255)
602601
msg.path = "%s.gif" % msg.path
603602
self.logger.info('Image converted to GIF: %s', msg.path)
604-
self.logger.info('Sending Image...')
605-
r = itchat.send_image(msg.path, UserName)
603+
self.logger.info('Sending Image...')
604+
r = itchat.send_image(msg.path, UserName)
605+
if msg.text:
606+
itchat.send_msg(msg.text, UserName)
606607
self.logger.info('Image sent with result %s', r)
607608
os.remove(msg.path)
608609
if not msg.mime == "image/gif":
609610
os.remove(msg.path[:-4])
610-
return r
611611
elif msg.type in [MsgType.File, MsgType.Video]:
612612
self.logger.info("Sending file to WeChat\nFileName: %s\nPath: %s", msg.text, msg.path)
613613
r = itchat.send_file(msg.path, UserName)
614+
if msg.text:
615+
itchat.send_msg(msg.text, UserName)
614616
os.remove(msg.path)
615-
return r
616617
else:
617618
raise EFBMessageTypeNotSupported()
618619

620+
if r.get('BaseResponse', []).get('Ret', -1) != 0:
621+
raise EFBMessageError(str(r))
622+
else:
623+
msg.uid = r.get("MsgId", None)
624+
return msg
625+
619626
# Extra functions
620627

621628
@extra(name="Show chat list",

0 commit comments

Comments
 (0)