SlashBot/SlashBot.py

158 lines
6.1 KiB
Python
Raw Normal View History

2020-10-26 02:11:53 +08:00
import os
2020-10-26 16:08:50 +08:00
import re
import requests
2021-12-13 04:54:02 +08:00
import telegram
2021-12-28 22:41:32 +08:00
from typing import Tuple, Optional, Callable, Union, Dict
2020-10-26 16:08:50 +08:00
from telegram.ext import Updater, MessageHandler, filters
2022-03-28 05:37:30 +08:00
from functools import partial
2020-10-26 16:08:50 +08:00
2020-10-26 02:11:53 +08:00
Filters = filters.Filters
2022-03-28 05:37:30 +08:00
parser = re.compile(r'^(?P<slash>[\\/]_?)'
2022-03-28 05:58:47 +08:00
r'(?P<predicate>([^\s\\]|\\.)*((?<=\S)\\)?)'
2022-03-28 05:37:30 +08:00
r'(\s+(?P<complement>.+))?$')
2022-03-28 05:58:47 +08:00
convertEscapes = partial(re.compile(r'\\(\s)').sub, r'\1')
2021-12-13 04:54:02 +08:00
htmlEscape = lambda s: s.replace("<", "&lt;").replace(">", "&gt;").replace("&", "&amp;")
2021-12-28 22:41:32 +08:00
mentionParser = re.compile(r'@([a-zA-Z]\w{4,})')
2021-12-13 04:54:02 +08:00
delUsername: Optional[Callable] = None # placeholder
2020-10-26 02:11:53 +08:00
# Docker env
Token = os.environ.get('TOKEN')
if not Token:
2020-10-26 02:11:53 +08:00
raise Exception('no token')
2021-12-13 04:54:02 +08:00
telegram_proxy = os.environ.get('PROXY', '')
requests_proxies = {'all': telegram_proxy} if telegram_proxy else None
2021-08-05 00:18:42 +08:00
2021-12-13 04:54:02 +08:00
class User:
def __init__(self, uid: Optional[int] = None, username: Optional[str] = None, name: Optional[str] = None):
if not (uid and name) and not username:
raise ValueError('invalid user')
self.name = name
self.uid = uid
self.username = username
if not self.name and self.username:
self.__get_user_by_username()
2021-08-05 00:18:42 +08:00
2021-12-13 04:54:02 +08:00
def __get_user_by_username(self):
r = requests.get(f'https://t.me/{self.username}', proxies=requests_proxies)
self.name = re.search(r'(?<=<meta property="og:title" content=").*(?=")', r.text, re.IGNORECASE).group(0)
page_title = re.search(r'(?<=<title>).*(?=</title>)', r.text, re.IGNORECASE).group(0)
if page_title == self.name: # user does not exist
self.name = None
2021-08-05 00:18:42 +08:00
def mention(self, mention_self: bool = False, pure: bool = False) -> str:
2021-12-13 04:54:02 +08:00
if not self.name:
return f'@{self.username}'
2021-12-13 04:54:02 +08:00
mention_deep_link = (f'tg://resolve?domain={self.username}'
if (self.username and (not self.uid or self.uid < 0))
else f'tg://user?id={self.uid}')
name = self.name if not mention_self else "自己"
return f'<a href ="{mention_deep_link}">{name}</a>' if not pure else name
2021-08-05 00:18:42 +08:00
2021-12-13 04:54:02 +08:00
def __eq__(self, other):
return (
type(self) == type(other)
and (
((self.uid or other.uid) and self.uid == other.uid) or
((self.username or other.username) and self.username == other.username)
)
)
2021-12-13 04:54:02 +08:00
def get_user(msg: telegram.Message) -> User:
user = msg.sender_chat or msg.from_user
return User(name=user.full_name or user.title, uid=user.id, username=user.username)
2021-12-13 04:54:02 +08:00
def get_users(msg: telegram.Message) -> Tuple[User, User]:
msg_from = msg
msg_rpl = msg.reply_to_message or msg_from
from_user, rpl_user = get_user(msg_from), get_user(msg_rpl)
return from_user, rpl_user
2020-10-26 02:11:53 +08:00
2021-12-28 22:41:32 +08:00
def parse_command(match: re.Match) -> Dict[str, Union[str, bool]]:
2022-03-28 05:37:30 +08:00
parsed = match.groupdict()
predicate = parsed['predicate']
2022-03-28 05:58:47 +08:00
omit_le = predicate.endswith('\\')
predicate = predicate[:-1] if omit_le else predicate
predicate = convertEscapes(predicate)
2022-03-28 05:37:30 +08:00
predicate = delUsername(predicate)
result = {'predicate': htmlEscape(predicate),
'complement': htmlEscape(parsed['complement'] or ''),
'slash': parsed['slash'],
2022-03-28 05:58:47 +08:00
'swap': parsed['slash'] != '/',
'omit_le': omit_le}
return result
2021-08-09 16:18:44 +08:00
2021-12-13 04:54:02 +08:00
def get_text(user_from: User, user_rpl: User, command: dict):
rpl_self = user_from == user_rpl
2021-12-13 04:54:02 +08:00
mention_from = user_from.mention()
mention_rpl = user_rpl.mention(mention_self=rpl_self)
2022-03-28 05:58:47 +08:00
slash, predicate, complement, omit_le = \
command['slash'], command['predicate'], command['complement'], command['omit_le']
2022-03-28 05:37:30 +08:00
if predicate == '':
ret = '!' if slash == '/' else '¡'
halfwidth_mark = None
elif predicate == 'me':
ret = f"{mention_from}{bool(complement) * ' '}{complement}"
halfwidth_mark = (complement or user_from.mention(pure=True))[-1].isascii()
elif predicate == 'you':
ret = f"{mention_rpl}{bool(complement) * ' '}{complement}"
halfwidth_mark = (complement or user_rpl.mention(mention_self=rpl_self, pure=True))[-1].isascii()
elif complement:
ret = f"{mention_from} {predicate} {mention_rpl} {complement}"
halfwidth_mark = complement[-1].isascii()
2020-10-26 16:08:50 +08:00
else:
2022-03-28 05:58:47 +08:00
ret = f"{mention_from} {predicate} "
ret += '' if not omit_le else ''
ret += mention_rpl
halfwidth_mark = mention_rpl[-1].isascii()
2022-03-28 05:37:30 +08:00
ret += '!' if halfwidth_mark else ('' if halfwidth_mark is not None else '')
return ret
2020-10-26 16:08:50 +08:00
2021-12-13 04:54:02 +08:00
def reply(update: telegram.Update, context: telegram.ext.CallbackContext):
2020-11-06 02:55:01 +08:00
print(update.to_dict())
2021-12-13 04:54:02 +08:00
msg = update.effective_message
from_user, rpl_user = get_users(msg)
command = parse_command(context.match)
if from_user == rpl_user:
mention_match = mentionParser.search(command['predicate'])
if mention_match:
mention = mentionParser.search(msg.text).group(1)
rpl_user = User(username=mention)
command['predicate'] = command['predicate'][:mention_match.start()]
2021-12-28 22:41:32 +08:00
else:
mention_match = mentionParser.search(command['complement'])
if mention_match:
mention = mentionParser.search(msg.text).group(1)
rpl_user = User(username=mention)
complement = command['complement']
complement = complement[:mention_match.start()] + complement[mention_match.end():]
command['complement'] = complement.strip()
2021-12-13 04:54:02 +08:00
if command['swap'] and (not from_user == rpl_user):
(from_user, rpl_user) = (rpl_user, from_user)
2020-10-26 15:36:12 +08:00
2021-12-13 04:54:02 +08:00
text = get_text(from_user, rpl_user, command)
print(text, end='\n\n')
2020-10-26 02:11:53 +08:00
2022-03-18 01:34:09 +08:00
update.effective_message.reply_text('\u200e' + text, parse_mode='HTML')
2020-10-26 02:11:53 +08:00
2021-08-05 11:47:04 +08:00
if __name__ == '__main__':
2021-08-09 17:57:43 +08:00
updater = Updater(token=Token, use_context=True, request_kwargs={'proxy_url': telegram_proxy})
2022-03-28 05:37:30 +08:00
delUsername = partial(re.compile(r'@' + updater.bot.username, re.I).sub, '')
2021-08-05 11:47:04 +08:00
dp = updater.dispatcher
2022-03-18 01:36:55 +08:00
dp.add_handler(MessageHandler(Filters.regex(parser), reply, run_async=True))
2021-08-05 11:47:04 +08:00
updater.start_polling()
updater.idle()