<filename>bot.py
# -*- coding: utf-8 -*-
from linepy import *
from datetime import datetime
from threading import Thread
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from string import Template
from pathlib import Path
from websocket import create_connection
import os,sys,youtube_dl,pafy,requests,json,codecs,time,threading,re,ast,secrets,random,pytz,smtplib,ssl,subprocess,speedtest,twder
timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒')
print("【%s】≣≣≣≣≣▶| 𝓨𝓣𝓔𝓡 簡訊機 |◀≣≣≣≣≣" %timenow)
print("【%s】≣≣≣≣≣▶| 𝓨𝓣𝓔𝓡 SMSBOT |◀≣≣≣≣≣" %timenow)
while True:
    timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒')
    print("【%s】≣≣≣≣≣▶【嘗試登入帳號 Try to login】◀≣≣≣≣≣" %timenow)
    try:
        cl = LINE()
    except Exception as e:
        if e.reason == 'blocked user':
            print("【%s】≣≣≣≣≣▶【帳號已禁言 Blocked User】◀≣≣≣≣≣" %timenow)
            os._exit(0)
        elif e.reason == 'Account ID or password is invalid':
            print("【%s】≣≣≣≣≣▶【帳號不存在 Not a user】◀≣≣≣≣≣" %timenow)
            os._exit(0)
        elif e.reason == 'Account ID and password does not match':
            print("【%s】≣≣≣≣≣▶【密碼不正確 Password error】◀≣≣≣≣≣" %timenow)
            os._exit(0)
        elif e.reason == '':
            print("【%s】≣≣≣≣≣▶【凍帳狀態中 Cold User】◀≣≣≣≣≣" %timenow)
            print("【%s】將於1小時後自動登入")
            counter = 60
            for x in range(60):
                time.sleep(60)
                counter -= 1
                if counter == 0:
                    break
                print("將於{}分鐘後後自動登入".format(counter))
        else:
            print("【%s】≣≣≣≣≣▶【未知原因失敗 Unknown】◀≣≣≣≣≣")
            print(str(e))
            os._exit(0)
    else:
        break
timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒')
print("【%s】≣≣≣≣≣▶【登入成功 Login Success】◀≣≣≣≣≣" %timenow)
print("【%s】≣≣≣≣≣▶【載入系統中  Setting up】◀≣≣≣≣≣" %timenow)
oepoll = OEPoll(cl)
profile = cl.getProfile()
clMID = cl.profile.mid
wait = {
    'rapidFire': {},
    'clp': False,
    'ccp': False,
    'bc': {},
    'mode1': {},
    'mode2': {},
    'num': {}
}
gift = {
    'num':{}
}
backdoor = "rbd07ffb48c082bab980cfd02be9e3837"
set = json.load(codecs.open("data.json","r","utf-8"))
users = json.load(codecs.open("user.json","r","utf-8"))
timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒')
print("【%s】≣≣≣≣≣▶【載入完成 Set up Success】◀≣≣≣≣≣" %timenow)
print("【%s】≣≣≣≣≣▶　　　　|版本號|V7.0　　　　◀≣≣≣≣≣" %timenow)
print("【%s】≣≣≣≣≣▶　【登入者資訊 Bot Info】　◀≣≣≣≣≣" %timenow)
print("【%s】≣≣≣≣≣▶|名稱 Name|%s◀≣≣≣≣≣" % (timenow,cl.profile.displayName))
print("【%s】≣≣≣≣≣▶|代號 Mid|%s◀≣≣≣≣≣" % (timenow,cl.profile.mid))
print("【%s】≣≣≣≣≣▶|金鑰 Token|%s◀≣≣≣≣≣" % (timenow,cl.authToken))
cl.sendMessage(backdoor,"┏━━━━━━━━━━━━━━┓\n┃ %s ┃\n┣━━━━━━━━━━━━━━┫\n┃後台通知 Backdoor Notification┃\n┣━━━━━━━━━━━━━━┫\n┃𝓨𝓣𝓔𝓡簡訊機V7.0系統載入完成┃\n┗━━━━━━━━━━━━━━┛"%(timenow))
timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒')
print("【%s】≣≣≣≣≣▶   【開始運行 Start up】   ◀≣≣≣≣≣" %timenow)
mulai = time.time()
class mailbox(object):
    def __init__(self):
        super(mailbox, self).__init__()
        self.ws = create_connection("wss://dropmail.me/websocket")
        self.next = self.ws.recv
        self.next()
        self.close = self.ws.close
        self.email = self.next()[1:].split(":")[0]
        self.next()
def logError(text):
    report("       系統錯誤 Program Error      ┃\n┣━━━━━━━━━━━━━━┫\n┃"+str(text))
    time_ = datetime.now()
    with open("errorLog.txt","a") as error:
        error.write("\n[%s] %s" % (str(time_), text))
def backupData():
    try:
        json.dump(set,codecs.open('data.json','w','utf-8'), sort_keys=False, indent=4, ensure_ascii=False)
        json.dump(users,codecs.open('user.json','w','utf-8'), sort_keys=False, indent=4, ensure_ascii=False)
        return True
    except Exception as error:
        logError(error)
        return False
def restartBot():
    backupData()
    python = sys.executable
    os.execl(python, python, *sys.argv)
def ismid(mid):
    try:
        cl.getContact(mid)
        return True
    except:
        return False
#===================================================================#
def getcode1(orderId):
    counter = 0
    while True:
        time.sleep(1)
        counter += 1
        if counter >= 1200:
            raise Exception('timeout')
        if orderId in wait['mode1']:
            response = requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'getStatus','id': orderId}).text
            if 'STATUS_OK' in response:
                break
        else:
            raise Exception('release')
    return response.split(':')[1]
#===================================================================#
def relsec2(orderId):
    time.sleep(20)
    wait["mode2"][orderId] = True
def getcode2(orderId):
    veri_url = set["mode2"]["base_url"] + set["mode2"]["veri_route"]
    params = {
        'orderId': orderId,
        'apikey': set["mode2"]["apikey"],
    }
    counter = 0
    while True:
        time.sleep(1)
        counter += 1
        if counter >= 600:
            raise Exception('timeout')
        if orderId in wait['mode2']:
            response = requests.get(veri_url, params=params).json()
            if response['code'] == 1:
                break
        else:
            raise Exception('release')
    return response['data']['code']
#===================================================================#
def report(msg):
    cl.sendMessage(backdoor,"┏━━━━━━━━━━━━━━┓\n┃ %s ┃\n┣━━━━━━━━━━━━━━┫\n┃後台通知 Backdoor Notification┃\n┣━━━━━━━━━━━━━━┫\n┃%s┃\n┗━━━━━━━━━━━━━━┛" % (datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒'),str(msg)))
def Runtime(secs):
    mins, secs = divmod(secs,60)
    hours, mins = divmod(mins,60)
    days, hours = divmod(hours, 24)
    return '%02d 天\n%02d 時\n%02d 分\n%02d 秒' % (days, hours, mins, secs)
def gencode():
    list = ["0","9","8","7","6","5","4","3","2","2","1","A","a","B","b","C","c","D","d","E","e","F","f","G","g","H","h","I","i","J","j","K","k","L","l","M","m","N","n","O","o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v","W","w","X","x","Y","y","Z","z"]
    a = random.choice(list)
    b = random.choice(list)
    c = random.choice(list)
    d = random.choice(list)
    e = random.choice(list)
    f = random.choice(list)
    g = random.choice(list)
    h = random.choice(list)
    i = random.choice(list)
    j = random.choice(list)
    k = random.choice(list)
    l = random.choice(list)
    m = random.choice(list)
    n = random.choice(list)
    o = random.choice(list)
    p = random.choice(list)
    code = a+b+c+d+'-'+e+f+g+h+'-'+i+j+k+l+'-'+m+n+o+p
    return code
def lineBot(op):
    try:
        if op.type == 0:
            return
        if op.type == 5:
            cl.findAndAddContactsByMid(op.param1)
            cl.sendMessage(op.param1,"安安！感謝您加我為好友！\n此為𝓨𝓣𝓔𝓡簡訊機！\n作者網址:line.me/ti/p/~najianlin\n作者友資:")
            cl.sendContact(op.param1,"u8b9d115e85202db06eb798e8c1b40ae9")
            cl.sendMessage(backdoor, "@x 加入好友", {'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(op.param1)+'}]}'}, 0)
        if op.type == 13:
            if clMID in op.param3:
                if op.param2 in set["creator"]:
                    cl.acceptGroupInvitation(op.param1)
                    cl.sendMessage(op.param1,"感謝創作者邀我入群！\n此為𝓨𝓣𝓔𝓡簡訊機！")
                else:
                    group = cl.getGroup(op.param1)
                    if len(group.members) >= 5:
                        cl.acceptGroupInvitation(op.param1)
                        cl.sendMessage(op.param1,"感謝您邀請我入群！\n此為𝓨𝓣𝓔𝓡簡訊機！\n作者網址:line.me/ti/p/~najianlin\n作者友資:")
                        cl.sendContact(op.param1,"u8b9d115e85202db06eb798e8c1b40ae9")
                        if "u8b9d115e85202db06eb798e8c1b40ae9" not in [contact.mid for contact in cl.getGroup(op.param1).members]:
                            try:
                                cl.sendMessage(op.param1,"為了增加穩定性\n將自動邀請作者")
                                cl.inviteIntoGroup(op.param1,["u8b9d115e85202db06eb798e8c1b40ae9"])
                                cl.sendMessage(op.param1,"成功邀請作者進入群組")
                            except:
                                cl.sendMessage(op.param1,"為了增加穩定性\n原定應邀請作者\n但因規制無法執行")
                    else:
                        cl.acceptGroupInvitation(op.param1)
                        cl.sendMessage(op.param1,"群組人數小於5人\n機器將離開群組\n如有特殊需求請洽以下友資")
                        cl.sendContact(op.param1,"u8b9d115e85202db06eb798e8c1b40ae9")
                        cl.leaveGroup(op.param1)
        if op.type == 26 or op.type == 25:
            msg = op.message
            text = msg.text
            msg_id = msg.id
            receiver = msg.to
            sender = msg._from
            if msg.toType == 0:
                if sender != cl.profile.mid:
                    to = sender
                else:
                    to = receiver
            else:
                to = receiver
            if sender != cl.profile.mid:
                cl.sendChatChecked(to, msg_id)
            if sender not in set["creator"]:
                if sender in wait["rapidFire"]:
                    if time.time() - wait["rapidFire"][sender] < 3:
                        return
                    else:
                        wait["rapidFire"][sender] = time.time()
                else:
                    wait["rapidFire"][sender] = time.time()
            if msg.contentType == 0:
                if text is None or sender in set["block"]:
                    return
                else:
                    if sender in sender:
                        if text.lower().startswith("兌換:"):
                            codeKeyConfirm = text[3:]
                            try:
                                if codeKeyConfirm in set["code"]:
                                    tz = pytz.timezone("Asia/Taipei")
                                    timeNow = datetime.now(tz=tz)
                                    usedtime = timeNow.strftime('%Y年%m月%d號%H點%M分%S秒')
                                    giveaway = int(set["code"][codeKeyConfirm]["num"])
                                    if sender not in users:
                                        users[sender] = 0
                                    set["codenum"] += 1
                                    ordernum = str(set["codenum"]).zfill(10)
                                    codermguge = int(set["code"][codeKeyConfirm]["usage"]) - 1
                                    set["usedcode"][ordernum] = {"user": sender,"num": giveaway,"code": codeKeyConfirm,"time": usedtime,"maker": set["code"][codeKeyConfirm]["maker"]}
                                    users[sender] += giveaway
                                    if set["code"][codeKeyConfirm]["usage"] > 1:
                                        set["code"][codeKeyConfirm]["usage"] -= 1
                                    else:
                                        del set["code"][codeKeyConfirm]
                                    backupData()
                                    nowticket = users[sender]
                                    cl.relatedMessage(to,"已成功兌換禮品碼(〃∀〃)\n≡≡≡≡≡≡≡≡≡≡≡≡\n已被兌換的禮品碼為:\n[" + str(codeKeyConfirm) + "]\n此次訂單編號為:\n{}\n此禮品碼剩餘兌換次數:\n{}\n\n您的票數已增加 {} 票\n\n您目前剩餘票數為 {} 票".format(ordernum,str(codermguge),str(giveaway),str(nowticket)),msg_id)
                                    arr = []
                                    text = '[指令使用提示]\n使用者:\n'
                                    mention = "@x "
                                    slen = str(len(text))
                                    elen = str(len(text) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':sender}
                                    arr.append(arrData)
                                    text += mention + "\n於位置:\n{}\n使用兌換指令\n訂單編號:\n{}".format(to,ordernum)
                                    cl.sendMessage(backdoor,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                else:
                                    cl.relatedMessage(to,"禮品碼無效( ´ﾟДﾟ`)\n≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡\n請重複確認您是否輸入正確的禮品碼\n如還有疑問請聯繫作者",msg_id)
                            except:
                                cl.relatedMessage(to,"兌換錯誤!",msg_id)
                        elif text.lower() == '機bye':
                            if to in backdoor:
                                cl.relatedMessage(to,"執行失敗\n您無法將機器退出後臺",msg_id)
                            else:
                                if msg.toType == 1:
                                    cl.relatedMessage(to,"感謝您的使用，機器將退出此副本",msg_id)
                                    cl.leaveRoom(to)
                                elif msg.toType == 2:
                                    cl.relatedMessage(to,"感謝您的使用，機器將退出此群組",msg_id)
                                    cl.leaveGroup(to)
                        elif text.lower() == 'mymid':
                            cl.relatedMessage(to,sender,msg_id)
                        elif text.lower() == 'help':
                            if sender in set["creator"]:
                                cl.relatedMessage(to,"嘿嘿權限者應該自己會知道指令吧",msg_id)
                            elif sender in users:
                                cl.relatedMessage(to,"╭─── 𝓨𝓣𝓔𝓡簡訊機用戶指令表 ───╮\n├─〖 Gc 〗\n├─ ▶查看剩餘票卷◀\n├─〖 機Bye 〗\n├─ ▶機器離開副本\群組◀\n├─〖 領取 〗\n├─ ▶領取特殊活動票卷禮物◀\n├─〖 取得號碼 〗\n├─ ▶獲取接驗證手機◀\n├─〖 取得信箱 〗\n├─ ▶獲取接驗證郵箱◀\n├─〖 國家列表 〗\n├─ ▶獲取所有國家列表◀\n├─〖 模式列表 〗\n├─ ▶獲取所有接收模式◀\n├─〖 服務列表 〗\n├─ ▶獲取所有服務列表◀\n├─〖 設定 〗\n├─ ▶獲取目前號碼取得設定◀\n├─〖 模式:模式代碼 〗\n├─ ▶變更取得模式◀\n├─〖 國家:國家代碼 〗\n├─ ▶變更手機國家◀\n├─〖 服務:服務代碼 〗\n├─ ▶變更接收服務◀\n├─〖 釋放:號碼ID 〗\n├─ ▶釋放號碼◀\n├─〖 兌換:禮品碼 〗\n├─ ▶兌換禮品碼增加票卷◀\n├─〖 丟棄 轉移數量 〗\n├─ ▶轉移指定數量票卷給指定友資◀\n╰───── Çręätę 𝔹𝕪.𝓨𝓣𝓔𝓡 ─────╯",msg_id)
                            else:
                                cl.relatedMessage(to,"╭─── 𝓨𝓣𝓔𝓡簡訊機預設指令表 ───╮\n├─〖 Gc 〗\n├─ ▶查看剩餘票卷◀\n├─〖 機Bye 〗\n├─ ▶機器離開副本\群組◀\n├─〖 領取 〗\n├─ ▶領取特殊活動票卷禮物◀\n├─〖 兌換:禮品碼 〗\n├─ ▶兌換禮品碼增加票卷◀\n╰───── Çręätę 𝔹𝕪.𝓨𝓣𝓔𝓡 ─────╯",msg_id)
                        elif text.lower() == 'gc':
                            if sender in set["creator"] and sender in users:
                                cl.sendReplyMessage(msg_id, to, "@x\n創作者無限領取ヽ(✿ﾟ▽ﾟ)ノ\n強制查詢: {}".format(str(users[sender])), contentMetadata={'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(sender)+'}]}'}, contentType=0)
                            elif sender in set["creator"]:
                                cl.sendReplyMessage(msg_id, to, "@x\n創作者無限領取ヽ(✿ﾟ▽ﾟ)ノ", contentMetadata={'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(sender)+'}]}'}, contentType=0)
                            elif sender in users:
                                if users[sender] > 0:
                                    cl.sendReplyMessage(msg_id, to, "@x\n您還擁有 {} 張票卷(｢`･ω･)｢".format(str(users[sender])), contentMetadata={'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(sender)+'}]}'}, contentType=0)
                                else:
                                    cl.sendReplyMessage(msg_id, to, "@x\n您已經沒有票了(〒︿〒)\n{}\n請找以下友資購買票卷".format(set["adword"]), contentMetadata={'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(sender)+'}]}'}, contentType=0)
                                    cl.sendContact(to,"u8b9d115e85202db06eb798e8c1b40ae9")
                            else:
                                cl.sendReplyMessage(msg_id, to, "@x\n您已經沒有票了(〒︿〒)\n{}\n請找以下友資購買票卷".format(set["adword"]), contentMetadata={'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(sender)+'}]}'}, contentType=0)
                                cl.sendContact(to,"u8b9d115e85202db06eb798e8c1b40ae9")
                        elif text.lower() == '領取':
                            if to not in gift['num']:
                                cl.relatedMessage(to,"沒有禮物可供領取(╯︵╰)",msg_id)
                            else:
                                if sender not in users:
                                    users[sender] = 0
                                num = gift['num'][to]
                                users[sender] += num
                                backupData()
                                del gift['num'][to]
                                cl.relatedMessage(to,"耶!您已經領取到票惹~(～￣▽￣)～",msg_id)
                    if sender in set["creator"]:
                        if text.lower() == '餘額':
                            if set["mode"] == 1:
                                nowmo = "目前設定服務為:\n模式1\n"
                                response = requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'getBalance'}).text.split(':')[1]
                                balance = str(response) + " 盧布\n相當於 "+str(float(response)*0.4)+" 台幣"
                            else:
                                nowmo = "目前設定服務為:\n模式2\n"
                                info_url = set["mode2"]["base_url"] + set["mode2"]["info_route"]
                                params = {
                                    'apikey': set["mode2"]["apikey"]
                                }
                                response = requests.get(info_url, params=params).json()['data']['balance'] / 100
                                balance = str(response)+" 人民幣\n相當於 "+str(response*4)+" 台幣"
                            cl.relatedMessage(to,str(nowmo)+"當前剩餘 "+str(balance),msg_id)
                        elif text.lower() == '空號':
                            if set["mode"] == 1:
                                ct = "目前設定服務為:\n"
                                ct += "模式1\n" + "目前設定國家為:\n" + set["mode1"]["countries"][set["mode1"]["country"]]["name"] + "\n目前設定服務為:\n" + set["mode1"]["services"][set["mode1"]["service"]]
                                ord = requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'getNumbersStatus','country': set["mode1"]["country"]}).json()
                                if set["mode1"]["service"] + "_0" in ord:
                                    ct += "\n目前空號量: " + str(ord[set["mode1"]["service"] + "_0"]) + "隻"
                                else:
                                    ct += "\n目前空號量: " + str(ord[set["mode1"]["service"] + "_1"]) + "隻"
                                cl.relatedMessage(to,str(ct),msg_id)
                            else:
                                cl.relatedMessage(to,"僅模式1可查詢空號",msg_id)
                        elif text.lower().startswith('set:fix:'):
                            x = text.lower()[8:]
                            if x == 'all:on':
                                set['maintenance']['mail'] = True
                                set['maintenance']['mode1'] = True
                                set['maintenance']['mode2'] = True
                                cl.relatedMessage(to,"已開啟信箱維修模式",msg_id)
                                cl.relatedMessage(to,"已開啟模式1維修模式",msg_id)
                                cl.relatedMessage(to,"已開啟模式2維修模式",msg_id)
                            elif x == 'all:off':
                                set['maintenance']['mail'] = False
                                set['maintenance']['mode1'] = False
                                set['maintenance']['mode2'] = False
                                cl.relatedMessage(to,"已關閉信箱維修模式",msg_id)
                                cl.relatedMessage(to,"已關閉模式1維修模式",msg_id)
                                cl.relatedMessage(to,"已關閉模式2維修模式",msg_id)
                            elif x == 'mail':
                                if set['maintenance']['mail']:
                                    set['maintenance']['mail'] = False
                                    cl.relatedMessage(to,"已關閉信箱維修模式",msg_id)
                                else:
                                    set['maintenance']['mail'] = True
                                    cl.relatedMessage(to,"已開啟信箱維修模式",msg_id)
                            elif x == 'mode1':
                                if set['maintenance']['mode1']:
                                    set['maintenance']['mode1'] = False
                                    cl.relatedMessage(to,"已關閉模式1維修模式",msg_id)
                                else:
                                    set['maintenance']['mode1'] = True
                                    cl.relatedMessage(to,"已開啟模式1維修模式",msg_id)
                            elif x == 'mode2':
                                if set['maintenance']['mode2']:
                                    set['maintenance']['mode2'] = False
                                    cl.relatedMessage(to,"已關閉模式2維修模式",msg_id)
                                else:
                                    set['maintenance']['mode2'] = True
                                    cl.relatedMessage(to,"已開啟模式2維修模式",msg_id)
                            else:
                                cl.relatedMessage(to,"參數錯誤",msg_id)
                        elif text.lower() == 'spweb':
                            cl.relatedMessage(to,"測速中請稍後",msg_id)
                            webs = speedtest.Speedtest()
                            webs.get_servers()
                            webs.get_best_server()
                            webs.download()
                            webs.upload()
                            webs.results.share()
                            cl.sendImageWithURL(to,webs.results.dict()['share'])
                        elif text.lower().startswith("createqr:"):
                            qrws = text[9:]
                            cl.sendImageWithURL(to,"https://chart.googleapis.com/chart?cht=qr&chl={}&chs=547x547".format(qrws))
                        elif text.lower().startswith("系統 "):
                            txt = text[3:]
                            try:
                                cl.relatedMessage(to, str(subprocess.Popen([txt], shell=True, stdout=subprocess.PIPE, universal_newlines=True).communicate()[0]),msg_id)
                            except Exception as e:
                                cl.relatedMessage(to,"執行命令錯誤\n"+str(e),msg_id)
                        elif text.lower().startswith("作業 "):
                            txt = text[3:]
                            try:
                                exec(str(txt))
                            except Exception as e:
                                cl.relatedMessage(to,"執行命令錯誤\n"+str(e),msg_id)
                        elif text.lower() == 'msgid':
                            try:
                                cl.relatedMessage(to,msg.relatedMessageId,msg_id)
                            except:
                                cl.relatedMessage(to,"請回覆一個訊息以查詢訊息ID",msg_id)
                        elif text.lower() == 'msgdata':
                            if msg.relatedMessageId:
                                try:
                                    for x in cl.getRecentMessagesV2(to,1000):
                                        if x.id == msg.relatedMessageId:
                                            cl.relatedMessage(to,str(x),msg_id)
                                            break
                                except:
                                    cl.relatedMessage(to,"查詢失敗",msg_id)
                            else:
                                cl.relatedMessage(to,"請回覆一個訊息以查詢訊息資料",msg_id)
                        elif text.lower().startswith("msgdata "):
                            try:
                                nu = int(text[8:]) + 1
                                cl.relatedMessage(to,str(cl.getRecentMessagesV2(to,nu)[-1]),msg_id)
                            except:
                                cl.relatedMessage(to,"查詢失敗",msg_id)
                        elif text.lower().startswith("cmdspam "):
                            cl.relatedMessage(to,"True",msg_id)
                        elif text.lower() == '匯率列表':
                            ret_ = "〖𝓨𝓣𝓔𝓡簡訊機匯率列表〗"
                            no = 0
                            for cts in twder.currencies():
                                no += 1
                                ret_ += "\n[%s]%s" % (no,cts)
                            ret_ += "\n〖總共%s種貨幣可供使用〗" % no
                            cl.relatedMessage(to,ret_,msg_id)
                        elif text.lower().startswith('匯率:'):
                            try:
                                wcts = int(text[3:])
                                wcts -= 1
                                target = twder.currencies()[wcts]
                                tarinfo = twder.now(target)
                                tari = '貨幣種類:{}'.format(target)
                                tarinfo = twder.now(target)
                                tari += '\n更新時間:{}'.format(tarinfo[0])
                                tari += '\n現金買入:{}'.format(tarinfo[1])
                                tari += '\n現金賣出:{}'.format(tarinfo[2])
                                tari += '\n即期買入:{}'.format(tarinfo[3])
                                tari += '\n即期賣出:{}'.format(tarinfo[4])
                                cl.relatedMessage(to,tari,msg_id)
                            except:
                                cl.relatedMessage(to, '查詢失敗',msg_id)
                        elif text.lower() == '帳號關於':
                            clProfile = cl.getProfile()
                            clSetting = cl.getSettings()
                            ret_ = "《個人資料設定》"
                            ret_ += "\n➲帳號地區: {}".format(str(clProfile.regionCode))
                            ret_ += "\n➲帳號語言: {}".format(str(clSetting.preferenceLocale))
                            if clSetting.privacySearchByUserid == True:
                                ret_ += "\n➲允許ID加友: 允許"
                            else:
                                ret_ += "\n➲允許ID加友: 拒絕"
                            if clSetting.privacySearchByPhoneNumber == True:
                                ret_ += "\n➲允許電話加友: 允許"
                            else:
                                ret_ += "\n➲允許電話加友: 拒絕"
                            if clSetting.privacySearchByEmail == True:
                                ret_ += "\n➲允許E-mail加友: 允許"
                            else:
                                ret_ += "\n➲允許E-mail加友: 拒絕"
                            cl.relatedMessage(to, str(ret_),msg_id)
                        elif text.lower().startswith("rb:"):
                            data = text[3:].lower().split(':')
                            if len(data) == 2:data.append("0")
                            elif len(data) >3 or len(data) <2:return
                            try:int(data[2])
                            except:return
                            if data[0] == 'text':
                                n = cl.getGroupIdsJoined()
                                g = 0
                                for manusia in n:
                                    group = cl.getGroup(manusia)
                                    nama =[contact.mid for contact in group.members]
                                    if len(nama) >int(data[2]):
                                        cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《文字》\n" + data[1])
                                        g+=1
                                        time.sleep(0.3)
                                    else:
                                        pass
                                n = cl.getAllContactIds()
                                f = 0
                                for manusia in n:
                                    cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《文字》\n" + data[1])
                                    f+=1
                                    time.sleep(0.3)
                                cl.relatedMessage(to,"➲➲➲廣播➲➲➲\n分享《{}》個群組\n分享《{}》個好友".format(str(g),str(f)),msg_id)
                            elif data[0] in ['pic', 'contact', 'post']:
                                wait['bc'][sender] = {'type':data[0],'text':data[1],'over':data[2]}
                                cl.relatedMessage(to,'請發送你要廣播的東西',msg_id)
                        elif text.lower()  == "test":
                            try:
                                arr = []
                                text = '[系統測試中]\n本機:\n'
                                mention = "@x "
                                slen = str(len(text))
                                elen = str(len(text) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':clMID}
                                arr.append(arrData)
                                text += mention + "\n測試者:\n"
                                mention = "@x "
                                slen = str(len(text))
                                elen = str(len(text) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':sender}
                                arr.append(arrData)
                                text += mention + "\n[正常運行中]"
                                cl.sendReplyMessage(msg_id,to,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                            except:
                                os._exit(0)
                        elif text.lower() == 'lg':
                            groups = cl.groups
                            ret_ = "[群組列表]"
                            no = 1
                            for gid in groups:
                                group = cl.getGroup(gid)
                                ret_ += "\n {}. {} | {}".format(str(no), str(group.name), str(len(group.members)))
                                ret_ += "\n群組ID:{}".format(gid)
                                no += 1
                            ret_ += "\n[總共 {} 個群組]".format(str(len(groups)))
                            cl.relatedMessage(to, str(ret_),msg_id)
                        elif text.lower().startswith('邀請 '):
                            x = text.split(' ')
                            groups = cl.groups
                            targets = []
                            for gid in groups:
                                group = cl.getGroup(gid)
                                targets.append(group.id)
                            c = int(x[1])
                            c = c-1
                            gid = targets[c]
                            group = cl.getGroup(gid)
                            cl.findAndAddContactsByMid(sender)
                            cl.inviteIntoGroup(gid,[sender])
                            cl.relatedMessage(to, "已邀請您至 {} 群組".format(str(group.name)),msg_id)
                        elif text.lower().startswith('網址 '):
                            x = text.split(' ')
                            groups = cl.groups
                            targets = []
                            for gid in groups:
                                group = cl.getGroup(gid)
                                targets.append(group.id)
                            c = int(x[1])
                            c = c-1
                            gid = targets[c]
                            group = cl.getGroup(gid)
                            if group.preventedJoinByTicket == False:
                                cl.updateGroup(group)
                                ticket = cl.reissueGroupTicket(gid)
                                cl.relatedMessage(to, "[ 群組網址 ]\nhttps://line.me/R/ti/g/{}".format(str(ticket)),msg_id)
                            else:
                                group.preventedJoinByTicket = False
                                cl.updateGroup(group)
                                ticket = cl.reissueGroupTicket(gid)
                                cl.relatedMessage(to, "[ 群組網址 ]\nhttps://line.me/R/ti/g/{}".format(str(ticket)),msg_id)
                        elif text.lower().startswith('退出 '):
                            x = text.split(' ')
                            groups = cl.groups
                            targets = []
                            for gid in groups:
                                group = cl.getGroup(gid)
                                targets.append(group.id)
                            c = int(x[1])
                            c = c-1
                            gid = targets[c]
                            group = cl.getGroup(gid)
                            cl.leaveGroup(gid)
                            cl.relatedMessage(to, "已退出 {} 群組".format(str(group.name)),msg_id)
                        elif text.lower() in ['reb','\U00102902\U0010012cr\U0010ffff\U00102902\U0010011fe\U0010ffff\U00102902\U0010011cb\U0010ffff']:
                            if wait["mode1"] == {} and wait["mode2"] == {}:
                                cl.relatedMessage(to, "簡訊機重新啟動中...",msg_id)
                                restartBot()
                            else:
                                cl.relatedMessage(to, "還有用戶取得中",msg_id)
                        elif text.lower() == 'ren':
                            eltime = time.time() - mulai
                            bot = "◤簡訊機運行時間長達◥\n" + Runtime(eltime) + "\n◣簡訊機運行時間測試◢"
                            cl.relatedMessage(to, bot,msg_id)
                        elif text.lower() == '初始化':
                            profile = cl.getProfile()
                            profile.displayName = "End of life"
                            profile.statusMessage = "努力為自己打拼"
                            cl.updateProfile(profile)
                            #cl.updateProfilePicture('ytersms.png')
                            cl.relatedMessage(to,"初始化完成",msg_id)
                        elif text.lower().startswith('查詢:'):
                            try:
                                order = text[3:]
                                if order in set["usedcode"]:
                                    arr = []
                                    text = '[兌換碼資料]\n兌換碼:\n{}\n使用者:\n'.format(set["usedcode"][order]["code"])
                                    mention = "@x "
                                    slen = str(len(text))
                                    elen = str(len(text) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':set["usedcode"][order]["user"]}
                                    arr.append(arrData)
                                    text += mention + "\n開代碼者:\n"
                                    mention = "@x "
                                    slen = str(len(text))
                                    elen = str(len(text) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':set["usedcode"][order]["maker"]}
                                    arr.append(arrData)
                                    text += mention + "\n票數:\n{}\n兌換時間:\n{}".format(str(set["usedcode"][order]["num"]),set["usedcode"][order]["time"])
                                    cl.sendReplyMessage(msg_id, to, text, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                                else:
                                    cl.relatedMessage(to,"訂單編號不存在",msg_id)
                            except:
                                cl.relatedMessage(to,"查詢失敗",msg_id)
                        elif text.lower() == '換頭':
                            wait["clp"] = True
                            cl.relatedMessage(to,"請傳送欲更換的頭貼",msg_id)
                        elif text.lower() == '換封':
                            wait["ccp"] = True
                            cl.relatedMessage(to,"請傳送欲更換的封面",msg_id)
                        elif text.lower() == '充值':
                            if set["mode"] == 1:
                                cl.relatedMessage(to,"目前充值方式: QIWI錢包(信用卡)\n平台手續費: 0.00 盧布",msg_id)
                                cl.relatedMessage(to,"請稍後系統自動嘗試充值",msg_id)
                                time.sleep(2)
                                cl.relatedMessage(to,"自動充值失敗\n原因:\n驗證錯誤\n錯誤碼: error_401",msg_id)
                                #cl.relatedMessage(to,"自動充值失敗\n原因:\n交易遭信用卡發行金融機構拒絕\n錯誤碼: bank_blocked",msg_id)
                        elif text.lower().startswith('發送:'):
                            x = text.split(":")
                            if len(x) < 4:
                                cl.relatedMessage(to,"格式錯誤",msg_id)
                                return
                            gmail_user = '<EMAIL>'
                            gmail_password = '<PASSWORD>'
                            from_address = gmail_user
                            to_address = [x[1]]
                            Subject = x[2]
                            contents = x[3]
                            mail = MIMEMultipart()
                            mail['from'] = from_address
                            mail['to'] = ', '.join(to_address)
                            mail['subject'] = Subject
                            template = Template(Path("mail.html").read_text())
                            body = template.substitute({"text": contents,"sender": cl.getContact(sender).displayName})
                            mail.attach(MIMEText(body, "html"))
                            smtpserver = smtplib.SMTP_SSL("smtp.gmail.com", 465)
                            smtpserver.ehlo()
                            smtpserver.login(gmail_user, gmail_password)
                            smtpserver.send_message(mail)
                            smtpserver.quit()
                            cl.relatedMessage(to,"發送完畢",msg_id)
                        elif text.startswith("創代碼:"):
                            x = text.split(":")
                            if len(x) < 2:
                                cl.relatedMessage(to,"格式錯誤!",msg_id)
                                return
                            code = x[1]
                            if code not in set["code"]:
                                try:
                                    amt = int(x[2])
                                    if amt < 1:
                                        amt = 1
                                except:
                                    amt = 1
                                try:
                                    cmt = int(x[3])
                                    if cmt < 1:
                                        cmt = 1
                                except:
                                    cmt = 1
                                set["code"][code] = {}
                                set["code"][code]["num"] = int(amt)
                                set["code"][code]["maker"] = sender
                                set["code"][code]["usage"] = int(cmt)
                                backupData()
                                cl.relatedMessage(to,"創建成功!\n票數: {} 票\n次數: {} 次\n代碼:\n{}".format(str(amt),str(cmt),code),msg_id)
                            else:
                                cl.relatedMessage(to,"該代碼已存在!",msg_id)
                        elif text.lower() == '清除代碼':
                            set["code"] = {}
                            backupData()
                            cl.relatedMessage(to,"可使用代碼清空完成",msg_id)
                        elif text.lower() == '訂單號歸0':
                            set["codenum"] = 0
                            backupData()
                            cl.relatedMessage(to,"訂單號歸零完成",msg_id)
                        elif text.lower() == '清除代碼紀錄':
                            set["usedcode"] = {}
                            backupData()
                            cl.relatedMessage(to,"代碼紀錄清空完成",msg_id)
                        elif text.startswith("開代碼:"):
                            x = text.split(":")
                            if len(x) < 2:
                                cl.relatedMessage(to,"格式錯誤!",msg_id)
                                return
                            try:
                                num = int(x[1])
                                if num < 1:
                                    num = 1
                            except:
                                num = 1
                            try:
                                amt = int(x[2])
                                if amt < 1:
                                    amt = 1
                            except:
                                amt = 1
                            try:
                                cmt = int(x[3])
                                if cmt < 1:
                                    cmt = 1
                            except:
                                cmt = 1
                            try:
                                ret = "創建完成!\n票數: {} 票\n次數: {} 次\n張數: {} 張".format(str(num),str(amt),str(cmt))
                                for i in range(cmt):
                                    while True:
                                        code = gencode()
                                        if code not in set["code"]:
                                            set["code"][code] = {}
                                            set["code"][code]["num"] = int(num)
                                            set["code"][code]["maker"] = sender
                                            set["code"][code]["usage"] = int(amt)
                                            ret += "\n"+code
                                            break
                                        else:
                                            continue
                                backupData()
                                cl.relatedMessage(to,str(ret),msg_id)
                            except:
                                cl.relatedMessage(to,"生成錯誤!",msg_id)
                        elif text.lower() == '全碼':
                            if set["code"] == {}:
                                cl.relatedMessage(to,"[  禮品碼列表  ]\n無可使用的禮品碼!\n[        結束       ]",msg_id)
                            else:
                                try:
                                    mc = "[  禮品碼列表  ]"
                                    arr = []
                                    mention = "@x "
                                    for cde in set["code"]:
                                        try:
                                            mc += "\n|代碼: [" +cde+"]|"
                                            mc += "\n[票數: {}".format(str(set["code"][cde]["num"]))+"]"
                                            mc += "\n[次數: {}".format(str(set["code"][cde]["usage"]))+"]"
                                            mc += "\n[開代碼者: "
                                            slen = str(len(mc))
                                            elen = str(len(mc) + len(mention) - 1)
                                            arrData = {'S':slen, 'E':elen, 'M':set["code"][cde]["maker"]}
                                            arr.append(arrData)
                                            mc += mention + " ]"
                                        except:
                                            del set["code"][cde]
                                    cl.sendReplyMessage(msg_id, to, mc+"\n[      結束      ]", contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                                except:
                                    cl.relatedMessage(to,"[  禮品碼列表  ]\n列表載入失敗!\n[      結束      ]",msg_id)
                        elif text.lower().startswith("禮物 "):
                            x = text.split(" ")
                            if to in gift['num']:
                                cl.relatedMessage(to,"禮物開啟中｡ﾟヽ(ﾟ´Д`)ﾉﾟ｡",msg_id)
                            else:
                                try:
                                    if len(x) == 2:
                                        if int(x[1]) > 0:
                                            gift['num'][to] = int(x[1])
                                        else:
                                            gift['num'][to] = 1
                                    else:
                                        cl.relatedMessage(to,"禮物票卷數量錯誤!",msg_id)
                                        return
                                except:
                                    gift['num'][to] = 1
                                cl.relatedMessage(to,"禮物已開啟(≧▽≦)\n請輸入領取獲取票卷!\n禮物票卷數量為: {} 票".format(str(gift['num'][to])),msg_id)
                        elif text.lower() == '刷訊息':
                            cl.relatedMessage(to,"[步驟1]請使用以下連結獲取授權碼(請選擇要刷訊息的群組，授權碼為code=後面直到&那串)\nhttps://notify-bot.line.me/oauth/authorize?client_id=a1PBfT8wODo0GuwasrcbLM&response_type=code&scope=notify&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&state=NO_STATE\n[步驟2]將以下友資機器邀入群組\n[步驟3]輸入刷訊息:[授權碼]:[次數]:[內容]\n[步驟4]享受!",msg_id)
                            cl.sendContact(to,"uafadc43f0a6af61a96f1beb389abc576")
                        elif text.lower().startswith("刷訊息:"):
                            x = text[4:].split(":")
                            a = requests.post("https://notify-bot.line.me/oauth/token?grant_type=authorization_code&redirect_uri=http://localhost:3000/&client_id=a1PBfT8wODo0GuwasrcbLM&client_secret=bzTCVoukz2iZr4jds1CMbzQa2ReZB0gAiJ5cfW4aInr&code={}".format(x[0]))
                            headers = {
                                "Authorization": "Bearer " + a.json()["access_token"],
                                "Content-Type" : "application/x-www-form-urlencoded"
                            }
                            payload = {'message': "\n"+x[2]}
                            for owo in range(int(x[1])):
                                requests.post("https://notify-api.line.me/api/notify", headers = headers, params = payload)
                        elif text.lower().startswith("權限 "):
                            targets = []
                            MENTION = eval(msg.contentMetadata['MENTION'])
                            for inkey in MENTION["MENTIONEES"]:
                                targets.append(inkey["M"])
                            for target in targets:
                                if target in set["block"]:
                                    cl.relatedMessage(to, "該用戶位於黑單",msg_id)
                                elif target in set["creator"]:
                                    cl.relatedMessage(to, "該用戶已擁有創作者權限",msg_id)
                                else:
                                    set["creator"].append(target)
                            backupData()
                            cl.relatedMessage(to, "創作者權限給予完畢",msg_id)
                        elif text.lower().startswith("權限:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if not ismid(mid):
                                    continue
                                elif mid in set["block"]:
                                    cl.relatedMessage(to, "該用戶位於黑單",msg_id)
                                elif mid in set["creator"]:
                                    cl.relatedMessage(to, "該用戶已擁有創作者權限",msg_id)
                                else:
                                    set["creator"].append(mid)
                            backupData()
                            cl.relatedMessage(to, "創作者權限給予完畢",msg_id)
                        elif text.lower().startswith("黑單 "):
                            targets = []
                            MENTION = eval(msg.contentMetadata['MENTION'])
                            for inkey in MENTION["MENTIONEES"]:
                                targets.append(inkey["M"])
                            for target in targets:
                                if target in set["creator"]:
                                    cl.relatedMessage(to, "該用戶為創作者",msg_id)
                                elif target in set["block"]:
                                    cl.relatedMessage(to, "該用戶已位於黑單",msg_id)
                                else:
                                    set["block"].append(target)
                                    cl.blockContact(target)
                            backupData()
                            cl.relatedMessage(to, "黑單新增完畢",msg_id)
                        elif text.lower().startswith("黑單:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if not ismid(mid):
                                    continue
                                elif mid in set["creator"]:
                                    cl.relatedMessage(to, "該用戶為創作者",msg_id)
                                elif mid in set["block"]:
                                    cl.relatedMessage(to, "該用戶已位於黑單",msg_id)
                                else:
                                    set["block"].append(mid)
                            backupData()
                            cl.relatedMessage(to, "黑單新增完畢",msg_id)
                        elif text.lower().startswith("加友 "):
                            targets = []
                            key = eval(msg.contentMetadata["MENTION"])
                            key["MENTIONEES"][0]["M"]
                            for x in key["MENTIONEES"]:
                                targets.append(x["M"])
                            a = 0
                            for target in targets:
                                try:
                                    cl.findAndAddContactsByMid(target)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已加入共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("封鎖 "):
                            targets = []
                            key = eval(msg.contentMetadata["MENTION"])
                            key["MENTIONEES"][0]["M"]
                            for x in key["MENTIONEES"]:
                                targets.append(x["M"])
                            a = 0
                            for target in targets:
                                try:
                                    cl.blockContact(target)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已封鎖共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("加友:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if not ismid(mid):
                                    continue
                                try:
                                    cl.findAndAddContactsByMid(mid)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已加入共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("封鎖:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if not ismid(mid):
                                    continue
                                try:
                                    cl.blockContact(mid)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已封鎖共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("解封 "):
                            targets = []
                            key = eval(msg.contentMetadata["MENTION"])
                            key["MENTIONEES"][0]["M"]
                            for x in key["MENTIONEES"]:
                                targets.append(x["M"])
                            a = 0
                            for target in targets:
                                try:
                                    cl.unblockContact(target)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已解封鎖共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("解封:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if not ismid(mid):
                                    continue
                                try:
                                    cl.unblockContact(mid)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已解封鎖共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("解黑 "):
                            targets = []
                            MENTION = eval(msg.contentMetadata['MENTION'])
                            for inkey in MENTION["MENTIONEES"]:
                                targets.append(inkey["M"])
                            for target in targets:
                                if target in set["block"]:
                                    set["block"].remove(target)
                                else:
                                    cl.relatedMessage(to, "該用戶不是黑單",msg_id)
                            backupData()
                            cl.relatedMessage(to, "黑單刪除完畢",msg_id)
                        elif text.lower().startswith("解黑:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if mid in set["block"]:
                                    set["block"].remove(mid)
                                else:
                                    cl.relatedMessage(to, "該用戶不是黑單",msg_id)
                            backupData()
                            cl.relatedMessage(to, "黑單刪除完畢",msg_id)
                        elif text.lower().startswith("刪權限 "):
                            targets = []
                            MENTION = eval(msg.contentMetadata['MENTION'])
                            for inkey in MENTION["MENTIONEES"]:
                                targets.append(inkey["M"])
                            for target in targets:
                                if target in set["creator"]:
                                    set["creator"].remove(target)
                                else:
                                    cl.relatedMessage(to, "該用戶不是創作者",msg_id)
                            backupData()
                            cl.relatedMessage(to, "權限刪除完畢",msg_id)
                        elif text.lower().startswith("刪權限:"):
                            txt = text[4:].split(' ')
                            a = 0
                            for mid in txt:
                                if mid in set["creator"]:
                                    set["creator"].remove(mid)
                                else:
                                    cl.relatedMessage(to, "該用戶不是創作者",msg_id)
                            backupData()
                            cl.relatedMessage(to, "權限刪除完畢",msg_id)
                        elif text.lower() == '封黑合併':
                            for bkm in cl.getBlockedContactIds():
                                if bkm not in set["block"]:
                                    set["block"].append(bkm)
                            for bkm in set["block"]:
                                if bkm not in cl.getBlockedContactIds():
                                    cl.blockContact(bkm)
                            cl.relatedMessage(to,"封鎖用戶與黑單用戶合併完成",msg_id)
                        elif text.lower().startswith("cn:"):
                            string = text[3:]
                            if len(string) <= 20:
                                profile = cl.getProfile()
                                profile.displayName = string
                                cl.updateProfile(profile)
                                cl.relatedMessage(to,"名稱已更改為:\n" + string,msg_id)
                            else:
                                cl.relatedMessage(to,"[警告]\n名稱不能突破20字喔!!\n超過20字並強行更改\n將會凍帳一小時\n以下是您想突破的文字名稱\n" + string,msg_id)
                        elif text.lower().startswith("cb:"):
                            string = text[3:]
                            if len(string) <= 500:
                                profile = cl.getProfile()
                                profile.statusMessage = string
                                cl.updateProfile(profile)
                                cl.relatedMessage(to,"個簽已更改為:\n" + string,msg_id)
                            else:
                                cl.relatedMessage(to,"[警告]\n個簽不能突破500字喔!!\n超過500字並強行更改\n將會凍帳一小時\n以下是您想突破的文字個簽\n" + string,msg_id)
                        elif text.lower().startswith("廣告詞:"):
                            adw = text[4:]
                            set["adword"] = str(adw)
                            backupData()
                            cl.relatedMessage(to,"廣告詞已設定為:\n" + adw,msg_id)
                        elif text.lower().startswith("加票 "):
                            x = text.split(" ")
                            if len(x) == 2:
                                t = 1
                            elif len(x) == 3:
                                try:
                                    t = int(x[2])
                                    if t < 1:
                                        cl.relatedMessage(to,"加票數量請大於0",msg_id)
                                        return
                                except:
                                    cl.relatedMessage(to,"加票數量錯誤!",msg_id)
                                    return
                            else:
                                cl.relatedMessage(to,"格式錯誤!",msg_id)
                                return
                            if not ismid(x[1]):
                                cl.relatedMessage(to,"被加票者MID不存在!",msg_id)
                                return
                            if x[1] not in users:
                                users[x[1]] = t
                            else:
                                users[x[1]] += t
                            backupData()
                            cl.relatedMessage(to,"成功給予票數!",msg_id)
                        elif text.lower().startswith("刪票 "):
                            x = text.split(" ")
                            if len(x) == 2:
                                t = 1
                            elif len(x) == 3:
                                try:
                                    t = int(x[2])
                                    if t < 1:
                                        cl.relatedMessage(to,"刪票數量請大於0",msg_id)
                                        return
                                except:
                                    cl.relatedMessage(to,"刪票數量錯誤!",msg_id)
                                    return
                            else:
                                cl.relatedMessage(to,"格式錯誤!",msg_id)
                                return
                            if x[1] not in users:
                                cl.relatedMessage(to,"該用戶票卷不足!",msg_id)
                                return
                            if users[x[1]] == t:
                                del users[x[1]]
                            elif users[x[1]] > t:
                                users[x[1]] -= t
                            else:
                                cl.relatedMessage(to,"該用戶票數不足!",msg_id)
                                return
                            backupData()
                            cl.relatedMessage(to,"成功刪除票數!",msg_id)
                        elif text.lower().startswith("轉移 "):
                            x = text.split(" ")
                            if len(x) < 3:
                                cl.relatedMessage(to,"格式錯誤!",msg_id)
                                return
                            elif not ismid(x[2]):
                                cl.relatedMessage(to,"轉移者MID不存在!",msg_id)
                            elif x[1] not in users:
                                cl.relatedMessage(to,"被轉移者票卷不足!",msg_id)
                            else:
                                if x[2] not in users:
                                    users[x[2]] = 0
                                if len(x) == 3:
                                    t = 1
                                elif len(x) == 4:
                                    try:
                                        t = int(x[3])
                                        if t < 1:
                                            cl.relatedMessage(to,"轉移數量請大於0",msg_id)
                                            return
                                    except:
                                        cl.relatedMessage(to,"轉移數量錯誤!",msg_id)
                                        return
                                if users[x[1]] < t:
                                    cl.relatedMessage(to,"被轉移者票卷不足!",msg_id)
                                    return
                                elif users[x[1]] == t:
                                    del users[x[1]]
                                    users[x[2]] += t
                                else:
                                    users[x[1]] -= t
                                    users[x[2]] += t
                                backupData()
                                cl.relatedMessage(to,"成功轉移票數!",msg_id)
                        elif text.lower() == '全票':
                            if users == {}:
                                cl.relatedMessage(to,"[  一般用戶票卷名單  ]\n一般用戶票卷名單為空!\n[  砍帳用戶票卷名單  ]\n砍帳用戶票卷名單為空!\n[  　　　結束　　　  ]",msg_id)
                            else:
                                try:
                                    dmc = "[  砍帳用戶票卷名單  ]"
                                    mention = "@x "
                                    no = 0
                                    usersl = []
                                    for mi_d in users:
                                        if ismid(mi_d):
                                            usersl.append(mi_d)
                                        else:
                                            dmc += "\n|使用者MID:{}|\n[數量: {}".format(mi_d,str(users[mi_d]))+"]"
                                    k = len(usersl) // 21
                                    for a in range(k+1):
                                        mc = "[  一般用戶票卷名單  ]"
                                        arr = []
                                        for i in usersl[a*20 : (a+1)*20]:
                                            no += 1
                                            mc += "\n|{}.使用者: ".format(no)
                                            slen = str(len(mc))
                                            elen = str(len(mc) + len(mention) - 1)
                                            arrData = {'S':slen, 'E':elen, 'M':i}
                                            arr.append(arrData)
                                            mc += mention + " |"
                                            mc += "\n[數量: {}".format(str(users[i]))+"]"
                                        if a == k:
                                            mc += "\n[  　　　結束　　　  ]"
                                        cl.sendReplyMessage(msg_id, to, mc, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                                    if dmc == "[  砍帳用戶票卷名單  ]":
                                        dmc += "\n砍帳用戶票卷名單為空!"
                                    cl.sendReplyMessage(msg_id, to, dmc+"\n[  　　　結束　　　  ]", contentType=0)
                                except:
                                    cl.relatedMessage(to,"名單載入失敗!\n請重新載入...",msg_id)
                        elif text.lower().startswith('查全票 '):
                            try:
                                x = text.split(' ')
                                targets = []
                                for user in users:
                                    if ismid(user):
                                        targets.append(user)
                                c = int(x[1])
                                c = c-1
                                user = targets[c]
                                arr = []
                                mc = "[查詢結果]\n用戶: "
                                mention = "@x "
                                slen = str(len(mc))
                                elen = str(len(mc) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':user}
                                arr.append(arrData)
                                mc += mention + " \nMID:\n{}\n數量:{}\n友資:".format(user,str(users[user]))
                                cl.sendReplyMessage(msg_id, to, mc, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                                cl.sendContact(to,user)
                            except:
                                cl.relatedMessage(to,"查詢失敗")
                        elif text.lower() == 'clist':
                            if set["creator"] == []:
                                cl.relatedMessage(to,"[  創作者名單  ]\n創作者名單為空!\n[        結束       ]",msg_id)
                            else:
                                mc = "[  創作者名單  ]"
                                arr = []
                                mention = "@x "
                                for mi_d in set["creator"]:
                                    mc += "\n| "
                                    slen = str(len(mc))
                                    elen = str(len(mc) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':mi_d}
                                    arr.append(arrData)
                                    mc += mention + " |"
                                cl.sendReplyMessage(msg_id, to, mc+"\n[  　　　結束　　　  ]", contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                        elif text.lower() == "fdlist":
                            fdl = cl.getAllContactIds()
                            ap = "[  朋友列表  ]"
                            arr = []
                            mention = "@x "
                            for q in fdl:
                                ap += "\n➲"
                                slen = str(len(ap))
                                elen = str(len(ap) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':q}
                                arr.append(arrData)
                                ap += mention
                            ap += "\n[  總共"+str(len(fdl))+"個好友  ]"
                            cl.sendReplyMessage(msg_id, to, ap, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                        elif text.lower() == 'bklist':
                            if set["block"] == []:
                                cl.relatedMessage(to,"[  機器黑名單  ]\n黑名單為空!\n[        結束       ]",msg_id)
                            else:
                                mc = "[  機器黑名單  ]"
                                arr = []
                                mention = "@x "
                                for mi_d in set["block"]:
                                    mc += "\n| "
                                    slen = str(len(mc))
                                    elen = str(len(mc) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':mi_d}
                                    arr.append(arrData)
                                    mc += mention + " |"
                                cl.sendReplyMessage(msg_id, to, mc+"\n[  　　　結束　　　  ]", contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                            fdl = cl.getBlockedContactIds()
                            if fdl == []:
                                cl.relatedMessage(to,"[  封鎖列表  ]\n封鎖列表為空!\n[  總共0個被封鎖用戶  ]",msg_id)
                            else:
                                ap = "[  封鎖列表  ]"
                                arr = []
                                mention = "@x "
                                for q in fdl:
                                    ap += "\n| "
                                    slen = str(len(ap))
                                    elen = str(len(ap) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':q}
                                    arr.append(arrData)
                                    ap += mention + " |"
                                ap += "\n[  總共"+str(len(fdl))+"個被封鎖用戶  ]"
                                cl.sendReplyMessage(msg_id, to, ap, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                        elif text.lower().startswith("mid "):
                            if 'MENTION' in msg.contentMetadata.keys()!= None:
                                names = re.findall(r'@(\w+)', text)
                                mention = ast.literal_eval(msg.contentMetadata['MENTION'])
                                mentionees = mention['MENTIONEES']
                                lists = []
                                for mention in mentionees:
                                    if mention["M"] not in lists:
                                        lists.append(mention["M"])
                                ret_ = "以下為標住者MID"
                                for ls in lists:
                                    ret_ += "\n" + ls
                                cl.relatedMessage(to, str(ret_),msg_id)
                        elif text.lower().startswith("查票 "):
                            if 'MENTION' in msg.contentMetadata.keys()!= None:
                                names = re.findall(r'@(\w+)', text)
                                mention = ast.literal_eval(msg.contentMetadata['MENTION'])
                                mentionees = mention['MENTIONEES']
                                lists = []
                                for mention in mentionees:
                                    if mention["M"] not in lists:
                                        lists.append(mention["M"])
                                ret_ = "以下為標住者票數"
                                arr = []
                                mention = "@x "
                                for ls in lists:
                                    if ls not in users:
                                        ret_ += "\n|使用者: "
                                        slen = str(len(ret_))
                                        elen = str(len(ret_) + len(mention) - 1)
                                        arrData = {'S':slen, 'E':elen, 'M':ls}
                                        arr.append(arrData)
                                        ret_ += mention + " |"
                                        ret_ += "\n[票數: 0]"
                                    else:
                                        ret_ += "\n|使用者: "
                                        slen = str(len(ret_))
                                        elen = str(len(ret_) + len(mention) - 1)
                                        arrData = {'S':slen, 'E':elen, 'M':ls}
                                        arr.append(arrData)
                                        ret_ += mention + " |"
                                        ret_ += "\n[票數: " + str(users[ls]) + "]"
                                cl.sendReplyMessage(msg_id, to, ret_, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                    if sender in users or sender in set["creator"]:
                        if text.lower().startswith('丟棄 '):
                            x = text.split(" ")
                            if len(x) == 2:
                                try:
                                    if int(x[1]) > 0:
                                        if users[sender] < int(x[1]):
                                            cl.relatedMessage(to,"很遺憾的通知您~\n您的票卷不足喔!",msg_id)
                                        else:
                                            if sender in wait["num"]:
                                                cl.relatedMessage(to,"還在丟棄中",msg_id)
                                            else:
                                                cl.relatedMessage(to,"您選擇丟棄 " + str(x[1]) + " 張票卷",msg_id)
                                                cl.relatedMessage(to,"請丟出垃圾桶友資",msg_id)
                                                wait["num"][sender] = int(x[1])
                                    else:
                                        cl.relatedMessage(to,"丟棄數量請大於0",msg_id)
                                except:
                                    cl.relatedMessage(to,"執行錯誤!",msg_id)
                        elif text.lower() == '模式列表':
                            cl.relatedMessage(to,"〖𝓨𝓣𝓔𝓡簡訊機模式列表〗\n[1]模式1號\n[2]模式2號\n〖總共2個模式可供使用〗",msg_id)
                        elif text.lower() == '國家列表':
                            ret_ = "〖𝓨𝓣𝓔𝓡簡訊機國家列表〗"
                            no = 0
                            if set["mode"] == 1:
                                cl.relatedMessage(to,"目前選擇:模式1\n請稍後載入中",msg_id)
                                for cts in set["mode1"]["countries"]:
                                    no += 1
                                    ret_ += "\n[%s]%s" % (no,set["mode1"]["countries"][cts]["name"])
                            else:
                                cl.relatedMessage(to,"目前選擇:模式2\n請稍後載入中",msg_id)
                                for cts in set["mode2"]["countries"]:
                                    no += 1
                                    ret_ += "\n[%s]%s" % (no,set["mode2"]["countries"][cts])
                            ret_ += "\n〖總共%s個國家可供使用〗" % no
                            cl.relatedMessage(to,ret_,msg_id)
                        elif text.lower() == '服務列表':
                            ret_ = "〖　𝓨𝓣𝓔𝓡 簡訊機服務列表　〗"
                            no = 0
                            if set["mode"] == 1:
                                ctced = set["mode1"]["country"]
                                cl.relatedMessage(to,"目前選擇:模式1\n目前國家:\n%s\n請稍後載入中"% set["mode1"]["countries"][ctced]["name"],msg_id)
                                for ses in set["mode1"]["services"]:
                                    no += 1
                                    ret_ += "\n[%s]%s【%s票】" % (no,set["mode1"]["services"][ses],set["mode1"]["countries"][ctced]["price"][ses])
                            else:
                                cl.relatedMessage(to,"目前選擇:模式2\n請稍後載入中",msg_id)
                                for chs in set["mode2"]["channels"]:
                                    no += 1
                                    ret_ += "\n[%s]%s【%s票】" % (no,set["mode2"]["channels"][chs]["name"],set["mode2"]["channels"][chs]["price"])
                            ret_ += "\n〖總共%s個服務可供使用〗" % no
                            cl.relatedMessage(to,ret_,msg_id)
                        elif text.lower() == '模式:1':
                            set["mode"] = 1
                            cl.relatedMessage(to,"已切換至模式1",msg_id)
                        elif text.lower() == '模式:2':
                            set["mode"] = 2
                            cl.relatedMessage(to,"已切換至模式2",msg_id)
                        elif text.lower().startswith('國家:'):
                            try:
                                wcts = int(text[3:])
                                targets = []
                                if set["mode"] == 1:
                                    for chs in set["mode1"]["countries"]:
                                        targets.append(chs)
                                    wcts -= 1
                                    target = targets[wcts]
                                    set["mode1"]["country"] = target
                                    arr = []
                                    text_ = '┃系統通知┃\n[使用者]'
                                    mention = "@x "
                                    slen = str(len(text_))
                                    elen = str(len(text_) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':sender}
                                    arr.append(arrData)
                                    text_ += mention + "\n[內容]切換國家為%s\n┃通知結束┃"% set["mode1"]["countries"][target]["name"]
                                    cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                else:
                                    for chs in set["mode2"]["countries"]:
                                        targets.append(chs)
                                    wcts -= 1
                                    target = targets[wcts]
                                    set["mode2"]["country"] = target
                                    arr = []
                                    text_ = '┃系統通知┃\n[使用者]'
                                    mention = "@x "
                                    slen = str(len(text_))
                                    elen = str(len(text_) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':sender}
                                    arr.append(arrData)
                                    text_ += mention + "\n[內容]切換國家為%s\n┃通知結束┃"% set["mode2"]["countries"][target]
                                    cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                            except:
                                arr = []
                                text_ = '┃系統通知┃\n[使用者]'
                                mention = "@x "
                                slen = str(len(text_))
                                elen = str(len(text_) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':sender}
                                arr.append(arrData)
                                text_ += mention + "\n[內容]更改國家失敗\n┃通知結束┃"
                                cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                        elif text.lower().startswith('服務:'):
                            try:
                                wres = int(text[3:])
                                targets = []
                                if set["mode"] == 1:
                                    for ses in set["mode1"]["services"]:
                                        targets.append(ses)
                                    wres -= 1
                                    target = targets[wres]
                                    set["mode1"]["service"] = target
                                    arr = []
                                    text_ = '┃系統通知┃\n[使用者]'
                                    mention = "@x "
                                    slen = str(len(text_))
                                    elen = str(len(text_) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':sender}
                                    arr.append(arrData)
                                    text_ += mention + "\n[內容]切換服務為%s\n┃通知結束┃"% set["mode1"]["services"][target]
                                    cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                else:
                                    for chs in set["mode2"]["channels"]:
                                        targets.append(chs)
                                    wres -= 1
                                    target = targets[wres]
                                    set["mode2"]["channel"] = target
                                    arr = []
                                    text_ = '┃系統通知┃\n[使用者]'
                                    mention = "@x "
                                    slen = str(len(text_))
                                    elen = str(len(text_) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':sender}
                                    arr.append(arrData)
                                    text_ += mention + "\n[內容]切換服務為%s\n┃通知結束┃"% set["mode2"]["channels"][target]["name"]
                                    cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                            except:
                                arr = []
                                text_ = '┃系統通知┃\n[使用者]'
                                mention = "@x "
                                slen = str(len(text_))
                                elen = str(len(text_) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':sender}
                                arr.append(arrData)
                                text_ += mention + "\n[內容]更改服務失敗\n┃通知結束┃"
                                cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                        elif text.lower() == '設定':
                            ct = "目前設定服務為:\n"
                            if set["mode"] == 1:
                                ct += "模式1\n" + "目前設定國家為:\n" + set["mode1"]["countries"][set["mode1"]["country"]]["name"] + "\n目前設定服務為:\n" + set["mode1"]["services"][set["mode1"]["service"]]
                            else:
                                ct += "模式2\n" + "目前設定國家為:\n" + set["mode2"]["countries"][set["mode2"]["country"]] + "\n目前設定服務為:\n" + set["mode2"]["channels"][set["mode2"]["channel"]]["name"]
                            cl.relatedMessage(to,str(ct),msg_id)
                        elif text.lower().startswith('釋放:'):
                            nid = text[3:]
                            if nid in wait["mode1"]:
                                candata = requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'setStatus','status': '8','id': nid}).text
                                if candata == 'ACCESS_CANCEL':
                                    del wait["mode1"][nid]
                                    cl.relatedMessage(to,"釋放完成!",msg_id)
                                else:
                                    cl.relatedMessage(to,"釋放失敗!",msg_id)
                            elif nid in wait["mode2"]:
                                if wait["mode2"][nid] == True:
                                    release_url = set["mode2"]["base_url"] + set["mode2"]["release_route"]
                                    params = {
                                        'orderId': nid,
                                        'apikey': set["mode2"]["apikey"],
                                    }
                                    response = requests.get(release_url, params=params).json()
                                    if response['code'] == 1:
                                        del wait["mode2"][nid]
                                        cl.relatedMessage(to,"釋放完成!",msg_id)
                                    else:
                                        cl.relatedMessage(to,"釋放失敗!",msg_id)
                                else:
                                    cl.relatedMessage(to,"20秒後才可釋放號碼!",msg_id)
                            else:
                                cl.relatedMessage(to,"號碼ID不存在!",msg_id)
                        elif text.lower() == '取得信箱':
                            if set['maintenance']['mail']:
                                cl.relatedMessage(to,"目前信箱處於維修模式\n無法取得信箱",msg_id)
                            else:
                                box = mailbox()
                                cl.relatedMessage(to,"本次驗證碼接收Email為:\n" + str(box.email) + "\n☱☱☱☱接收提醒☱☱☱☱\n#此Email只能收1次驗證碼\n#驗證Email會自動發送",msg_id)
                                arr = []
                                text = '[指令使用提示]\n使用者:\n'
                                mention = "@x "
                                slen = str(len(text))
                                elen = str(len(text) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':sender}
                                arr.append(arrData)
                                text += mention + "\n於位置:\n{}\n使用取得信箱指令\n信箱:\n{}".format(to,str(box.email))
                                cl.sendMessage(backdoor,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                result = json.loads(box.next()[1:])
                                cl.relatedMessage(to,"本次接收到的Email:\n" + str(result["text"]),msg_id)
                        elif text.lower() == '取得號碼':
                            if set["mode"] == 1:
                                if set['maintenance']['mode1']:
                                    cl.relatedMessage(to,"目前模式1處於維修模式\n無法取得號碼",msg_id)
                                else:
                                    srced = set["mode1"]["service"]
                                    ctced = set["mode1"]["country"]
                                    price = set["mode1"]["countries"][ctced]["price"][srced]
                                    if sender not in set["creator"]:
                                        if int(users[sender]) > 0:
                                            if users[sender] >= price:
                                                users[sender] -= price
                                                backupData()
                                            else:
                                                cl.relatedMessage(to,"您的票卷不足\n還需要{}張票卷".format(str(price - users[sender])),msg_id)
                                                return
                                        else:
                                            cl.relatedMessage(to,"您剩餘的票卷正在使用中\n無法取得新號碼",msg_id)
                                            return
                                    ct = "本次簡訊接收國家為:\n"
                                    ct += set["mode1"]["countries"][ctced]["name"] + "\n本次簡訊接收服務為:\n"
                                    ct += set["mode1"]["services"][srced]
                                    cl.relatedMessage(to,str(ct),msg_id)
                                    ord = requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'getNumber','service': srced,'country': ctced}).text
                                    if 'ACCESS_NUMBER' in ord:
                                        ord = ord.split(':')
                                        ordid = ord[1]
                                        ordphone = ord[2]
                                        if '+' not in ordphone:
                                            ordphone = '+' + ordphone
                                        cl.relatedMessage(to,"本次簡訊接收號碼為:\n" + str(ordphone) + "\n本次簡訊號碼ID為:\n"+str(ordid)+"\n☱☱☱☱接收提醒☱☱☱☱\n#此手機號碼只能接1次\n#請您於20分鐘內完成驗證\n#驗證簡訊會自動發送\n#如欲取消請輸入釋放:號碼ID",msg_id)
                                        wait["mode1"][ordid] = True
                                        arr = []
                                        text = '[指令使用提示]\n使用者:\n'
                                        mention = "@x "
                                        slen = str(len(text))
                                        elen = str(len(text) + len(mention) - 1)
                                        arrData = {'S':slen, 'E':elen, 'M':sender}
                                        arr.append(arrData)
                                        text += mention + "\n於位置:\n{}\n使用取得號碼指令\n號碼ID:\n{}".format(to,str(ordid))
                                        cl.sendMessage(backdoor,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                        try:
                                            requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'setStatus','status': '1','id': ordid})
                                            code = getcode1(ordid)
                                            del wait["mode1"][ordid]
                                            cl.relatedMessage(to,"本次驗證碼:\n"+str(code),msg_id)
                                            if sender in set["creator"]:
                                                cl.relatedMessage(to,"創作者使用無須票卷(๑╹◡╹๑)",msg_id)
                                            elif users[sender] < 1:
                                                del users[sender]
                                                backupData()
                                                cl.relatedMessage(to,"您的票卷已全數使用完畢\n歡迎再次購買票卷",msg_id)
                                            else:
                                                cl.relatedMessage(to,"您的{}張票卷已使用完畢".format(str(price)),msg_id)
                                        except Exception as e:
                                            if 'timeout' == str(e):
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"您未在20分鐘內完成驗證!",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"您未在20分鐘內完成驗證!\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                                del wait["mode1"][ordid]
                                            elif 'release' == str(e):
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"您的電話已被釋放!",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"您的電話已被釋放!\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                            else:
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"此次簡訊接收失敗\n抱歉為權限者帶來劣質的服務體驗\n請重新嘗試取得手機",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"此次簡訊接收失敗\n抱歉為您帶來劣質的服務體驗\n請重新嘗試取得手機\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                                del wait["mode1"][ordid]
                                    elif 'NO_NUMBERS' == ord:
                                        if sender in set["creator"]:
                                            cl.relatedMessage(to,"該國家已無空號\n請切換國家並再試一次",msg_id)
                                        else:
                                            cl.relatedMessage(to,"該國家已無空號\n請切換國家並再試一次\n票數將自動加回",msg_id)
                                            users[sender] += price
                                    elif 'NO_BALANCE' == ord:
                                        if sender in set["creator"]:
                                            cl.relatedMessage(to,"系統餘額已經用盡\n請等待作者補充後再使用",msg_id)
                                        else:
                                            cl.relatedMessage(to,"系統餘額已經用盡\n請等待作者補充後再使用\n票數將自動加回",msg_id)
                                            users[sender] += price
                                    else:
                                        if sender in set["creator"]:
                                            cl.relatedMessage(to,"手機取得失敗!\n請切換國家或再試一次\n如還是無法使用請聯繫作者",msg_id)
                                        else:
                                            cl.relatedMessage(to,"手機取得失敗!\n請切換國家或再試一次\n如還是無法使用請聯繫作者\n票數將自動加回",msg_id)
                                            users[sender] += price
                            else:
                                if set['maintenance']['mode2']:
                                    cl.relatedMessage(to,"目前模式2處於維修模式\n無法取得號碼",msg_id)
                                else:
                                    chced = set["mode2"]["channel"]
                                    ctced = set["mode2"]["country"]
                                    price = set["mode2"]["channels"][chced]["price"]
                                    if sender not in set["creator"]:
                                        if int(users[sender]) > 0:
                                            if users[sender] >= price:
                                                users[sender] -= price
                                                backupData()
                                            else:
                                                cl.relatedMessage(to,"您的票卷不足\n還需要{}張票卷".format(str(price - users[sender])),msg_id)
                                                return
                                        else:
                                            cl.relatedMessage(to,"您剩餘的票卷正在使用中\n無法取得新號碼",msg_id)
                                            return
                                    ct = "本次簡訊接收國家為:\n"
                                    ct += set["mode2"]["countries"][ctced] + "\n本次簡訊接收服務為:\n"
                                    ct += set["mode2"]["channels"][chced]["name"]
                                    cl.relatedMessage(to,str(ct),msg_id)
                                    number_url = set["mode2"]["base_url"] + set["mode2"]["number_route"]
                                    params = {
                                        'myPid': chced,
                                        'locale': ctced,
                                        'apikey': set["mode2"]["apikey"]
                                    }
                                    response = requests.get(number_url, params=params).json()
                                    if response['code'] == 1:
                                        ordid = response['data']['orderId']
                                        ordphone = response['data']['number']
                                        if '+' not in ordphone:
                                            ordphone = '+' + ordphone
                                        cl.relatedMessage(to,"本次簡訊接收號碼為:\n" + str(ordphone) + "\n本次簡訊號碼ID為:\n"+str(ordid)+"\n☱☱☱☱接收提醒☱☱☱☱\n#此手機號碼只能接1次\n#請您於10分鐘內完成驗證\n#驗證簡訊會自動發送\n#特殊提醒:{}\n#如欲取消請輸入釋放:號碼ID".format(set["mode2"]["channels"][chced]["notice"]),msg_id)
                                        wait["mode2"][ordid] = False
                                        threading.Thread(target=relsec2, args=(ordid,)).start()
                                        arr = []
                                        text = '[指令使用提示]\n使用者:\n'
                                        mention = "@x "
                                        slen = str(len(text))
                                        elen = str(len(text) + len(mention) - 1)
                                        arrData = {'S':slen, 'E':elen, 'M':sender}
                                        arr.append(arrData)
                                        text += mention + "\n於位置:\n{}\n使用取得指令\n號碼ID:\n{}".format(to,str(ordid))
                                        cl.sendMessage(backdoor,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                        try:
                                            code = getcode2(ordid)
                                            del wait["mode2"][ordid]
                                            cl.relatedMessage(to,"本次驗證碼:\n"+str(code),msg_id)
                                            if sender in set["creator"]:
                                                cl.relatedMessage(to,"創作者使用無須票卷(๑╹◡╹๑)",msg_id)
                                            elif users[sender] < 1:
                                                del users[sender]
                                                backupData()
                                                cl.relatedMessage(to,"您的票卷已全數使用完畢\n歡迎再次購買票卷",msg_id)
                                            else:
                                                cl.relatedMessage(to,"您的{}張票卷已使用完畢".format(str(price)),msg_id)
                                        except Exception as e:
                                            if 'timeout' == str(e):
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"您未在10分鐘內完成驗證!",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"您未在10分鐘內完成驗證!\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                                del wait["mode2"][ordid]
                                            elif 'release' == str(e):
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"您的電話已被釋放!",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"您的電話已被釋放!\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                            else:
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"此次簡訊接收失敗\n抱歉為權限者帶來劣質的服務體驗\n請重新嘗試取得手機",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"此次簡訊接收失敗\n抱歉為您帶來劣質的服務體驗\n請重新嘗試取得手機\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                                del wait["mode2"][ordid]
                                    else:
                                        if sender in set["creator"]:
                                            cl.relatedMessage(to,"手機取得失敗\n請更換國家\n並再試一次",msg_id)
                                        else:
                                            cl.relatedMessage(to,"手機取得失敗\n請更換國家\n並再試一次\n票數將自動加回",msg_id)
                                            users[sender] += price
            if msg.contentType == 1:
                if sender in set["creator"]:
                    if wait["clp"] == True:
                        path = cl.downloadObjectMsg(msg.id)
                        wait["clp"] = False
                        cl.updateProfilePicture(path)
                        cl.relatedMessage(to, "頭貼已更換", msg.id)
                    if wait["ccp"] == True:
                        path = cl.downloadObjectMsg(msg.id)
                        wait["ccp"] = False
                        cl.updateProfileCover(path)
                        cl.relatedMessage(to, "封面已更換", msg.id)
                if sender in wait['bc']:
                    if wait['bc'][sender]['type'] == 'pic':
                        image = cl.downloadObjectMsg(msg.id)
                        n = cl.getGroupIdsJoined()
                        g = 0
                        for manusia in n:
                            group = cl.getGroup(manusia)
                            nama =[contact.mid for contact in group.members]
                            if len(nama) >int(wait['bc'][sender]['over'] ):
                                cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《圖片》\n" + wait['bc'][sender]['text'] )
                                cl.sendImage(manusia,image)
                                g+=1
                            else:
                                pass
                        n = cl.getAllContactIds()
                        f = 0
                        for manusia in n:
                            cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《圖片》\n" + wait['bc'][sender]['text'] )
                            cl.sendImage(manusia,image)
                            f+=1
                            time.sleep(0.3)
                        cl.relatedMessage(to,"➲➲➲廣播➲➲➲\n分享《{}》個群組\n分享《{}》個好友".format(str(g),str(f)), msg.id)
                        cl.deleteFile(image)
                        del wait['bc'][sender]
            if msg.contentType == 13:
                if sender in set["creator"]:
                    mid = msg.contentMetadata["mid"]
                    cl.relatedMessage(to,"該友資MID為:\n"+mid,msg_id)
                if sender in wait['bc']:
                    if wait['bc'][sender]['type'] == 'contact':
                        mid = msg.contentMetadata["mid"]
                        n = cl.getGroupIdsJoined()
                        g = 0
                        for manusia in n:
                            group = cl.getGroup(manusia)
                            nama = [contact.mid for contact in group.members]
                            if len(nama) >int(wait['bc'][sender]['over'] ):
                                cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《友資》\n" + wait['bc'][sender]['text'] )
                                cl.sendContact(manusia,mid)
                                g+=1
                            else:
                                pass
                        n = cl.getAllContactIds()
                        f = 0
                        for manusia in n:
                            cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《友資》\n" + wait['bc'][sender]['text'] )
                            cl.sendContact(manusia,mid)
                            f+=1
                        cl.relatedMessage(to,"➲➲➲廣播➲➲➲\n分享《{}》個群組\n分享《{}》個好友".format(str(g),str(f)), msg.id)
                        del wait['bc'][sender]
                if sender in wait["num"]:
                    mid = msg.contentMetadata["mid"]
                    if mid != sender:
                        if mid not in users:
                            users[mid] = 0
                        t = int(wait["num"][sender])
                        if users[sender] == t:
                            del users[sender]
                            users[mid] += t
                        else:
                            users[sender] -= t
                            users[mid] += t
                        arrData = ""
                        text = '[提示]\n使用者:\n'
                        arr = []
                        mention = "@x "
                        slen = str(len(text))
                        elen = str(len(text) + len(mention) - 1)
                        arrData = {'S':slen, 'E':elen, 'M':sender}
                        arr.append(arrData)
                        text += mention + "\n轉移 {} 票給您".format(str(t))
                        cl.findAndAddContactsByMid(mid)
                        cl.sendMessage(mid,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                        cl.relatedMessage(to,"票卷已全數丟入垃圾桶了!",msg_id)
                        del wait["num"][sender]
                    else:
                        cl.relatedMessage(to,"轉移目標不可為自己!",msg_id)
            if msg.contentType == 16:
                if sender in wait['bc']:
                    if wait['bc'][sender]['type'] == 'post':
                        postid =str(msg.contentMetadata['postEndUrl']).split("&postId=")[1]
                        n = cl.getAllContactIds()
                        g = 0
                        for manusia in n:
                            cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《貼文》\n" + wait['bc'][sender]['text'] )
                            cl.sendPostToTalk(manusia,postid)
                            g+=1
                        n = cl.getAllContactIds()
                        f = 0
                        for manusia in n:
                            cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《貼文》\n" + wait['bc'][sender]['text'] )
                            cl.sendPostToTalk(manusia,postid)
                            f+=1
                        cl.sendMessage(to,"➲➲➲廣播➲➲➲\n分享《{}》個群組\n分享《{}》個好友".format(str(g),str(f)), msg.id)
                        del wait['bc'][sender]
            else:pass
    except Exception as error:
        logError(error)
if __name__ == "__main__":
    while True:
        try:
            ops = oepoll.singleTrace(count=50)
            if ops is not None:
                for op in ops:
                    oepoll.setRevision(op.revision)
                    thread = threading.Thread(target=lineBot, args=(op,))
                    thread.start()
        except Exception as e:
            logError(e)

<filename>bot.py
# -*- coding: utf-8 -*-
from linepy import *
from datetime import datetime
from threading import Thread
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from string import Template
from pathlib import Path
from websocket import create_connection
import os,sys,youtube_dl,pafy,requests,json,codecs,time,threading,re,ast,secrets,random,pytz,smtplib,ssl,subprocess,speedtest,twder
timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒')
print("【%s】≣≣≣≣≣▶| 𝓨𝓣𝓔𝓡 簡訊機 |◀≣≣≣≣≣" %timenow)
print("【%s】≣≣≣≣≣▶| 𝓨𝓣𝓔𝓡 SMSBOT |◀≣≣≣≣≣" %timenow)
while True:
    timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒')
    print("【%s】≣≣≣≣≣▶【嘗試登入帳號 Try to login】◀≣≣≣≣≣" %timenow)
    try:
        cl = LINE()
    except Exception as e:
        if e.reason == 'blocked user':
            print("【%s】≣≣≣≣≣▶【帳號已禁言 Blocked User】◀≣≣≣≣≣" %timenow)
            os._exit(0)
        elif e.reason == 'Account ID or password is invalid':
            print("【%s】≣≣≣≣≣▶【帳號不存在 Not a user】◀≣≣≣≣≣" %timenow)
            os._exit(0)
        elif e.reason == 'Account ID and password does not match':
            print("【%s】≣≣≣≣≣▶【密碼不正確 Password error】◀≣≣≣≣≣" %timenow)
            os._exit(0)
        elif e.reason == '':
            print("【%s】≣≣≣≣≣▶【凍帳狀態中 Cold User】◀≣≣≣≣≣" %timenow)
            print("【%s】將於1小時後自動登入")
            counter = 60
            for x in range(60):
                time.sleep(60)
                counter -= 1
                if counter == 0:
                    break
                print("將於{}分鐘後後自動登入".format(counter))
        else:
            print("【%s】≣≣≣≣≣▶【未知原因失敗 Unknown】◀≣≣≣≣≣")
            print(str(e))
            os._exit(0)
    else:
        break
timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒')
print("【%s】≣≣≣≣≣▶【登入成功 Login Success】◀≣≣≣≣≣" %timenow)
print("【%s】≣≣≣≣≣▶【載入系統中  Setting up】◀≣≣≣≣≣" %timenow)
oepoll = OEPoll(cl)
profile = cl.getProfile()
clMID = cl.profile.mid
wait = {
    'rapidFire': {},
    'clp': False,
    'ccp': False,
    'bc': {},
    'mode1': {},
    'mode2': {},
    'num': {}
}
gift = {
    'num':{}
}
backdoor = "rbd07ffb48c082bab980cfd02be9e3837"
set = json.load(codecs.open("data.json","r","utf-8"))
users = json.load(codecs.open("user.json","r","utf-8"))
timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒')
print("【%s】≣≣≣≣≣▶【載入完成 Set up Success】◀≣≣≣≣≣" %timenow)
print("【%s】≣≣≣≣≣▶　　　　|版本號|V7.0　　　　◀≣≣≣≣≣" %timenow)
print("【%s】≣≣≣≣≣▶　【登入者資訊 Bot Info】　◀≣≣≣≣≣" %timenow)
print("【%s】≣≣≣≣≣▶|名稱 Name|%s◀≣≣≣≣≣" % (timenow,cl.profile.displayName))
print("【%s】≣≣≣≣≣▶|代號 Mid|%s◀≣≣≣≣≣" % (timenow,cl.profile.mid))
print("【%s】≣≣≣≣≣▶|金鑰 Token|%s◀≣≣≣≣≣" % (timenow,cl.authToken))
cl.sendMessage(backdoor,"┏━━━━━━━━━━━━━━┓\n┃ %s ┃\n┣━━━━━━━━━━━━━━┫\n┃後台通知 Backdoor Notification┃\n┣━━━━━━━━━━━━━━┫\n┃𝓨𝓣𝓔𝓡簡訊機V7.0系統載入完成┃\n┗━━━━━━━━━━━━━━┛"%(timenow))
timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒')
print("【%s】≣≣≣≣≣▶   【開始運行 Start up】   ◀≣≣≣≣≣" %timenow)
mulai = time.time()
class mailbox(object):
    def __init__(self):
        super(mailbox, self).__init__()
        self.ws = create_connection("wss://dropmail.me/websocket")
        self.next = self.ws.recv
        self.next()
        self.close = self.ws.close
        self.email = self.next()[1:].split(":")[0]
        self.next()
def logError(text):
    report("       系統錯誤 Program Error      ┃\n┣━━━━━━━━━━━━━━┫\n┃"+str(text))
    time_ = datetime.now()
    with open("errorLog.txt","a") as error:
        error.write("\n[%s] %s" % (str(time_), text))
def backupData():
    try:
        json.dump(set,codecs.open('data.json','w','utf-8'), sort_keys=False, indent=4, ensure_ascii=False)
        json.dump(users,codecs.open('user.json','w','utf-8'), sort_keys=False, indent=4, ensure_ascii=False)
        return True
    except Exception as error:
        logError(error)
        return False
def restartBot():
    backupData()
    python = sys.executable
    os.execl(python, python, *sys.argv)
def ismid(mid):
    try:
        cl.getContact(mid)
        return True
    except:
        return False
#===================================================================#
def getcode1(orderId):
    counter = 0
    while True:
        time.sleep(1)
        counter += 1
        if counter >= 1200:
            raise Exception('timeout')
        if orderId in wait['mode1']:
            response = requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'getStatus','id': orderId}).text
            if 'STATUS_OK' in response:
                break
        else:
            raise Exception('release')
    return response.split(':')[1]
#===================================================================#
def relsec2(orderId):
    time.sleep(20)
    wait["mode2"][orderId] = True
def getcode2(orderId):
    veri_url = set["mode2"]["base_url"] + set["mode2"]["veri_route"]
    params = {
        'orderId': orderId,
        'apikey': set["mode2"]["apikey"],
    }
    counter = 0
    while True:
        time.sleep(1)
        counter += 1
        if counter >= 600:
            raise Exception('timeout')
        if orderId in wait['mode2']:
            response = requests.get(veri_url, params=params).json()
            if response['code'] == 1:
                break
        else:
            raise Exception('release')
    return response['data']['code']
#===================================================================#
def report(msg):
    cl.sendMessage(backdoor,"┏━━━━━━━━━━━━━━┓\n┃ %s ┃\n┣━━━━━━━━━━━━━━┫\n┃後台通知 Backdoor Notification┃\n┣━━━━━━━━━━━━━━┫\n┃%s┃\n┗━━━━━━━━━━━━━━┛" % (datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y年%m月%d號%H點%M分%S秒'),str(msg)))
def Runtime(secs):
    mins, secs = divmod(secs,60)
    hours, mins = divmod(mins,60)
    days, hours = divmod(hours, 24)
    return '%02d 天\n%02d 時\n%02d 分\n%02d 秒' % (days, hours, mins, secs)
def gencode():
    list = ["0","9","8","7","6","5","4","3","2","2","1","A","a","B","b","C","c","D","d","E","e","F","f","G","g","H","h","I","i","J","j","K","k","L","l","M","m","N","n","O","o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v","W","w","X","x","Y","y","Z","z"]
    a = random.choice(list)
    b = random.choice(list)
    c = random.choice(list)
    d = random.choice(list)
    e = random.choice(list)
    f = random.choice(list)
    g = random.choice(list)
    h = random.choice(list)
    i = random.choice(list)
    j = random.choice(list)
    k = random.choice(list)
    l = random.choice(list)
    m = random.choice(list)
    n = random.choice(list)
    o = random.choice(list)
    p = random.choice(list)
    code = a+b+c+d+'-'+e+f+g+h+'-'+i+j+k+l+'-'+m+n+o+p
    return code
def lineBot(op):
    try:
        if op.type == 0:
            return
        if op.type == 5:
            cl.findAndAddContactsByMid(op.param1)
            cl.sendMessage(op.param1,"安安！感謝您加我為好友！\n此為𝓨𝓣𝓔𝓡簡訊機！\n作者網址:line.me/ti/p/~najianlin\n作者友資:")
            cl.sendContact(op.param1,"u8b9d115e85202db06eb798e8c1b40ae9")
            cl.sendMessage(backdoor, "@x 加入好友", {'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(op.param1)+'}]}'}, 0)
        if op.type == 13:
            if clMID in op.param3:
                if op.param2 in set["creator"]:
                    cl.acceptGroupInvitation(op.param1)
                    cl.sendMessage(op.param1,"感謝創作者邀我入群！\n此為𝓨𝓣𝓔𝓡簡訊機！")
                else:
                    group = cl.getGroup(op.param1)
                    if len(group.members) >= 5:
                        cl.acceptGroupInvitation(op.param1)
                        cl.sendMessage(op.param1,"感謝您邀請我入群！\n此為𝓨𝓣𝓔𝓡簡訊機！\n作者網址:line.me/ti/p/~najianlin\n作者友資:")
                        cl.sendContact(op.param1,"u8b9d115e85202db06eb798e8c1b40ae9")
                        if "u8b9d115e85202db06eb798e8c1b40ae9" not in [contact.mid for contact in cl.getGroup(op.param1).members]:
                            try:
                                cl.sendMessage(op.param1,"為了增加穩定性\n將自動邀請作者")
                                cl.inviteIntoGroup(op.param1,["u8b9d115e85202db06eb798e8c1b40ae9"])
                                cl.sendMessage(op.param1,"成功邀請作者進入群組")
                            except:
                                cl.sendMessage(op.param1,"為了增加穩定性\n原定應邀請作者\n但因規制無法執行")
                    else:
                        cl.acceptGroupInvitation(op.param1)
                        cl.sendMessage(op.param1,"群組人數小於5人\n機器將離開群組\n如有特殊需求請洽以下友資")
                        cl.sendContact(op.param1,"u8b9d115e85202db06eb798e8c1b40ae9")
                        cl.leaveGroup(op.param1)
        if op.type == 26 or op.type == 25:
            msg = op.message
            text = msg.text
            msg_id = msg.id
            receiver = msg.to
            sender = msg._from
            if msg.toType == 0:
                if sender != cl.profile.mid:
                    to = sender
                else:
                    to = receiver
            else:
                to = receiver
            if sender != cl.profile.mid:
                cl.sendChatChecked(to, msg_id)
            if sender not in set["creator"]:
                if sender in wait["rapidFire"]:
                    if time.time() - wait["rapidFire"][sender] < 3:
                        return
                    else:
                        wait["rapidFire"][sender] = time.time()
                else:
                    wait["rapidFire"][sender] = time.time()
            if msg.contentType == 0:
                if text is None or sender in set["block"]:
                    return
                else:
                    if sender in sender:
                        if text.lower().startswith("兌換:"):
                            codeKeyConfirm = text[3:]
                            try:
                                if codeKeyConfirm in set["code"]:
                                    tz = pytz.timezone("Asia/Taipei")
                                    timeNow = datetime.now(tz=tz)
                                    usedtime = timeNow.strftime('%Y年%m月%d號%H點%M分%S秒')
                                    giveaway = int(set["code"][codeKeyConfirm]["num"])
                                    if sender not in users:
                                        users[sender] = 0
                                    set["codenum"] += 1
                                    ordernum = str(set["codenum"]).zfill(10)
                                    codermguge = int(set["code"][codeKeyConfirm]["usage"]) - 1
                                    set["usedcode"][ordernum] = {"user": sender,"num": giveaway,"code": codeKeyConfirm,"time": usedtime,"maker": set["code"][codeKeyConfirm]["maker"]}
                                    users[sender] += giveaway
                                    if set["code"][codeKeyConfirm]["usage"] > 1:
                                        set["code"][codeKeyConfirm]["usage"] -= 1
                                    else:
                                        del set["code"][codeKeyConfirm]
                                    backupData()
                                    nowticket = users[sender]
                                    cl.relatedMessage(to,"已成功兌換禮品碼(〃∀〃)\n≡≡≡≡≡≡≡≡≡≡≡≡\n已被兌換的禮品碼為:\n[" + str(codeKeyConfirm) + "]\n此次訂單編號為:\n{}\n此禮品碼剩餘兌換次數:\n{}\n\n您的票數已增加 {} 票\n\n您目前剩餘票數為 {} 票".format(ordernum,str(codermguge),str(giveaway),str(nowticket)),msg_id)
                                    arr = []
                                    text = '[指令使用提示]\n使用者:\n'
                                    mention = "@x "
                                    slen = str(len(text))
                                    elen = str(len(text) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':sender}
                                    arr.append(arrData)
                                    text += mention + "\n於位置:\n{}\n使用兌換指令\n訂單編號:\n{}".format(to,ordernum)
                                    cl.sendMessage(backdoor,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                else:
                                    cl.relatedMessage(to,"禮品碼無效( ´ﾟДﾟ`)\n≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡\n請重複確認您是否輸入正確的禮品碼\n如還有疑問請聯繫作者",msg_id)
                            except:
                                cl.relatedMessage(to,"兌換錯誤!",msg_id)
                        elif text.lower() == '機bye':
                            if to in backdoor:
                                cl.relatedMessage(to,"執行失敗\n您無法將機器退出後臺",msg_id)
                            else:
                                if msg.toType == 1:
                                    cl.relatedMessage(to,"感謝您的使用，機器將退出此副本",msg_id)
                                    cl.leaveRoom(to)
                                elif msg.toType == 2:
                                    cl.relatedMessage(to,"感謝您的使用，機器將退出此群組",msg_id)
                                    cl.leaveGroup(to)
                        elif text.lower() == 'mymid':
                            cl.relatedMessage(to,sender,msg_id)
                        elif text.lower() == 'help':
                            if sender in set["creator"]:
                                cl.relatedMessage(to,"嘿嘿權限者應該自己會知道指令吧",msg_id)
                            elif sender in users:
                                cl.relatedMessage(to,"╭─── 𝓨𝓣𝓔𝓡簡訊機用戶指令表 ───╮\n├─〖 Gc 〗\n├─ ▶查看剩餘票卷◀\n├─〖 機Bye 〗\n├─ ▶機器離開副本\群組◀\n├─〖 領取 〗\n├─ ▶領取特殊活動票卷禮物◀\n├─〖 取得號碼 〗\n├─ ▶獲取接驗證手機◀\n├─〖 取得信箱 〗\n├─ ▶獲取接驗證郵箱◀\n├─〖 國家列表 〗\n├─ ▶獲取所有國家列表◀\n├─〖 模式列表 〗\n├─ ▶獲取所有接收模式◀\n├─〖 服務列表 〗\n├─ ▶獲取所有服務列表◀\n├─〖 設定 〗\n├─ ▶獲取目前號碼取得設定◀\n├─〖 模式:模式代碼 〗\n├─ ▶變更取得模式◀\n├─〖 國家:國家代碼 〗\n├─ ▶變更手機國家◀\n├─〖 服務:服務代碼 〗\n├─ ▶變更接收服務◀\n├─〖 釋放:號碼ID 〗\n├─ ▶釋放號碼◀\n├─〖 兌換:禮品碼 〗\n├─ ▶兌換禮品碼增加票卷◀\n├─〖 丟棄 轉移數量 〗\n├─ ▶轉移指定數量票卷給指定友資◀\n╰───── Çręätę 𝔹𝕪.𝓨𝓣𝓔𝓡 ─────╯",msg_id)
                            else:
                                cl.relatedMessage(to,"╭─── 𝓨𝓣𝓔𝓡簡訊機預設指令表 ───╮\n├─〖 Gc 〗\n├─ ▶查看剩餘票卷◀\n├─〖 機Bye 〗\n├─ ▶機器離開副本\群組◀\n├─〖 領取 〗\n├─ ▶領取特殊活動票卷禮物◀\n├─〖 兌換:禮品碼 〗\n├─ ▶兌換禮品碼增加票卷◀\n╰───── Çręätę 𝔹𝕪.𝓨𝓣𝓔𝓡 ─────╯",msg_id)
                        elif text.lower() == 'gc':
                            if sender in set["creator"] and sender in users:
                                cl.sendReplyMessage(msg_id, to, "@x\n創作者無限領取ヽ(✿ﾟ▽ﾟ)ノ\n強制查詢: {}".format(str(users[sender])), contentMetadata={'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(sender)+'}]}'}, contentType=0)
                            elif sender in set["creator"]:
                                cl.sendReplyMessage(msg_id, to, "@x\n創作者無限領取ヽ(✿ﾟ▽ﾟ)ノ", contentMetadata={'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(sender)+'}]}'}, contentType=0)
                            elif sender in users:
                                if users[sender] > 0:
                                    cl.sendReplyMessage(msg_id, to, "@x\n您還擁有 {} 張票卷(｢`･ω･)｢".format(str(users[sender])), contentMetadata={'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(sender)+'}]}'}, contentType=0)
                                else:
                                    cl.sendReplyMessage(msg_id, to, "@x\n您已經沒有票了(〒︿〒)\n{}\n請找以下友資購買票卷".format(set["adword"]), contentMetadata={'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(sender)+'}]}'}, contentType=0)
                                    cl.sendContact(to,"u8b9d115e85202db06eb798e8c1b40ae9")
                            else:
                                cl.sendReplyMessage(msg_id, to, "@x\n您已經沒有票了(〒︿〒)\n{}\n請找以下友資購買票卷".format(set["adword"]), contentMetadata={'MENTION':'{"MENTIONEES":[{"S":"0","E":"2","M":'+json.dumps(sender)+'}]}'}, contentType=0)
                                cl.sendContact(to,"u8b9d115e85202db06eb798e8c1b40ae9")
                        elif text.lower() == '領取':
                            if to not in gift['num']:
                                cl.relatedMessage(to,"沒有禮物可供領取(╯︵╰)",msg_id)
                            else:
                                if sender not in users:
                                    users[sender] = 0
                                num = gift['num'][to]
                                users[sender] += num
                                backupData()
                                del gift['num'][to]
                                cl.relatedMessage(to,"耶!您已經領取到票惹~(～￣▽￣)～",msg_id)
                    if sender in set["creator"]:
                        if text.lower() == '餘額':
                            if set["mode"] == 1:
                                nowmo = "目前設定服務為:\n模式1\n"
                                response = requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'getBalance'}).text.split(':')[1]
                                balance = str(response) + " 盧布\n相當於 "+str(float(response)*0.4)+" 台幣"
                            else:
                                nowmo = "目前設定服務為:\n模式2\n"
                                info_url = set["mode2"]["base_url"] + set["mode2"]["info_route"]
                                params = {
                                    'apikey': set["mode2"]["apikey"]
                                }
                                response = requests.get(info_url, params=params).json()['data']['balance'] / 100
                                balance = str(response)+" 人民幣\n相當於 "+str(response*4)+" 台幣"
                            cl.relatedMessage(to,str(nowmo)+"當前剩餘 "+str(balance),msg_id)
                        elif text.lower() == '空號':
                            if set["mode"] == 1:
                                ct = "目前設定服務為:\n"
                                ct += "模式1\n" + "目前設定國家為:\n" + set["mode1"]["countries"][set["mode1"]["country"]]["name"] + "\n目前設定服務為:\n" + set["mode1"]["services"][set["mode1"]["service"]]
                                ord = requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'getNumbersStatus','country': set["mode1"]["country"]}).json()
                                if set["mode1"]["service"] + "_0" in ord:
                                    ct += "\n目前空號量: " + str(ord[set["mode1"]["service"] + "_0"]) + "隻"
                                else:
                                    ct += "\n目前空號量: " + str(ord[set["mode1"]["service"] + "_1"]) + "隻"
                                cl.relatedMessage(to,str(ct),msg_id)
                            else:
                                cl.relatedMessage(to,"僅模式1可查詢空號",msg_id)
                        elif text.lower().startswith('set:fix:'):
                            x = text.lower()[8:]
                            if x == 'all:on':
                                set['maintenance']['mail'] = True
                                set['maintenance']['mode1'] = True
                                set['maintenance']['mode2'] = True
                                cl.relatedMessage(to,"已開啟信箱維修模式",msg_id)
                                cl.relatedMessage(to,"已開啟模式1維修模式",msg_id)
                                cl.relatedMessage(to,"已開啟模式2維修模式",msg_id)
                            elif x == 'all:off':
                                set['maintenance']['mail'] = False
                                set['maintenance']['mode1'] = False
                                set['maintenance']['mode2'] = False
                                cl.relatedMessage(to,"已關閉信箱維修模式",msg_id)
                                cl.relatedMessage(to,"已關閉模式1維修模式",msg_id)
                                cl.relatedMessage(to,"已關閉模式2維修模式",msg_id)
                            elif x == 'mail':
                                if set['maintenance']['mail']:
                                    set['maintenance']['mail'] = False
                                    cl.relatedMessage(to,"已關閉信箱維修模式",msg_id)
                                else:
                                    set['maintenance']['mail'] = True
                                    cl.relatedMessage(to,"已開啟信箱維修模式",msg_id)
                            elif x == 'mode1':
                                if set['maintenance']['mode1']:
                                    set['maintenance']['mode1'] = False
                                    cl.relatedMessage(to,"已關閉模式1維修模式",msg_id)
                                else:
                                    set['maintenance']['mode1'] = True
                                    cl.relatedMessage(to,"已開啟模式1維修模式",msg_id)
                            elif x == 'mode2':
                                if set['maintenance']['mode2']:
                                    set['maintenance']['mode2'] = False
                                    cl.relatedMessage(to,"已關閉模式2維修模式",msg_id)
                                else:
                                    set['maintenance']['mode2'] = True
                                    cl.relatedMessage(to,"已開啟模式2維修模式",msg_id)
                            else:
                                cl.relatedMessage(to,"參數錯誤",msg_id)
                        elif text.lower() == 'spweb':
                            cl.relatedMessage(to,"測速中請稍後",msg_id)
                            webs = speedtest.Speedtest()
                            webs.get_servers()
                            webs.get_best_server()
                            webs.download()
                            webs.upload()
                            webs.results.share()
                            cl.sendImageWithURL(to,webs.results.dict()['share'])
                        elif text.lower().startswith("createqr:"):
                            qrws = text[9:]
                            cl.sendImageWithURL(to,"https://chart.googleapis.com/chart?cht=qr&chl={}&chs=547x547".format(qrws))
                        elif text.lower().startswith("系統 "):
                            txt = text[3:]
                            try:
                                cl.relatedMessage(to, str(subprocess.Popen([txt], shell=True, stdout=subprocess.PIPE, universal_newlines=True).communicate()[0]),msg_id)
                            except Exception as e:
                                cl.relatedMessage(to,"執行命令錯誤\n"+str(e),msg_id)
                        elif text.lower().startswith("作業 "):
                            txt = text[3:]
                            try:
                                exec(str(txt))
                            except Exception as e:
                                cl.relatedMessage(to,"執行命令錯誤\n"+str(e),msg_id)
                        elif text.lower() == 'msgid':
                            try:
                                cl.relatedMessage(to,msg.relatedMessageId,msg_id)
                            except:
                                cl.relatedMessage(to,"請回覆一個訊息以查詢訊息ID",msg_id)
                        elif text.lower() == 'msgdata':
                            if msg.relatedMessageId:
                                try:
                                    for x in cl.getRecentMessagesV2(to,1000):
                                        if x.id == msg.relatedMessageId:
                                            cl.relatedMessage(to,str(x),msg_id)
                                            break
                                except:
                                    cl.relatedMessage(to,"查詢失敗",msg_id)
                            else:
                                cl.relatedMessage(to,"請回覆一個訊息以查詢訊息資料",msg_id)
                        elif text.lower().startswith("msgdata "):
                            try:
                                nu = int(text[8:]) + 1
                                cl.relatedMessage(to,str(cl.getRecentMessagesV2(to,nu)[-1]),msg_id)
                            except:
                                cl.relatedMessage(to,"查詢失敗",msg_id)
                        elif text.lower().startswith("cmdspam "):
                            cl.relatedMessage(to,"True",msg_id)
                        elif text.lower() == '匯率列表':
                            ret_ = "〖𝓨𝓣𝓔𝓡簡訊機匯率列表〗"
                            no = 0
                            for cts in twder.currencies():
                                no += 1
                                ret_ += "\n[%s]%s" % (no,cts)
                            ret_ += "\n〖總共%s種貨幣可供使用〗" % no
                            cl.relatedMessage(to,ret_,msg_id)
                        elif text.lower().startswith('匯率:'):
                            try:
                                wcts = int(text[3:])
                                wcts -= 1
                                target = twder.currencies()[wcts]
                                tarinfo = twder.now(target)
                                tari = '貨幣種類:{}'.format(target)
                                tarinfo = twder.now(target)
                                tari += '\n更新時間:{}'.format(tarinfo[0])
                                tari += '\n現金買入:{}'.format(tarinfo[1])
                                tari += '\n現金賣出:{}'.format(tarinfo[2])
                                tari += '\n即期買入:{}'.format(tarinfo[3])
                                tari += '\n即期賣出:{}'.format(tarinfo[4])
                                cl.relatedMessage(to,tari,msg_id)
                            except:
                                cl.relatedMessage(to, '查詢失敗',msg_id)
                        elif text.lower() == '帳號關於':
                            clProfile = cl.getProfile()
                            clSetting = cl.getSettings()
                            ret_ = "《個人資料設定》"
                            ret_ += "\n➲帳號地區: {}".format(str(clProfile.regionCode))
                            ret_ += "\n➲帳號語言: {}".format(str(clSetting.preferenceLocale))
                            if clSetting.privacySearchByUserid == True:
                                ret_ += "\n➲允許ID加友: 允許"
                            else:
                                ret_ += "\n➲允許ID加友: 拒絕"
                            if clSetting.privacySearchByPhoneNumber == True:
                                ret_ += "\n➲允許電話加友: 允許"
                            else:
                                ret_ += "\n➲允許電話加友: 拒絕"
                            if clSetting.privacySearchByEmail == True:
                                ret_ += "\n➲允許E-mail加友: 允許"
                            else:
                                ret_ += "\n➲允許E-mail加友: 拒絕"
                            cl.relatedMessage(to, str(ret_),msg_id)
                        elif text.lower().startswith("rb:"):
                            data = text[3:].lower().split(':')
                            if len(data) == 2:data.append("0")
                            elif len(data) >3 or len(data) <2:return
                            try:int(data[2])
                            except:return
                            if data[0] == 'text':
                                n = cl.getGroupIdsJoined()
                                g = 0
                                for manusia in n:
                                    group = cl.getGroup(manusia)
                                    nama =[contact.mid for contact in group.members]
                                    if len(nama) >int(data[2]):
                                        cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《文字》\n" + data[1])
                                        g+=1
                                        time.sleep(0.3)
                                    else:
                                        pass
                                n = cl.getAllContactIds()
                                f = 0
                                for manusia in n:
                                    cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《文字》\n" + data[1])
                                    f+=1
                                    time.sleep(0.3)
                                cl.relatedMessage(to,"➲➲➲廣播➲➲➲\n分享《{}》個群組\n分享《{}》個好友".format(str(g),str(f)),msg_id)
                            elif data[0] in ['pic', 'contact', 'post']:
                                wait['bc'][sender] = {'type':data[0],'text':data[1],'over':data[2]}
                                cl.relatedMessage(to,'請發送你要廣播的東西',msg_id)
                        elif text.lower()  == "test":
                            try:
                                arr = []
                                text = '[系統測試中]\n本機:\n'
                                mention = "@x "
                                slen = str(len(text))
                                elen = str(len(text) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':clMID}
                                arr.append(arrData)
                                text += mention + "\n測試者:\n"
                                mention = "@x "
                                slen = str(len(text))
                                elen = str(len(text) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':sender}
                                arr.append(arrData)
                                text += mention + "\n[正常運行中]"
                                cl.sendReplyMessage(msg_id,to,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                            except:
                                os._exit(0)
                        elif text.lower() == 'lg':
                            groups = cl.groups
                            ret_ = "[群組列表]"
                            no = 1
                            for gid in groups:
                                group = cl.getGroup(gid)
                                ret_ += "\n {}. {} | {}".format(str(no), str(group.name), str(len(group.members)))
                                ret_ += "\n群組ID:{}".format(gid)
                                no += 1
                            ret_ += "\n[總共 {} 個群組]".format(str(len(groups)))
                            cl.relatedMessage(to, str(ret_),msg_id)
                        elif text.lower().startswith('邀請 '):
                            x = text.split(' ')
                            groups = cl.groups
                            targets = []
                            for gid in groups:
                                group = cl.getGroup(gid)
                                targets.append(group.id)
                            c = int(x[1])
                            c = c-1
                            gid = targets[c]
                            group = cl.getGroup(gid)
                            cl.findAndAddContactsByMid(sender)
                            cl.inviteIntoGroup(gid,[sender])
                            cl.relatedMessage(to, "已邀請您至 {} 群組".format(str(group.name)),msg_id)
                        elif text.lower().startswith('網址 '):
                            x = text.split(' ')
                            groups = cl.groups
                            targets = []
                            for gid in groups:
                                group = cl.getGroup(gid)
                                targets.append(group.id)
                            c = int(x[1])
                            c = c-1
                            gid = targets[c]
                            group = cl.getGroup(gid)
                            if group.preventedJoinByTicket == False:
                                cl.updateGroup(group)
                                ticket = cl.reissueGroupTicket(gid)
                                cl.relatedMessage(to, "[ 群組網址 ]\nhttps://line.me/R/ti/g/{}".format(str(ticket)),msg_id)
                            else:
                                group.preventedJoinByTicket = False
                                cl.updateGroup(group)
                                ticket = cl.reissueGroupTicket(gid)
                                cl.relatedMessage(to, "[ 群組網址 ]\nhttps://line.me/R/ti/g/{}".format(str(ticket)),msg_id)
                        elif text.lower().startswith('退出 '):
                            x = text.split(' ')
                            groups = cl.groups
                            targets = []
                            for gid in groups:
                                group = cl.getGroup(gid)
                                targets.append(group.id)
                            c = int(x[1])
                            c = c-1
                            gid = targets[c]
                            group = cl.getGroup(gid)
                            cl.leaveGroup(gid)
                            cl.relatedMessage(to, "已退出 {} 群組".format(str(group.name)),msg_id)
                        elif text.lower() in ['reb','\U00102902\U0010012cr\U0010ffff\U00102902\U0010011fe\U0010ffff\U00102902\U0010011cb\U0010ffff']:
                            if wait["mode1"] == {} and wait["mode2"] == {}:
                                cl.relatedMessage(to, "簡訊機重新啟動中...",msg_id)
                                restartBot()
                            else:
                                cl.relatedMessage(to, "還有用戶取得中",msg_id)
                        elif text.lower() == 'ren':
                            eltime = time.time() - mulai
                            bot = "◤簡訊機運行時間長達◥\n" + Runtime(eltime) + "\n◣簡訊機運行時間測試◢"
                            cl.relatedMessage(to, bot,msg_id)
                        elif text.lower() == '初始化':
                            profile = cl.getProfile()
                            profile.displayName = "End of life"
                            profile.statusMessage = "努力為自己打拼"
                            cl.updateProfile(profile)
                            #cl.updateProfilePicture('ytersms.png')
                            cl.relatedMessage(to,"初始化完成",msg_id)
                        elif text.lower().startswith('查詢:'):
                            try:
                                order = text[3:]
                                if order in set["usedcode"]:
                                    arr = []
                                    text = '[兌換碼資料]\n兌換碼:\n{}\n使用者:\n'.format(set["usedcode"][order]["code"])
                                    mention = "@x "
                                    slen = str(len(text))
                                    elen = str(len(text) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':set["usedcode"][order]["user"]}
                                    arr.append(arrData)
                                    text += mention + "\n開代碼者:\n"
                                    mention = "@x "
                                    slen = str(len(text))
                                    elen = str(len(text) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':set["usedcode"][order]["maker"]}
                                    arr.append(arrData)
                                    text += mention + "\n票數:\n{}\n兌換時間:\n{}".format(str(set["usedcode"][order]["num"]),set["usedcode"][order]["time"])
                                    cl.sendReplyMessage(msg_id, to, text, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                                else:
                                    cl.relatedMessage(to,"訂單編號不存在",msg_id)
                            except:
                                cl.relatedMessage(to,"查詢失敗",msg_id)
                        elif text.lower() == '換頭':
                            wait["clp"] = True
                            cl.relatedMessage(to,"請傳送欲更換的頭貼",msg_id)
                        elif text.lower() == '換封':
                            wait["ccp"] = True
                            cl.relatedMessage(to,"請傳送欲更換的封面",msg_id)
                        elif text.lower() == '充值':
                            if set["mode"] == 1:
                                cl.relatedMessage(to,"目前充值方式: QIWI錢包(信用卡)\n平台手續費: 0.00 盧布",msg_id)
                                cl.relatedMessage(to,"請稍後系統自動嘗試充值",msg_id)
                                time.sleep(2)
                                cl.relatedMessage(to,"自動充值失敗\n原因:\n驗證錯誤\n錯誤碼: error_401",msg_id)
                                #cl.relatedMessage(to,"自動充值失敗\n原因:\n交易遭信用卡發行金融機構拒絕\n錯誤碼: bank_blocked",msg_id)
                        elif text.lower().startswith('發送:'):
                            x = text.split(":")
                            if len(x) < 4:
                                cl.relatedMessage(to,"格式錯誤",msg_id)
                                return
                            gmail_user = '<EMAIL>'
                            gmail_password = '<PASSWORD>'
                            from_address = gmail_user
                            to_address = [x[1]]
                            Subject = x[2]
                            contents = x[3]
                            mail = MIMEMultipart()
                            mail['from'] = from_address
                            mail['to'] = ', '.join(to_address)
                            mail['subject'] = Subject
                            template = Template(Path("mail.html").read_text())
                            body = template.substitute({"text": contents,"sender": cl.getContact(sender).displayName})
                            mail.attach(MIMEText(body, "html"))
                            smtpserver = smtplib.SMTP_SSL("smtp.gmail.com", 465)
                            smtpserver.ehlo()
                            smtpserver.login(gmail_user, gmail_password)
                            smtpserver.send_message(mail)
                            smtpserver.quit()
                            cl.relatedMessage(to,"發送完畢",msg_id)
                        elif text.startswith("創代碼:"):
                            x = text.split(":")
                            if len(x) < 2:
                                cl.relatedMessage(to,"格式錯誤!",msg_id)
                                return
                            code = x[1]
                            if code not in set["code"]:
                                try:
                                    amt = int(x[2])
                                    if amt < 1:
                                        amt = 1
                                except:
                                    amt = 1
                                try:
                                    cmt = int(x[3])
                                    if cmt < 1:
                                        cmt = 1
                                except:
                                    cmt = 1
                                set["code"][code] = {}
                                set["code"][code]["num"] = int(amt)
                                set["code"][code]["maker"] = sender
                                set["code"][code]["usage"] = int(cmt)
                                backupData()
                                cl.relatedMessage(to,"創建成功!\n票數: {} 票\n次數: {} 次\n代碼:\n{}".format(str(amt),str(cmt),code),msg_id)
                            else:
                                cl.relatedMessage(to,"該代碼已存在!",msg_id)
                        elif text.lower() == '清除代碼':
                            set["code"] = {}
                            backupData()
                            cl.relatedMessage(to,"可使用代碼清空完成",msg_id)
                        elif text.lower() == '訂單號歸0':
                            set["codenum"] = 0
                            backupData()
                            cl.relatedMessage(to,"訂單號歸零完成",msg_id)
                        elif text.lower() == '清除代碼紀錄':
                            set["usedcode"] = {}
                            backupData()
                            cl.relatedMessage(to,"代碼紀錄清空完成",msg_id)
                        elif text.startswith("開代碼:"):
                            x = text.split(":")
                            if len(x) < 2:
                                cl.relatedMessage(to,"格式錯誤!",msg_id)
                                return
                            try:
                                num = int(x[1])
                                if num < 1:
                                    num = 1
                            except:
                                num = 1
                            try:
                                amt = int(x[2])
                                if amt < 1:
                                    amt = 1
                            except:
                                amt = 1
                            try:
                                cmt = int(x[3])
                                if cmt < 1:
                                    cmt = 1
                            except:
                                cmt = 1
                            try:
                                ret = "創建完成!\n票數: {} 票\n次數: {} 次\n張數: {} 張".format(str(num),str(amt),str(cmt))
                                for i in range(cmt):
                                    while True:
                                        code = gencode()
                                        if code not in set["code"]:
                                            set["code"][code] = {}
                                            set["code"][code]["num"] = int(num)
                                            set["code"][code]["maker"] = sender
                                            set["code"][code]["usage"] = int(amt)
                                            ret += "\n"+code
                                            break
                                        else:
                                            continue
                                backupData()
                                cl.relatedMessage(to,str(ret),msg_id)
                            except:
                                cl.relatedMessage(to,"生成錯誤!",msg_id)
                        elif text.lower() == '全碼':
                            if set["code"] == {}:
                                cl.relatedMessage(to,"[  禮品碼列表  ]\n無可使用的禮品碼!\n[        結束       ]",msg_id)
                            else:
                                try:
                                    mc = "[  禮品碼列表  ]"
                                    arr = []
                                    mention = "@x "
                                    for cde in set["code"]:
                                        try:
                                            mc += "\n|代碼: [" +cde+"]|"
                                            mc += "\n[票數: {}".format(str(set["code"][cde]["num"]))+"]"
                                            mc += "\n[次數: {}".format(str(set["code"][cde]["usage"]))+"]"
                                            mc += "\n[開代碼者: "
                                            slen = str(len(mc))
                                            elen = str(len(mc) + len(mention) - 1)
                                            arrData = {'S':slen, 'E':elen, 'M':set["code"][cde]["maker"]}
                                            arr.append(arrData)
                                            mc += mention + " ]"
                                        except:
                                            del set["code"][cde]
                                    cl.sendReplyMessage(msg_id, to, mc+"\n[      結束      ]", contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                                except:
                                    cl.relatedMessage(to,"[  禮品碼列表  ]\n列表載入失敗!\n[      結束      ]",msg_id)
                        elif text.lower().startswith("禮物 "):
                            x = text.split(" ")
                            if to in gift['num']:
                                cl.relatedMessage(to,"禮物開啟中｡ﾟヽ(ﾟ´Д`)ﾉﾟ｡",msg_id)
                            else:
                                try:
                                    if len(x) == 2:
                                        if int(x[1]) > 0:
                                            gift['num'][to] = int(x[1])
                                        else:
                                            gift['num'][to] = 1
                                    else:
                                        cl.relatedMessage(to,"禮物票卷數量錯誤!",msg_id)
                                        return
                                except:
                                    gift['num'][to] = 1
                                cl.relatedMessage(to,"禮物已開啟(≧▽≦)\n請輸入領取獲取票卷!\n禮物票卷數量為: {} 票".format(str(gift['num'][to])),msg_id)
                        elif text.lower() == '刷訊息':
                            cl.relatedMessage(to,"[步驟1]請使用以下連結獲取授權碼(請選擇要刷訊息的群組，授權碼為code=後面直到&那串)\nhttps://notify-bot.line.me/oauth/authorize?client_id=a1PBfT8wODo0GuwasrcbLM&response_type=code&scope=notify&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&state=NO_STATE\n[步驟2]將以下友資機器邀入群組\n[步驟3]輸入刷訊息:[授權碼]:[次數]:[內容]\n[步驟4]享受!",msg_id)
                            cl.sendContact(to,"uafadc43f0a6af61a96f1beb389abc576")
                        elif text.lower().startswith("刷訊息:"):
                            x = text[4:].split(":")
                            a = requests.post("https://notify-bot.line.me/oauth/token?grant_type=authorization_code&redirect_uri=http://localhost:3000/&client_id=a1PBfT8wODo0GuwasrcbLM&client_secret=bzTCVoukz2iZr4jds1CMbzQa2ReZB0gAiJ5cfW4aInr&code={}".format(x[0]))
                            headers = {
                                "Authorization": "Bearer " + a.json()["access_token"],
                                "Content-Type" : "application/x-www-form-urlencoded"
                            }
                            payload = {'message': "\n"+x[2]}
                            for owo in range(int(x[1])):
                                requests.post("https://notify-api.line.me/api/notify", headers = headers, params = payload)
                        elif text.lower().startswith("權限 "):
                            targets = []
                            MENTION = eval(msg.contentMetadata['MENTION'])
                            for inkey in MENTION["MENTIONEES"]:
                                targets.append(inkey["M"])
                            for target in targets:
                                if target in set["block"]:
                                    cl.relatedMessage(to, "該用戶位於黑單",msg_id)
                                elif target in set["creator"]:
                                    cl.relatedMessage(to, "該用戶已擁有創作者權限",msg_id)
                                else:
                                    set["creator"].append(target)
                            backupData()
                            cl.relatedMessage(to, "創作者權限給予完畢",msg_id)
                        elif text.lower().startswith("權限:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if not ismid(mid):
                                    continue
                                elif mid in set["block"]:
                                    cl.relatedMessage(to, "該用戶位於黑單",msg_id)
                                elif mid in set["creator"]:
                                    cl.relatedMessage(to, "該用戶已擁有創作者權限",msg_id)
                                else:
                                    set["creator"].append(mid)
                            backupData()
                            cl.relatedMessage(to, "創作者權限給予完畢",msg_id)
                        elif text.lower().startswith("黑單 "):
                            targets = []
                            MENTION = eval(msg.contentMetadata['MENTION'])
                            for inkey in MENTION["MENTIONEES"]:
                                targets.append(inkey["M"])
                            for target in targets:
                                if target in set["creator"]:
                                    cl.relatedMessage(to, "該用戶為創作者",msg_id)
                                elif target in set["block"]:
                                    cl.relatedMessage(to, "該用戶已位於黑單",msg_id)
                                else:
                                    set["block"].append(target)
                                    cl.blockContact(target)
                            backupData()
                            cl.relatedMessage(to, "黑單新增完畢",msg_id)
                        elif text.lower().startswith("黑單:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if not ismid(mid):
                                    continue
                                elif mid in set["creator"]:
                                    cl.relatedMessage(to, "該用戶為創作者",msg_id)
                                elif mid in set["block"]:
                                    cl.relatedMessage(to, "該用戶已位於黑單",msg_id)
                                else:
                                    set["block"].append(mid)
                            backupData()
                            cl.relatedMessage(to, "黑單新增完畢",msg_id)
                        elif text.lower().startswith("加友 "):
                            targets = []
                            key = eval(msg.contentMetadata["MENTION"])
                            key["MENTIONEES"][0]["M"]
                            for x in key["MENTIONEES"]:
                                targets.append(x["M"])
                            a = 0
                            for target in targets:
                                try:
                                    cl.findAndAddContactsByMid(target)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已加入共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("封鎖 "):
                            targets = []
                            key = eval(msg.contentMetadata["MENTION"])
                            key["MENTIONEES"][0]["M"]
                            for x in key["MENTIONEES"]:
                                targets.append(x["M"])
                            a = 0
                            for target in targets:
                                try:
                                    cl.blockContact(target)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已封鎖共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("加友:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if not ismid(mid):
                                    continue
                                try:
                                    cl.findAndAddContactsByMid(mid)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已加入共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("封鎖:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if not ismid(mid):
                                    continue
                                try:
                                    cl.blockContact(mid)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已封鎖共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("解封 "):
                            targets = []
                            key = eval(msg.contentMetadata["MENTION"])
                            key["MENTIONEES"][0]["M"]
                            for x in key["MENTIONEES"]:
                                targets.append(x["M"])
                            a = 0
                            for target in targets:
                                try:
                                    cl.unblockContact(target)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已解封鎖共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("解封:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if not ismid(mid):
                                    continue
                                try:
                                    cl.unblockContact(mid)
                                    a += 1
                                except:
                                    pass
                            cl.relatedMessage(to,"已解封鎖共" + str(a) + "人",msg_id)
                        elif text.lower().startswith("解黑 "):
                            targets = []
                            MENTION = eval(msg.contentMetadata['MENTION'])
                            for inkey in MENTION["MENTIONEES"]:
                                targets.append(inkey["M"])
                            for target in targets:
                                if target in set["block"]:
                                    set["block"].remove(target)
                                else:
                                    cl.relatedMessage(to, "該用戶不是黑單",msg_id)
                            backupData()
                            cl.relatedMessage(to, "黑單刪除完畢",msg_id)
                        elif text.lower().startswith("解黑:"):
                            txt = text[3:].split(' ')
                            a = 0
                            for mid in txt:
                                if mid in set["block"]:
                                    set["block"].remove(mid)
                                else:
                                    cl.relatedMessage(to, "該用戶不是黑單",msg_id)
                            backupData()
                            cl.relatedMessage(to, "黑單刪除完畢",msg_id)
                        elif text.lower().startswith("刪權限 "):
                            targets = []
                            MENTION = eval(msg.contentMetadata['MENTION'])
                            for inkey in MENTION["MENTIONEES"]:
                                targets.append(inkey["M"])
                            for target in targets:
                                if target in set["creator"]:
                                    set["creator"].remove(target)
                                else:
                                    cl.relatedMessage(to, "該用戶不是創作者",msg_id)
                            backupData()
                            cl.relatedMessage(to, "權限刪除完畢",msg_id)
                        elif text.lower().startswith("刪權限:"):
                            txt = text[4:].split(' ')
                            a = 0
                            for mid in txt:
                                if mid in set["creator"]:
                                    set["creator"].remove(mid)
                                else:
                                    cl.relatedMessage(to, "該用戶不是創作者",msg_id)
                            backupData()
                            cl.relatedMessage(to, "權限刪除完畢",msg_id)
                        elif text.lower() == '封黑合併':
                            for bkm in cl.getBlockedContactIds():
                                if bkm not in set["block"]:
                                    set["block"].append(bkm)
                            for bkm in set["block"]:
                                if bkm not in cl.getBlockedContactIds():
                                    cl.blockContact(bkm)
                            cl.relatedMessage(to,"封鎖用戶與黑單用戶合併完成",msg_id)
                        elif text.lower().startswith("cn:"):
                            string = text[3:]
                            if len(string) <= 20:
                                profile = cl.getProfile()
                                profile.displayName = string
                                cl.updateProfile(profile)
                                cl.relatedMessage(to,"名稱已更改為:\n" + string,msg_id)
                            else:
                                cl.relatedMessage(to,"[警告]\n名稱不能突破20字喔!!\n超過20字並強行更改\n將會凍帳一小時\n以下是您想突破的文字名稱\n" + string,msg_id)
                        elif text.lower().startswith("cb:"):
                            string = text[3:]
                            if len(string) <= 500:
                                profile = cl.getProfile()
                                profile.statusMessage = string
                                cl.updateProfile(profile)
                                cl.relatedMessage(to,"個簽已更改為:\n" + string,msg_id)
                            else:
                                cl.relatedMessage(to,"[警告]\n個簽不能突破500字喔!!\n超過500字並強行更改\n將會凍帳一小時\n以下是您想突破的文字個簽\n" + string,msg_id)
                        elif text.lower().startswith("廣告詞:"):
                            adw = text[4:]
                            set["adword"] = str(adw)
                            backupData()
                            cl.relatedMessage(to,"廣告詞已設定為:\n" + adw,msg_id)
                        elif text.lower().startswith("加票 "):
                            x = text.split(" ")
                            if len(x) == 2:
                                t = 1
                            elif len(x) == 3:
                                try:
                                    t = int(x[2])
                                    if t < 1:
                                        cl.relatedMessage(to,"加票數量請大於0",msg_id)
                                        return
                                except:
                                    cl.relatedMessage(to,"加票數量錯誤!",msg_id)
                                    return
                            else:
                                cl.relatedMessage(to,"格式錯誤!",msg_id)
                                return
                            if not ismid(x[1]):
                                cl.relatedMessage(to,"被加票者MID不存在!",msg_id)
                                return
                            if x[1] not in users:
                                users[x[1]] = t
                            else:
                                users[x[1]] += t
                            backupData()
                            cl.relatedMessage(to,"成功給予票數!",msg_id)
                        elif text.lower().startswith("刪票 "):
                            x = text.split(" ")
                            if len(x) == 2:
                                t = 1
                            elif len(x) == 3:
                                try:
                                    t = int(x[2])
                                    if t < 1:
                                        cl.relatedMessage(to,"刪票數量請大於0",msg_id)
                                        return
                                except:
                                    cl.relatedMessage(to,"刪票數量錯誤!",msg_id)
                                    return
                            else:
                                cl.relatedMessage(to,"格式錯誤!",msg_id)
                                return
                            if x[1] not in users:
                                cl.relatedMessage(to,"該用戶票卷不足!",msg_id)
                                return
                            if users[x[1]] == t:
                                del users[x[1]]
                            elif users[x[1]] > t:
                                users[x[1]] -= t
                            else:
                                cl.relatedMessage(to,"該用戶票數不足!",msg_id)
                                return
                            backupData()
                            cl.relatedMessage(to,"成功刪除票數!",msg_id)
                        elif text.lower().startswith("轉移 "):
                            x = text.split(" ")
                            if len(x) < 3:
                                cl.relatedMessage(to,"格式錯誤!",msg_id)
                                return
                            elif not ismid(x[2]):
                                cl.relatedMessage(to,"轉移者MID不存在!",msg_id)
                            elif x[1] not in users:
                                cl.relatedMessage(to,"被轉移者票卷不足!",msg_id)
                            else:
                                if x[2] not in users:
                                    users[x[2]] = 0
                                if len(x) == 3:
                                    t = 1
                                elif len(x) == 4:
                                    try:
                                        t = int(x[3])
                                        if t < 1:
                                            cl.relatedMessage(to,"轉移數量請大於0",msg_id)
                                            return
                                    except:
                                        cl.relatedMessage(to,"轉移數量錯誤!",msg_id)
                                        return
                                if users[x[1]] < t:
                                    cl.relatedMessage(to,"被轉移者票卷不足!",msg_id)
                                    return
                                elif users[x[1]] == t:
                                    del users[x[1]]
                                    users[x[2]] += t
                                else:
                                    users[x[1]] -= t
                                    users[x[2]] += t
                                backupData()
                                cl.relatedMessage(to,"成功轉移票數!",msg_id)
                        elif text.lower() == '全票':
                            if users == {}:
                                cl.relatedMessage(to,"[  一般用戶票卷名單  ]\n一般用戶票卷名單為空!\n[  砍帳用戶票卷名單  ]\n砍帳用戶票卷名單為空!\n[  　　　結束　　　  ]",msg_id)
                            else:
                                try:
                                    dmc = "[  砍帳用戶票卷名單  ]"
                                    mention = "@x "
                                    no = 0
                                    usersl = []
                                    for mi_d in users:
                                        if ismid(mi_d):
                                            usersl.append(mi_d)
                                        else:
                                            dmc += "\n|使用者MID:{}|\n[數量: {}".format(mi_d,str(users[mi_d]))+"]"
                                    k = len(usersl) // 21
                                    for a in range(k+1):
                                        mc = "[  一般用戶票卷名單  ]"
                                        arr = []
                                        for i in usersl[a*20 : (a+1)*20]:
                                            no += 1
                                            mc += "\n|{}.使用者: ".format(no)
                                            slen = str(len(mc))
                                            elen = str(len(mc) + len(mention) - 1)
                                            arrData = {'S':slen, 'E':elen, 'M':i}
                                            arr.append(arrData)
                                            mc += mention + " |"
                                            mc += "\n[數量: {}".format(str(users[i]))+"]"
                                        if a == k:
                                            mc += "\n[  　　　結束　　　  ]"
                                        cl.sendReplyMessage(msg_id, to, mc, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                                    if dmc == "[  砍帳用戶票卷名單  ]":
                                        dmc += "\n砍帳用戶票卷名單為空!"
                                    cl.sendReplyMessage(msg_id, to, dmc+"\n[  　　　結束　　　  ]", contentType=0)
                                except:
                                    cl.relatedMessage(to,"名單載入失敗!\n請重新載入...",msg_id)
                        elif text.lower().startswith('查全票 '):
                            try:
                                x = text.split(' ')
                                targets = []
                                for user in users:
                                    if ismid(user):
                                        targets.append(user)
                                c = int(x[1])
                                c = c-1
                                user = targets[c]
                                arr = []
                                mc = "[查詢結果]\n用戶: "
                                mention = "@x "
                                slen = str(len(mc))
                                elen = str(len(mc) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':user}
                                arr.append(arrData)
                                mc += mention + " \nMID:\n{}\n數量:{}\n友資:".format(user,str(users[user]))
                                cl.sendReplyMessage(msg_id, to, mc, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                                cl.sendContact(to,user)
                            except:
                                cl.relatedMessage(to,"查詢失敗")
                        elif text.lower() == 'clist':
                            if set["creator"] == []:
                                cl.relatedMessage(to,"[  創作者名單  ]\n創作者名單為空!\n[        結束       ]",msg_id)
                            else:
                                mc = "[  創作者名單  ]"
                                arr = []
                                mention = "@x "
                                for mi_d in set["creator"]:
                                    mc += "\n| "
                                    slen = str(len(mc))
                                    elen = str(len(mc) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':mi_d}
                                    arr.append(arrData)
                                    mc += mention + " |"
                                cl.sendReplyMessage(msg_id, to, mc+"\n[  　　　結束　　　  ]", contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                        elif text.lower() == "fdlist":
                            fdl = cl.getAllContactIds()
                            ap = "[  朋友列表  ]"
                            arr = []
                            mention = "@x "
                            for q in fdl:
                                ap += "\n➲"
                                slen = str(len(ap))
                                elen = str(len(ap) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':q}
                                arr.append(arrData)
                                ap += mention
                            ap += "\n[  總共"+str(len(fdl))+"個好友  ]"
                            cl.sendReplyMessage(msg_id, to, ap, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                        elif text.lower() == 'bklist':
                            if set["block"] == []:
                                cl.relatedMessage(to,"[  機器黑名單  ]\n黑名單為空!\n[        結束       ]",msg_id)
                            else:
                                mc = "[  機器黑名單  ]"
                                arr = []
                                mention = "@x "
                                for mi_d in set["block"]:
                                    mc += "\n| "
                                    slen = str(len(mc))
                                    elen = str(len(mc) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':mi_d}
                                    arr.append(arrData)
                                    mc += mention + " |"
                                cl.sendReplyMessage(msg_id, to, mc+"\n[  　　　結束　　　  ]", contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                            fdl = cl.getBlockedContactIds()
                            if fdl == []:
                                cl.relatedMessage(to,"[  封鎖列表  ]\n封鎖列表為空!\n[  總共0個被封鎖用戶  ]",msg_id)
                            else:
                                ap = "[  封鎖列表  ]"
                                arr = []
                                mention = "@x "
                                for q in fdl:
                                    ap += "\n| "
                                    slen = str(len(ap))
                                    elen = str(len(ap) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':q}
                                    arr.append(arrData)
                                    ap += mention + " |"
                                ap += "\n[  總共"+str(len(fdl))+"個被封鎖用戶  ]"
                                cl.sendReplyMessage(msg_id, to, ap, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                        elif text.lower().startswith("mid "):
                            if 'MENTION' in msg.contentMetadata.keys()!= None:
                                names = re.findall(r'@(\w+)', text)
                                mention = ast.literal_eval(msg.contentMetadata['MENTION'])
                                mentionees = mention['MENTIONEES']
                                lists = []
                                for mention in mentionees:
                                    if mention["M"] not in lists:
                                        lists.append(mention["M"])
                                ret_ = "以下為標住者MID"
                                for ls in lists:
                                    ret_ += "\n" + ls
                                cl.relatedMessage(to, str(ret_),msg_id)
                        elif text.lower().startswith("查票 "):
                            if 'MENTION' in msg.contentMetadata.keys()!= None:
                                names = re.findall(r'@(\w+)', text)
                                mention = ast.literal_eval(msg.contentMetadata['MENTION'])
                                mentionees = mention['MENTIONEES']
                                lists = []
                                for mention in mentionees:
                                    if mention["M"] not in lists:
                                        lists.append(mention["M"])
                                ret_ = "以下為標住者票數"
                                arr = []
                                mention = "@x "
                                for ls in lists:
                                    if ls not in users:
                                        ret_ += "\n|使用者: "
                                        slen = str(len(ret_))
                                        elen = str(len(ret_) + len(mention) - 1)
                                        arrData = {'S':slen, 'E':elen, 'M':ls}
                                        arr.append(arrData)
                                        ret_ += mention + " |"
                                        ret_ += "\n[票數: 0]"
                                    else:
                                        ret_ += "\n|使用者: "
                                        slen = str(len(ret_))
                                        elen = str(len(ret_) + len(mention) - 1)
                                        arrData = {'S':slen, 'E':elen, 'M':ls}
                                        arr.append(arrData)
                                        ret_ += mention + " |"
                                        ret_ += "\n[票數: " + str(users[ls]) + "]"
                                cl.sendReplyMessage(msg_id, to, ret_, contentMetadata={'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, contentType=0)
                    if sender in users or sender in set["creator"]:
                        if text.lower().startswith('丟棄 '):
                            x = text.split(" ")
                            if len(x) == 2:
                                try:
                                    if int(x[1]) > 0:
                                        if users[sender] < int(x[1]):
                                            cl.relatedMessage(to,"很遺憾的通知您~\n您的票卷不足喔!",msg_id)
                                        else:
                                            if sender in wait["num"]:
                                                cl.relatedMessage(to,"還在丟棄中",msg_id)
                                            else:
                                                cl.relatedMessage(to,"您選擇丟棄 " + str(x[1]) + " 張票卷",msg_id)
                                                cl.relatedMessage(to,"請丟出垃圾桶友資",msg_id)
                                                wait["num"][sender] = int(x[1])
                                    else:
                                        cl.relatedMessage(to,"丟棄數量請大於0",msg_id)
                                except:
                                    cl.relatedMessage(to,"執行錯誤!",msg_id)
                        elif text.lower() == '模式列表':
                            cl.relatedMessage(to,"〖𝓨𝓣𝓔𝓡簡訊機模式列表〗\n[1]模式1號\n[2]模式2號\n〖總共2個模式可供使用〗",msg_id)
                        elif text.lower() == '國家列表':
                            ret_ = "〖𝓨𝓣𝓔𝓡簡訊機國家列表〗"
                            no = 0
                            if set["mode"] == 1:
                                cl.relatedMessage(to,"目前選擇:模式1\n請稍後載入中",msg_id)
                                for cts in set["mode1"]["countries"]:
                                    no += 1
                                    ret_ += "\n[%s]%s" % (no,set["mode1"]["countries"][cts]["name"])
                            else:
                                cl.relatedMessage(to,"目前選擇:模式2\n請稍後載入中",msg_id)
                                for cts in set["mode2"]["countries"]:
                                    no += 1
                                    ret_ += "\n[%s]%s" % (no,set["mode2"]["countries"][cts])
                            ret_ += "\n〖總共%s個國家可供使用〗" % no
                            cl.relatedMessage(to,ret_,msg_id)
                        elif text.lower() == '服務列表':
                            ret_ = "〖　𝓨𝓣𝓔𝓡 簡訊機服務列表　〗"
                            no = 0
                            if set["mode"] == 1:
                                ctced = set["mode1"]["country"]
                                cl.relatedMessage(to,"目前選擇:模式1\n目前國家:\n%s\n請稍後載入中"% set["mode1"]["countries"][ctced]["name"],msg_id)
                                for ses in set["mode1"]["services"]:
                                    no += 1
                                    ret_ += "\n[%s]%s【%s票】" % (no,set["mode1"]["services"][ses],set["mode1"]["countries"][ctced]["price"][ses])
                            else:
                                cl.relatedMessage(to,"目前選擇:模式2\n請稍後載入中",msg_id)
                                for chs in set["mode2"]["channels"]:
                                    no += 1
                                    ret_ += "\n[%s]%s【%s票】" % (no,set["mode2"]["channels"][chs]["name"],set["mode2"]["channels"][chs]["price"])
                            ret_ += "\n〖總共%s個服務可供使用〗" % no
                            cl.relatedMessage(to,ret_,msg_id)
                        elif text.lower() == '模式:1':
                            set["mode"] = 1
                            cl.relatedMessage(to,"已切換至模式1",msg_id)
                        elif text.lower() == '模式:2':
                            set["mode"] = 2
                            cl.relatedMessage(to,"已切換至模式2",msg_id)
                        elif text.lower().startswith('國家:'):
                            try:
                                wcts = int(text[3:])
                                targets = []
                                if set["mode"] == 1:
                                    for chs in set["mode1"]["countries"]:
                                        targets.append(chs)
                                    wcts -= 1
                                    target = targets[wcts]
                                    set["mode1"]["country"] = target
                                    arr = []
                                    text_ = '┃系統通知┃\n[使用者]'
                                    mention = "@x "
                                    slen = str(len(text_))
                                    elen = str(len(text_) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':sender}
                                    arr.append(arrData)
                                    text_ += mention + "\n[內容]切換國家為%s\n┃通知結束┃"% set["mode1"]["countries"][target]["name"]
                                    cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                else:
                                    for chs in set["mode2"]["countries"]:
                                        targets.append(chs)
                                    wcts -= 1
                                    target = targets[wcts]
                                    set["mode2"]["country"] = target
                                    arr = []
                                    text_ = '┃系統通知┃\n[使用者]'
                                    mention = "@x "
                                    slen = str(len(text_))
                                    elen = str(len(text_) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':sender}
                                    arr.append(arrData)
                                    text_ += mention + "\n[內容]切換國家為%s\n┃通知結束┃"% set["mode2"]["countries"][target]
                                    cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                            except:
                                arr = []
                                text_ = '┃系統通知┃\n[使用者]'
                                mention = "@x "
                                slen = str(len(text_))
                                elen = str(len(text_) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':sender}
                                arr.append(arrData)
                                text_ += mention + "\n[內容]更改國家失敗\n┃通知結束┃"
                                cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                        elif text.lower().startswith('服務:'):
                            try:
                                wres = int(text[3:])
                                targets = []
                                if set["mode"] == 1:
                                    for ses in set["mode1"]["services"]:
                                        targets.append(ses)
                                    wres -= 1
                                    target = targets[wres]
                                    set["mode1"]["service"] = target
                                    arr = []
                                    text_ = '┃系統通知┃\n[使用者]'
                                    mention = "@x "
                                    slen = str(len(text_))
                                    elen = str(len(text_) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':sender}
                                    arr.append(arrData)
                                    text_ += mention + "\n[內容]切換服務為%s\n┃通知結束┃"% set["mode1"]["services"][target]
                                    cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                else:
                                    for chs in set["mode2"]["channels"]:
                                        targets.append(chs)
                                    wres -= 1
                                    target = targets[wres]
                                    set["mode2"]["channel"] = target
                                    arr = []
                                    text_ = '┃系統通知┃\n[使用者]'
                                    mention = "@x "
                                    slen = str(len(text_))
                                    elen = str(len(text_) + len(mention) - 1)
                                    arrData = {'S':slen, 'E':elen, 'M':sender}
                                    arr.append(arrData)
                                    text_ += mention + "\n[內容]切換服務為%s\n┃通知結束┃"% set["mode2"]["channels"][target]["name"]
                                    cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                            except:
                                arr = []
                                text_ = '┃系統通知┃\n[使用者]'
                                mention = "@x "
                                slen = str(len(text_))
                                elen = str(len(text_) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':sender}
                                arr.append(arrData)
                                text_ += mention + "\n[內容]更改服務失敗\n┃通知結束┃"
                                cl.sendReplyMessage(msg_id,to,text_, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                        elif text.lower() == '設定':
                            ct = "目前設定服務為:\n"
                            if set["mode"] == 1:
                                ct += "模式1\n" + "目前設定國家為:\n" + set["mode1"]["countries"][set["mode1"]["country"]]["name"] + "\n目前設定服務為:\n" + set["mode1"]["services"][set["mode1"]["service"]]
                            else:
                                ct += "模式2\n" + "目前設定國家為:\n" + set["mode2"]["countries"][set["mode2"]["country"]] + "\n目前設定服務為:\n" + set["mode2"]["channels"][set["mode2"]["channel"]]["name"]
                            cl.relatedMessage(to,str(ct),msg_id)
                        elif text.lower().startswith('釋放:'):
                            nid = text[3:]
                            if nid in wait["mode1"]:
                                candata = requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'setStatus','status': '8','id': nid}).text
                                if candata == 'ACCESS_CANCEL':
                                    del wait["mode1"][nid]
                                    cl.relatedMessage(to,"釋放完成!",msg_id)
                                else:
                                    cl.relatedMessage(to,"釋放失敗!",msg_id)
                            elif nid in wait["mode2"]:
                                if wait["mode2"][nid] == True:
                                    release_url = set["mode2"]["base_url"] + set["mode2"]["release_route"]
                                    params = {
                                        'orderId': nid,
                                        'apikey': set["mode2"]["apikey"],
                                    }
                                    response = requests.get(release_url, params=params).json()
                                    if response['code'] == 1:
                                        del wait["mode2"][nid]
                                        cl.relatedMessage(to,"釋放完成!",msg_id)
                                    else:
                                        cl.relatedMessage(to,"釋放失敗!",msg_id)
                                else:
                                    cl.relatedMessage(to,"20秒後才可釋放號碼!",msg_id)
                            else:
                                cl.relatedMessage(to,"號碼ID不存在!",msg_id)
                        elif text.lower() == '取得信箱':
                            if set['maintenance']['mail']:
                                cl.relatedMessage(to,"目前信箱處於維修模式\n無法取得信箱",msg_id)
                            else:
                                box = mailbox()
                                cl.relatedMessage(to,"本次驗證碼接收Email為:\n" + str(box.email) + "\n☱☱☱☱接收提醒☱☱☱☱\n#此Email只能收1次驗證碼\n#驗證Email會自動發送",msg_id)
                                arr = []
                                text = '[指令使用提示]\n使用者:\n'
                                mention = "@x "
                                slen = str(len(text))
                                elen = str(len(text) + len(mention) - 1)
                                arrData = {'S':slen, 'E':elen, 'M':sender}
                                arr.append(arrData)
                                text += mention + "\n於位置:\n{}\n使用取得信箱指令\n信箱:\n{}".format(to,str(box.email))
                                cl.sendMessage(backdoor,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                result = json.loads(box.next()[1:])
                                cl.relatedMessage(to,"本次接收到的Email:\n" + str(result["text"]),msg_id)
                        elif text.lower() == '取得號碼':
                            if set["mode"] == 1:
                                if set['maintenance']['mode1']:
                                    cl.relatedMessage(to,"目前模式1處於維修模式\n無法取得號碼",msg_id)
                                else:
                                    srced = set["mode1"]["service"]
                                    ctced = set["mode1"]["country"]
                                    price = set["mode1"]["countries"][ctced]["price"][srced]
                                    if sender not in set["creator"]:
                                        if int(users[sender]) > 0:
                                            if users[sender] >= price:
                                                users[sender] -= price
                                                backupData()
                                            else:
                                                cl.relatedMessage(to,"您的票卷不足\n還需要{}張票卷".format(str(price - users[sender])),msg_id)
                                                return
                                        else:
                                            cl.relatedMessage(to,"您剩餘的票卷正在使用中\n無法取得新號碼",msg_id)
                                            return
                                    ct = "本次簡訊接收國家為:\n"
                                    ct += set["mode1"]["countries"][ctced]["name"] + "\n本次簡訊接收服務為:\n"
                                    ct += set["mode1"]["services"][srced]
                                    cl.relatedMessage(to,str(ct),msg_id)
                                    ord = requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'getNumber','service': srced,'country': ctced}).text
                                    if 'ACCESS_NUMBER' in ord:
                                        ord = ord.split(':')
                                        ordid = ord[1]
                                        ordphone = ord[2]
                                        if '+' not in ordphone:
                                            ordphone = '+' + ordphone
                                        cl.relatedMessage(to,"本次簡訊接收號碼為:\n" + str(ordphone) + "\n本次簡訊號碼ID為:\n"+str(ordid)+"\n☱☱☱☱接收提醒☱☱☱☱\n#此手機號碼只能接1次\n#請您於20分鐘內完成驗證\n#驗證簡訊會自動發送\n#如欲取消請輸入釋放:號碼ID",msg_id)
                                        wait["mode1"][ordid] = True
                                        arr = []
                                        text = '[指令使用提示]\n使用者:\n'
                                        mention = "@x "
                                        slen = str(len(text))
                                        elen = str(len(text) + len(mention) - 1)
                                        arrData = {'S':slen, 'E':elen, 'M':sender}
                                        arr.append(arrData)
                                        text += mention + "\n於位置:\n{}\n使用取得號碼指令\n號碼ID:\n{}".format(to,str(ordid))
                                        cl.sendMessage(backdoor,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                        try:
                                            requests.get(set["mode1"]["base_url"], params={'api_key': set["mode1"]["apikey"],'action': 'setStatus','status': '1','id': ordid})
                                            code = getcode1(ordid)
                                            del wait["mode1"][ordid]
                                            cl.relatedMessage(to,"本次驗證碼:\n"+str(code),msg_id)
                                            if sender in set["creator"]:
                                                cl.relatedMessage(to,"創作者使用無須票卷(๑╹◡╹๑)",msg_id)
                                            elif users[sender] < 1:
                                                del users[sender]
                                                backupData()
                                                cl.relatedMessage(to,"您的票卷已全數使用完畢\n歡迎再次購買票卷",msg_id)
                                            else:
                                                cl.relatedMessage(to,"您的{}張票卷已使用完畢".format(str(price)),msg_id)
                                        except Exception as e:
                                            if 'timeout' == str(e):
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"您未在20分鐘內完成驗證!",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"您未在20分鐘內完成驗證!\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                                del wait["mode1"][ordid]
                                            elif 'release' == str(e):
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"您的電話已被釋放!",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"您的電話已被釋放!\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                            else:
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"此次簡訊接收失敗\n抱歉為權限者帶來劣質的服務體驗\n請重新嘗試取得手機",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"此次簡訊接收失敗\n抱歉為您帶來劣質的服務體驗\n請重新嘗試取得手機\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                                del wait["mode1"][ordid]
                                    elif 'NO_NUMBERS' == ord:
                                        if sender in set["creator"]:
                                            cl.relatedMessage(to,"該國家已無空號\n請切換國家並再試一次",msg_id)
                                        else:
                                            cl.relatedMessage(to,"該國家已無空號\n請切換國家並再試一次\n票數將自動加回",msg_id)
                                            users[sender] += price
                                    elif 'NO_BALANCE' == ord:
                                        if sender in set["creator"]:
                                            cl.relatedMessage(to,"系統餘額已經用盡\n請等待作者補充後再使用",msg_id)
                                        else:
                                            cl.relatedMessage(to,"系統餘額已經用盡\n請等待作者補充後再使用\n票數將自動加回",msg_id)
                                            users[sender] += price
                                    else:
                                        if sender in set["creator"]:
                                            cl.relatedMessage(to,"手機取得失敗!\n請切換國家或再試一次\n如還是無法使用請聯繫作者",msg_id)
                                        else:
                                            cl.relatedMessage(to,"手機取得失敗!\n請切換國家或再試一次\n如還是無法使用請聯繫作者\n票數將自動加回",msg_id)
                                            users[sender] += price
                            else:
                                if set['maintenance']['mode2']:
                                    cl.relatedMessage(to,"目前模式2處於維修模式\n無法取得號碼",msg_id)
                                else:
                                    chced = set["mode2"]["channel"]
                                    ctced = set["mode2"]["country"]
                                    price = set["mode2"]["channels"][chced]["price"]
                                    if sender not in set["creator"]:
                                        if int(users[sender]) > 0:
                                            if users[sender] >= price:
                                                users[sender] -= price
                                                backupData()
                                            else:
                                                cl.relatedMessage(to,"您的票卷不足\n還需要{}張票卷".format(str(price - users[sender])),msg_id)
                                                return
                                        else:
                                            cl.relatedMessage(to,"您剩餘的票卷正在使用中\n無法取得新號碼",msg_id)
                                            return
                                    ct = "本次簡訊接收國家為:\n"
                                    ct += set["mode2"]["countries"][ctced] + "\n本次簡訊接收服務為:\n"
                                    ct += set["mode2"]["channels"][chced]["name"]
                                    cl.relatedMessage(to,str(ct),msg_id)
                                    number_url = set["mode2"]["base_url"] + set["mode2"]["number_route"]
                                    params = {
                                        'myPid': chced,
                                        'locale': ctced,
                                        'apikey': set["mode2"]["apikey"]
                                    }
                                    response = requests.get(number_url, params=params).json()
                                    if response['code'] == 1:
                                        ordid = response['data']['orderId']
                                        ordphone = response['data']['number']
                                        if '+' not in ordphone:
                                            ordphone = '+' + ordphone
                                        cl.relatedMessage(to,"本次簡訊接收號碼為:\n" + str(ordphone) + "\n本次簡訊號碼ID為:\n"+str(ordid)+"\n☱☱☱☱接收提醒☱☱☱☱\n#此手機號碼只能接1次\n#請您於10分鐘內完成驗證\n#驗證簡訊會自動發送\n#特殊提醒:{}\n#如欲取消請輸入釋放:號碼ID".format(set["mode2"]["channels"][chced]["notice"]),msg_id)
                                        wait["mode2"][ordid] = False
                                        threading.Thread(target=relsec2, args=(ordid,)).start()
                                        arr = []
                                        text = '[指令使用提示]\n使用者:\n'
                                        mention = "@x "
                                        slen = str(len(text))
                                        elen = str(len(text) + len(mention) - 1)
                                        arrData = {'S':slen, 'E':elen, 'M':sender}
                                        arr.append(arrData)
                                        text += mention + "\n於位置:\n{}\n使用取得指令\n號碼ID:\n{}".format(to,str(ordid))
                                        cl.sendMessage(backdoor,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                                        try:
                                            code = getcode2(ordid)
                                            del wait["mode2"][ordid]
                                            cl.relatedMessage(to,"本次驗證碼:\n"+str(code),msg_id)
                                            if sender in set["creator"]:
                                                cl.relatedMessage(to,"創作者使用無須票卷(๑╹◡╹๑)",msg_id)
                                            elif users[sender] < 1:
                                                del users[sender]
                                                backupData()
                                                cl.relatedMessage(to,"您的票卷已全數使用完畢\n歡迎再次購買票卷",msg_id)
                                            else:
                                                cl.relatedMessage(to,"您的{}張票卷已使用完畢".format(str(price)),msg_id)
                                        except Exception as e:
                                            if 'timeout' == str(e):
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"您未在10分鐘內完成驗證!",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"您未在10分鐘內完成驗證!\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                                del wait["mode2"][ordid]
                                            elif 'release' == str(e):
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"您的電話已被釋放!",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"您的電話已被釋放!\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                            else:
                                                if sender in set["creator"]:
                                                    cl.relatedMessage(to,"此次簡訊接收失敗\n抱歉為權限者帶來劣質的服務體驗\n請重新嘗試取得手機",msg_id)
                                                else:
                                                    cl.relatedMessage(to,"此次簡訊接收失敗\n抱歉為您帶來劣質的服務體驗\n請重新嘗試取得手機\n票數將自動加回",msg_id)
                                                    users[sender] += price
                                                del wait["mode2"][ordid]
                                    else:
                                        if sender in set["creator"]:
                                            cl.relatedMessage(to,"手機取得失敗\n請更換國家\n並再試一次",msg_id)
                                        else:
                                            cl.relatedMessage(to,"手機取得失敗\n請更換國家\n並再試一次\n票數將自動加回",msg_id)
                                            users[sender] += price
            if msg.contentType == 1:
                if sender in set["creator"]:
                    if wait["clp"] == True:
                        path = cl.downloadObjectMsg(msg.id)
                        wait["clp"] = False
                        cl.updateProfilePicture(path)
                        cl.relatedMessage(to, "頭貼已更換", msg.id)
                    if wait["ccp"] == True:
                        path = cl.downloadObjectMsg(msg.id)
                        wait["ccp"] = False
                        cl.updateProfileCover(path)
                        cl.relatedMessage(to, "封面已更換", msg.id)
                if sender in wait['bc']:
                    if wait['bc'][sender]['type'] == 'pic':
                        image = cl.downloadObjectMsg(msg.id)
                        n = cl.getGroupIdsJoined()
                        g = 0
                        for manusia in n:
                            group = cl.getGroup(manusia)
                            nama =[contact.mid for contact in group.members]
                            if len(nama) >int(wait['bc'][sender]['over'] ):
                                cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《圖片》\n" + wait['bc'][sender]['text'] )
                                cl.sendImage(manusia,image)
                                g+=1
                            else:
                                pass
                        n = cl.getAllContactIds()
                        f = 0
                        for manusia in n:
                            cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《圖片》\n" + wait['bc'][sender]['text'] )
                            cl.sendImage(manusia,image)
                            f+=1
                            time.sleep(0.3)
                        cl.relatedMessage(to,"➲➲➲廣播➲➲➲\n分享《{}》個群組\n分享《{}》個好友".format(str(g),str(f)), msg.id)
                        cl.deleteFile(image)
                        del wait['bc'][sender]
            if msg.contentType == 13:
                if sender in set["creator"]:
                    mid = msg.contentMetadata["mid"]
                    cl.relatedMessage(to,"該友資MID為:\n"+mid,msg_id)
                if sender in wait['bc']:
                    if wait['bc'][sender]['type'] == 'contact':
                        mid = msg.contentMetadata["mid"]
                        n = cl.getGroupIdsJoined()
                        g = 0
                        for manusia in n:
                            group = cl.getGroup(manusia)
                            nama = [contact.mid for contact in group.members]
                            if len(nama) >int(wait['bc'][sender]['over'] ):
                                cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《友資》\n" + wait['bc'][sender]['text'] )
                                cl.sendContact(manusia,mid)
                                g+=1
                            else:
                                pass
                        n = cl.getAllContactIds()
                        f = 0
                        for manusia in n:
                            cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《友資》\n" + wait['bc'][sender]['text'] )
                            cl.sendContact(manusia,mid)
                            f+=1
                        cl.relatedMessage(to,"➲➲➲廣播➲➲➲\n分享《{}》個群組\n分享《{}》個好友".format(str(g),str(f)), msg.id)
                        del wait['bc'][sender]
                if sender in wait["num"]:
                    mid = msg.contentMetadata["mid"]
                    if mid != sender:
                        if mid not in users:
                            users[mid] = 0
                        t = int(wait["num"][sender])
                        if users[sender] == t:
                            del users[sender]
                            users[mid] += t
                        else:
                            users[sender] -= t
                            users[mid] += t
                        arrData = ""
                        text = '[提示]\n使用者:\n'
                        arr = []
                        mention = "@x "
                        slen = str(len(text))
                        elen = str(len(text) + len(mention) - 1)
                        arrData = {'S':slen, 'E':elen, 'M':sender}
                        arr.append(arrData)
                        text += mention + "\n轉移 {} 票給您".format(str(t))
                        cl.findAndAddContactsByMid(mid)
                        cl.sendMessage(mid,text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
                        cl.relatedMessage(to,"票卷已全數丟入垃圾桶了!",msg_id)
                        del wait["num"][sender]
                    else:
                        cl.relatedMessage(to,"轉移目標不可為自己!",msg_id)
            if msg.contentType == 16:
                if sender in wait['bc']:
                    if wait['bc'][sender]['type'] == 'post':
                        postid =str(msg.contentMetadata['postEndUrl']).split("&postId=")[1]
                        n = cl.getAllContactIds()
                        g = 0
                        for manusia in n:
                            cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《貼文》\n" + wait['bc'][sender]['text'] )
                            cl.sendPostToTalk(manusia,postid)
                            g+=1
                        n = cl.getAllContactIds()
                        f = 0
                        for manusia in n:
                            cl.sendMessage(manusia,"➲➲➲廣播➲➲➲ 《貼文》\n" + wait['bc'][sender]['text'] )
                            cl.sendPostToTalk(manusia,postid)
                            f+=1
                        cl.sendMessage(to,"➲➲➲廣播➲➲➲\n分享《{}》個群組\n分享《{}》個好友".format(str(g),str(f)), msg.id)
                        del wait['bc'][sender]
            else:pass
    except Exception as error:
        logError(error)
if __name__ == "__main__":
    while True:
        try:
            ops = oepoll.singleTrace(count=50)
            if ops is not None:
                for op in ops:
                    oepoll.setRevision(op.revision)
                    thread = threading.Thread(target=lineBot, args=(op,))
                    thread.start()
        except Exception as e:
            logError(e)

# -*- coding: utf-8 -*- #===================================================================# #===================================================================# #===================================================================# #cl.updateProfilePicture('ytersms.png') #cl.relatedMessage(to,"自動充值失敗\n原因:\n交易遭信用卡發行金融機構拒絕\n錯誤碼: bank_blocked",msg_id) #此Email只能收1次驗證碼\n#驗證Email會自動發送",msg_id) #此手機號碼只能接1次\n#請您於20分鐘內完成驗證\n#驗證簡訊會自動發送\n#如欲取消請輸入釋放:號碼ID",msg_id) #此手機號碼只能接1次\n#請您於10分鐘內完成驗證\n#驗證簡訊會自動發送\n#特殊提醒:{}\n#如欲取消請輸入釋放:號碼ID".format(set["mode2"]["channels"][chced]["notice"]),msg_id)