from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode
import telegram.utils.helpers as helpers
import logging
import sys
import subprocess

# å�¯ç”¨æ—¥å¿—
logging.basicConfig(format='%(asctime)s-%(name)s-%(levelname)s-%(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)

admin_id = '---'


# æ—¥å¿—è£…é¥°å™¨
def lof_logger(func):
    def wrapper(update, context, *args):
        logging.info(" Message Info ==> %s \n error ==> %s" % (update.message, context.error))
        func(update, context, *args)

    return wrapper


def start(update, context):
    from_user_id = update.message.from_user.id
    if admin_id == str(from_user_id):
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text='%s\n%s\n%s\n%s' % ('é™�åˆ¶è‡ªå·±ä½¿ç”¨çš„Google Drive è½¬å­˜æœºå™¨äºº',
                                                        '/start å¼€å§‹',
                                                        '/copy è½¬å­˜Google driveæ–‡ä»¶ã€‚å�‚è€ƒï¼š/copy è¦�å¤�åˆ¶çš„æ–‡ä»¶å¤¹ID è‡ªå·±ç›˜ID /ç»�å¯¹è·¯å¾„ç›®å½•/',
                                                        '/bash æ‰§è¡Œæ‰§è¡Œå‘½ä»¤ /bashå®Œæ•´çš„å‘½ä»¤å°±è¡Œã€‚å�‚è€ƒï¼š/bash ls -l'))
    else:
        update.message.reply_text(text='æ­¤ä¸ºç§�äººä½¿ç”¨bot,ä¸�èƒ½æ‰§è¡Œæ‚¨çš„æŒ‡ä»¤ï¼�')


@lof_logger
def copy(update, context):
    from_user_id = update.message.from_user.id

    if admin_id == str(from_user_id):
        commands = update.message.text.split()
        commands.remove('/copy')
        if len(commands) == 3:
            command = 'gclone copy gc:{%s} gc:{%s}%s --drive-server-side-across-configs -v' % (
                commands[0], commands[1], commands[2])
            rsl = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,
                                   universal_newlines=True)

            while True:
                next_line = rsl.stdout.readline()
                update.message.reply_text(text=str(next_line.strip()))
                if next_line == '' and rsl.poll() is not None:
                    break
        else:
            update.message.reply_text(text='copyæŒ‡ä»¤æ ¼å¼�é”™è¯¯ï¼Œè¯·é‡�æ–°å�‘é€�ï¼�\n å�‚è€ƒï¼š/copy è¦�å¤�åˆ¶çš„æ–‡ä»¶å¤¹ID è‡ªå·±ç›˜ID /ç»�å¯¹è·¯å¾„ç›®å½•/')
    else:
        update.message.reply_text(text='æ­¤ä¸ºç§�äººä½¿ç”¨bot,ä¸�èƒ½æ‰§è¡Œæ‚¨çš„æŒ‡ä»¤ï¼�')


@lof_logger
def bash(update, context):
    from_user_id = update.message.from_user.id

    if admin_id == str(from_user_id):
        commands = update.message.text.split()
        commands.remove('/bash')
        if len(commands) > 1:
            command_list = ['ls', 'rclone', 'gclone', 'cat', 'history']
            if commands[0] in command_list:
                rsl = subprocess.Popen(' '.join(commands), shell=True, stdout=subprocess.PIPE,
                                       universal_newlines=True)

                while True:
                    next_line = rsl.stdout.readline()
                    update.message.reply_text(text=str(next_line.strip()))
                    if next_line == '' and rsl.poll() is not None:
                        break
            else:
                update.message.reply_text(text='bot æš‚æ—¶ä¸�æ”¯æŒ�æ‰§è¡Œ%sæŒ‡ä»¤' % (commands[0]))
        else:
            update.message.reply_text(text='bash æŒ‡ä»¤æ ¼å¼�é”™è¯¯ï¼Œè¯·é‡�æ–°å�‘é€�ï¼�\n å�‚è€ƒï¼š/bash ls -l')
    else:
        update.message.reply_text(text='æ­¤ä¸ºç§�äººä½¿ç”¨bot,ä¸�èƒ½æ‰§è¡Œæ‚¨çš„æŒ‡ä»¤ï¼�')


@lof_logger
def unknown(update, context):
    from_user_id = update.message.from_user.id
    if admin_id == str(from_user_id):
        tg_user_name = "%s%s" % (
            update.message.from_user.last_name if update.message.from_user.last_name is not None else '',
            update.message.from_user.first_name)
        update.message.reply_text(text="ğŸˆ²ï¸�%s ç��è¾“ä»€ä¹ˆä¸œè¥¿ï¼Œæ˜¯ä¸�æ˜¯æƒ³æŒ¨æ��ã€‚" % helpers.mention_html(from_user_id, tg_user_name),
                                  parse_mode=ParseMode.HTML)
    else:
        update.message.reply_text(text='æ­¤ä¸ºç§�äººä½¿ç”¨bot,ä¸�èƒ½æ‰§è¡Œæ‚¨çš„æŒ‡ä»¤ï¼�')


def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)


def main():
    if len(sys.argv) < 3:
        print("Usage: cmd <admin telegram user id> <bot Token> ")
        exit(0)

    global admin_id
    admin_id = sys.argv[1]
    bot_token = sys.argv[2]

    # åˆ›å»ºæ›´æ–°ç¨‹åº�å¹¶å�‚æ•°ä¸ºä½ Botçš„TOKENã€‚
    updater = Updater(bot_token, use_context=True)

    # è�·å�–è°ƒåº¦ç¨‹åº�æ�¥æ³¨å†Œå¤„ç�†ç¨‹åº�
    dp = updater.dispatcher

    # é€šè¿‡ start å‡½æ•° å“�åº” '/start' å‘½ä»¤
    dp.add_handler(CommandHandler('start', start))

    # é€šè¿‡ lucky å‡½æ•° å“�åº” '/copy' å‘½ä»¤
    dp.add_handler(CommandHandler('copy', copy))

    # é€šè¿‡ lucky å‡½æ•° å“�åº” '/copy' å‘½ä»¤
    dp.add_handler(CommandHandler('bash', bash))

    # unknownå‡½æ•°æ�¥å“�åº”æ™®é€šæ–‡æœ¬æ¶ˆæ�¯
    # dp.add_handler(MessageHandler(Filters.text, unknown))

    # unknownå‡½æ•°æ�¥å“�åº”æ™®é€šæ–‡æœ¬æ¶ˆæ�¯
    # dp.add_handler(MessageHandler(Filters.photo, unknown))

    # æ²¡æ‰¾åˆ°å¯¹åº”æŒ‡ä»¤
    dp.add_handler(MessageHandler(Filters.command, unknown))

    dp.add_error_handler(error)

    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()
