telegram, irc: Refactor and improve routine for conversion of mentions
patch 274ec21ecc7d6c159237df2648668f54b65d5332
Author: E. Bosch <presidev@AT@gmail.com>
Date: Sat Jul 8 01:58:26 CEST 2023
* telegram, irc: Refactor and improve routine for conversion of mentions
hunk ./telegram.py 66
+ self.sorted_len_usernames = []
hunk ./telegram.py 136
+ self.add_sorted_len_usernames(self.tg_username)
hunk ./telegram.py 152
+ self.add_sorted_len_usernames(tg_ni)
hunk ./telegram.py 409
- def repl_mentioned(text, me_nick, received, mark, index, rargs):
- if text and text[index] == mark:
+ def repl_mentioned(text, me_nick, received, mark, repl_pref, repl_suff):
+ new_text = text
+
+ for user in self.sorted_len_usernames:
+ if user == self.tg_username:
+ if me_nick:
+ username = me_nick
+ else:
+ continue
+ else:
+ username = self.irc.users[user].irc_nick
+
hunk ./telegram.py 422
- subtext = text[1:]
- else:
- subtext = text[:-1]
- part = subtext.lower()
- if me_nick and part == self.tg_username:
- return replacement(me_nick, **rargs)
- if part in self.irc.users:
- return replacement(self.irc.users[part].irc_nick, **rargs)
- return text
-
- def replacement(nick, repl_pref, repl_suff):
- return '{}{}{}'.format(repl_pref, nick, repl_suff)
+ mention = mark + user
+ mention_case = mark + username
+ else: # sent
+ mention = user + mark
+ mention_case = username + mark
+ replcmnt = repl_pref + username + repl_suff
+
+ # Start of the text
+ for ment in (mention, mention_case):
+ if new_text.startswith(ment):
+ new_text = new_text.replace(ment, replcmnt, 1)
+
+ # Next words (with space as separator)
+ mention = ' ' + mention
+ mention_case = ' ' + mention_case
+ replcmnt = ' ' + replcmnt
+ new_text = new_text.replace(mention, replcmnt).replace(mention_case, replcmnt)
+
+ return new_text
hunk ./telegram.py 444
- index = 0
hunk ./telegram.py 446
- else:
+ else: # sent
hunk ./telegram.py 448
- index = -1
hunk ./telegram.py 452
- words = text.split(' ')
- words_replaced = [repl_mentioned(elem, me_nick, received, mark, index, rargs) for elem in words]
- text_replaced = ' '.join(words_replaced)
+ text_replaced = repl_mentioned(text, me_nick, received, mark, **rargs)
hunk ./telegram.py 462
+ def add_sorted_len_usernames(self, username):
+ self.sorted_len_usernames.append(username)
+ self.sorted_len_usernames.sort(key=lambda k: len(k), reverse=True)
+