コード例 #1
0
    def setUp(self):
        self.handler = WebhookHandler('channel_secret')
        self.calls = []

        @self.handler.add(MessageEvent, message=TextMessage)
        def message_text(event):
            self.calls.append('1 ' + event.type + '_' + event.message.type)

        @self.handler.add(
            MessageEvent, message=(ImageMessage, VideoMessage, AudioMessage))
        def message_content(event):
            self.calls.append('2 ' + event.type + '_' + event.message.type)

        @self.handler.add(MessageEvent, message=StickerMessage)
        def message_sticker(event):
            self.calls.append('3 ' + event.type + '_' + event.message.type)

        @self.handler.add(MessageEvent)
        def message(event):
            self.calls.append(event.type + '_' + event.message.type)

        @self.handler.add(FollowEvent)
        def follow(event):
            self.calls.append('4 ' + event.type)

        @self.handler.add(JoinEvent)
        def join(event):
            self.calls.append('5 ' + event.type)

        @self.handler.add(PostbackEvent)
        def postback(event):
            self.calls.append('6 ' + event.type)

        @self.handler.add(BeaconEvent)
        def beacon(event):
            self.calls.append('7 ' + event.type)

        @self.handler.default()
        def default(event):
            self.calls.append('default ' + event.type)
コード例 #2
0
class TestWebhookHandler(unittest.TestCase):
    def setUp(self):
        self.handler = WebhookHandler('channel_secret')
        self.calls = []

        @self.handler.add(MessageEvent, message=TextMessage)
        def message_text(event):
            self.calls.append('1 ' + event.type + '_' + event.message.type)

        @self.handler.add(
            MessageEvent, message=(ImageMessage, VideoMessage, AudioMessage))
        def message_content(event):
            self.calls.append('2 ' + event.type + '_' + event.message.type)

        @self.handler.add(MessageEvent, message=StickerMessage)
        def message_sticker(event):
            self.calls.append('3 ' + event.type + '_' + event.message.type)

        @self.handler.add(MessageEvent)
        def message(event):
            self.calls.append(event.type + '_' + event.message.type)

        @self.handler.add(FollowEvent)
        def follow(event):
            self.calls.append('4 ' + event.type)

        @self.handler.add(JoinEvent)
        def join(event):
            self.calls.append('5 ' + event.type)

        @self.handler.add(PostbackEvent)
        def postback(event):
            self.calls.append('6 ' + event.type)

        @self.handler.add(BeaconEvent)
        def beacon(event):
            self.calls.append('7 ' + event.type)

        @self.handler.default()
        def default(event):
            self.calls.append('default ' + event.type)

    def test_handler(self):
        file_dir = os.path.dirname(__file__)
        webhook_sample_json_path = os.path.join(file_dir, 'text', 'webhook.json')
        with open(webhook_sample_json_path) as fp:
            body = fp.read()

        # mock
        self.handler.parser.signature_validator.validate = lambda a, b: True

        self.handler.handle(body, 'signature')

        self.assertEqual(self.calls[0], '1 message_text')
        self.assertEqual(self.calls[1], '2 message_image')
        self.assertEqual(self.calls[2], '2 message_video')
        self.assertEqual(self.calls[3], '2 message_audio')
        self.assertEqual(self.calls[4], 'message_location')
        self.assertEqual(self.calls[5], '3 message_sticker')
        self.assertEqual(self.calls[6], '4 follow')
        self.assertEqual(self.calls[7], 'default unfollow')
        self.assertEqual(self.calls[8], '5 join')
        self.assertEqual(self.calls[9], 'default leave')
        self.assertEqual(self.calls[10], '6 postback')
        self.assertEqual(self.calls[11], '7 beacon')
        self.assertEqual(self.calls[12], '7 beacon')
        self.assertEqual(self.calls[13], '1 message_text')
        self.assertEqual(self.calls[14], '1 message_text')
        self.assertEqual(self.calls[15], '6 postback')
        self.assertEqual(self.calls[16], '6 postback')
        self.assertEqual(self.calls[17], '6 postback')
コード例 #3
0
ファイル: app.py プロジェクト: gene1230/robot-1
from flask import Flask, request, abort

from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import (
    MessageEvent,
    TextMessage,
    TextSendMessage,
)

app = Flask(__name__)

line_bot_api = LineBotApi(
    'TQEVNDlgG9Y/zyfcDAMMPkr94JGJ9hvtdvhdyqMIe4eypAkojdi5aP57zksZUulad7Y8B8thdUMN+Typ5Y+MBiXSR4wetpEgcDRvH+JxBUDRvm1U7qKqRnIfbWPxrrrX0vR/iWcYnwjvpzM8mW9L+gdB04t89/1O/w1cDnyilFU='
)
handler = WebhookHandler('fc6d95d953b66402cb0af3ac3550c015')


@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)
コード例 #4
0
ファイル: app.py プロジェクト: Chung-Yun/Education-Platform
#    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)

app = Flask(__name__)

# get KEYS from your environment variable
channel_secret = config('LINE_CHANNEL_SECRET')
channel_access_token = config('LINE_CHANNEL_ACCESS_TOKEN')
line_bot_api = LineBotApi(channel_access_token, timeout = 30)
handler = WebhookHandler(channel_secret)


@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 InvalidSignatureError:
コード例 #5
0
from flask import Flask, request, abort

from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import (
    MessageEvent,
    TextMessage,
    TextSendMessage,
)

app = Flask(__name__)

line_bot_api = LineBotApi(
    'sA7NOs4hqtmLF/dcFXxo7XU75QDAJB7tH+7XizXyrEWssjeeECPT+uVj1ylcYtw4Az99heGKPrYiU9pTRkY2COLyl5b0UoXV7Bl+qS29R+CqmCAtjwkgL8RIwsKj40NbK+UVGewiHSVy3rpUYOCB8AdB04t89/1O/w1cDnyilFU='
)  #YOUR_CHANNEL_ACCESS_TOKEN
handler = WebhookHandler(
    'fb7f861ad12ec1cbdf8e9711b7c7c7c5')  #YOUR_CHANNEL_SECRET
count = 0
error_count = 0


@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:
コード例 #6
0
ファイル: app.py プロジェクト: fred0405/maggie-001
# -*- coding: utf-8 -*-
from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage, TemplateSendMessage, flex_message
from linebot.models import *
import random

    
app = Flask(__name__)


line_bot_api = LineBotApi('Jb3cS2e1C1ihbAM38Vv/CBl3fgPkIm22CesgJsrMjjrLXPKr102lOBVLXk7gSvOGT0nCcVRiIqVqdWt9kqwvg4ChHUliu23KzQNbH54dWW6XthIgNmQ16EIzXsbiTMSZSFzyqv4iv7EyP5TPVQTx4QdB04t89/1O/w1cDnyilFU=')
handler = WebhookHandler('58acda0f2c42346d072457c2e8fd39f3')

msg_type = ["早安", "午安", "晚安", "唸書", "吃飯", "睡不著"]
msg_data = {"早安":['https://www.dropbox.com/s/3twgnopog0i60gx/_6914312.m4a?dl=0', 'https://www.dropbox.com/s/do3fixcjp6qcaib/_6914313.m4a?dl=0', 'https://www.dropbox.com/s/0cqls86lgjec2od/_6914314.m4a?dl=0', 'https://www.dropbox.com/s/p7cbyfih9h6ukwt/_6914315.m4a?dl=0', 'https://www.dropbox.com/s/cry1isljb2d3j93/_6914316.m4a?dl=0', 'https://www.dropbox.com/s/0ob0cn930vz9kqb/_6914317.m4a?dl=0'], 
		"午安":['https://www.dropbox.com/s/3q7a8ge4yl775wh/_6914331.m4a?dl=0', 'https://www.dropbox.com/s/y0d2vk3dgul2ejd/_6914332.m4a?dl=0', 'https://www.dropbox.com/s/ux9sv8050ftx6w4/_6914333.m4a?dl=0', 'https://www.dropbox.com/s/r09k1z494zco42k/_6914334.m4a?dl=0', 'https://www.dropbox.com/s/cle23ix5qukesmn/_6914335.m4a?dl=0', 'https://www.dropbox.com/s/ouo4xj0vmaqvr4v/_6914336.m4a?dl=0'], 
		"晚安":['https://www.dropbox.com/s/m5db7oygjo35xj2/_6914338.m4a?dl=0', 'https://www.dropbox.com/s/k3mlfx7yxdjieb2/_6914339.m4a?dl=0', 'https://www.dropbox.com/s/0g2756kmz4kt8uh/_6914340.m4a?dl=0', 'https://www.dropbox.com/s/0lxj7g4rvnrz650/_6914341.m4a?dl=0', 'https://www.dropbox.com/s/aatu4ojsx27lx5k/_6914342.m4a?dl=0', 'https://www.dropbox.com/s/thjnnr7wo9tl1dv/_6914343.m4a?dl=0'], 
		"唸書":['https://www.dropbox.com/s/aoew8kpk5uw2eb3/_6914345.m4a?dl=0', 'https://www.dropbox.com/s/xh5hrkyd4m7c316/_6914346.m4a?dl=0', 'https://www.dropbox.com/s/v4msc1ffrwar1h5/_6914347.m4a?dl=0', 'https://www.dropbox.com/s/pn8bhzrjpdgrdaz/_6914348.m4a?dl=0', 'https://www.dropbox.com/s/wp8oe5jq89xr4at/_6914349.m4a?dl=0'], 
		"吃飯":['https://www.dropbox.com/s/jhicd9xui5mkfl3/_6914351.m4a?dl=0', 'https://www.dropbox.com/s/pnb1doyll9x0zwi/_6914352.m4a?dl=0', 'https://www.dropbox.com/s/r5wnedsvrbhwd02/_6914353.m4a?dl=0', 'https://www.dropbox.com/s/4wd8yfij3konh07/_6914354.m4a?dl=0', 'https://www.dropbox.com/s/dtnw9pgieldd4c9/_6914355.m4a?dl=0'], 
		"睡不著":['https://www.dropbox.com/s/rvaa7icw1jok9pm/_6914357.m4a?dl=0', 'https://www.dropbox.com/s/5kuq1ss5x2zfj3o/_6914358.m4a?dl=0', 'https://www.dropbox.com/s/ywy9njvan1ljuri/_6914359.m4a?dl=0', 'https://www.dropbox.com/s/77q0n61scmrug72/_6914360.m4a?dl=0', 'https://www.dropbox.com/s/lhwunhy4axzkwa5/_6914361.m4a?dl=0', 'https://www.dropbox.com/s/ucpf96f217xaox9/_6914362.m4a?dl=0']}


@app.route('/', methods = ['GET'])
def hello():
	return "Hello World!"

@app.route('/callback', methods = ['POST'])
def callback():
	signature = request.headers['X-Line-Signature']
コード例 #7
0
ファイル: app.py プロジェクト: changroly/ch7
from flask import Flask, request, abort
from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import *
import mongodb
import re

app = Flask(__name__)

# 必須放上自己的Channel Access Token
line_bot_api = LineBotApi(
    'YZHwUMJOodTEUSgqKxGhXEnH4Q7u7R/HvnlIfKECuX+P/+ZxAu4VxjLwj5CmiwKaAov0hH02FM1p9LTA1zxjUqVtFoQ7LCco0kAayVwDOlHGIMcUA6ERKaQK1FzGDlOnDUtx0zDv7BkqqNHoXjSqGAdB04t89/1O/w1cDnyilFU='
)
# 必須放上自己的Channel Secret
handler = WebhookHandler('83db3b0c577edee00b11bfebd0ab125e')

line_bot_api.push_message('U5510bf50c625658f2987a2f52e68defa',
                          TextSendMessage(text='你可以開始了'))


# 監聽所有來自 /callback 的 Post Request
@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)
    line_bot_api.push_message('U5510bf50c625658f2987a2f52e68defa',
コード例 #8
0
ファイル: app.py プロジェクト: yoshi-kin/pachinko_calculate
    BubbleContainer, ImageComponent, BoxComponent, TextComponent,
    SpacerComponent, IconComponent, ButtonComponent, SeparatorComponent)
from argparse import ArgumentParser
import os, sys, logging, re
import config
from machines import kamen, singaro
from module import is_int, is_float, regular_int, regular_float
from model import User

app = Flask(__name__)

# app.logger.addHandler(logging.StreamHandler(sys.stdout))
# app.logger.setLevel(logging.INFO)

line_bot_api = LineBotApi(config.CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(config.CHANNEL_SECRET)

users = {}


@app.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    return 'OK'
コード例 #9
0
from linebot.models import *

logger = logging.getLogger("django")
"""
line_bot_api = LineBotApi(settings.CHANNEL_ACCESS_TOKEN)
parser  = WebhookParser(settings.LINE_CHANNEL_SECRET)

"""
app = Flask(__name__)

# 必須放上自己的Channel Access Token
line_bot_api = LineBotApi(
    '528gEzSdPX8Pw9mTJlfpXRpTBdETmaT0LJuHs8+3/qBsiz1lWzBRIfWXQexgOdiPyGxeLtL9HAggCjAp0LBJcqKAdv7h8Ux5JQpKMioyobyYoBQpwer/eA3cA1e89/b80sl219M34lvpXlAAFud++wdB04t89/1O/w1cDnyilFU='
)
# 必須放上自己的Channel Secret
handler = WebhookHandler('43664ae683e1af5eb58087c85b74216d')

line_bot_api.push_message('Ub8e3cf75739079f25a50f82b2cbd4c63',
                          TextSendMessage(text='你可以開始了'))


@csrf_exempt
@require_POST
def callback(request):
    signature = request.META['HTTP_X_Line_Signature']
    body = request.body.decode('utf-8')

    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        messages = (
コード例 #10
0
ファイル: event.py プロジェクト: yoyok173/linebot_test
from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)

from linebot.models import (
    MessageEvent,
    TextMessage,
    TextSendMessage,
)

# Channel Access Token
line_bot_api = LineBotApi(
    '+wjG+A6ltvlFVrmQmxyBaXcfljMtYaCTMXnVBoTxhWwMcSRX9+1mMObUO6oVongrp2y7parq1a1/bbbwvOhn/iO26lASkwoWX1u0HBisf7ZRr4cfMzcXFYM/8eFwpeQkdcXYz2obPYl1sE6+kWyC4QdB04t89/1O/w1cDnyilFU='
)
# Channel Secret
handler = WebhookHandler('4c154ea12f7a284b5edd99087d760143')

score_sheet_ID = '1F0aMMBcADRSXm07IT2Bxb_h22cIjNXlsCfBYRk53PHA'
my_database_sheet_ID = '1RaGPlEJKQeg_xnUGi1mlUt95-Gc6n-XF_czwudIP5Qk'
april_ID = 'Udf8f28a8b752786fa7a6be7d8c808ec6'
auth_json_path = "./auth.json"


def auth_gss_client(path, scopes):
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        path, scopes)
    return gspread.authorize(credentials)


gss_scopes = ['https://spreadsheets.google.com/feeds']
gss_client = auth_gss_client(auth_json_path, gss_scopes)
コード例 #11
0
from weather import *

from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import (
    MessageEvent,
    TextMessage,
    TextSendMessage,
)

app = Flask(__name__)

line_bot_api = LineBotApi(
    'wOq1fV72a9qiUfck9YKsb/3OvZVDNusDvTu3iTYNqT1eZxxa17LG24yMFzT+vQKV0NUkk2rhpTZa3RA2F58V4fhLkt9qYWq/DEy+xs3Z/66M0prHZGutN2ObaZJkQGpqog6ut/lblNlwzZPivTYbFgdB04t89/1O/w1cDnyilFU='
)
handler = WebhookHandler('48a925c4588ef8ebdcb55a215b9fa0d7')


@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 = json.loads(request.get_data(as_text=True))
    #raise Exception(body)
    #app.logger.info("Request body: " + body)

    if not ("召喚!" in body['events'][0]['message']['text']):
        r = requests.get(
            'https://chatbot-api.userlocal.jp/api/chat?message=' +
コード例 #12
0
            message = '\n'.join(self.search_database(channel_id, 0, text[12:]))
        else:
            message = 'そのコマンドは存在しません'
        return message


app = Flask(__name__)

# 環境変数取得
LINE_CHANNEL_ACCESS_TOKEN = os.environ["LINE_CHANNEL_ACCESS_TOKEN"]
LINE_CHANNEL_SECRET = os.environ["LINE_CHANNEL_SECRET"]
slack_token = os.environ["SLACK_CHANNEL_ACCESS_TOKEN"]

# Line Botのインスタンスを生成しWebhookの設定を行う
line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(LINE_CHANNEL_SECRET)

# CLASのインスタンスを生成
clas = CLAS(slack_token)


# Lineのコールバックメソッド
@app.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
コード例 #13
0
from django.conf import settings
from linebot import LineBotApi, WebhookHandler

line_bot_api = LineBotApi(settings.LINE_BOT_ACCESS_TOKEN)
handler = WebhookHandler(settings.LINE_BOT_ACCESS_SECRET)

demo_image_url = 'https://pbs.twimg.com/profile_images/912149878431563776/JbLZR5nP_400x400.jpg'
connect_image_url = 'https://cdn-ak.f.st-hatena.com/images/fotolife/n/nanashinodonbee/20180620/20180620004737.png'
コード例 #14
0
from __future__ import unicode_literals
import os
import requests
import json
from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage

app = Flask(__name__)

# LINE 聊天機器人的基本資料
line_bot_api = LineBotApi(
    'NuU/O3Gakontmd+VP+lWJIXtcRTV/AWoi8VQ2Lo8YXFUzROmJkv3NnxoAl6Gb4nsU50Vy2aHUGbKBiaoORR6ypbEURivY/cxr4uUqEmSDW64zEUOgdQp7grvDHAlcipdQnCCYYUeGv+cGpom3qnApgdB04t89/1O/w1cDnyilFU='
)
handler = WebhookHandler('353503ef0dcd61cf1f2988ac7f371f8b')


# 接收 LINE 的資訊
@app.route('/callback', methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']

    body = request.get_data(as_text=True)

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

    except InvalidSignatureError:
        abort(400)
コード例 #15
0
# -*- coding: UTF-8 -*-

#Python module requirement: line-bot-sdk, flask
from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
import threading
import time

# LineBot

line_bot_api = LineBotApi(
    'u9XQ2KL9EBO2OLK/M5gSA99diX39xfUruuSvXM+FcClBNKxFZv9RaIG4GJT974IaVm1N9rDWpGLrRpd5mdiCVuRejzUsH3DwQaaw5avl3MZ7ukbvdIYgtaA7+NQlP8naiBfSsoXoHp7P02xGHEHFewdB04t89/1O/w1cDnyilFU='
)  #LineBot's Channel access token
handler = WebhookHandler(
    '0674da225d51246d3a057838b59813d3')  #LineBot's Channel secret
user_id_set = set()  #LineBot's Friend's user id
app = Flask(__name__)


def loadUserId():
    try:
        idFile = open('idfile', 'r')
        idList = idFile.readlines()
        idFile.close()
        idList = idList[0].split(';')
        idList.pop()
        return idList
    except Exception as e:
        print(e)
        return None
コード例 #16
0
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt


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

line_bot_api = LineBotApi('Tt/6pVp5+vesr8rBsjerS/jKvK6b0Ub0thNxIjakCH03OhFXwe2h5aTRf/ZPbWFgLvqTZGvZAkavMaGee+yqxIb3B+LxEnK7bNsJ+aNv6CnAF8Ohj76R98VDmdXm8PcqhGb1UcD4O0djVSkRsHY0qQdB04t89/1O/w1cDnyilFU=')
handler = WebhookHandler('5d0535d7643a12130edd5db54a65d226')

@csrf_exempt
def echo(request):

    if request.method == 'POST':
        signature = request.META['HTTP_X_LINE_SIGNATURE']
        body = request.body.decode('utf-8')

        try:
            events = handler.handle(body, signature)
        except InvalidSignatureError:
            return HttpResponseForbidden()
        except LineBotApiError:
            return HttpResponseBadRequest()

        for event in events:
            if isinstance(event, MessageEvent):
                line_bot_api.reply_message(
                    event.reply_token,
                   TextSendMessage(text=event.message.text)
コード例 #17
0
    PostbackAction, DatetimePickerAction,
    CarouselTemplate, CarouselColumn, PostbackEvent,
    StickerMessage, StickerSendMessage, LocationMessage, LocationSendMessage,
    ImageMessage, VideoMessage, AudioMessage, FileMessage,
    UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent, BeaconEvent,
    FlexSendMessage, BubbleContainer, ImageComponent, BoxComponent,
    TextComponent, SpacerComponent, IconComponent, ButtonComponent,
    SeparatorComponent,
)

app = Flask(__name__)

# Channel Access Token
line_bot_api = LineBotApi('yWd/qztLmGITsgYno4GCHIKUqWx2E+zcCv9Lt6JJb6rEupJjAFOZilzTomieXvYLGeAfYbHtuZ7WY+2wm6fKWYe8HMHzcIhqXd+DyT8zI6Fy8w68HGWtnI2Urb5bdyuklQUDAzUW7Fg8PipfU2rmagdB04t89/1O/w1cDnyilFU=')
# Channel Secret
handler = WebhookHandler('e380402fa7f0185604728343907205d2')
#===========[ NOTE SAVER ]=======================
notes = {}

#REQUEST NAMA SURAT

def carisurat(nomorsurat):
    URLsurat = "https://api.banghasan.com/quran/format/json/surat"+str(nomorsurat)+"/pre"
    r = requests.get(URLsurat)
    data = r.json()
    err = "data tidak ditemukan"

    status = data['status']
    if(status == "ok"):
        nomor_surat = data['hasil'][0]['nomor']
        nama_surat = data['hasil'][0]['nama']
コード例 #18
0
from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)

app = Flask(__name__)

line_bot_api = LineBotApi('a9wq8oYltxx4+s2ebaSHKL48pDGnJcbyGuq3ZuLqy+EJzFvm4WhYNSqEStL20bVsKuDIC9QwKo/WdVedCxu9hKVQS8bIMcmrJwqbtohTgc+vsfk2fou6diEtnOrjiWwCR7i28g91afwCqHt579+YdQdB04t89/1O/w1cDnyilFU=')
handler = WebhookHandler('41ffe2b4e5016d11dabd5694a9d9c771')

@app.route('/')
def test():
    return "ok!!"

@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
コード例 #19
0
from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
import pya3rt
#from flask_ngrok import run_with_ngrok

app = Flask(__name__)
#run_with_ngrok(app)

linebot_api = LineBotApi('uxn6DE0iHNkb4GtWlOTSclWXY+2pjzOp9DjvaV0pW5px6hTQDxQQAIRKj6ebIX3bjx62vW2ZD9Icy/PhHYPcFSSMDEEGePmJaDdimrnHi1p8hBCttEhZlF5KBDBXBXaXLKR+QhMFq6QVXpMNZf5n+QdB04t89/1O/w1cDnyilFU=')
handler = WebhookHandler('a0053246627ae928a2f35b5806a07fc3')

# @app.route('/')
# def hello_world():
#     return "Hello World!" 


@app.route('/callback', methods=['POST'])
def callback():
    # リクエストがLINE Platformから送られてきたかを確認
    signature = request.headers["X-Line-Signature"]
    body = request.get_data(as_text=True)

    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    
    return 'OK'
コード例 #20
0
# line_auth_init.py
# encoding=UTF-8
import os
import sys
from linebot import (LineBotApi, WebhookHandler)

CHANNEL_ACCESS_TOKEN = os.getenv(
    '3/cEBpOR0mjAMUtnHKrSrx3N6FnMVNPYfXBIwMO6HNGaljxuxTxZz2fGrmZYFwqfV3dvAWMa7FEGrmOONfbZ7or1wxYgpjbtFMS0Mkk+RftjvYSrUpThxAHGiivf2M662z2zM5P8BSKby0dJiBG3GQdB04t89/1O/w1cDnyilFU=',
    None)
CHANNEL_SECRET = os.getenv(' a6b4b1a80d9f25eb0a719fc92cef7d86 ', None)

if CHANNEL_ACCESS_TOKEN is None:
    print(
        '(Error) Need to specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.'
    )
    sys.exit(1)
if CHANNEL_SECRET is None:
    print('(Error) Need Specify LINE_CHANNEL_SECRET as environment variable.')
    sys.exit(1)

line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(CHANNEL_SECRET)
コード例 #21
0
from chat_module.image_process import image_process

DB = Database(os.environ.get('DATABASE_URL'), db_type='postgres')
app = Flask(__name__, static_url_path='')
app.config['JSON_AS_ASCII'] = False
data = Data()
line_bot_api = None

account = {}  # 帳號設定問問題用的
account_q = 0  # 記住帳號設定的題數

if os.environ.get("FLASK_ENV") == "development":
    line_bot_api = LineBotApi(os.environ.get("TOKEN"), "http://*****:*****@app.route('/report/<path:name>')
def reportroute(name):
    name = 'index.html' if name is "" else name
    path = os.path.join("report", name)
    with open(path, encoding="utf-8") as f:
        content = f.read()
    return content


def send_js(name):
    return send_from_directory('js', name)

コード例 #22
0
ファイル: lineBot.py プロジェクト: 1am9trash/IOT
import urllib
import json
import socket
import configparser

app = Flask(__name__)

# basic information for line bot
# in short, we store the data in config.ini, and read from it
# it's a better way that we can control the data when the scale is large
config = configparser.ConfigParser()
config.read('config.ini')
# create an objest, we use function "reply_message()"
# "reply_message()" can only reply exactly once receiving each message, it can tell by reply_token
line_bot_api = LineBotApi(config.get('line-bot', 'channel_access_token'))
handler = WebhookHandler(config.get('line-bot', 'channel_secret'))

# MCS id and key
deviceId = "noHacking"
deviceKey = "noHacking"


class FSM():
    choose = 0
    enterDate = 1
    enterTime = 2


# get data from cloud, add history parameter to get historitic record
def getToMCS(channel, deviceId, deviceKey, history):
    host = "http://api.mediatek.com"
コード例 #23
0
from flask import Flask, request, abort
from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import (
    MessageEvent,
    TextMessage,
    TextSendMessage,
)

api = Flask(__name__)

#Channel access token
line_bot_api = LineBotApi('')
#Channel secret
handler = WebhookHandler('')


@api.route("/")
def hello():
    return "Hello World!"


@api.route("/webhook", methods=['POST'])
def webhook():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    api.logger.info("Request body: " + body)
コード例 #24
0
ファイル: test.py プロジェクト: machopman/pro
                            CarouselTemplate, CarouselColumn,
                            MessageTemplateAction, URITemplateAction)
import re
from flask.ext.pymongo import PyMongo

from review import movie_review
from spoil import movie_spoil
from type import movie_type
from datetime import datetime

app = Flask(__name__)

line_bot_api = LineBotApi(
    'iYDoDLW1k4yIYJvMnHVi18Vhl0NXPh5ec6a4FLdlR/en3nqmGCWsF/QeYKX8MPj2DYUFbjsEos/+HGUA7LgF4OimIUh1WD9j/phhG/vqX9zZD92iiw/t+kpE1AadWCIdwkzMuxEvAbCM84LtdTkQSgdB04t89/1O/w1cDnyilFU='
)
handler = WebhookHandler('935cecc6bf121cf08c1cea288956462b')
app.config['MONGO_DBNAME'] = 'moviebot'
app.config[
    'MONGO_URI'] = 'mongodb://*****:*****@ds139942.mlab.com:39942/moviebot'
mongo = PyMongo(app)

reverse_dictionary = json.load(open("reverse_dictionaryCNNnew.txt"))
final_embeddings = np.loadtxt('final_embeddingsCNNnew.txt')
dictionary = {v: int(k) for k, v in reverse_dictionary.items()}


@app.route("/")
def hello():
    return "Hello World!"

コード例 #25
0
ファイル: app.py プロジェクト: oange6214/Tibame_Projects
import pytz

try:
    from theDays import crawler  # heroku
except:
    import crawler

# 載入 line secret key
secretFileContentJson = json.load(open("./line_secret_key", "r", encoding="utf8"))

# 設定 Server 啟用細節
app = Flask(__name__, static_url_path="/images", static_folder="./images/")

# 生成實體物件
line_bot_api = LineBotApi(secretFileContentJson.get("LINE_CHANNEL_ACCESS_TOKEN"))
handler = WebhookHandler(secretFileContentJson.get("LINE_CHANNEL_SECRET"))

total_function = {
    '翻譯': False,
    '天氣': False,
    '樂透': False,
    '發票': False,
    '油價': False,
    '介紹': False
}

# 翻譯用 快速按鈕
en_postback = QuickReplyButton(action=PostbackAction(label="英文", data="langs=en"))
fr_postback = QuickReplyButton(action=PostbackAction(label="法文", data="langs=fr"))
ja_postback = QuickReplyButton(action=PostbackAction(label="日文", data="langs=ja"))
ko_postback = QuickReplyButton(action=PostbackAction(label="韓文", data="langs=ko"))
コード例 #26
0
     LineBotApi, WebhookHandler
 )
 from linebot.exceptions import (
     InvalidSignatureError
 )
 from linebot.models import *
 
 app = Flask(__name__)
 
 ACCESS_TOKEN= os.environ['ACCESS_TOKEN']
 SECRET= os.environ['CHANNEL_SECRET']
 
 # Channel Access Token
 line_bot_api = LineBotApi(ACCESS_TOKEN)
 # Channel Secret
 handler = WebhookHandler(SECRET)
 
 
 @app.route("/")
 def hello_world():
     return "hello world!"
 
 
 # 監聽所有來自 /callback 的 Post Request
 @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)
コード例 #27
0
ファイル: app.py プロジェクト: ConceptionC/Juilliard-Musical
import os
import json

from flask import Flask, request, abort

from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import (MessageEvent, FollowEvent, TextMessage,
                            TextSendMessage, FlexSendMessage,
                            CarouselContainer, BubbleContainer)

app = Flask(__name__)

line_bot_api = LineBotApi(os.environ['CHANNEL_ACCESS_TOKEN'])
handler = WebhookHandler(os.environ['CHANNEL_SECRET'])


@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 InvalidSignatureError:
        print(
コード例 #28
0
rich_menu_id_generator = cfg['line_server']['rich_menu_id_generator'].replace(
    '"', '')
rich_menu_id_style = cfg['line_server']['rich_menu_id_style'].replace('"', '')
mid_total_num = int(cfg['model_server']['mid_total_num'].replace('"', ''))
music_length_second = int(cfg['model_server']['music_length_second'].replace(
    '"', ''))

# 設定Server啟用細節
# static_url_path,static_folder --> 共享目錄
app = Flask(__name__,
            static_url_path="/output_music_to_linebot",
            static_folder="/output_music_to_linebot/")

# 生成實體物件
line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(secret_key)


# 啟動server對外接口,使Line能丟消息進來
@app.route("/", 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)
コード例 #29
0
ファイル: line_main.py プロジェクト: kons16/ScrapingPlayer
from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import (
    MessageEvent,
    TextMessage,
    TextSendMessage,
)

lineapp = Flask(__name__)

# 環境変数取得
YOUR_CHANNEL_ACCESS_TOKEN = os.environ['YOUR_CHANNEL_ACCESS_TOKEN']
YOUR_CHANNEL_SECRET = os.environ['YOUR_CHANNEL_SECRET']

line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(YOUR_CHANNEL_SECRET)


@lineapp.route("/")
def hello_world():
    return "hello world!"


@lineapp.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']
    body = request.get_data(as_text=True)
    lineapp.logger.info("Request body: " + body)

    try:
        handler.handle(body, signature)
コード例 #30
0
from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,StickerSendMessage
)

app = Flask(__name__)

line_bot_api = LineBotApi('UuFC5fbqdgL67j393u+fCS9p1E+D7r4k/YXJre//MSE2DHdSUX2XEXPylVVyHQ92H5OKsaXoKO548DrfAluosEhV7afy1IrAD9aLovhPeWnGsiN8PoHjfkbNf/U6CgAGJ3BC/ZtBcGSpRRFUQu4h6gdB04t89/1O/w1cDnyilFU=')
handler = WebhookHandler('2e4fc1cc109dbfb49cd9518122597af8')


@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 InvalidSignatureError:
コード例 #31
0
ファイル: line.py プロジェクト: crazyrabbitpei/mywatcher
import os
import sys
import logging
from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError, LineBotApiError)
from linebot.models import (MessageEvent, FollowEvent, UnfollowEvent,
                            TextSendMessage, TemplateSendMessage,
                            ButtonsTemplate, ConfirmTemplate, CarouselTemplate,
                            MessageAction)

line_bot_api = LineBotApi(os.getenv('CHANNEL_ACCESS_TOKEN'))
handler = WebhookHandler(os.getenv('CHANNEL_SECRET'))


def push_message(*, user_id, message=None):
    '''
    return (ok_or_not:boolean, user_id, status_code, message)
    '''
    try:
        line_bot_api.push_message(user_id, TextSendMessage(text=f'{message}'))
    except LineBotApiError as e:
        return (False, user_id, e.status_code, e.message)

    return (True, user_id, 200, 'ok')
コード例 #32
0
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage, ImageSendMessage, SourceUser,
    TemplateSendMessage, ButtonsTemplate, PostbackEvent,
    PostbackTemplateAction, MessageTemplateAction, MessageImagemapAction,
    URITemplateAction, DatetimePickerTemplateAction, ConfirmTemplate,
    CarouselTemplate, CarouselColumn, ImageCarouselTemplate,
    ImageCarouselColumn, VideoSendMessage, BaseSize)

app = Flask(__name__)

# Channel Access Token
line_bot_api = LineBotApi(
    '3Qkr3SNlqPpzhZ0FYrPZupD/TcYAxK0+Kdh7J0u3JzH2qQkzZVGVjivLQ32olTcPIWOPg/jSaRvyekXU3gsLRs5BLHgCZEw1sHcTZoEy8yMOnTuXGvqh+27/RHYrQHVjTibPpU/YsK+qDXR+mrgEEQdB04t89/1O/w1cDnyilFU='
)
# Channel Secret
handler = WebhookHandler('2aeccaa784bd1a4d7f86f6516d91851a')


# 監聽所有來自 /callback 的 Post Request
@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)