Skip to content

Commit deed5bb

Browse files
committed
1.4.4-dev.8 — EWS:
Add support for “Tencent News” (newsapp) messages (ehForwarderBot#21) Modified behaviour for `extra_links_on_message`.
1 parent e8d26a4 commit deed5bb

File tree

5 files changed

+90
-20
lines changed

5 files changed

+90
-20
lines changed

channel.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -242,8 +242,8 @@ class EFBMsg:
242242
'uid': 'Destination UID',
243243
}
244244
target = None
245-
uid = "Message UID"
246-
text = "Message"
245+
uid = None
246+
text = ""
247247
url = None
248248
path = None
249249
file = None

docs/EWS.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ eh_wechat_slave = {
103103
* `"alias"`: [UM] Alias of the user
104104
* `"uin"`: [UG] WeChat Unique Identifier for all chats, **Not always available**.
105105
* `extra_links_on_message` _(bool)_ [Default: `False`]
106-
List out all other messages (more than first one) for link messages with more than one link from MPS accounts.
106+
Send all links from MPS messages with multiple links as individual messages. Only the first link is sent by default.
107107
* `max_quote_length` _(int)_ [Default: `-1`]
108108
Maximum length of text for quotation messages. Set to 0 to fully disable quotation. Set to -1 to always quote full message.
109109
* `qr_reload` _(str)_ [Default: `"master_qr_code"`]

main.py

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

13-
__version__ = "1.4.4-dev.7"
13+
__version__ = "1.4.4-dev.8"
1414

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

plugins/eh_telegram_master/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -951,7 +951,7 @@ def msg(self, bot, update):
951951
m.path, m.mime = self._download_file(update.message, tg_file_id, m.type)
952952
m.file = open(m.path, "rb")
953953
elif mtype == TGMsgType.Document:
954-
m.text = update.message.document.file_name + "\n" + update.message.caption
954+
m.text = update.message.caption
955955
tg_file_id = update.message.document.file_id
956956
self.logger.debug("tg: Document file received")
957957
if update.message.document.mime_type == "video/mp4":
@@ -1033,7 +1033,7 @@ def _download_file(self, tg_msg, file_id, msg_type):
10331033
self.logger.warning("File %s with mime %s has no matching extensions.", fullpath, mime)
10341034
ext = ".jpeg" if mime == "image/jpeg" else guess_ext
10351035
os.rename(fullpath, "%s%s" % (fullpath, ext))
1036-
fullpath = "%s.%s" % (fullpath, ext)
1036+
fullpath = "%s%s" % (fullpath, ext)
10371037
return fullpath, mime
10381038

10391039
def _download_gif(self, tg_msg, file_id, msg_type):

plugins/eh_wechat_slave.py

+84-14
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,26 @@
2020

2121

2222
def incomeMsgMeta(func):
23-
def wcFunc(self, msg, isGroupChat=False):
23+
def wcFunc(self, *args, **kwargs):
24+
msg = args[0]
25+
isGroupChat = kwargs.get("isGroupChat", False)
2426
logger = logging.getLogger("plugins.%s.incomeMsgMeta" % self.channel_id)
25-
mobj = func(self, msg, isGroupChat)
27+
logger.debug("Raw message: %s" % repr(msg))
28+
mobj = func(self, *args, **kwargs)
29+
if mobj is None:
30+
return
2631
mobj.uid = msg.get("MsgId", time.time())
2732
me = msg['FromUserName'] == self.itchat.loginInfo['User']['UserName']
2833
logger.debug("me, %s", me)
2934
if me:
3035
msg['FromUserName'], msg['ToUserName'] = msg['ToUserName'], msg['FromUserName']
3136
FromUser = self.search_user(UserName=msg['FromUserName']) or \
32-
self.search_user(UserName=msg['FromUserName'], refresh=True) or \
33-
[{"NickName": "Chat not found. (UE01)", "RemarkName": "Chat not found. (UE01)", "Uin": 0}]
37+
self.search_user(UserName=msg['FromUserName'], refresh=True) or \
38+
[{"NickName": "Chat not found. (UE01)", "RemarkName": "Chat not found. (UE01)", "Uin": 0}]
3439
FromUser = FromUser[0]
3540
logger.debug("From user, %s", FromUser)
3641
if isGroupChat:
37-
logger.debug("groupchat")
42+
logger.debug("Group chat")
3843
if me:
3944
msg['ActualUserName'] = msg['ToUserName']
4045
member = {"NickName": self.itchat.loginInfo['User']['NickName'], "DisplayName": "You", "Uin": self.itchat.loginInfo['User']['Uin']}
@@ -464,9 +469,12 @@ def wcSysLog(msg):
464469

465470
@incomeMsgMeta
466471
def textMsg(self, msg, isGroupChat=False):
467-
self.logger.info("TextMsg!!!\n---")
472+
if msg['FromUserName'] == "newsapp" and msg['Content'].startswith("<mmreader>"):
473+
self.newsapp_msg(msg)
474+
return
468475
if msg['Text'].startswith("http://weixin.qq.com/cgi-bin/redirectforward?args="):
469-
return self.locationMsg(msg, isGroupChat)
476+
self.locationMsg(msg, isGroupChat)
477+
return
470478
mobj = EFBMsg(self)
471479
mobj.text = msg['Text']
472480
mobj.type = MsgType.Text
@@ -495,8 +503,8 @@ def linkMsg(self, msg, isGroupChat=False):
495503
mobj = EFBMsg(self)
496504
# parse XML
497505
itchat.utils.emoji_formatter(msg, 'Content')
498-
xmldata = msg['Content']
499-
data = xmltodict.parse(xmldata)
506+
xml_data = msg['Content']
507+
data = xmltodict.parse(xml_data)
500508
# set attributes
501509
mobj.attributes = {
502510
"title": data['msg']['appmsg']['title'],
@@ -515,10 +523,34 @@ def linkMsg(self, msg, isGroupChat=False):
515523
extra_link = data.get('msg', {}).get('appmsg', {}).get('mmreader', {}).get('category', {}).get('item', [])
516524
if type(extra_link) is list and len(extra_link):
517525
for i in extra_link:
518-
mobj.text += "🔗 %s\n%s\n%s\n🖼 %s\n\n" % (i['title'], i['digest'], i['url'], i['cover'])
526+
# mobj.text += "🔗 %s\n%s\n%s\n🖼 %s\n\n" % (i['title'], i['digest'], i['url'], i['cover'])
527+
self.raw_linkMsg(msg, i['title'], i['digest'], i['cover'], i['url'])
528+
return
519529
mobj.type = MsgType.Link
520530
return mobj
521531

532+
@incomeMsgMeta
533+
def raw_linkMsg(self, msg, title, description, image, url):
534+
mobj = EFBMsg(self)
535+
mobj.type = MsgType.Link
536+
mobj.attributes = {
537+
"title": title,
538+
"description": description,
539+
"image": image,
540+
"url": url
541+
}
542+
543+
return mobj
544+
545+
def newsapp_msg(self, msg):
546+
data = xmltodict.parse(msg['Content'])
547+
news = data.get('mmreader', {}).get('category', {}).get('newitem', [])
548+
if news:
549+
self.raw_linkMsg(msg, news[0]['title'], news[0]['digest'], news[0]['cover'], news[0]['shorturl'])
550+
if self._flag("extra_links_on_message", False):
551+
for i in news[1:]:
552+
self.raw_linkMsg(msg, i['title'], i['digest'], i['cover'], i['shorturl'])
553+
522554
@incomeMsgMeta
523555
def pictureMsg(self, msg, isGroupChat=False):
524556
mobj = EFBMsg(self)
@@ -630,7 +662,7 @@ def save_file(self, msg, msg_type):
630662
self.logger.warning("File %s with mime %s has no matching extensions.", fullpath, mime)
631663
ext = ".jpeg" if mime == "image/jpeg" else guess_ext
632664
os.rename(fullpath, "%s%s" % (fullpath, ext))
633-
fullpath = "%s.%s" % (fullpath, ext)
665+
fullpath = "%s%s" % (fullpath, ext)
634666
self.logger.info("File saved from WeChat\nFull path: %s\nMIME: %s", fullpath, mime)
635667
return fullpath, mime
636668

@@ -716,9 +748,9 @@ def send_message(self, msg):
716748
pass
717749
elif msg.type in (MsgType.File, MsgType.Audio):
718750
self.logger.info("Sending %s to WeChat\nFileName: %s\nPath: %s\nFilename: %s", msg.type, msg.text, msg.path, msg.filename)
719-
r = self._itchat_send_file(msg.path, UserName, filename=msg.filename)
751+
r = self._itchat_send_file(msg.path, toUserName=UserName, filename=msg.filename)
720752
if msg.text:
721-
self._itchat_send_msg(msg.text, UserName)
753+
self._itchat_send_msg(msg.text, toUserName=UserName)
722754
os.remove(msg.path)
723755
elif msg.type == MsgType.Video:
724756
self.logger.info("Sending video to WeChat\nFileName: %s\nPath: %s", msg.text, msg.path)
@@ -943,8 +975,46 @@ def _itchat_send_msg(self, *args, **kwargs):
943975
raise EFBMessageError(repr(e))
944976

945977
def _itchat_send_file(self, *args, **kwargs):
978+
def _itchat_send_fn(self, fileDir, toUserName=None, mediaId=None, filename=None):
979+
from itchat.returnvalues import ReturnValue
980+
from itchat import config
981+
import os, time, json
982+
if toUserName is None: toUserName = self.storageClass.userName
983+
if mediaId is None:
984+
r = self.upload_file(fileDir)
985+
if r:
986+
mediaId = r['MediaId']
987+
else:
988+
return r
989+
fn = filename or os.path.basename(fileDir)
990+
url = '%s/webwxsendappmsg?fun=async&f=json' % self.loginInfo['url']
991+
data = {
992+
'BaseRequest': self.loginInfo['BaseRequest'],
993+
'Msg': {
994+
'Type': 6,
995+
'Content': ("<appmsg appid='wxeb7ec651dd0aefa9' sdkver=''><title>%s</title>" % fn +
996+
"<des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl>" +
997+
"<appattach><totallen>%s</totallen><attachid>%s</attachid>" % (
998+
str(os.path.getsize(fileDir)), mediaId) +
999+
"<fileext>%s</fileext></appattach><extinfo></extinfo></appmsg>" % fn[1].replace('.', '')),
1000+
'FromUserName': self.storageClass.userName,
1001+
'ToUserName': toUserName,
1002+
'LocalID': int(time.time() * 1e4),
1003+
'ClientMsgId': int(time.time() * 1e4), },
1004+
'Scene': 0, }
1005+
headers = {
1006+
'User-Agent': config.USER_AGENT,
1007+
'Content-Type': 'application/json;charset=UTF-8', }
1008+
r = self.s.post(url, headers=headers,
1009+
data=json.dumps(data, ensure_ascii=False).encode('utf8'))
1010+
return ReturnValue(rawResponse=r)
1011+
9461012
try:
947-
return self.itchat.send_file(*args, **kwargs)
1013+
fn = kwargs.get("filename", None)
1014+
if fn is not None:
1015+
return _itchat_send_fn(self.itchat, *args, **kwargs)
1016+
else:
1017+
return self.itchat.send_file(*args, **kwargs)
9481018
except Exception as e:
9491019
raise EFBMessageError(repr(e))
9501020

0 commit comments

Comments
 (0)