SlashBot/SlashBot.py
2020-10-29 01:06:18 +08:00

56 lines
1.6 KiB
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import re
from telegram.ext import Updater, MessageHandler, filters
Filters = filters.Filters
parser = re.compile(r'^\/(\S+)([  ]*)(.*)$')
# Docker env
if os.environ.get('TOKEN') and os.environ['TOKEN'] != 'X':
Token = os.environ['TOKEN']
else:
raise Exception('no token')
def mention(user):
space = ' '
if 'last_name' not in user:
user['last_name'] = ''
space = ''
return f"[{user['first_name']}{space}{user['last_name']}](tg://user?id={user['id']})"
def get_text(mention_from, mention_rpl, command):
parsed = parser.search(delUsername.sub('', command)).groups()
if parsed[2]:
return f"{mention_from} {parsed[0]} {mention_rpl} {parsed[2]}"
else:
return f"{mention_from} {parsed[0]}{mention_rpl}"
def reply(update, context):
print(repr(update.to_dict()))
msg = update.to_dict()['message']
command = msg['text']
msg_from = msg['from']
if 'reply_to_message' in msg.keys() and msg['reply_to_message']['from'] != msg_from:
msg_rpl = msg['reply_to_message']['from']
else:
msg_rpl = {'first_name': '自己', 'id': msg_from['id']}
mention_from = mention(msg_from)
mention_rpl = mention(msg_rpl)
text = get_text(mention_from, mention_rpl, command)
update.effective_message.reply_text(text, parse_mode='Markdown')
updater = Updater(token=Token, use_context=True)
delUsername = re.compile('@' + updater.bot.username, re.I)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.regex(parser), reply))
updater.start_polling()
updater.idle()