text: # -*- coding: utf-8 -*-
  
  # ===============引入模組================ #
  from __future__ import unicode_literals
  from argparse import ArgumentParser
  from flask import Flask, request, abort, send_from_directory
  from werkzeug.middleware.proxy_fix import ProxyFix
  from urlextract import URLExtract
  from bs4 import BeautifulSoup
  import threading
  import requests
  import urllib.parse
  import youtube_dl
  import pafy
  import tempfile
  import sys
  import os
  import json
  import errno
  import datetime
  import random
  import re
  import subprocess
  import codecs
  import time
  import traceback
  from linebot import (
      LineBotApi, WebhookHandler
  )
  from linebot.exceptions import (
      LineBotApiError, InvalidSignatureError
  )
  from linebot.models import (
      MessageEvent, TextMessage, TextSendMessage, Sender,
      SourceUser, SourceGroup, SourceRoom,
      TemplateSendMessage, ConfirmTemplate, MessageAction,
      ButtonsTemplate, ImageCarouselTemplate, ImageCarouselColumn, URIAction,
      PostbackAction, DatetimePickerAction,
      CameraAction, CameraRollAction, LocationAction,
      CarouselTemplate, CarouselColumn, PostbackEvent,
      StickerMessage, StickerSendMessage, LocationMessage, LocationSendMessage,
      ImageMessage, VideoMessage, AudioMessage, FileMessage,
      UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent, BeaconEvent,
      MemberJoinedEvent, MemberLeftEvent,
      FlexSendMessage, BubbleContainer, ImageComponent, BoxComponent,
      TextComponent, IconComponent, ButtonComponent,
      SeparatorComponent, QuickReply, QuickReplyButton,
      ImageSendMessage)
  # ===============引入模組================ #
  
  # ============定義短網址Class============ #
  
  
  class UrlShortenTinyurl:
      URL = 'http://tinyurl.com/api-create.php'
  
      def shorten(self, url_long):
          url = self.URL + '?' \
              + urllib.parse.urlencode({'url': url_long})
          res = requests.get(url)
          if res.status_code == requests.codes.ok:
              return str(res.text)
          else:
              raise
  # ============定義短網址Class============ #
  
  
  # ===============Flask設定=============== #
  app = Flask(__name__)
  app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1, x_proto=1)
  # ===============Flask設定=============== #
  
  # ======機器參數設定(非必要請勿觸動)======= #
  channel_secret = '[請更改成自己的]'
  channel_access_token = '[請更改成自己的]'
  # ======機器參數設定(非必要請勿觸動)======= #
  
  # ============載入JSON儲存檔============= #
  set = json.load(codecs.open('set.json', 'r', 'utf-8'))
  ops = json.load(codecs.open('ops.json', 'r', 'utf-8'))
  reply = json.load(codecs.open('reply.json', 'r', 'utf-8'))
  # ============載入JSON儲存檔============= #
  
  # ==========執行API,定義BOT資訊========== #
  jloa = LineBotApi(channel_access_token)
  handler = WebhookHandler(channel_secret)
  # ==========執行API,定義BOT資訊========== #
  
  # ===========定義URL提取Class============ #
  extractor = URLExtract()
  # ===========定義URL提取Class============ #
  
  # ===========定義URL縮短Class============ #
  urlshort = UrlShortenTinyurl()
  # ===========定義URL縮短Class============ #
  
  # =============定義貼圖種類============== #
  stktype = {
      'POPUP': '彈出 Popup',
      'ANIMATION_SOUND': '動畫(含聲音) Animation with sound',
      'STATIC': '靜態 Static',
      'ANIMATION': '動畫 Animation',
      'SOUND': '聲音 Sound',
      'NAME': '名稱 Name',
      'POPUP_SOUND': '彈出(含聲音) Popup with sound',
      'NAME_TEXT': '隨你填 Text',
      'PER_STICKER_TEXT': '訊息 Message'
  }
  # =============定義貼圖種類============== #
  
  # =============定義備份函數============== #
  
  
  def backupData():
      json.dump(set, codecs.open('set.json', 'w', 'utf-8'),
                sort_keys=True, indent=4, ensure_ascii=False)
      json.dump(ops, codecs.open('ops.json', 'w', 'utf-8'),
                sort_keys=True, indent=4, ensure_ascii=False)
      json.dump(reply, codecs.open('reply.json', 'w', 'utf-8'),
                sort_keys=True, indent=4, ensure_ascii=False)
  # =============定義備份函數============== #
  
  # =============定義重啟函數============== #
  
  
  def restartBot():
      requests.post('https://notify-api.line.me/api/notify', headers={'Authorization': 'Bearer {}'.format(
          set['line_notify_token']), 'Content-Type': 'application/x-www-form-urlencoded'}, params={'message': '非官已關閉🔴'})
      backupData()
      python = sys.executable
      os.execl(python, python, *sys.argv)
  # =============定義重啟函數============== #
  
  # ===========定義好友偵測函數============ #
  
  
  def isfriend(mid):
      try:
          jloa.get_profile(mid)
          return True
      except:
          return False
  # ===========定義好友偵測函數============ #
  
  # ========定義Youtube影片下載函數========= #
  
  
  def get_video_info(youtube_url):
      with youtube_dl.YoutubeDL() as ydl:
          info = ydl.extract_info(youtube_url, download=False)
      return info
  # ========定義Youtube影片下載函數========= #
  
  
  @app.route('/callback', methods=['POST'])
  def callback():
      # get X-Line-Signature header value
      signature = request.headers['X-Line-Signature']
  
      # get request body as text
      body = request.get_data(as_text=True)
      #app.logger.info('Request body: ' + body)
  
      # handle webhook body
      try:
          handler.handle(body, signature)
      except LineBotApiError as e:
          print('\n=====警告=====\n[API錯誤]\n%s\n' % e.message)
          for m in e.error.details:
              print('  %s: %s\n' % (m.property, m.message))
          print('=====警告=====\n')
      except InvalidSignatureError:
          abort(400)
  
      return 'OK'
  
  
  @handler.add(MessageEvent, message=TextMessage)
  def handle_text_message(event):
      text = event.message.text
      cmd = text.lower()
      sender = event.source.user_id
      if isinstance(event.source, SourceGroup):
          to = event.source.group_id
      elif isinstance(event.source, SourceRoom):
          to = event.source.room_id
      else:
          to = sender
  
      if sender in ops['author']:
          if cmd == 'reb':
              jloa.reply_message(
                  event.reply_token, TextSendMessage(text='非官重新啟動中...\nOA restarting...'))
              restartBot()
          elif cmd == 'notify_token':
              response = requests.get('https://notify-api.line.me/api/status', headers={
                                      'Authorization': 'Bearer {}'.format(set['line_notify_token'])})
              response1 = response.json()
              response2 = response.headers
              if response1['status'] == 200:
                  ret_ = '可用狀態:是'
              else:
                  ret_ = '可用狀態:否'
              if response1['targetType'] == 'USER':
                  ret_ += '\n目標類型:使用者'
              else:
                  ret_ += '\n目標類型:群組'
              if response1['target'] == 'null.':
                  ret_ += '\n目標名稱:不可用'
              else:
                  ret_ += '\n目標名稱:{}'.format(response1['target'])
              ret_ += '\n每小時最高使用次數:{}'.format(response2['X-RateLimit-Limit'])
              ret_ += '\n每小時剩餘使用次數:{}'.format(response2['X-RateLimit-Remaining'])
              ret_ += '\n使用次數重設時間:{}'.format(time.strftime(
                  "%Y/%m/%d %H:%M:%S", time.localtime(int(response2['X-RateLimit-Reset']))))
              jloa.reply_message(
                  event.reply_token, TextSendMessage(text=ret_))
          elif cmd == 'test':
              test_result = jloa.test_webhook_endpoint()
              webhook = jloa.get_webhook_endpoint()
              bot_info = jloa.get_bot_info()
              ret_ = '機器運行狀態:True'
              ret_ += '\n非官聊天狀態:{}'.format(bot_info.chat_mode)
              ret_ += '\nWebhook測試狀態:'
              ret_ += '\n　活躍狀態:{}'.format(webhook.active)
              ret_ += '\n　正常執行:{}'.format(test_result.success)
              ret_ += '\n　時間戳:{}'.format(test_result.timestamp)
              ret_ += '\n　回應碼:{}'.format(test_result.status_code)
              ret_ += '\n　原因:{}'.format(test_result.reason)
              ret_ += '\n　詳細資料:{}'.format(test_result.detail)
              jloa.reply_message(
                  event.reply_token, TextSendMessage(text=ret_))
          elif cmd.startswith('aop:'):
              link_re = re.compile('U[a-z0-9]{32}')
              mids = link_re.findall(text[4:])
              if event.message.mention:
                  n_mids = [u.user_id for u in event.message.mention.mentionees]
              else:
                  n_mids = []
              all_mids = []
              for l in mids:
                  if l not in all_mids:
                      all_mids.append(l)
              for l in n_mids:
                  if l not in all_mids:
                      all_mids.append(l)
              n = 0
              for l in all_mids:
                  if l not in ops['admin'] and l not in ops['author']:
                      ops['admin'].append(l)
                      n += 1
              jloa.reply_message(
                  event.reply_token,
                  [
                      TextSendMessage(text='輸入:\n您輸入 {} 個MID\n您標註 {} 個使用者\n您共提供 {} 個使用者'.format(
                          len(mids), len(n_mids), len(mids) + len(n_mids))),
                      TextSendMessage(text='錯誤:\n共有 {} 個使用者為重複\n共有 {} 個使用者已擁有至少管理員權限'.format(
                          len(mids) + len(n_mids) - len(all_mids), len(all_mids) - n)),
                      TextSendMessage(text='結果:\n已新增 {} 個管理員'.format(n))
                  ]
              )
          elif cmd.startswith('daop:'):
              link_re = re.compile('U[a-z0-9]{32}')
              mids = link_re.findall(text[5:])
              if event.message.mention:
                  n_mids = [u.user_id for u in event.message.mention.mentionees]
              else:
                  n_mids = []
              all_mids = []
              for l in mids:
                  if l not in all_mids:
                      all_mids.append(l)
              for l in n_mids:
                  if l not in all_mids:
                      all_mids.append(l)
              n = 0
              for l in all_mids:
                  if l in ops['admin']:
                      ops['admin'].remove(l)
                      n += 1
              jloa.reply_message(
                  event.reply_token,
                  [
                      TextSendMessage(text='輸入:\n您輸入 {} 個MID\n您標註 {} 個使用者\n您共提供 {} 個使用者'.format(
                          len(mids), len(n_mids), len(mids) + len(n_mids))),
                      TextSendMessage(text='錯誤:\n共有 {} 個使用者為重複\n共有 {} 個使用者未擁有管理員權限'.format(
                          len(mids) + len(n_mids) - len(all_mids), len(all_mids) - n)),
                      TextSendMessage(text='結果:\n已移除 {} 個管理員'.format(n))
                  ]
              )
          elif cmd.startswith('cop:'):
              link_re = re.compile('U[a-z0-9]{32}')
              mids = link_re.findall(text[4:])
              if event.message.mention:
                  n_mids = [u.user_id for u in event.message.mention.mentionees]
              else:
                  n_mids = []
              all_mids = []
              for l in mids:
                  if l not in all_mids:
                      all_mids.append(l)
              for l in n_mids:
                  if l not in all_mids:
                      all_mids.append(l)
              n = 0
              for l in all_mids:
                  if l not in ops['admin'] and l not in ops['author'] and l not in ops['creator']:
                      ops['creator'].append(l)
                      n += 1
              jloa.reply_message(
                  event.reply_token,
                  [
                      TextSendMessage(text='輸入:\n您輸入 {} 個MID\n您標註 {} 個使用者\n您共提供 {} 個使用者'.format(
                          len(mids), len(n_mids), len(mids) + len(n_mids))),
                      TextSendMessage(text='錯誤:\n共有 {} 個使用者為重複\n共有 {} 個使用者已擁有至少創作者權限'.format(
                          len(mids) + len(n_mids) - len(all_mids), len(all_mids) - n)),
                      TextSendMessage(text='結果:\n已新增 {} 個創作者'.format(n))
                  ]
              )
          elif cmd.startswith('dcop:'):
              link_re = re.compile('U[a-z0-9]{32}')
              mids = link_re.findall(text[4:])
              if event.message.mention:
                  n_mids = [u.user_id for u in event.message.mention.mentionees]
              else:
                  n_mids = []
              all_mids = []
              for l in mids:
                  if l not in all_mids:
                      all_mids.append(l)
              for l in n_mids:
                  if l not in all_mids:
                      all_mids.append(l)
              n = 0
              for l in all_mids:
                  if l in ops['creator']:
                      ops['creator'].remove(l)
                      n += 1
              jloa.reply_message(
                  event.reply_token,
                  [
                      TextSendMessage(text='輸入:\n您輸入 {} 個MID\n您標註 {} 個使用者\n您共提供 {} 個使用者'.format(
                          len(mids), len(n_mids), len(mids) + len(n_mids))),
                      TextSendMessage(text='錯誤:\n共有 {} 個使用者為重複\n共有 {} 個使用者未擁有創作者權限'.format(
                          len(mids) + len(n_mids) - len(all_mids), len(all_mids) - n)),
                      TextSendMessage(text='結果:\n已移除 {} 個創作者'.format(n))
                  ]
              )
          elif cmd.startswith('sys:'):
              txt = text[4:]
              try:
                  jloa.reply_message(
                      event.reply_token, [
                          TextSendMessage(text=str(subprocess.Popen(
                              [txt], shell=True, stdout=subprocess.PIPE, universal_newlines=True).communicate()[0]))
                      ]
                  )
              except Exception as e:
                  jloa.reply_message(
                      event.reply_token, [
                          TextSendMessage(text='執行指令錯誤\n以下為錯誤訊息'),
                          TextSendMessage(text=str(e))
                      ]
                  )
          elif cmd.startswith('cmd:'):
              txt = text[4:]
              try:
                  exec(str(txt))
              except Exception as e:
                  jloa.reply_message(
                      event.reply_token, [
                          TextSendMessage(text='執行操作錯誤\n以下為錯誤訊息'),
                          TextSendMessage(text=str(e))
                      ]
                  )
          elif cmd == 'lock':
              if isinstance(event.source, SourceUser):
                  jloa.reply_message(
                      event.reply_token, TextSendMessage(text='私聊無法鎖定'))
              elif to == set['backdoor']:
                  jloa.reply_message(
                      event.reply_token, TextSendMessage(text='後臺無須鎖定'))
              elif to in set['leave_lock']:
                  set['leave_lock'].remove(to)
                  jloa.reply_message(
                      event.reply_token, [TextSendMessage(text='{} 已從退出鎖定清單移除'.format(to)), TextSendMessage(text='取消鎖定完成')])
              else:
                  set['leave_lock'].append(to)
                  jloa.reply_message(
                      event.reply_token, [TextSendMessage(text='{} 已加入退出鎖定清單'.format(to)), TextSendMessage(text='鎖定完成')])
          elif cmd == 'yt':
              if set['yt']:
                  set['yt'] = False
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='Youtube影片資料顯示:關閉')
                  )
              else:
                  set['yt'] = True
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='Youtube影片資料顯示:開啟')
                  )
          elif cmd == 'sr':
              if set['sr']:
                  set['sr'] = False
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='貼圖回覆:關閉')
                  )
              else:
                  set['sr'] = True
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='貼圖回覆:開啟')
                  )
          elif cmd == 'ssr':
              if set['ssr']:
                  set['ssr'] = False
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='貼圖資料顯示:關閉')
                  )
              else:
                  set['ssr'] = True
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='貼圖資料顯示:開啟')
                  )
          elif cmd == 'eq':
              if set['eq']:
                  set['eq'] = False
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='地震資料查詢:關閉')
                  )
              else:
                  set['eq'] = True
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='地震資料查詢:開啟')
                  )
          elif cmd == 'sudo':
              if set['sudo']:
                  set['sudo'] = False
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='SUDO任意改寫模式:關閉')
                  )
              else:
                  set['sudo'] = True
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(
                          text='SUDO任意改寫模式:開啟\n*這可能直接或間接導致資料毀損或程式執行錯誤')
                  )
          elif cmd == 'lg':
              if set['lg']:
                  set['lg'] = False
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='自離群組:關閉')
                  )
              else:
                  set['lg'] = True
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='自離群組:開啟')
                  )
          elif cmd == 'lr':
              if set['lr']:
                  set['lr'] = False
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='自離副本:關閉')
                  )
              else:
                  set['lr'] = True
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='自離副本:開啟')
                  )
          elif cmd == 'link_token' and isinstance(event.source, SourceUser):
              link_token_response = jloa.issue_link_token(event.source.user_id)
              jloa.reply_message(
                  event.reply_token, [
                      TextSendMessage(text='Link token: ' +
                                      link_token_response.link_token)
                  ]
              )
      if sender in ops['author'] or sender in ops['admin']:
          if cmd.startswith('sr:'):
              x = text.split(':')
              if len(x) != 3:
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='[提示]\n指令格式:\nsr:貼圖ID:文字(不可包含:)')
                  )
              else:
                  if x[1] == '':
                      jloa.reply_message(
                          event.reply_token,
                          TextSendMessage(text='[提示]\n您沒有輸入要設定回覆的貼圖ID')
                      )
                  elif x[2] == '':
                      jloa.reply_message(
                          event.reply_token,
                          TextSendMessage(text='[提示]\n您沒有輸入要回覆的文字(不可包含:)')
                      )
                  elif x[1] in reply['sticker']:
                      reply['sticker'][x[1]] = x[2]
                      jloa.reply_message(
                          event.reply_token,
                          TextSendMessage(
                              text='[更新貼圖回覆]\n貼圖ID:{}\n回覆文字:{}'.format(x[1], x[2]))
                      )
                  else:
                      reply['sticker'][x[1]] = x[2]
                      jloa.reply_message(
                          event.reply_token,
                          TextSendMessage(
                              text='[設定貼圖回覆]\n貼圖ID:{}\n回覆文字:{}'.format(x[1], x[2]))
                      )
          elif cmd.startswith('dsr:'):
              x = text.split(':')
              if len(x) != 2:
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='[提示]\n指令格式:\ndsr:貼圖ID')
                  )
              else:
                  if x[1] == '':
                      jloa.reply_message(
                          event.reply_token,
                          TextSendMessage(text='[提示]\n您沒有輸入要刪除回覆的貼圖ID')
                      )
                  elif x[1] in reply['sticker']:
                      del reply['sticker'][x[1]]
                      jloa.reply_message(
                          event.reply_token,
                          TextSendMessage(text='[刪除貼圖回覆]\n貼圖ID:{}'.format(x[1]))
                      )
                  else:
                      jloa.reply_message(
                          event.reply_token,
                          TextSendMessage(text='[提示]\n該貼圖ID沒有設定回覆')
                      )
      if sender in ops['author'] or sender in ops['admin'] or sender in ops['creator']:
          if cmd == 'qtb':
              quota = jloa.get_message_quota()
              quota_consumption = quota.value - jloa.get_message_quota_consumption().total_usage
              if quota.type == 'limited':
                  qt = '限量 Limited'
              else:
                  qt - '無限 Unlimited'
              jloa.reply_message(
                  event.reply_token, [
                      TextSendMessage(text='形式 Type: ' + qt),
                      TextSendMessage(text='可用總量 Available: ' +
                                      str(quota.value)),
                      TextSendMessage(text='剩餘數量 Balance: ' +
                                      str(quota_consumption))
                  ]
              )
          elif cmd.startswith('mid '):
              if event.message.mention:
                  ret_ = '以下為標註者MID'
                  for mention in [u.user_id for u in event.message.mention.mentionees]:
                      ret_ += '\n' + mention
                  jloa.reply_message(
                      event.reply_token, TextSendMessage(text=ret_))
              else:
                  jloa.reply_message(
                      event.reply_token, TextSendMessage(text='請標註使用者以查詢MID'))
      if cmd in ['profile', 'me', 'info']:
          if isinstance(event.source, SourceGroup):
              profile = jloa.get_group_member_profile(to, sender)
              try:
                  url = urlshort.shorten(profile.picture_url)
              except:
                  url = profile.picture_url
              if sender in ops['author']:
                  opl = '作者 Author'
              elif sender in ops['admin']:
                  opl = '管理員 Admin'
              elif sender in ops['creator']:
                  opl = '創作者 Creator'
              else:
                  opl = '無權限 No op'
              jloa.reply_message(
                  event.reply_token, [
                      TextSendMessage(
                          text='[ 名稱 Display Name ]\n' + profile.display_name),
                      TextSendMessage(text='[ 頭貼網址 Picture Url ]\n' + url),
                      TextSendMessage(text='[ 權限等級 Op level ]\n' + opl)
                  ]
              )
          elif isinstance(event.source, SourceRoom):
              profile = jloa.get_room_member_profile(to, sender)
              try:
                  url = urlshort.shorten(profile.picture_url)
              except:
                  url = profile.picture_url
              if sender in ops['author']:
                  opl = '作者 Author'
              elif sender in ops['admin']:
                  opl = '管理員 Admin'
              elif sender in ops['creator']:
                  opl = '創作者 Creator'
              else:
                  opl = '無權限 No op'
              jloa.reply_message(
                  event.reply_token, [
                      TextSendMessage(
                          text='[ 名稱 Display Name ]\n' + profile.display_name),
                      TextSendMessage(text='[ 頭貼網址 Picture Url ]\n' + url),
                      TextSendMessage(text='[ 權限等級 Op level ]\n' + opl)
                  ]
              )
          else:
              profile = jloa.get_profile(sender)
              try:
                  url = urlshort.shorten(profile.picture_url)
              except:
                  url = profile.picture_url
              if sender in ops['author']:
                  opl = '作者 Author'
              elif sender in ops['admin']:
                  opl = '管理員 Admin'
              elif sender in ops['creator']:
                  opl = '創作者 Creator'
              else:
                  opl = '無權限 No op'
              jloa.reply_message(
                  event.reply_token, [
                      TextSendMessage(
                          text='[ 名稱 Display Name ]\n' + profile.display_name),
                      TextSendMessage(
                          text='[ 個簽 Bio ]\n' + str(profile.status_message)),
                      TextSendMessage(text='[ 頭貼網址 Picture Url ]\n' + url),
                      TextSendMessage(text='[ 權限等級 Op level ]\n' + opl)
                  ]
              )
      elif cmd.startswith('搜尋:'):
          txt = text[3:]
          response = requests.get(
              'https://cdn.nic20.tk/search?q={}'.format(txt)).json()
          botd = jloa.get_bot_info()
          if 'title' in response:
              aub = {
                  "type": "bubble",
                  "body": {
                      "type": "box",
                      "layout": "vertical",
                      "contents": [
                          {
                              "type": "box",
                              "layout": "horizontal",
                              "contents": [
                                  {
                                      "type": "box",
                                      "layout": "vertical",
                                      "contents": [
                                          {
                                              "type": "image",
                                              "url": "https://i.imgur.com/WXdLDsd.png",
                                              "aspectMode": "cover",
                                              "size": "full"
                                          }
                                      ],
                                      "cornerRadius": "100px",
                                      "width": "72px",
                                      "height": "72px"
                                  },
                                  {
                                      "type": "box",
                                      "layout": "vertical",
                                      "contents": [
                                          {
                                              "type": "text",
                                              "contents": [
                                                  {
                                                      "type": "span",
                                                      "text": "Google搜尋成功",
                                                      "color": "#000000",
                                                      "style": "normal"
                                                  }
                                              ],
                                              "size": "sm",
                                              "wrap": True
                                          },
                                          {
                                              "type": "text",
                                              "wrap": True,
                                              "size": "lg",
                                              "contents": [
                                                  {
                                                      "type": "span",
                                                      "text": "{}".format(response['title']),
                                                      "weight": "bold",
                                                      "decoration": "underline"
                                                  }
                                              ],
                                              "action": {
                                                  "type": "uri",
                                                  "label": "action",
                                                  "uri": "{}".format(response['url'])
                                              }
                                          },
                                          {
                                              "type": "text",
                                              "wrap": True,
                                              "size": "md",
                                              "contents": [
                                                  {
                                                      "type": "span",
                                                      "text": "{}".format(response['description'])
                                                  }
                                              ]
                                          }
                                      ]
                                  }
                              ],
                              "spacing": "xl",
                              "paddingAll": "20px"
                          }
                      ],
                      "paddingAll": "0px"
                  }
              }
              message = FlexSendMessage(
                  alt_text='{} 傳送了一則模板訊息'.format(botd.display_name), contents=aub)
          else:
              aub = {
                  "type": "bubble",
                  "body": {
                      "type": "box",
                      "layout": "vertical",
                      "contents": [
                          {
                              "type": "box",
                              "layout": "horizontal",
                              "contents": [
                                  {
                                      "type": "box",
                                      "layout": "vertical",
                                      "contents": [
                                          {
                                              "type": "image",
                                              "url": "https://i.imgur.com/auVArMb.png",
                                              "aspectMode": "cover",
                                              "size": "full"
                                          }
                                      ],
                                      "cornerRadius": "100px",
                                      "width": "72px",
                                      "height": "72px"
                                  },
                                  {
                                      "type": "box",
                                      "layout": "vertical",
                                      "contents": [
                                          {
                                              "type": "text",
                                              "contents": [
                                                  {
                                                      "type": "span",
                                                      "text": "Google搜尋失敗",
                                                      "color": "#000000",
                                                      "style": "normal"
                                                  }
                                              ],
                                              "size": "sm",
                                              "wrap": True
                                          },
                                          {
                                              "type": "text",
                                              "wrap": True,
                                              "size": "lg",
                                              "contents": [
                                                  {
                                                      "type": "span",
                                                      "text": "找不到結果",
                                                      "weight": "bold",
                                                      "decoration": "underline"
                                                  }
                                              ]
                                          },
                                          {
                                              "type": "text",
                                              "wrap": True,
                                              "size": "md",
                                              "contents": [
                                                  {
                                                      "type": "span",
                                                      "text": "您可以試著更換用詞或再試一次"
                                                  }
                                              ]
                                          }
                                      ]
                                  }
                              ],
                              "spacing": "xl",
                              "paddingAll": "20px"
                          }
                      ],
                      "paddingAll": "0px"
                  }
              }
              message = FlexSendMessage(
                  alt_text='{} 傳送了一則模板訊息'.format(botd.display_name), contents=aub)
          jloa.reply_message(event.reply_token, message)
      elif cmd == 'bye':
          if to == set['backdoor']:
              jloa.reply_message(
                  event.reply_token, TextSendMessage(text='''無法退出後臺\nCan't leave backdoor.'''))
          elif to in set['leave_lock']:
              jloa.reply_message(
                  event.reply_token, TextSendMessage(text='此位置為退出鎖定狀態\nThis room/group is in leave lock status.'))
          elif isinstance(event.source, SourceGroup):
              jloa.reply_message(
                  event.reply_token, TextSendMessage(text='退出群組\nLeave Group'))
              jloa.leave_group(event.source.group_id)
          elif isinstance(event.source, SourceRoom):
              jloa.reply_message(
                  event.reply_token, TextSendMessage(text='離開副本\nLeave Room'))
              jloa.leave_room(event.source.room_id)
      elif cmd in ['bot', 'author', 'about', '關於', '機器', '作者']:
          botd = jloa.get_bot_info()
          autd = jloa.get_profile(ops['jl'])
          aub = {
              "type": "bubble",
              "body": {
                  "type": "box",
                  "layout": "vertical",
                  "contents": [
                      {
                          "type": "image",
                          "url": "https://i.imgur.com/PYGq5V6.jpg",
                          "size": "full",
                          "aspectMode": "cover",
                          "aspectRatio": "10:11",
                          "gravity": "center"
                      },
                      {
                          "type": "box",
                          "layout": "vertical",
                          "contents": [
                              {
                                  "type": "box",
                                  "layout": "vertical",
                                  "contents": [
                                      {
                                          "type": "text",
                                          "text": "{}".format(botd.display_name),
                                          "color": "#FFFFFF",
                                          "size": "lg",
                                          "weight": "bold"
                                      }
                                  ]
                              },
                              {
                                  "type": "box",
                                  "layout": "vertical",
                                  "contents": [
                                      {
                                          "type": "filler"
                                      }
                                  ],
                                  "width": "132px",
                                  "height": "1px",
                                  "margin": "xs",
                                  "backgroundColor": "#E0E0E0aa"
                              },
                              {
                                  "type": "box",
                                  "layout": "horizontal",
                                  "contents": [
                                      {
                                          "type": "box",
                                          "layout": "vertical",
                                          "contents": [
                                              {
                                                  "type": "image",
                                                  "url": "{}".format(botd.picture_url),
                                                  "size": "full",
                                                  "aspectMode": "cover",
                                                  "action": {
                                                      "type": "uri",
                                                      "uri": "line://nv/profilePopup/mid=u4d3cca0f6669e24caf76655497abf346"
                                                  }
                                              }
                                          ],
                                          "cornerRadius": "100px",
                                          "width": "72px",
                                          "height": "72px"
                                      },
                                      {
                                          "type": "box",
                                          "layout": "vertical",
                                          "contents": [
                                              {
                                                  "type": "box",
                                                  "layout": "vertical",
                                                  "contents": [
                                                      {
                                                          "type": "text",
                                                          "text": "{}".format(botd.display_name),
                                                          "size": "lg",
                                                          "align": "center",
                                                          "color": "#FFFFFF"
                                                      }
                                                  ],
                                                  "margin": "lg"
                                              },
                                              {
                                                  "type": "box",
                                                  "layout": "vertical",
                                                  "contents": [
                                                      {
                                                          "type": "text",
                                                          "text": "奈柔專用非官",
                                                          "color": "#FFFFFF",
                                                          "align": "center",
                                                          "size": "sm"
                                                      }
                                                  ]
                                              }
                                          ],
                                          "spacing": "xs"
                                      }
                                  ],
                                  "margin": "xl",
                                  "spacing": "xxl"
                              },
                              {
                                  "type": "box",
                                  "layout": "horizontal",
                                  "contents": [
                                      {
                                          "type": "box",
                                          "layout": "vertical",
                                          "contents": [
                                              {
                                                  "type": "image",
                                                  "url": "{}".format(autd.picture_url),
                                                  "size": "full",
                                                  "aspectMode": "cover",
                                                  "action": {
                                                      "type": "uri",
                                                      "uri": "line://nv/profilePopup/mid=u8b9d115e85202db06eb798e8c1b40ae9"
                                                  }
                                              }
                                          ],
                                          "cornerRadius": "100px",
                                          "width": "72px",
                                          "height": "72px"
                                      },
                                      {
                                          "type": "box",
                                          "layout": "vertical",
                                          "contents": [
                                              {
                                                  "type": "box",
                                                  "layout": "vertical",
                                                  "contents": [
                                                      {
                                                          "type": "text",
                                                          "text": "{}".format(autd.display_name),
                                                          "size": "xl",
                                                          "align": "center",
                                                          "color": "#FFFFFF"
                                                      }
                                                  ],
                                                  "margin": "md"
                                              },
                                              {
                                                  "type": "box",
                                                  "layout": "vertical",
                                                  "contents": [
                                                      {
                                                          "type": "text",
                                                          "text": "偉大的作者",
                                                          "color": "#FFFFFF",
                                                          "align": "center",
                                                          "size": "sm"
                                                      }
                                                  ]
                                              }
                                          ],
                                          "spacing": "xs"
                                      }
                                  ],
                                  "margin": "xl",
                                  "spacing": "xxl"
                              },
                              {
                                  "type": "box",
                                  "layout": "vertical",
                                  "contents": [
                                      {
                                          "type": "filler"
                                      },
                                      {
                                          "type": "box",
                                          "layout": "baseline",
                                          "contents": [
                                              {
                                                  "type": "filler"
                                              },
                                              {
                                                  "type": "text",
                                                  "text": "歡迎按下",
                                                  "color": "#ffffff",
                                                  "offsetTop": "-2px",
                                                  "flex": 0
                                              },
                                              {
                                                  "type": "filler"
                                              }
                                          ],
                                          "spacing": "sm"
                                      },
                                      {
                                          "type": "filler"
                                      }
                                  ],
                                  "spacing": "sm",
                                  "margin": "xxl",
                                  "height": "40px",
                                  "borderWidth": "1px",
                                  "borderColor": "#FFFFFF",
                                  "cornerRadius": "4px",
                                  "action": {
                                      "type": "message",
                                      "text": "我愛奈柔❤"
                                  }
                              }
                          ],
                          "position": "absolute",
                          "offsetBottom": "0px",
                          "offsetStart": "0px",
                          "offsetEnd": "0px",
                          "offsetTop": "0px",
                          "paddingAll": "35px",
                          "paddingTop": "31px",
                          "backgroundColor": "#7B7B7BAA"
                      }
                  ],
                  "paddingAll": "0px"
              }
          }
          message = FlexSendMessage(
              alt_text='{} 傳送了一則模板訊息'.format(botd.display_name), contents=aub)
          jloa.reply_message(event.reply_token, message)
      elif 'youtube.com/watch?' in cmd or 'https://youtu.be/' in cmd:
          if set['yt'] == True:
              link_re = re.compile(
                  """(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&"'<> #]+)""")
              links = link_re.findall(text)
              urls = []
              for l in links:
                  if l not in urls:
                      urls.append(l)
              messages = []
              botname = jloa.get_bot_info().display_name
              for url in urls:
                  video_info = get_video_info(url)
                  upd = time.strptime(str(
                      video_info['upload_date']), '%Y%m%d')
                  mins, secs = divmod(video_info['duration'], 60)
                  hours, mins = divmod(mins, 60)
                  long = ''
                  if hours != 0:
                      long += '{}小時'.format(hours)
                  if mins != 0:
                      long += '{}分鐘'.format(mins)
                  long += '{}秒'.format(secs)
                  bub = {
                      "type": "bubble",
                      "hero": {
                          "type": "image",
                          "url": "{}".format(video_info['thumbnail']),
                          "size": "full",
                          "aspectMode": "cover",
                          "action": {
                              "type": "uri",
                              "uri": "https://youtu.be/{}".format(video_info['id'])
                          },
                          "aspectRatio": "{}:{}".format(video_info['width'], video_info['height'])
                      },
                      "body": {
                          "type": "box",
                          "layout": "vertical",
                          "contents": [
                              {
                                  "type": "text",
                                  "text": "{}".format(video_info['title']),
                                  "weight": "bold",
                                  "size": "md",
                                  "wrap": True
                              },
                              {
                                  "type": "box",
                                  "layout": "baseline",
                                  "contents": [
                                      {
                                          "type": "text",
                                          "text": "上傳頻道",
                                          "size": "sm",
                                          "weight": "bold",
                                          "flex": 5
                                      },
                                      {
                                          "type": "text",
                                          "text": "{}".format(video_info['uploader']),
                                          "wrap": True,
                                          "color": "#666666",
                                          "size": "sm",
                                          "flex": 12,
                                          "decoration": "underline",
                                          "action": {
                                              "type": "uri",
                                              "uri": "{}".format(video_info['uploader_url'])
                                          }
                                      }
                                  ]
                              },
                              {
                                  "type": "box",
                                  "layout": "baseline",
                                  "contents": [
                                      {
                                          "type": "text",
                                          "text": "觀看次數",
                                          "size": "sm",
                                          "weight": "bold",
                                          "flex": 5
                                      },
                                      {
                                          "type": "text",
                                          "text": "{}".format(video_info['view_count']),
                                          "wrap": True,
                                          "color": "#666666",
                                          "size": "sm",
                                          "flex": 12
                                      }
                                  ]
                              },
                              {
                                  "type": "box",
                                  "layout": "baseline",
                                  "contents": [
                                      {
                                          "type": "text",
                                          "text": "上傳日期",
                                          "size": "sm",
                                          "weight": "bold",
                                          "flex": 5
                                      },
                                      {
                                          "type": "text",
                                          "text": "{}年{}月{}號".format(str(upd.tm_year), str(upd.tm_mon), str(upd.tm_mday)),
                                          "wrap": True,
                                          "color": "#666666",
                                          "size": "sm",
                                          "flex": 12
                                      }
                                  ]
                              },
                              {
                                  "type": "box",
                                  "layout": "baseline",
                                  "contents": [
                                      {
                                          "type": "text",
                                          "text": "影片長度",
                                          "size": "sm",
                                          "weight": "bold",
                                          "flex": 5
                                      },
                                      {
                                          "type": "text",
                                          "text": "{}".format(long),
                                          "wrap": True,
                                          "color": "#666666",
                                          "size": "sm",
                                          "flex": 12
                                      }
                                  ]
                              },
                              {
                                  "type": "box",
                                  "layout": "vertical",
                                  "contents": [
                                      {
                                          "type": "box",
                                          "layout": "horizontal",
                                          "contents": [
                                              {
                                                  "type": "box",
                                                  "layout": "baseline",
                                                  "contents": [
                                                      {
                                                          "type": "icon",
                                                          "url": "https://i.ibb.co/X7HCjh0/good1.png",
                                                          "margin": "21px",
                                                          "size": "md",
                                                          "offsetTop": "3px"
                                                      },
                                                      {
                                                          "type": "text",
                                                          "text": "喜歡",
                                                          "weight": "bold",
                                                          "size": "sm"
                                                      }
                                                  ]
                                              },
                                              {
                                                  "type": "box",
                                                  "layout": "baseline",
                                                  "contents": [
                                                      {
                                                          "type": "icon",
                                                          "url": "https://i.ibb.co/qCbPy7c/bad1.png",
                                                          "margin": "14px",
                                                          "size": "md",
                                                          "offsetTop": "3px"
                                                      },
                                                      {
                                                          "type": "text",
                                                          "text": "不喜歡",
                                                          "weight": "bold",
                                                          "size": "sm"
                                                      }
                                                  ]
                                              },
                                              {
                                                  "type": "box",
                                                  "layout": "baseline",
                                                  "contents": [
                                                      {
                                                          "type": "icon",
                                                          "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png",
                                                          "margin": "14px",
                                                          "size": "md",
                                                          "offsetTop": "2px"
                                                      },
                                                      {
                                                          "type": "text",
                                                          "text": "星星數",
                                                          "weight": "bold",
                                                          "size": "sm"
                                                      }
                                                  ]
                                              }
                                          ]
                                      },
                                      {
                                          "type": "box",
                                          "layout": "horizontal",
                                          "contents": [
                                              {
                                                  "type": "box",
                                                  "layout": "baseline",
                                                  "contents": [
                                                      {
                                                          "type": "text",
                                                          "text": "{}".format(video_info['like_count']),
                                                          "size": "sm",
                                                          "align": "center"
                                                      }
                                                  ]
                                              },
                                              {
                                                  "type": "box",
                                                  "layout": "baseline",
                                                  "contents": [
                                                      {
                                                          "type": "text",
                                                          "text": "{}".format(video_info['dislike_count']),
                                                          "size": "sm",
                                                          "align": "center"
                                                      }
                                                  ]
                                              },
                                              {
                                                  "type": "box",
                                                  "layout": "baseline",
                                                  "contents": [
                                                      {
                                                          "type": "text",
                                                          "text": "{}".format(video_info['average_rating']),
                                                          "size": "sm",
                                                          "align": "center"
                                                      }
                                                  ]
                                              }
                                          ]
                                      }
                                  ],
                                  "spacing": "none",
                                  "margin": "none"
                              }
                          ]
                      }
                  }
                  messages.append(FlexSendMessage(
                      alt_text='{} 傳送了一則模板訊息'.format(botname), contents=bub))
              jloa.reply_message(
                  event.reply_token, messages
              )
          else:
              jloa.reply_message(
                  event.reply_token,
                  TextSendMessage(
                      text="查詢Youtube影片資料功能未開啟\nThe function of geting Youtube videos' data is not enabled")
              )
          #url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', text)
          #video_info = get_video_info(text)
          #video_info['ID'] = info.get('id')
          #video_info['標題'] = info.get('title')
          #video_info['影片縮圖'] = info.get('thumbnail')
          #video_info['上傳者'] = info.get('uploader')
          #video_info['上傳者網址'] = info.get('uploader_url')
          #video_info['影片長度(秒)'] = info.get('duration')
          #video_info['觀看次數'] = info.get('view_count')
          # video_info['留言數'] = info.get('comment_count') # -
          #video_info['喜歡數'] = info.get('like_count')
          #video_info['不喜歡數'] = info.get('dislike_count')
          #video_info['平均評分'] = info.get('average_rating')
          #video_info['描述'] = info.get('description')
          #video_info['標籤'] = info.get('tags')
          #video_info['網頁網址'] = info.get('webpage_url')
          #video_info['上傳日期'] = info.get('upload_date')
      elif cmd == '彩券':
          res = requests.get('http://www.taiwanlottery.com.tw/index_new.aspx')
          soup = BeautifulSoup(res.text, 'html.parser')
          '''開獎日期 期數'''
          date = []  # Announced date
          periods = []  # Number of periods
          for span in soup.select('span'):
              match = re.search(
                  r'^<span class="font_black15">(.*?)\s(.*?)</span>', str(span))
              if match:
                  date.append(match.group(1))
                  periods.append(match.group(2))
  
          '''special_ball 特別號'''
          special_ball = []
          for div in soup.select('div'):
              match = re.search(r'^<div class="ball_red">(.*?)<', str(div))
              if match:
                  special_ball.append(match.group(1))
          '''lemon_ball 今彩五三九 三九樂合彩'''
          lemon_ball = []
          for div in soup.select('div'):
              match = re.search(
                  r'^<div class="ball_tx ball_lemon">(.*?)<', str(div))
              if match:
                  lemon_ball.append(match.group(1))
  
          def wei_li():
              wei_li__order = []
              wei_li__sorted = []
              counter = 0
              for div in soup.select('div'):
                  match = re.search(
                      r'^<div class="ball_tx ball_green">(.*?)<', str(div))
                  if match:
                      counter += 1
                      if counter <= 6:
                          wei_li__order.append(match.group(1))
                      elif 6 < counter <= 12:
                          wei_li__sorted.append(match.group(1))
  
              return '威力彩、38樂合彩\n　{} {}'.format(date[2], periods[2]) + '\n　開獎順序: ' + ''.join(wei_li__order) + '\n　大小排序: ' + ''.join(wei_li__sorted) + '\n　第二區號: {}'.format(special_ball[1])
  
          def big_lottery():
              big_lottery__order = []
              big_lottery__sorted = []
              counter = 0
              for div in soup.select('div'):
                  match = re.search(
                      r'^<div class="ball_tx ball_yellow">(.*?)<', str(div))
                  if match:
                      counter += 1
                      if 21 <= counter <= 26:
                          big_lottery__order.append(match.group(1))
                      elif 27 <= counter <= 32:
                          big_lottery__sorted.append(match.group(1))
  
              return '大樂透、49樂合彩\n　{} {}'.format(date[4], periods[4]) + '\n　開獎順序: ' + ''.join(big_lottery__order) + '\n　大小排序: ' + ''.join(big_lottery__sorted) + '\n　特別號碼: {}'.format(special_ball[2])
  
          def colorful_539():
              colorful_539__order = lemon_ball[0:5]
              colorful_539__sorted = lemon_ball[5:10]
  
              return '今彩539、39樂合彩\n　{} {}'.format(date[6], periods[6]) + '\n　開獎順序: ' + ''.join(colorful_539__order) + '\n　大小排序: ' + ''.join(colorful_539__sorted)
  
          ''' Bingo Bingo '''
          def bingoBingo():
              bingoDiv = soup.find('div', class_='contents_box01')
  
              yellowBalls = bingoDiv.find_all(
                  "div", class_='ball_tx ball_yellow')    # 開出獎號
              redBall = bingoDiv.find(
                  'div', class_='ball_red')                       # 超級獎號
              blueBall = bingoDiv.find(
                  'div', class_='ball_blue_BB1')                 # 猜大小
              purpleBall = bingoDiv.find(
                  'div', class_='ball_blue_BB2')               # 猜單雙
  
              return 'BINGO BINGO賓果賓果\n　{} {}'.format(date[0], periods[0]) + '\n　開出獎號: ' + ''.join([number.text for index, number in enumerate(yellowBalls)]) + '\n　超級獎號: {}\n　猜大小: {}\n　猜單雙: {}'.format(redBall.text, blueBall.text, purpleBall.text)
  
          def doubleWin():
              bingoDiv = soup.find('div', class_='contents_box06')
  
              balls = bingoDiv.find_all("div", class_='ball_tx ball_blue')
  
              return '雙贏彩\n　{} {}'.format(date[1], periods[1]) + '\n　開獎順序: ' + ''.join([number.text for index, number in enumerate(balls) if index <= (len(balls)/2-1)]) + '\n　大小順序: ' + ''.join([number.text for index, number in enumerate(balls) if index > (len(balls)/2-1)])
  
          ''' 三星彩 '''
          def threeStar():
              bingoDiv = soup.find_all('div', class_='contents_box04')
  
              balls = bingoDiv[0].find_all("div", class_='ball_tx ball_purple')
  
              return '三星彩\n　{} {}'.format(date[-2], periods[-2]) + '\n　中獎號碼: ' + ''.join([number.text for number in balls])
  
          ''' 四星彩 '''
          def fourStar():
              bingoDiv = soup.find_all('div', class_='contents_box04')
  
              balls = bingoDiv[1].find_all("div", class_='ball_tx ball_purple')
  
              return '四星彩\n　{} {}'.format(date[-1], periods[-1]) + '\n　中獎號碼: ' + ''.join([number.text for number in balls])
  
          jloa.reply_message(
              event.reply_token,
              [
                  TextSendMessage(text=bingoBingo() + '\n' + doubleWin()),
                  TextSendMessage(text=wei_li() + '\n' +
                                  big_lottery() + '\n' + colorful_539()),
                  TextSendMessage(text=threeStar() + '\n' + fourStar())
              ]
          )
      elif cmd.startswith('calc:'):
          txt = text[5:]
          try:
              jloa.reply_message(
                  event.reply_token,
                  [
                      TextSendMessage(
                          text='算式:\n{}\n結果:\n{}'.format(txt, eval(txt))),
                      TextSendMessage(text='P.S.:我嚴重懷疑你的數學程度')
                  ]
              )
          except:
              jloa.reply_message(
                  event.reply_token,
                  [
                      TextSendMessage(
                          text='算式:\n{}\n結果:\n算不出來:('.format(txt)),
                      TextSendMessage(text='P.S.:我嚴重懷疑你的數學程度')
                  ]
              )
      elif cmd == 'covid19':
          response = requests.get(
              'https://api.covid19api.com/country/taiwan').json()
          ret_ = '【台灣】\n'
          ret_ += '最後更新時間為:{}\n'.format(response[-1]['Date'])
          ret_ += '確診人數:{}\n'.format(response[-1]['Confirmed'])
          ret_ += '恢復人數:{}\n'.format(response[-1]['Recovered'])
          ret_ += '死亡人數:{}\n'.format(response[-1]['Deaths'])
          ret_ += '救治中人數:{}'.format(response[-1]['Active'])
          jloa.reply_message(
              event.reply_token,
              TextSendMessage(
                  text=ret_)
          )
      elif cmd in ['meme', '迷因', '抽迷因', '隨機迷因']:
          response = requests.get('https://cdn.nic20.tk/meme').json()
          jloa.reply_message(
              event.reply_token,
              [
                  TextSendMessage(text=response['title']),
                  ImageSendMessage(
                      original_content_url=response['image_url'],
                      preview_image_url=response['image_url']
                  )
              ]
          )
      elif cmd in ['貓咪', '貓貓', '抽貓咪', '抽貓']:
          response = requests.get('https://cdn.nic20.tk/images/cat').json()
          jloa.reply_message(
              event.reply_token,
              [
                  TextSendMessage(text=response['title']),
                  ImageSendMessage(
                      original_content_url=response['image_url'],
                      preview_image_url=response['image_url']
                  )
              ]
          )
      elif cmd in ['食物', '抽食物']:
          response = requests.get('https://cdn.nic20.tk/images/food').json()
          jloa.reply_message(
              event.reply_token,
              [
                  TextSendMessage(text=response['title']),
                  ImageSendMessage(
                      original_content_url=response['image_url'],
                      preview_image_url=response['image_url']
                  )
              ]
          )
      elif cmd in ['英豪', '抽英豪']:
          response = requests.get('https://cdn.nic20.tk/api/type=porn').json()
          jloa.reply_message(
              event.reply_token,
              ImageSendMessage(
                  original_content_url=response['url'],
                  preview_image_url=response['url']
              )
          )
      elif cmd == '地震':
          if set['eq'] == True:
              res = requests.get(
                  'https://opendata.cwb.gov.tw/api/v1/rest/datastore/E-A0015-001?Authorization=CWB-548B4309-6B20-40F5-A933-CDF24A1F2DE3&limit=1&format=JSON')
              if res.status_code == requests.codes.ok:
                  res = res.json()
                  if res['success'] == 'true':
                      eqd0 = '最近一次地震資料'
                      eqd0 += '\n地震編號:{}'.format(
                          str(res['records']['earthquake'][0]['earthquakeNo']))
                      eqd0 += '\n報告連結:{}'.format(res['records']
                                                 ['earthquake'][0]['web'])
                      eqd0 += '\n發生時間:{}'.format(res['records']['earthquake']
                                                 [0]['earthquakeInfo']['originTime'])
                      eqd0 += '\n芮氏規模:{}'.format(str(
                          res['records']['earthquake'][0]['earthquakeInfo']['magnitude']['magnitudeValue']))
                      eqd0 += '\n嚴重程度:{}'.format(res['records']
                                                 ['earthquake'][0]['reportColor'])
                      eqd0 += '\n報告內文:{}'.format(res['records']
                                                 ['earthquake'][0]['reportContent'])
                      eqd0 += '\n詳細資料:'
                      eqd0 += '\n　發生地點:'
                      eqd0 += '\n　　相對位置:{}'.format(
                          res['records']['earthquake'][0]['earthquakeInfo']['epiCenter']['location'])
                      eqd0 += '\n　　絕對位置:'
                      eqd0 += '\n　　　經度:{}°E'.format(str(
                          res['records']['earthquake'][0]['earthquakeInfo']['epiCenter']['epiCenterLon']['value']))
                      eqd0 += '\n　　　緯度:{}°N'.format(str(
                          res['records']['earthquake'][0]['earthquakeInfo']['epiCenter']['epiCenterLat']['value']))
                      eqd0 += '\n　影響地區:'
                      eqd1 = None
                      eqd2 = None
                      eqd3 = None
                      eqd4 = None
                      eqd5 = None
                      eqd6 = None
                      eqd7 = None
                      for eqds in res['records']['earthquake'][0]['intensity']['shakingArea']:
                          if eqds['areaDesc'] == '最大震度1級地區':
                              eqd1 = eqds['areaName']
                          elif eqds['areaDesc'] == '最大震度2級地區':
                              eqd2 = eqds['areaName']
                          elif eqds['areaDesc'] == '最大震度3級地區':
                              eqd3 = eqds['areaName']
                          elif eqds['areaDesc'] == '最大震度4級地區':
                              eqd4 = eqds['areaName']
                          elif eqds['areaDesc'] == '最大震度5級地區':
                              eqd5 = eqds['areaName']
                          elif eqds['areaDesc'] == '最大震度6級地區':
                              eqd6 = eqds['areaName']
                          elif eqds['areaDesc'] == '最大震度7級地區':
                              eqd7 = eqds['areaName']
                      if eqd7:
                          eqd0 += '\n　　七級:{}'.format(eqd7)
                      if eqd6:
                          eqd0 += '\n　　六級:{}'.format(eqd6)
                      if eqd5:
                          eqd0 += '\n　　五級:{}'.format(eqd5)
                      if eqd4:
                          eqd0 += '\n　　四級:{}'.format(eqd4)
                      if eqd3:
                          eqd0 += '\n　　三級:{}'.format(eqd3)
                      if eqd2:
                          eqd0 += '\n　　二級:{}'.format(eqd2)
                      if eqd1:
                          eqd0 += '\n　　一級:{}'.format(eqd1)
                      jloa.reply_message(
                          event.reply_token,
                          [
                              TextSendMessage(text=eqd0),
                              ImageSendMessage(
                                  original_content_url=res['records']['earthquake'][0]['reportImageURI'],
                                  preview_image_url=res['records']['earthquake'][0]['reportImageURI']
                              ),
                              ImageSendMessage(
                                  original_content_url=res['records']['earthquake'][0]['shakemapImageURI'],
                                  preview_image_url=res['records']['earthquake'][0]['shakemapImageURI']
                              )
                          ]
                      )
                  else:
                      jloa.reply_message(
                          event.reply_token,
                          TextSendMessage(
                              text='地震報告取得失敗，請重新取得\nGet earth quake data failed. Please retry.')
                      )
              else:
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(
                          text='地震報告取得失敗，請重新取得\nGet earth quake data failed. Please retry.')
                  )
          else:
              jloa.reply_message(
                  event.reply_token,
                  TextSendMessage(
                      text="取得地震報告功能未開啟\nThe function of geting earth quakes' data is not enabled.")
              )
      elif cmd.startswith('flex:'):
          txt = text[5:]
          bubble1 = {
              "type": "bubble",
              "body": {
                  "type": "box",
                  "layout": "vertical",
                  "contents": [
                      {
                          "type": "text",
                          "text": "{}".format(txt),
                          "weight": "bold",
                          "size": "xl",
                          "wrap": True
                      }
                  ],
                  "backgroundColor": "#FF2D2D"
              }
          }
          bubble2 = {
              "type": "bubble",
              "body": {
                  "type": "box",
                  "layout": "vertical",
                  "contents": [
                      {
                          "type": "text",
                          "text": "{}".format(txt),
                          "weight": "bold",
                          "size": "xl",
                          "wrap": True
                      }
                  ],
                  "backgroundColor": "#FFFF37"
              }
          }
          bubble3 = {
              "type": "bubble",
              "body": {
                  "type": "box",
                  "layout": "vertical",
                  "contents": [
                      {
                          "type": "text",
                          "text": "{}".format(txt),
                          "weight": "bold",
                          "size": "xl",
                          "wrap": True
                      }
                  ],
                  "backgroundColor": "#00DB00"
              }
          }
          bubble4 = {
              "type": "bubble",
              "body": {
                  "type": "box",
                  "layout": "vertical",
                  "contents": [
                      {
                          "type": "text",
                          "text": "{}".format(txt),
                          "weight": "bold",
                          "size": "xl",
                          "wrap": True
                      }
                  ],
                  "backgroundColor": "#0080FF"
              }
          }
          bubble5 = {
              "type": "bubble",
              "body": {
                  "type": "box",
                  "layout": "vertical",
                  "contents": [
                      {
                          "type": "text",
                          "text": "{}".format(txt),
                          "weight": "bold",
                          "size": "xl",
                          "wrap": True,
                          "color": "#ffffff"
                      }
                  ],
                  "backgroundColor": "#000000"
              }
          }
          botname = jloa.get_bot_info().display_name
          message1 = FlexSendMessage(
              alt_text='{} 傳送了一則模板訊息'.format(botname), contents=bubble1)
          message2 = FlexSendMessage(
              alt_text='{} 傳送了一則模板訊息'.format(botname), contents=bubble2)
          message3 = FlexSendMessage(
              alt_text='{} 傳送了一則模板訊息'.format(botname), contents=bubble3)
          message4 = FlexSendMessage(
              alt_text='{} 傳送了一則模板訊息'.format(botname), contents=bubble4)
          message5 = FlexSendMessage(
              alt_text='{} 傳送了一則模板訊息'.format(botname), contents=bubble5)
          jloa.reply_message(
              event.reply_token, [
                  message1,
                  message2,
                  message3,
                  message4,
                  message5
              ]
          )
      elif cmd.startswith('vote:'):
          x = text.split(':')
          if x[1] == '':
              aa = '我是智障'
          else:
              aa = x[1]
          try:
              bb = x[2]
          except:
              bb = '你覺得誰' + random.choice(['是笨蛋', '最白痴', '最低能'])
          bubble = BubbleContainer(
              direction='ltr',
              hero=ImageComponent(
                  url='https://img.onl/p4W2QU',
                  size='full',
                  aspect_ratio='2:1',
                  aspect_mode='cover',
              ),
              body=BoxComponent(
                  layout='vertical',
                  contents=[
                      # title
                      TextComponent(text='[投票] ' + bb, weight='bold', size='xl'),
                      # review
                      BoxComponent(
                          layout='baseline',
                          margin='md',
                          contents=[
                              TextComponent(text='請前往投票頁面中投票', size='sm', color='#666666', margin='md',
                                            flex=0)
                          ]
                      ),
                      # info
                      BoxComponent(
                          layout='vertical',
                          margin='lg',
                          spacing='sm',
                          contents=[
                              BoxComponent(
                                  layout='baseline',
                                  spacing='sm',
                                  contents=[
                                      TextComponent(
                                          text=' ',
                                          color='#2894FF',
                                          size='sm',
                                          flex=1
                                      ),
                                      TextComponent(
                                          text=' ',
                                          wrap=True,
                                          color='#FFFFFF',
                                          size='sm',
                                          flex=5
                                      )
                                  ],
                              ),
                          ],
                      )
                  ],
              ),
              footer=BoxComponent(
                  layout='vertical',
                  spacing='sm',
                  contents=[
                      # callAction
                      ButtonComponent(
                          style='link',
                          height='sm',
                          action=MessageAction(label='立即投票', text=aa),
                      ),
                  ]
              ),
          )
          botname = jloa.get_bot_info().display_name
          message = FlexSendMessage(
              alt_text='{} 傳送了一則投票訊息'.format(botname), contents=bubble)
          jloa.reply_message(
              event.reply_token,
              message
          )
      elif '/ti/g/' in cmd:
          link_re = re.compile(
              '(?:line\:\/|line\.me\/R)\/ti\/g\/([a-zA-Z0-9_-]+)?')
          links = link_re.findall(text)
          n_links = []
          urls = []
          for l in links:
              if l not in n_links:
                  n_links.append(l)
          for ticket_id in n_links:
              urls.append(URIAction(label='加入群組({})'.format(ticket_id),
                          uri='https://line.me/R/ti/g/{}'.format(ticket_id)))
          buttons_template = ButtonsTemplate(
              title='群組網址解析', text='共有 {} 個群組網址在此則訊息中'.format(str(len(n_links))), actions=urls)
          botname = jloa.get_bot_info().display_name
          template_message = TemplateSendMessage(
              alt_text='{} 傳送了一則模板訊息'.format(botname), template=buttons_template)
          jloa.reply_message(event.reply_token, template_message)
      elif cmd == 'mymid':
          jloa.reply_message(
              event.reply_token,
              TextSendMessage(text=event.source.user_id)
          )
      elif cmd == 'place':
          jloa.reply_message(
              event.reply_token,
              TextSendMessage(text=to)
          )
  
  
  @handler.add(MessageEvent, message=LocationMessage)
  def handle_location_message(event):
      jloa.reply_message(
          event.reply_token,
          TextSendMessage(
              text='[位置資料 Location Data]\n經度 Longitude:\n{}\n緯度 Latitude:\n{}\n地址 Address:\n{}'.format(event.message.longitude, event.message.latitude, event.message.address))
      )
  
  
  @handler.add(MessageEvent, message=StickerMessage)
  def handle_sticker_message(event):
      sender = event.source.user_id
      if isinstance(event.source, SourceGroup):
          to = event.source.group_id
      elif isinstance(event.source, SourceRoom):
          to = event.source.room_id
      else:
          to = sender
      if isinstance(event.source, SourceUser):
          if sender in ops['author'] or sender in ops['admin']:
              jloa.reply_message(
                  event.reply_token,
                  [
                      TextSendMessage(text='[上]貼圖回覆設定/更新\n[下]貼圖回覆刪除'),
                      TextSendMessage(text='sr:{}:文字(不可包含:)'.format(
                          str(event.message.sticker_id))),
                      TextSendMessage(text='dsr:{}'.format(
                          str(event.message.sticker_id)))
                  ]
              )
      else:
          if event.message.sticker_id in reply['sticker']:
              if set['sr'] == True:
                  if isinstance(event.source, SourceGroup):
                      profile = jloa.get_group_member_profile(to, sender)
                      jloa.reply_message(
                          event.reply_token,
                          FlexSendMessage(alt_text='{} 傳送了一則模板訊息'.format(profile.display_name), sender=Sender(name=profile.display_name, icon_url=profile.picture_url), contents={
                              "type": "bubble",
                              "body": {
                                  "type": "box",
                                  "layout": "vertical",
                                  "contents": [
                                      {
                                          "type": "text",
                                          "text": "{}".format(reply["sticker"][event.message.sticker_id]),
                                          "weight": "bold",
                                          "size": "xl",
                                          "wrap": True
                                      }
                                  ],
                                  "backgroundColor": "#BEBEBE"
                              }
                          })
                      )
                  elif isinstance(event.source, SourceRoom):
                      profile = jloa.get_room_member_profile(to, sender)
                      jloa.reply_message(
                          event.reply_token,
                          FlexSendMessage(alt_text='{} 傳送了一則模板訊息'.format(profile.display_name), sender=Sender(name=profile.display_name, icon_url=profile.picture_url), contents={
                              "type": "bubble",
                              "body": {
                                  "type": "box",
                                  "layout": "vertical",
                                  "contents": [
                                      {
                                          "type": "text",
                                          "text": "{}".format(reply["sticker"][event.message.sticker_id]),
                                          "weight": "bold",
                                          "size": "xl",
                                          "wrap": True
                                      }
                                  ],
                                  "backgroundColor": "#BEBEBE"
                              }
                          })
                      )
          else:
              if set['ssr'] == True:
                  if event.message.sticker_resource_type in stktype:
                      st = stktype[event.message.sticker_resource_type]
                  else:
                      st = '其它 Other({})'.format(
                          event.message.sticker_resource_type)
                  jloa.reply_message(
                      event.reply_token,
                      TextSendMessage(text='[貼圖資料 Sticker Data]\n貼圖ID Sticker id:\n{}\n貼圖包ID Sticker Package id:\n{}\n類型 Type:\n{}'.format(
                          str(event.message.sticker_id), str(event.message.package_id), st))
                  )
      # jloa.reply_message(
      #    event.reply_token,
      #    StickerSendMessage(
      #        package_id=event.message.package_id,
      #        sticker_id=event.message.sticker_id)
      # )
  
  
  @handler.add(FollowEvent)
  def handle_follow(event):
      app.logger.info('Got Follow event:' + event.source.user_id)
  
  
  @handler.add(UnfollowEvent)
  def handle_unfollow(event):
      app.logger.info('Got Unfollow event:' + event.source.user_id)
  
  
  @handler.add(JoinEvent)
  def handle_join(event):
      if isinstance(event.source, SourceGroup):
          if set['lg']:
              jloa.reply_message(
                  event.reply_token,
                  TextSendMessage(
                      text='自離群組為開啟狀態\nAuto leave group is enable.')
              )
              jloa.leave_group(event.source.group_id)
          else:
              botname = jloa.get_bot_info().display_name
              message = FlexSendMessage(alt_text='{} 傳送了一則模板訊息'.format(botname), contents={
                  "type": "carousel",
                  "contents": [
                      {
                          "type": "bubble",
                          "body": {
                              "type": "box",
                              "layout": "vertical",
                              "contents": [
                                  {
                                      "type": "image",
                                      "url": "https://i.imgur.com/l5b4cuv.png",
                                      "size": "full",
                                      "aspectMode": "cover",
                                      "aspectRatio": "2:3",
                                      "gravity": "top"
                                  },
                                  {
                                      "type": "box",
                                      "layout": "vertical",
                                      "contents": [
                                          {
                                              "type": "box",
                                              "layout": "vertical",
                                              "contents": [
                                                  {
                                                      "type": "text",
                                                      "text": "感謝您的邀請",
                                                      "size": "3xl",
                                                      "color": "#ffffff",
                                                      "weight": "bold"
                                                  }
                                              ]
                                          },
                                          {
                                              "type": "box",
                                              "layout": "baseline",
                                              "contents": [
                                                  {
                                                      "type": "text",
                                                      "text": "邀請類別:群組",
                                                      "color": "#ebebeb",
                                                      "size": "xl",
                                                      "flex": 0
                                                  }
                                              ],
                                              "spacing": "lg"
                                          }
                                      ],
                                      "position": "absolute",
                                      "offsetBottom": "0px",
                                      "offsetStart": "0px",
                                      "offsetEnd": "0px",
                                      "backgroundColor": "#03303Acc",
                                      "paddingAll": "20px",
                                      "paddingTop": "18px"
                                  }
                              ],
                              "paddingAll": "0px"
                          }
                      },
                      {
                          "type": "bubble",
                          "body": {
                              "type": "box",
                              "layout": "vertical",
                              "contents": [
                                  {
                                      "type": "image",
                                      "url": "https://i.imgur.com/BkneBPr.jpg",
                                      "size": "full",
                                      "aspectMode": "cover",
                                      "aspectRatio": "2:3",
                                      "gravity": "top"
                                  },
                                  {
                                      "type": "box",
                                      "layout": "vertical",
                                      "contents": [
                                          {
                                              "type": "box",
                                              "layout": "vertical",
                                              "contents": [
                                                  {
                                                      "type": "text",
                                                      "text": "加入作者好友",
                                                      "size": "xxl",
                                                      "color": "#ffffff",
                                                      "weight": "bold"
                                                  }
                                              ]
                                          },
                                          {
                                              "type": "box",
                                              "layout": "vertical",
                                              "contents": [
                                                  {
                                                      "type": "filler"
                                                  },
                                                  {
                                                      "type": "box",
                                                      "layout": "baseline",
                                                      "contents": [
                                                          {
                                                              "type": "filler"
                                                          },
                                                          {
                                                              "type": "text",
                                                              "text": "加入作者好友",
                                                              "color": "#ffffff",
                                                              "flex": 0,
                                                              "offsetTop": "-2px",
                                                              "size": "xl"
                                                          },
                                                          {
                                                              "type": "filler"
                                                          }
                                                      ],
                                                      "spacing": "sm"
                                                  },
                                                  {
                                                      "type": "filler"
                                                  }
                                              ],
                                              "borderWidth": "2px",
                                              "cornerRadius": "100px",
                                              "borderColor": "#ffffff",
                                              "height": "50px",
                                              "backgroundColor": "#7B7B7Baa",
                                              "action": {
                                                  "type": "uri",
                                                  "label": "action",
                                                  "uri": "line://nv/profilePopup/mid=u8b9d115e85202db06eb798e8c1b40ae9"
                                              },
                                              "spacing": "sm",
                                              "margin": "xl"
                                          }
                                      ],
                                      "position": "absolute",
                                      "offsetBottom": "0px",
                                      "offsetStart": "0px",
                                      "offsetEnd": "0px",
                                      "backgroundColor": "#8E8E8Ecc",
                                      "paddingAll": "20px",
                                      "paddingTop": "18px"
                                  }
                              ],
                              "paddingAll": "0px"
                          }
                      }
                  ]
              })
              jloa.reply_message(
                  event.reply_token,
                  message
              )
      elif isinstance(event.source, SourceRoom):
          if set['lr']:
              jloa.reply_message(
                  event.reply_token,
                  TextSendMessage(
                      text='自離副本為開啟狀態\nAuto leave room is enable.')
              )
              jloa.leave_room(event.source.room_id)
          else:
              botname = jloa.get_bot_info().display_name
              message = FlexSendMessage(alt_text='{} 傳送了一則模板訊息'.format(botname), contents={
                  "type": "carousel",
                  "contents": [
                      {
                          "type": "bubble",
                          "body": {
                              "type": "box",
                              "layout": "vertical",
                              "contents": [
                                  {
                                      "type": "image",
                                      "url": "https://i.imgur.com/2Kpw96s.jpg",
                                      "size": "full",
                                      "aspectMode": "cover",
                                      "aspectRatio": "2:3",
                                      "gravity": "top"
                                  },
                                  {
                                      "type": "box",
                                      "layout": "vertical",
                                      "contents": [
                                          {
                                              "type": "box",
                                              "layout": "vertical",
                                              "contents": [
                                                  {
                                                      "type": "text",
                                                      "text": "感謝您的邀請",
                                                      "size": "3xl",
                                                      "color": "#ffffff",
                                                      "weight": "bold"
                                                  }
                                              ]
                                          },
                                          {
                                              "type": "box",
                                              "layout": "baseline",
                                              "contents": [
                                                  {
                                                      "type": "text",
                                                      "text": "邀請類別:副本",
                                                      "color": "#ebebeb",
                                                      "size": "xl",
                                                      "flex": 0
                                                  }
                                              ],
                                              "spacing": "lg"
                                          }
                                      ],
                                      "position": "absolute",
                                      "offsetBottom": "0px",
                                      "offsetStart": "0px",
                                      "offsetEnd": "0px",
                                      "backgroundColor": "#03303Acc",
                                      "paddingAll": "20px",
                                      "paddingTop": "18px"
                                  }
                              ],
                              "paddingAll": "0px"
                          }
                      },
                      {
                          "type": "bubble",
                          "body": {
                              "type": "box",
                              "layout": "vertical",
                              "contents": [
                                  {
                                      "type": "image",
                                      "url": "https://i.imgur.com/BkneBPr.jpg",
                                      "size": "full",
                                      "aspectMode": "cover",
                                      "aspectRatio": "2:3",
                                      "gravity": "top"
                                  },
                                  {
                                      "type": "box",
                                      "layout": "vertical",
                                      "contents": [
                                          {
                                              "type": "box",
                                              "layout": "vertical",
                                              "contents": [
                                                  {
                                                      "type": "text",
                                                      "text": "加入作者好友",
                                                      "size": "xxl",
                                                      "color": "#ffffff",
                                                      "weight": "bold"
                                                  }
                                              ]
                                          },
                                          {
                                              "type": "box",
                                              "layout": "vertical",
                                              "contents": [
                                                  {
                                                      "type": "filler"
                                                  },
                                                  {
                                                      "type": "box",
                                                      "layout": "baseline",
                                                      "contents": [
                                                          {
                                                              "type": "filler"
                                                          },
                                                          {
                                                              "type": "text",
                                                              "text": "加入作者好友",
                                                              "color": "#ffffff",
                                                              "flex": 0,
                                                              "offsetTop": "-2px",
                                                              "size": "xl"
                                                          },
                                                          {
                                                              "type": "filler"
                                                          }
                                                      ],
                                                      "spacing": "sm"
                                                  },
                                                  {
                                                      "type": "filler"
                                                  }
                                              ],
                                              "borderWidth": "2px",
                                              "cornerRadius": "100px",
                                              "borderColor": "#ffffff",
                                              "height": "50px",
                                              "backgroundColor": "#7B7B7Baa",
                                              "action": {
                                                  "type": "uri",
                                                  "label": "action",
                                                  "uri": "line://nv/profilePopup/mid=u8b9d115e85202db06eb798e8c1b40ae9"
                                              },
                                              "spacing": "sm",
                                              "margin": "xl"
                                          }
                                      ],
                                      "position": "absolute",
                                      "offsetBottom": "0px",
                                      "offsetStart": "0px",
                                      "offsetEnd": "0px",
                                      "backgroundColor": "#8E8E8Ecc",
                                      "paddingAll": "20px",
                                      "paddingTop": "18px"
                                  }
                              ],
                              "paddingAll": "0px"
                          }
                      }
                  ]
              })
              jloa.reply_message(
                  event.reply_token,
                  message
              )
  
  
  @handler.add(LeaveEvent)
  def handle_leave():
      app.logger.info('Got leave event')
  
  
  @handler.add(PostbackEvent)
  def handle_postback(event):
      if event.postback.data == 'ping':
          jloa.reply_message(
              event.reply_token, TextSendMessage(text='pong'))
      elif event.postback.data == 'datetime_postback':
          jloa.reply_message(
              event.reply_token, TextSendMessage(text=event.postback.params['datetime']))
      elif event.postback.data == 'date_postback':
          jloa.reply_message(
              event.reply_token, TextSendMessage(text=event.postback.params['date']))
  
  
  @handler.add(BeaconEvent)
  def handle_beacon(event):
      jloa.reply_message(
          event.reply_token,
          TextSendMessage(
              text='Got beacon event. hwid={}, device_message(hex string)={}'.format(
                  event.beacon.hwid, event.beacon.dm)))
  
  
  @handler.add(MemberJoinedEvent)
  def handle_member_joined(event):
      if isinstance(event.source, SourceGroup):
          joinmer = []
          gname = jloa.get_group_summary(event.source.group_id).group_name
          for ouo in event.joined.members:
              name = jloa.get_group_member_profile(
                  event.source.group_id, ouo.user_id).display_name
              joinmer.append(TextSendMessage(
                  text='[通知]\n歡迎 {} 加入 {} 的大家庭'.format(name, gname)))
          jloa.reply_message(
              event.reply_token,
              joinmer
          )
      else:
          joinmer = []
          for ouo in event.joined.members:
              name = jloa.get_room_member_profile(
                  event.source.room_id, ouo.user_id).display_name
              joinmer.append(TextSendMessage(
                  text='[通知]\n歡迎 {} 加入我們的大家庭'.format(name)))
          jloa.reply_message(
              event.reply_token,
              joinmer
          )
  
  
  @handler.add(MemberLeftEvent)
  def handle_member_left(event):
      if isinstance(event.source, SourceGroup):
          for ouo in event.left.members:
              print('\n=====提示=====\n有人退出/被踢出群組\n用戶ID:{}\nGid:{}\n=====提示=====\n'.format(
                  ouo.user_id, event.source.group_id))
      else:
          for ouo in event.left.members:
              print('\n=====提示=====\n有人離開副本\n用戶ID:{}\nRid:{}\n=====提示=====\n'.format(
                  ouo.user_id, event.source.room_id))
  
  
  # =============定義執行函數============== #
  if __name__ == '__main__':
      arg_parser = ArgumentParser(
          usage='Usage: python ' + __file__ + ' [--port <port>] [--help]'
      )
      arg_parser.add_argument('-p', '--port', type=int,
                              default=8000, help='port')
      arg_parser.add_argument('-d', '--debug', default=False, help='debug')
      options = arg_parser.parse_args()
  
      os.system('clear')
      print('非官機器啟動\nOA bot start\n')
      requests.post('https://notify-api.line.me/api/notify', headers={'Authorization': 'Bearer {}'.format(
          set['line_notify_token']), 'Content-Type': 'application/x-www-form-urlencoded'}, params={'message': '非官已啟動🔵'})
  
      app.run(debug=options.debug, port=options.port, threaded=True)
  # =============定義執行函數============== #
  