Пример #1
0
    def create_line_bot(self):
        if self._channel_access_token is not None and self._channel_secret is not None:
            self._line_bot_api = LineBotApi(self._channel_access_token)
            self._parser = WebhookParser(self._channel_secret)

        else:
            YLogger.error(self, "Line channel access token and/or secret missing, unable to create line bot")
Пример #2
0
 def __init__(self,
              bot=None,
              *,
              threads=None,
              debug=False,
              channel_secret=None,
              channel_access_token=None,
              **kwargs):
     """
     Parameters
     ----------
     bot : minette.Minette, default None
         Instance of Minette.
         If None, create new instance of Minette by using `**kwargs`
     channel_secret : str, default None
         Channel Secret
     channel_access_token : str, default None
         Channel Access Token
     threads : int, default None
         Number of worker threads to process requests
     debug : bool, default None
         Debug mode
     """
     super().__init__(bot=bot, threads=threads, debug=debug, **kwargs)
     self.channel_secret = channel_secret or \
         self.config.get(section="line_bot_api", key="channel_secret")
     self.channel_access_token = channel_access_token or \
         self.config.get(section="line_bot_api", key="channel_access_token")
     self.parser = WebhookParser(self.channel_secret)
     self.api = LineBotApi(self.channel_access_token)
Пример #3
0
def callback():
    if channel_secret is None:
        print('Specify LINE_CHANNEL_SECRET as environment variable.')
        sys.exit(1)
    if channel_access_token is None:
        print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
        sys.exit(1)

    line_bot_api = LineBotApi(channel_access_token)
    parser = WebhookParser(channel_secret)
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    # app.logger.info("Request body: " + body)
    print("Request body: %s" % body)

    # parse webhook body
    try:
        events = parser.parse(body, signature)
        for event in events:
            if isinstance(event, MessageEvent):
                handle_message(event)
    except InvalidSignatureError:
        abort(400)

    return 'OK~~'
Пример #4
0
def linebot(request):
    signature = request.headers['X-Line-Signature']

    # get channel_secret and channel_access_token from your environment variable
    channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)
    channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)
    if channel_secret is None:
        print('Specify LINE_CHANNEL_SECRET as environment variable.')
        sys.exit(1)
    if channel_access_token is None:
        print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
        sys.exit(1)

    line_bot_api = LineBotApi(channel_access_token)
    parser = WebhookParser(channel_secret)

    # get request body as text
    body = request.get_data(as_text=True)

    events = parser.parse(body, signature)

    # if event is MessageEvent and message is TextMessage, then echo text
    for event in events:
        if not isinstance(event, MessageEvent):
            continue
        if not isinstance(event.message, TextMessage):
            continue

        line_bot_api.reply_message(event.reply_token,
                                   set_reply_message(event.message.text))
Пример #5
0
def callback(channel_id):
    global line_bot_api
    global handler

    # Query channel information using channel_id
    app.logger.info("Channel_id from Webhook: " + channel_id)
    channel_secret, channel_access_token = utils.get_channel(channel_id)

    # start up line_bot_api and handler
    line_bot_api = LineBotApi(channel_access_token)
    handler.parser = WebhookParser(channel_secret)

    # 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)

    # set current channel_id
    user_id = json.loads(body)['events'][0]['source']['userId']
    r.set(user_id + ':channel_id', channel_id)

    # handle webhook body
    try:
        handler.handle(body, signature)
        print(handler)

    except InvalidSignatureError:
        print(
            "Invalid signature. Please check your channel access token/channel secret."
        )
        abort(400)

    return 'OK'
Пример #6
0
def callback():
    channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)
    channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)
    if not channel_secret:
        print('Specify LINE_CHANNEL_SECRET as environment variable.')
        abort(500)
    if not channel_access_token:
        print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
        abort(500)

    line_bot_api = LineBotApi(channel_access_token)
    parser = WebhookParser(channel_secret)
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # parse webhook body
    try:
        events = parser.parse(body, signature)
        # if event is MessageEvent and message is TextMessage, then echo text
        for event in events:
            if not isinstance(event, MessageEvent):
                continue
            if not isinstance(event.message, TextMessage):
                continue

            line_bot_api.reply_message(event.reply_token,
                                       get_message(event.message.text))

    except InvalidSignatureError:
        abort(400)

    return 'OK'
Пример #7
0
class LineBot(Chat):
    code_leave = 1
    code_normal = 0
    line_bot_api = LineBotApi(os.environ['LINE_CHANNEL_ACCESS_TOKEN'])
    line_webhook_parser = WebhookParser(os.environ['LINE_CHANNEL_SECRET'])

    def retrieve(self):
        if self.query in Chat.kickout_key and self.idtype != 'user':
            l = len(Chat.kickout_response)
            return Chat.kickout_response[random.randint(0, l -
                                                        1)], LineBot.code_leave
        else:
            return super(LineBot, self).retrieve(), LineBot.code_normal

    def leave(self):
        try:
            if self.idtype == 'group':
                LineBot.line_bot_api.leave_group(self.uid)
            elif self.idtype == 'room':
                LineBot.line_bot_api.leave_room(self.uid)

        except LineBotApiError as err:
            self.logger.error(
                'okbot.chat_app.bots.LineBot.leave, message: {}'.format(err))

        self._upsert_user(active=False)
Пример #8
0
def main(request):
    body = request.get_data(as_text=True)
    line_receiver_id = request.headers.get('LINE_RECEIVER_ID')

    if line_receiver_id and request.headers.get('GOOD_MORNING_AUTH') == GOOD_MORNING_AUTH:
      push_good_morning_image(line_receiver_id)
    else:
      hash = hmac.new(LINE_CHANNEL_SECRET.encode('utf-8'),
          body.encode('utf-8'), hashlib.sha256).digest()
      signature = base64.b64encode(hash).decode()
      parser = WebhookParser(LINE_CHANNEL_SECRET)

      if signature != request.headers['X_LINE_SIGNATURE']:
          return abort(405)
      try:
          events = parser.parse(body, signature)
      except InvalidSignatureError:
          return abort(405)

      for event in events:
          if not isinstance(event, MessageEvent):
              continue
          if isinstance(event.message, ImageMessage) and (event.source.type == 'room' and event.source.user_id == LINE_TARGET_ID):
              image_message_id = event.message.id
              image_content = line_bot_api.get_message_content(image_message_id).content
              upload_image(image_content, GOOD_MORNING_ALBUM_ID)
    return jsonify({ 'message': 'ok'})
def register_temperature(request):
    execution_id = request.headers.get('Function-Execution-Id')
    channel_secret = os.environ.get('LINE_CHANNEL_SECRET')
    channel_access_token = os.environ.get('LINE_CHANNEL_ACCESS_TOKEN')

    bot_api = LineBotApi(channel_access_token)
    parser = WebhookParser(channel_secret)

    body = request.get_data(as_text=True)
    hash = hmac.new(channel_secret.encode('utf-8'),
                    body.encode('utf-8'), hashlib.sha256).digest()
    signature = base64.b64encode(hash).decode()

    if signature != request.headers['X_LINE_SIGNATURE']:
        return abort(405)

    try:
        events = parser.parse(body, signature)
    except InvalidSignatureError:
        return abort(405)

    for event in events:
        if not isinstance(event, MessageEvent):
            continue
        if not isinstance(event.message, TextMessage):
            continue

        handle_event(event, channel_access_token, bot_api, execution_id)
    return jsonify({'message': 'ok'})
Пример #10
0
def line(event, context):

    # イベントデータの表示
    logger.info('headers:' + str(event['headers']['X-Line-Signature']))
    logger.info('body:' + str(event['body']))

    # リクエスト本体と、X-LINE-Signatureヘッダを取出す
    body = event['body']
    signature = event['headers']['X-Line-Signature']

    # Channel Secretを使って入力が正しいかを確認する
    secret = 'ここにシークレットを入力'
    parser = WebhookParser(secret)

    try:
        events = parser.parse(body,signature)
    except InvalidSignatureError:
        logger.error('InvalidSignatureError')
        return {"stautsCode" : 400,"body" : ""};

    # LineBotAPIオブジェクトを作成する
    token = 'ここにトークンを入力'
    line_bot_api = LineBotApi(token)

    try:
        events = parser.parse(body,signature)
    except InvalidSignatureError:
        return {"stautsCode" : 400,"body" : ""};

    # for event in events:
    logger.info('events:' + str(events))

    # DBにメッセージを保存
    user_id = events[0].source.user_id
    line_message = events[0].message.text

    put_response = table.put_item(
        Item={
            'timestamp': int(datetime.datetime.now().timestamp()),
            'id': user_id,
            'message': line_message
        }
    )

    reply_token = events[0].reply_token
    success_message = TextSendMessage(
        text='メッセージを登録しました!\n\n'
             'メッセージを修正する場合はもう一度メッセージを送ってください\n\n'
             'メッセージにはあなたのお名前がわかるようにしてください'
    )

    try:
        line_bot_api.reply_message(reply_token,success_message)
    except LineBotApiError as e:
        print(e.status_code)
        print(e.error.message)
        print(e.error.details)

    return {"stautsCode" : 200,"body" : "OK"};
    def callback(self, signature, body):
        parser = WebhookParser(self.CHANNEL_SECRET)

        try:
            events = parser.parse(body, signature)
            self.__handle_message(events[0])
        except InvalidSignatureError as e:
            print(e)
Пример #12
0
 def __init__(
     self,
     access_token: Text,
     secret: Text,
     on_new_message: Callable[[UserMessage], Awaitable[Any]],
 ) -> None:
     self.on_new_message = on_new_message
     self.client = LineBotApi(access_token)
     self.parser = WebhookParser(secret)
     self.output_collector = LineOutput(self.client)
Пример #13
0
def main(request):
    """This is a LINE Bot function

    Args:
        request (flask.Request): [description]

    Returns:
        Response|HTTPException: [description]
    """

    # LINEアプリ設定(環境変数)
    channel_secret = os.environ.get('LINE_CHANNEL_SECRET')
    channel_access_token = os.environ.get('LINE_CHANNEL_ACCESS_TOKEN')

    # LINE Bot(Messaging) API
    line_bot_api = LineBotApi(channel_access_token)
    parser = WebhookParser(channel_secret)

    # WebhookリクエストからBODYを取得
    body = request.get_data(as_text=True)

    # チャネルの秘密鍵からシグネチャを取得
    hashcode = hmac.new(channel_secret.encode('utf-8'), body.encode('utf-8'),
                        hashlib.sha256).digest()
    signature = base64.b64encode(hashcode).decode()

    # シグネチャの合致判定
    if signature != request.headers['X_LINE_SIGNATURE']:
        return abort(405)

    # リクエストボディからWebhookイベントオブジェクト(Payload)を取得
    try:
        events = parser.parse(body, signature)
    except InvalidSignatureError:
        return abort(405)

    # Webhookイベントオブジェクトを処理
    for event in events:
        if not isinstance(event, MessageEvent):  # メッセージイベント以外は未処理
            continue
        if not isinstance(event.message, TextMessage):  # テキスト以外は未処理
            continue

        if event.message.text == u'おわり':  # エコーバックしないワードの処理
            # 「おわり」というメッセで「ほんとに?」を返す
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=u"ほんとに?"))
        else:
            # 上記以外のメッセはそのままオウム返し
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text=event.message.text))

    return ("", 200)
Пример #14
0
 def __init__(self, channel_access_token:str, channel_secret:str,
              host="localhost", port="5000", webhook_suffix="line",
              dispatcher=RequestDispatcher.load(), message_parser=LineParser):
     super().__init__(dispatcher=dispatcher, message_parser=message_parser)
     self.channel_access_token = channel_access_token
     self.channel_secret = channel_secret
     self.port = port
     self.webhook_suffix = webhook_suffix
     self.host = host
     self.line_bot_api = LineBotApi(self.channel_access_token)
     self.webhook_handler = WebhookHandler(self.channel_secret)
     self.parser = WebhookParser(self.channel_secret)
     bottle.default_app().route(path='/', callback=self.landing)
     bottle.default_app().route('/{}'.format(webhook_suffix), callback=self.webhook_callback, method="POST")
Пример #15
0
 def __init__(self, client):
     self.lock = Lock()
     with Acquire(client.lock, self.lock):
         self.client = client
     with Acquire(self.lock):
         self.thread = None
             
         self._1client = LineBotApi(self.channelAccessToken)
         if self.channelSecret is None:
             self.parser = None
         else:
             self.parser = WebhookParser(self.channelSecret)
         self.idLocks = {}
         self.adminObjs = []
         self.running = False
Пример #16
0
 def __init__(self):
     line_config = ConfigParser()
     root_dir = os.environ.get('ROOT_DIR')
     line_config_path = os.path.join(root_dir, 'credential',
                                     'line_config.ini')
     line_config.read(line_config_path)
     if not line_config.has_option('Line Config', 'ACCESS_TOKEN'):
         print('Specify LINE_CHANNEL_SECRET as environment variable.')
         sys.exit(1)
     if not line_config.has_option('Line Config', 'SECRET'):
         print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
         sys.exit(1)
     channel_secret = line_config['Line Config']['SECRET']
     channel_access_token = line_config['Line Config']['ACCESS_TOKEN']
     self.line_bot_api = LineBotApi(channel_access_token)
     self.parser = WebhookParser(channel_secret)
Пример #17
0
def main(request):
    line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)
    parser = WebhookParser(LINE_CHANNEL_SECRET)

    body = request.get_data(as_text=True)
    hash = hmac.new(LINE_CHANNEL_SECRET.encode('utf-8'), body.encode('utf-8'),
                    hashlib.sha256).digest()
    signature = base64.b64encode(hash).decode()

    if signature != request.headers['X_LINE_SIGNATURE']:
        return abort(405)

    try:
        events = parser.parse(body, signature)
    except InvalidSignatureError:
        return abort(405)

    for event in events:
        if not isinstance(event, MessageEvent):
            continue
        if not isinstance(event.message, TextMessage):
            continue
        text = event.message.text
        if '新增圖片\n' in text:
            tmp, desc, image_url = text.split('\n')
            response = upload_image_by_url(image_url, desc, MAIN_ALBUM_ID)
            message = ('格式錯誤 新增失敗', '新增成功')[response.status_code == 200]
            reply_instance = TextSendMessage(text=message)
        elif text == '關鍵字查詢':
            images = get_images(MAIN_ALBUM_ID)
            desc_list = [image['description'] for image in images]
            #uniqueness
            uniq_desc_list = list(set(desc_list))
            reply_instance = TextSendMessage(text=','.join(uniq_desc_list))
        else:
            #從一般相簿中過濾 or 從美女相簿中隨機
            images = ([
                image for image in get_images(MAIN_ALBUM_ID)
                if image['description'] == text
            ], get_images(SUB_ALBUM_ID))[text == '抽']
            image_url = random.choice(images)['link']
            reply_instance = ImageSendMessage(original_content_url=image_url,
                                              preview_image_url=image_url)

        line_bot_api.reply_message(event.reply_token, reply_instance)
    return jsonify({'message': 'ok'})
Пример #18
0
async def main(port=8000):
    session = aiohttp.ClientSession()
    async_http_client = AiohttpAsyncHttpClient(session)
    line_bot_api = AsyncLineBotApi(channel_access_token, async_http_client)
    parser = WebhookParser(channel_secret)

    handler = Handler(line_bot_api, parser)

    app = web.Application()
    app.add_routes([web.post('/callback', handler.echo)])

    runner = web.AppRunner(app)
    await runner.setup()
    site = TCPSite(runner=runner, port=port)
    await site.start()
    while True:
        await asyncio.sleep(3600)  # sleep forever
Пример #19
0
def callback():
    signature = request.headers['X-Line-Signature']  
    body = request.get_data(as_text = True)
    events = WebhookParser(chatBotConfig.channel['channelSecret']).parse(body, signature)
    lineId = events[0].source.user_id
    bus = events[0].message.text
    query.set(bus)
    pic_url = 'https://storage.googleapis.com/aibigdata-ntut-107598064.appspot.com/bus/1593174590.jpg'
    if (query.gettime()):
        text = query.getbus() + '\n' + query.getdest() + '\n' + query.gettime()
    else:
        text = query.getbus() + '\n' + query.getdest() + '\n' + query.getstatus()

    print(text)
    line_bot_api.push_message(lineId, TextSendMessage(text = text, disable_web_page_preview = True))
    line_bot_api.push_message(lineId, ImageSendMessage(original_content_url='https://storage.googleapis.com/aibigdata-ntut-107598064.appspot.com/bus/1593174590.jpg', preview_image_url = 'https://storage.googleapis.com/aibigdata-ntut-107598064.appspot.com/bus/1593174590.jpg'))
    return 'OK'
Пример #20
0
async def main(req: func.HttpRequest) -> func.HttpResponse:
    # create api client
    line_api = AioLineBotApi(
        channel_access_token="<YOUR CHANNEL ACCESS TOKEN>")

    # get events from request
    parser = WebhookParser(channel_secret="<YOUR CHANNEL SECRET>")
    events = parser.parse(req.get_body().decode("utf-8"),
                          req.headers.get("X-Line-Signature", ""))

    for ev in events:
        # reply echo
        await line_api.reply_message(
            ev.reply_token, TextMessage(text=f"You said: {ev.message.text}"))

    # 200 response
    return func.HttpResponse("ok")
Пример #21
0
def auto_gen_line_message(sender, **kwargs):
    line_bot_api = LineBotApi(settings.LINE_CHANNEL_ACCESS_TOKEN)
    parser = WebhookParser(settings.LINE_CHANNEL_SECRET)
    to = kwargs.get('instance').RoomID
    user_send = UserInTheRoom.objects.filter(RoomId=to).values(
        'User')  # .User_set.values('username')
    list_result = [entry for entry in user_send]
    list_to = []
    message = kwargs.get('instance').detail
    for item in list_result:
        for key in item:
            user = User.objects.filter(id=item[key]).values('username').get()
            list_to.append(user['username'])
    try:
        for item in list_to:
            line_bot_api.push_message(item, TextSendMessage(text=str(message)))
    except LineBotApiError as e:
        print(e)
Пример #22
0
async def main(req: func.HttpRequest) -> func.HttpResponse:
    # APIインターフェイスの初期化
    # api = LineBotApi(channel_access_token="<YOUR CHANNEL ACCESS TOKEN>")      # <-- 同期APIを利用した場合
    api = AioLineBotApi(channel_access_token="<YOUR CHANNEL ACCESS TOKEN>")

    # リクエストからイベントを取得
    parser = WebhookParser(channel_secret="<YOUR CHANNEL SECRET>")
    events = parser.parse(req.get_body().decode("utf-8"),
                          req.headers.get("X-Line-Signature", ""))

    for ev in events:
        # おうむ返し
        # api.reply_message(ev.reply_token, TextMessage(text=f"You said: {ev.message.text}"))      # <-- 同期APIを利用した場合
        await api.reply_message(
            ev.reply_token, TextMessage(text=f"You said: {ev.message.text}"))

    # HTTPのレスポンス
    return func.HttpResponse("ok")
Пример #23
0
def home(request):
    line_bot_api = LineBotApi(LINE_CAT)
    webhook_parser = WebhookParser(LINE_CS)
    signature = ""
    if request.META["HTTP_X_LINE_SIGNATURE"]:
        signature = request.META["HTTP_X_LINE_SIGNATURE"]
    body = request.body

    try:
        events = webhook_parser.parse(body, signature)
        for event in events:
            print event.reply_token
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text=event.message.text))
    except InvalidSignatureError:
        return HttpResponse("Signature invalid")

    return HttpResponse("")
Пример #24
0
import hmac


def load_credentials():
    xdoc = minidom.parse("credentials.xml")
    token = xdoc.getElementsByTagName("token")[0].childNodes[0].data
    secret = xdoc.getElementsByTagName("secret")[0].childNodes[0].data
    return (token, secret)


app = Flask(__name__)
app.config['DEBUG'] = False

token, secret = load_credentials()
line_bot_api = LineBotApi(token)
parser = WebhookParser(secret)


def check_profile(source):
    '''
    analyzes the "source" element of an event
    if it's from a new user or event, adds that to the logic class.
    returns the user_id and group_id(which is None if
    it's not a group chat or chatroom.)
    '''
    user_id = source.user_id
    group_id = None
    if source.type == "group":
        group_id = source.group_id
    elif source.type == "room":
        group_id = source.room_id
Пример #25
0
)

app = Flask(__name__, static_url_path="")

# get channel_secret and channel_access_token from your environment variable
channel_secret = os.getenv("LINE_CHANNEL_SECRET", None)
channel_access_token = os.getenv("LINE_CHANNEL_ACCESS_TOKEN", None)
if channel_secret is None:
    print("Specify LINE_CHANNEL_SECRET as environment variable.")
    sys.exit(1)
if channel_access_token is None:
    print("Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.")
    sys.exit(1)

line_bot_api = LineBotApi(channel_access_token)
parser = WebhookParser(channel_secret)
canmessage = TemplateSendMessage(
    alt_text='Buttons template',
    template=ButtonsTemplate(thumbnail_image_url='https://ppt.cc/[email protected]',
                             title='請問需要什麼服務?',
                             text='如需更多功能請按其他鍵或輸入"其他"',
                             actions=[
                                 MessageTemplateAction(label='今日運勢',
                                                       text='今日運勢'),
                                 MessageTemplateAction(label='火車訂票',
                                                       text='火車訂票'),
                                 MessageTemplateAction(label='高鐵訂票',
                                                       text='高鐵訂票'),
                                 MessageTemplateAction(label='其他', text='其他')
                             ]))
canmessage1 = TemplateSendMessage(
Пример #26
0
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
#from linebot.models import MessageEvent, TextSendMessage
from linebot import LineBotApi, WebhookParser
from linebot.exceptions import InvalidSignatureError, LineBotApiError
from linebot.models import MessageEvent, TextMessage, TextSendMessage, PostbackEvent
from module import func
from urllib.parse import parse_qsl
from hotelapi.models import users

line_bot_api = LineBotApi(settings.LINE_CHANNEL_ACCESS_TOKEN)
parser = WebhookParser(settings.LINE_CHANNEL_SECRET)


@csrf_exempt
def callback(request):
    if request.method == 'POST':
        signature = request.META['HTTP_X_LINE_SIGNATURE']
        body = request.body.decode('utf-8')
        try:
            events = parser.parse(body, signature)

        except InvalidSignatureError:
            return HttpResponseForbidden()
        except LineBotApiError:
            return HttpResponseBadRequest()

        for event in events:
            user_id = event.source.user_id
            if not (users.objects.filter(uid=user_id).exists()):
Пример #27
0
from linebot.utils import PY3

Channel_Secret = os.getenv('f22ad583bf1918e828c378a0902903fd', None)
Channel_access_token = os.getenv(
    'd51pvCfNquzJxSXnH3c0tKfCfESz+O+bzpODt93BxuZj+kwPyksU6O/jBgRgUWChc8K92dX26r9qdAEUCsYAIb8G3ZX09pB29t26bSqWTile8foNwGzUwi43U1Ae/PL50D0fRtxpK8fPrqIK/mKwsRsgwYf1m9tXTHnc/ZQT38Y=',
    None)
if Channel_Secret is None:
    print('Specify LINE_Channel_Secret as environment variable')
    sys.exit(1)
if Channel_access_token is None:
    print('Specify LINE_Channel_access_token as environment variable')
    sys.exit(1)

line_bot_api = LineBotApi(Channel_access_token)
parser = WebhookParser(Channel_Secret)


def application(environ, start_response):
    if environ['PATH_INFO'] != '/callback':
        start_response('404 NOT Found', [])
        return create_body('Not Found')
    if environ['REQUEST_METHOD'] != 'POST':
        start_response('405 Method Not Allowed', [])
        return create_body('Method Not Allowed')
    signature = environ['HTTP_X_LINE_SIGNATURE']

    wsgi_input = environ['wsgi.input']
    content_length = int(environ['CONTENT_LENGTH'])
    body = wsgi_input.read(content_length).decode('utf-8')
Пример #28
0
 def initialize(cls, **kwargs):
     cls.line_bot_api = LineBotApi(channel_access_token)
     cls.parser = WebhookParser(channel_secret)
     print("linebot conn initialize")
Пример #29
0
import requests

from .bots import LineBot, MessengerBot

logger = logging.getLogger('okbot_chat_view')
logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
chformatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s',
                                datefmt='[%d/%b/%Y %H:%M:%S]')
ch.setLevel(logging.INFO)
ch.setFormatter(chformatter)
logger.addHandler(ch)

line_bot_api = LineBotApi(os.environ['LINE_CHANNEL_ACCESS_TOKEN'])
line_webhook_parser = WebhookParser(os.environ['LINE_CHANNEL_SECRET'])

OKBOT_PAGE_ACCESS_KEY = os.environ['OKBOT_PAGE_ACCESS_KEY']
OKBOT_VERIFY_TOKEN = os.environ['OKBOT_VERIFY_TOKEN']

SLACK_WEBHOOK = os.environ['SLACK_WEBHOOK']

# Create your views here.

GRAPH_API_URL = 'https://graph.facebook.com/v2.6/me/messages'


def home(request):
    response = TemplateResponse(request, 'privacypolicy.html', {})
    return response
Пример #30
0
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt

from linebot import LineBotApi, WebhookParser
from linebot.exceptions import InvalidSignatureError, LineBotApiError
from linebot.models import MessageEvent, TextMessage, TextSendMessage

from LuisChatbot import Chatbot  # 引入處理 Echo 與天氣詢問的機器人

chatbot = Chatbot()
line_bot_api = LineBotApi(settings.LINE_CHANNEL_ACCESS_TOKEN)
parser = WebhookParser(settings.LINE_CHANNEL_SECRET)  # 用於處理 Line 傳過來的訊息


# 用於防範 CSRF
@csrf_exempt
def callback(request):
    if request.method == 'POST':

        # 取得憑證,用於解析時確認訊息是真的來自 Line-Server
        signature = request.META['HTTP_X_LINE_SIGNATURE']
        body = request.body.decode('utf-8')
        # 解析事件類型
        try:
            events = parser.parse(body, signature)
        except InvalidSignatureError:  # 訊息並非來自 Line Server
            return HttpResponseForbidden()
        except LineBotApiError:  # Line Server 出現狀況
            return HttpResponseBadRequest()
        for event in events: