Skip to content

Commit 713c237

Browse files
committed
1.3.2-dev.reauth.1: EWS — WeChat Reauth Concept
EWS New flags: "qr_reload", "on_log_out"
1 parent ec79299 commit 713c237

File tree

5 files changed

+133
-77
lines changed

5 files changed

+133
-77
lines changed

docs/EWS.md

+12-4
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,16 @@ eh_wechat_slave = {
104104
List out all other messages (more than first one) for link messages with more than one link from MPS accounts.
105105
* `max_quote_length` _(int)_ [Default: `-1`]
106106
Maximum length of text for quotation messages. Set to 0 to fully disable quotation. Set to -1 to always quote full message.
107-
* `qr_target` _(string)_ [Default: `"console"`]
108-
The target channel which should receive a QR code to login the Wechat account.
107+
* `qr_reload` _(str)_ [Default: `"master_qr_code"`]
108+
Method to display QR code during reauthentication.
109109
Available values:
110-
* `"console"`: the command line interface
111-
* `"master"`: the master channel
110+
* `"console_qr_code"`: QR code is printed to the console or log, depend on the logger setting.
111+
* `"master_qr_code"`: QR code is sent to the master channel as system message.
112+
!!! note
113+
The QR code refreshes every 5 to 10 seconds, be aware that sending system messages may lead to flood of message in your conversation.
114+
* `on_log_out` _(str)_ [Default: `"command"`]
115+
Behavior when WeChat server logs out the user.
116+
Available values:
117+
* `"idle"`: Notify the user, then do nothing.
118+
* `"reauth"`: Notify the user, then immediately start reauthentication.
119+
* `"command"`: Notify the user, then send the user a command message to trigger reauthentication process.

docs/channel.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -34,17 +34,17 @@ Methods below are required to be implemented for respective channel types noted,
3434

3535
**__init__(self, queue)** _(for slave channels)_
3636
**__init__(self, queue, slaves)** _(for master channels)_
37-
Initialize the channel and log in the account (if necessary) with in this method. `super().__init__(queue)` must always be called in the beginning.
37+
Initialize the channel with in this method. `super().__init__(queue)` must always be called in the beginning.
3838

3939
Args:
4040

4141
* `queue` (queue.Queue): Global message queue, used for message delivery from slave channels to the master channel.
4242
* `slaves` (dict): All enabled slave channel objects. Format: `"channel_id": channel_object`.
4343

4444
**poll(self)** _(for both types)_
45-
Message polling from your chat platform should be done in this method. When all channels are initialized, `poll` from all enabled channels are called in separated threads, and run concurrently. While polling for messages, the channel should always check for `self.stop_polling` (bool). When the user gracefully stops EFB, `self.stop_polling` will turn to `True`, and immediately the channel should stop polling and clean up everything necessary.
45+
Messages from your chat platform should be polled in this method. When all channels are initialized, `poll` from all enabled channels are called in separated threads, and ran concurrently. While polling for messages, the channel should always check for `self.stop_polling` (bool). When the user gracefully stops EFB, `self.stop_polling` will turn to `True`, and immediately the channel should stop polling and clean up everything necessary.
4646

47-
Method of getting messages which requires extra set up by the user or which may reduce compatibility, including Webhooks, shall be avoided or used as an alternative method.
47+
Method of getting messages which requires extra set up by the user or which may reduce compatibility, including Webhooks, shall be avoided or only used as an alternative method.
4848

4949
**get_extra_functions(self)** _(ready implemented, for slave channels)_
5050
Returns a `dict` of all extra functions of the slave channel, in the format of `"callable_name": callable`.

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.3.2-dev.6"
13+
__version__ = "1.3.2-dev.reauth.1"
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

+34-27
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ def _reply_error(bot, update, errmsg):
189189
Returns:
190190
telegram.Message: Message sent
191191
"""
192-
return bot.sendMessage(update.message.chat.id, errmsg, reply_to_message_id=update.message.message_id)
192+
return bot.send_message(update.message.chat.id, errmsg, reply_to_message_id=update.message.message_id)
193193

194194
def process_msg(self, msg):
195195
"""
@@ -247,7 +247,10 @@ def process_msg(self, msg):
247247
else "%s (%s)" % (msg.origin["alias"], msg.origin["name"])
248248
msg_template = "%s %s [%s]:\n%s" % (emoji_prefix, msg_prefix, name_prefix, "%s")
249249
elif msg.source == MsgSource.System:
250-
msg_template = "System Message: %s"
250+
emoji_prefix = msg.channel_emoji + utils.Emojis.get_source_emoji(msg.source)
251+
name_prefix = msg.origin["name"] if msg.origin["alias"] == msg.origin["name"] or not msg.origin['alias'] \
252+
else "%s (%s)" % (msg.origin["alias"], msg.origin["name"])
253+
msg_template = "%s %s:\n%s" % (emoji_prefix, name_prefix, "%s")
251254

252255
# Type dispatching
253256
self.logger.debug("%s, process_msg_step_2", xid)
@@ -287,9 +290,9 @@ def process_msg(self, msg):
287290
else:
288291
self.logger.debug("%s, process_msg_step_3_0_3", xid)
289292
try:
290-
tg_msg = self.bot.bot.sendMessage(tg_dest, text=msg_template % msg.text, parse_mode=parse_mode)
293+
tg_msg = self.bot.bot.send_message(tg_dest, text=msg_template % msg.text, parse_mode=parse_mode)
291294
except telegram.error.BadRequest:
292-
tg_msg = self.bot.bot.sendMessage(tg_dest, text=msg_template % msg.text)
295+
tg_msg = self.bot.bot.send_message(tg_dest, text=msg_template % msg.text)
293296
self.logger.debug("%s, process_msg_step_3_0_4, tg_msg = %s", xid, tg_msg)
294297
self.logger.debug("%s, process_msg_step_3_1", xid)
295298
elif msg.type == MsgType.Link:
@@ -299,21 +302,21 @@ def process_msg(self, msg):
299302
if msg.text:
300303
text += "\n\n" + msg.text
301304
try:
302-
tg_msg = self.bot.bot.sendMessage(tg_dest, text=msg_template % text, parse_mode="HTML")
305+
tg_msg = self.bot.bot.send_message(tg_dest, text=msg_template % text, parse_mode="HTML")
303306
except telegram.error.BadRequest:
304307
text = "🔗 %s\n%s\n\n%s" % (html.escape(msg.attributes["title"] or ""),
305308
html.escape(msg.attributes["description"] or ""),
306309
urllib.parse.quote(msg.attributes["url"] or "", safe="?=&#:/"))
307310
if msg.text:
308311
text += "\n\n" + msg.text
309-
tg_msg = self.bot.bot.sendMessage(tg_dest, text=msg_template % msg.text)
312+
tg_msg = self.bot.bot.send_message(tg_dest, text=msg_template % msg.text)
310313
elif msg.type in [MsgType.Image, MsgType.Sticker]:
311314
self.logger.debug("%s, process_msg_step_3_2", xid)
312-
self.logger.info("Received %s \nPath: %s\nSize: %s\nMIME: %s", msg.type, msg.path,
313-
os.stat(msg.path).st_size, msg.mime)
315+
self.logger.debug("Received %s\nPath: %s\nMIME: %s", msg.type, msg.path, msg.mime)
316+
self.logger.debug("Path: %s\nSize: %s", msg.path, os.stat(msg.path).st_size)
314317
if os.stat(msg.path).st_size == 0:
315318
os.remove(msg.path)
316-
tg_msg = self.bot.bot.sendMessage(tg_dest,
319+
tg_msg = self.bot.bot.send_message(tg_dest,
317320
msg_template % ("Error: Empty %s received. (MS01)" % msg.type))
318321
else:
319322
if not msg.text:
@@ -333,21 +336,21 @@ def process_msg(self, msg):
333336
elif msg.type == MsgType.File:
334337
if os.stat(msg.path).st_size == 0:
335338
os.remove(msg.path)
336-
tg_msg = self.bot.bot.sendMessage(tg_dest,
339+
tg_msg = self.bot.bot.send_message(tg_dest,
337340
msg_template % ("Error: Empty %s received. (MS02)" % msg.type))
338341
else:
339342
if not msg.text:
340343
file_name = os.path.basename(msg.path)
341344
msg.text = "sent a file."
342345
else:
343346
file_name = msg.text
344-
tg_msg = self.bot.bot.sendDocument(tg_dest, msg.file, caption=msg_template % msg.text,
347+
tg_msg = self.bot.bot.send_document(tg_dest, msg.file, caption=msg_template % msg.text,
345348
filename=file_name)
346349
os.remove(msg.path)
347350
elif msg.type == MsgType.Audio:
348351
if os.stat(msg.path).st_size == 0:
349352
os.remove(msg.path)
350-
return self.bot.bot.sendMessage(tg_dest,
353+
return self.bot.bot.send_message(tg_dest,
351354
msg_template % ("Error: Empty %s received. (MS03)" % msg.type))
352355
msg.text = msg.text or ''
353356
self.logger.debug("%s, process_msg_step_4_1, no_conversion = %s", xid,
@@ -359,7 +362,11 @@ def process_msg(self, msg):
359362
else:
360363
tg_msg = self.bot.bot.sendDocument(tg_dest, msg.file, caption=msg_template % msg.text)
361364
else:
362-
pydub.AudioSegment.from_file(msg.file).export("%s.ogg" % msg.path, format="ogg", codec="libopus")
365+
pydub.AudioSegment.from_file(msg.file).export("%s.ogg" % msg.path,
366+
format="ogg",
367+
codec="libopus",
368+
bitrate=65536,
369+
parameters=["-vbr", "on", "-compression_level", "10"])
363370
ogg_file = open("%s.ogg" % msg.path, 'rb')
364371
tg_msg = self.bot.bot.sendVoice(tg_dest, ogg_file, caption=msg_template % msg.text)
365372
os.remove("%s.ogg" % msg.path)
@@ -373,7 +380,7 @@ def process_msg(self, msg):
373380
elif msg.type == MsgType.Video:
374381
if os.stat(msg.path).st_size == 0:
375382
os.remove(msg.path)
376-
return self.bot.bot.sendMessage(tg_dest, msg_template % ("Error: Empty %s recieved" % msg.type))
383+
return self.bot.bot.send_message(tg_dest, msg_template % ("Error: Empty %s recieved" % msg.type))
377384
if not msg.text:
378385
msg.text = "sent a video."
379386
tg_msg = self.bot.bot.sendVideo(tg_dest, video=msg.file, caption=msg_template % msg.text)
@@ -389,7 +396,7 @@ def process_msg(self, msg):
389396
"text": msg_template % msg.text,
390397
"commands": msg.attributes['commands']}
391398
else:
392-
tg_msg = self.bot.bot.sendMessage(tg_dest, msg_template % "Unsupported incoming message type. (UT01)")
399+
tg_msg = self.bot.bot.send_message(tg_dest, msg_template % "Unsupported incoming message type. (UT01)")
393400
self.logger.debug("%s, process_msg_step_4", xid)
394401
if msg.source in (MsgSource.User, MsgSource.Group):
395402
msg_log = {"master_msg_id": "%s.%s" % (tg_msg.chat.id, tg_msg.message_id),
@@ -523,7 +530,7 @@ def link_chat_gen_list(self, bot, chat_id, message_id=None, offset=0, filter="")
523530
offset: Offset for pagination.
524531
"""
525532
if not message_id:
526-
message_id = bot.sendMessage(chat_id, "Processing...").message_id
533+
message_id = bot.send_message(chat_id, "Processing...").message_id
527534

528535
msg_text = "Please choose the chat you want to link with ...\n\nLegend:\n"
529536
legend, chat_btn_list = self.slave_chats_pagination("%s.%s" % (chat_id, message_id), offset, filter=filter)
@@ -633,17 +640,17 @@ def link_chat_exec(self, bot, tg_chat_id, tg_msg_id, callback_uid):
633640

634641
def unlink_all(self, bot, update):
635642
if update.message.chat.id == update.message.from_user.id:
636-
return bot.sendMessage(update.message.chat.id, "Send `/unlink_all` to a group to unlink all remote chats "
643+
return bot.send_message(update.message.chat.id, "Send `/unlink_all` to a group to unlink all remote chats "
637644
"from it.",
638645
parse_mode=telegram.ParseMode.MARKDOWN,
639646
reply_to_message_id=update.message.message_id)
640647
assocs = db.get_chat_assoc(master_uid="%s.%s" % (self.channel_id, update.message.chat.id))
641648
if len(assocs) < 1:
642-
return bot.sendMessage(update.message.chat.id, "No chat is linked to the group.",
649+
return bot.send_message(update.message.chat.id, "No chat is linked to the group.",
643650
reply_to_message_id=update.message.message_id)
644651
else:
645652
db.remove_chat_assoc(master_uid="%s.%s" % (self.channel_id, update.message.chat.id))
646-
return bot.sendMessage(update.message.chat.id, "All chats has been unlinked from this group. (%s)" % len(assocs),
653+
return bot.send_message(update.message.chat.id, "All chats has been unlinked from this group. (%s)" % len(assocs),
647654
reply_to_message_id=update.message.message_id)
648655

649656
def start_chat_list(self, bot, update, args=None):
@@ -672,7 +679,7 @@ def chat_head_req_generate(self, bot, chat_id, message_id=None, offset=0, filter
672679
filter: Regex String used as a filter.
673680
"""
674681
if not message_id:
675-
message_id = bot.sendMessage(chat_id, text="Processing...").message_id
682+
message_id = bot.send_message(chat_id, text="Processing...").message_id
676683

677684
legend, chat_btn_list = self.slave_chats_pagination("%s.%s" % (chat_id, message_id), offset, filter=filter)
678685
msg_text = "Choose a chat you want to start with...\n\nLegend:\n"
@@ -784,7 +791,7 @@ def extra_help(self, bot, update):
784791
fn_name, xfns[j].name, xfns[j].desc.format(function_name=fn_name))
785792
else:
786793
msg += "No command found."
787-
bot.sendMessage(update.message.chat.id, msg, parse_mode="HTML")
794+
bot.send_message(update.message.chat.id, msg, parse_mode="HTML")
788795

789796
def extra_call(self, bot, update, groupdict=None):
790797
"""
@@ -802,7 +809,7 @@ def extra_call(self, bot, update, groupdict=None):
802809
if groupdict['command'] not in fns:
803810
return self._reply_error(bot, update, "Command not found in selected channel. (XC02)")
804811
header = "%s %s: %s\n-------\n" % (ch.channel_emoji, ch.channel_name, fns[groupdict['command']].name)
805-
msg = bot.sendMessage(update.message.chat.id, header + "Please wait...")
812+
msg = bot.send_message(update.message.chat.id, header + "Please wait...")
806813
result = fns[groupdict['command']](" ".join(update.message.text.split(' ', 1)[1:]))
807814
bot.editMessageText(text=header + result, chat_id=update.message.chat.id, message_id=msg.message_id)
808815

@@ -1061,7 +1068,7 @@ def start(self, bot, update, args=[]):
10611068
txt = "Chat '%s' is now linked." % chat_display_name
10621069
unlink_btn = telegram.InlineKeyboardMarkup(
10631070
[[telegram.InlineKeyboardButton("Unlink", callback_data="unlink 0")]])
1064-
new_msg = bot.sendMessage(update.message.chat.id, text=txt, reply_markup=unlink_btn)
1071+
new_msg = bot.send_message(update.message.chat.id, text=txt, reply_markup=unlink_btn)
10651072
self.msg_status[args[0]] = \
10661073
self.msg_status["%s.%s" % (update.message.chat.id, new_msg.message_id)] = \
10671074
Flags.EXEC_LINK
@@ -1076,7 +1083,7 @@ def start(self, bot, update, args=[]):
10761083
else:
10771084
txt = "Welcome to EH Forwarder Bot: EFB Telegram Master Channel.\n\n" \
10781085
"To learn more, please visit https://github.com/blueset/ehForwarderBot ."
1079-
bot.sendMessage(update.message.from_user.id, txt)
1086+
bot.send_message(update.message.from_user.id, txt)
10801087

10811088
def recognize_speech(self, bot, update, args=[]):
10821089
"""
@@ -1150,7 +1157,7 @@ def recognize(self, *args, **kwargs):
11501157
for j in results[i]:
11511158
msg += "%s\n" % j
11521159
msg = "Results:\n%s" % msg
1153-
bot.sendMessage(update.message.reply_to_message.chat.id, msg,
1160+
bot.send_message(update.message.reply_to_message.chat.id, msg,
11541161
reply_to_message_id=update.message.reply_to_message.message_id,
11551162
parse_mode=telegram.ParseMode.MARKDOWN)
11561163
os.remove(path)
@@ -1187,9 +1194,9 @@ def error(self, bot, update, error):
11871194
if "Conflict: terminated by other long poll or webhook (409)" in str(error):
11881195
msg = 'Please immediately turn off all EFB instances.\nAnother bot instance or web-hook detected.'
11891196
self.logger.error(msg)
1190-
bot.sendMessage(getattr(config, self.channel_id)['admins'][0], msg)
1197+
bot.send_message(getattr(config, self.channel_id)['admins'][0], msg)
11911198
else:
1192-
bot.sendMessage(getattr(config, self.channel_id)['admins'][0],
1199+
bot.send_message(getattr(config, self.channel_id)['admins'][0],
11931200
"EFB Telegram Master channel encountered error <code>%s</code> "
11941201
"caused by update <code>%s</code>.\n\n"
11951202
"Report issue: <a href=\"https://github.com/blueset/ehForwarderBot/issues/new\">GitHub Issue Page</a>" %

0 commit comments

Comments
 (0)