class TestLineBotApi(unittest.TestCase): def setUp(self): self.tested = LineBotApi('channel_secret') @responses.activate def test_leave_group(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/gid/leave', json={}, status=200 ) self.tested.leave_group('gid') request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/gid/leave') @responses.activate def test_leave_room(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/rid/leave', json={}, status=200 ) self.tested.leave_room('rid') request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/rid/leave')
class TestLineBotApi(unittest.TestCase): def setUp(self): self.tested = LineBotApi('channel_secret') @responses.activate def test_get_group_member_profile(self): responses.add( responses.GET, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/group_id/member/user_id', json={ "displayName": "LINE taro", "userId": "Uxxxxxxxxxxxxxx...", "pictureUrl": "http://obs.line-apps.com/..." }, status=200 ) profile = self.tested.get_group_member_profile('group_id', 'user_id') request = responses.calls[0].request self.assertEqual(request.method, 'GET') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/group_id/member/user_id') self.assertEqual(profile.display_name, 'LINE taro') self.assertEqual(profile.user_id, 'Uxxxxxxxxxxxxxx...') self.assertEqual(profile.picture_url, 'http://obs.line-apps.com/...') @responses.activate def test_get_room_member_profile(self): responses.add( responses.GET, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/room_id/member/user_id', json={ "displayName": "LINE taro", "userId": "Uxxxxxxxxxxxxxx...", "pictureUrl": "http://obs.line-apps.com/..." }, status=200 ) profile = self.tested.get_room_member_profile('room_id', 'user_id') request = responses.calls[0].request self.assertEqual(request.method, 'GET') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/room_id/member/user_id') self.assertEqual(profile.display_name, 'LINE taro') self.assertEqual(profile.user_id, 'Uxxxxxxxxxxxxxx...') self.assertEqual(profile.picture_url, 'http://obs.line-apps.com/...')
def setUp(self): self.tested = LineBotApi('channel_secret') self.imagemap_message = ImagemapSendMessage( base_url='https://example.com/base', alt_text='this is an imagemap', base_size=BaseSize(height=1040, width=1040), actions=[ URIImagemapAction( link_uri='https://example.com/', area=ImagemapArea( x=0, y=0, width=520, height=1040 ) ), MessageImagemapAction( text='hello', area=ImagemapArea( x=520, y=0, width=520, height=1040 ) ) ] ) self.message = [{ "type": "imagemap", "baseUrl": "https://example.com/base", "altText": "this is an imagemap", "baseSize": { "height": 1040, "width": 1040 }, "actions": [ { "type": "uri", "linkUri": "https://example.com/", "area": { "x": 0, "y": 0, "width": 520, "height": 1040 } }, { "type": "message", "text": "hello", "area": { "x": 520, "y": 0, "width": 520, "height": 1040 } } ] }]
def setUp(self): self.tested = LineBotApi('channel_secret') self.sticker_message = StickerSendMessage( package_id='1', sticker_id='1' ) self.message = [{ "type": "sticker", "packageId": "1", "stickerId": "1" }]
def setUp(self): self.tested = LineBotApi('channel_secret') self.video_message = VideoSendMessage( original_content_url='https://example.com/original.mp4', preview_image_url='https://example.com/preview.jpg' ) self.message = [{ "type": "video", "originalContentUrl": "https://example.com/original.mp4", "previewImageUrl": "https://example.com/preview.jpg", }]
def setUp(self): self.tested = LineBotApi('channel_secret') self.location_message = LocationSendMessage( title='my location', address='Tokyo', latitude=35.65910807942215, longitude=139.70372892916203 ) self.message = [{ "type": "location", "title": "my location", "address": "Tokyo", "latitude": 35.65910807942215, "longitude": 139.70372892916203 }]
class TestSendTestMessage(unittest.TestCase): def setUp(self): self.tested = LineBotApi('channel_secret') # test data self.text_message = TextSendMessage(text='Hello, world') self.message = [{"type": "text", "text": "Hello, world"}] @responses.activate def test_push_text_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={}, status=200 ) self.tested.push_message('to', self.text_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') self.assertEqual( json.loads(request.body), { "to": "to", "messages": self.message } ) @responses.activate def test_reply_text_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', json={}, status=200 ) self.tested.reply_message('replyToken', self.text_message) request = responses.calls[0].request self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') self.assertEqual(request.method, 'POST') self.assertEqual( json.loads(request.body), { "replyToken": "replyToken", "messages": self.message } ) @responses.activate def test_multicast_text_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', json={}, status=200 ) self.tested.multicast(['to1', 'to2'], self.text_message) request = responses.calls[0].request self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') self.assertEqual(request.method, 'POST') self.assertEqual( json.loads(request.body), { "to": ['to1', 'to2'], "messages": self.message } )
import sqlite3 from linebot import LineBotApi from linebot.models import TextSendMessage from linebot.exceptions import LineBotApiError import time import datetime from datetime import datetime import re line_bot_api = LineBotApi('rnuFsrNrw2fh/leoqhtMFGjfivyr1woxUjxXZXNENa9mf6JDtIPHZIszHfUwlfMRMNW9c2klgeHdHN05mfaU1iFQf8q7NA8FAd8JQfsaU7w6ST5pTpG3Mylyj9LMOpw2DCxJCC8S81BPEroQ5TylgwdB04t89/1O/w1cDnyilFU=') #データベース接続 dbpath = "ScheduleInformation.sqlite" conn = sqlite3.connect(dbpath) #データベース抽出 cur = conn.cursor() cur.execute("SELECT user_Id,ScheduleDate,ScheduleContents FROM Schedule") Schedule_data = cur.fetchall() #データをリスト化 Schedule_list = Schedule_data[0] ScheduleDate = Schedule_list[1] Schedule_contents = Schedule_list[2] userId = Schedule_list[0] push_message = ScheduleDate + "の時間です。"
class TestLineBotApi(unittest.TestCase): def setUp(self): self.tested = LineBotApi('channel_secret') @responses.activate def test_error_handle(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={ "message": "Invalid reply token" }, status=401 ) try: self.tested.push_message('to', TextSendMessage(text='hoge')) except LineBotApiError as e: self.assertEqual(e.status_code, 401) self.assertEqual(e.error.message, 'Invalid reply token') @responses.activate def test_error_with_detail_handle(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={ "message": "The request body has 2 error(s)", "details": [ { "message": "May not be empty", "property": "messages[0].text" }, { "message": "Must be one of the following values: [text" ", image, video, audio, location, sticker, " "richmessage, template, imagemap]", "property": "messages[1].type" } ] }, status=400 ) try: self.tested.push_message( 'to', TextSendMessage(text='hoge') ) except LineBotApiError as e: self.assertEqual(e.status_code, 400) self.assertEqual(e.error.message, 'The request body has 2 error(s)') self.assertEqual(e.error.details[0].message, 'May not be empty') self.assertEqual(e.error.details[0].property, 'messages[0].text') self.assertEqual( e.error.details[1].message, "Must be one of the following " "values: [text" ", image, video, audio, " "location, sticker, " "richmessage, template, imagemap]" ) self.assertEqual(e.error.details[1].property, 'messages[1].type') @responses.activate def test_error_handle_get_message_content(self): responses.add( responses.GET, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/1/content', json={ "message": "Invalid reply token" }, status=404 ) try: self.tested.get_message_content(1) except LineBotApiError as e: self.assertEqual(e.status_code, 404) self.assertEqual(e.error.message, 'Invalid reply token')
TextSendMessage, ) app = Flask(__name__) # 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) 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)
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( 'M/D9KAvebBE3jRKjwXc+KfXnq60CbrCJyJ8/t7+21P5Jq6rdaXtK8SM9vW0GoF8DPkmpwkMmHUutPp3rCnvlwrIpNn4xwkgMp/LENoWKiTSrHKMTxEHtHzatR/ICbuWqpjzyFvOuBckVEhdtDgvDcgdB04t89/1O/w1cDnyilFU=' ) handler = WebhookHandler('c42b619dc627ff83d93df74fc4ee8761') @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( "Invalid signature. Please check your channel access token/channel secret." )
from flask import Flask, request, abort import json import requests from linebot import LineBotApi, WebhookHandler from linebot.exceptions import InvalidSignatureError from linebot.models import MessageEvent, TextMessage, TextSendMessage import os from os.path import join, dirname from dotenv import load_dotenv app = Flask(__name__) load_dotenv(join(dirname(__file__), ".env")) #環境変数の取得 token = os.environ.get("YOUR_CHANNEL_ACCESS_TOKEN") secret = os.environ.get("YOUR_CHANNEL_SECRET") line_bot_api = LineBotApi(token) handler = WebhookHandler(secret) # HTTPヘッダを設定 HEADERS = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token, } app = Flask(__name__) load_dotenv(join(dirname(__file__), ".env")) @app.route("/callback", methods=["POST"]) def callback(): signature = request.headers["X-Line-Signature"]
from linebot import (LineBotApi, WebhookHandler) from linebot.exceptions import (InvalidSignatureError) from linebot.models import * # package import re from datetime import datetime # customer module import mongodb import corwler app = Flask(__name__) line_bot_api = LineBotApi( 'x0yuYkAq8xjvnGiEo+Sr3IrcCf2ikmx+vxvZGnD8gd2UsLYGM53lVDZ4ABxGtFxOqS2aSOnUebbQHc3/EespnS6Tbvn1obs053Q8iCw0qdvqRrv7mEZUlw7K+HC04N1awz7De9Nos1onKfJeSQ5UaQdB04t89/1O/w1cDnyilFU=)' ) handler = WebhookHandler('ab34a27c6c3fe481a2cbfd31297b9f4f') @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
from flask import Flask, request, abort from linebot import (LineBotApi, WebhookHandler) from linebot.exceptions import (InvalidSignatureError) from linebot.models import * import QAresume as qa import json app = Flask(__name__) # Channel Access Token line_bot_api = LineBotApi('') # Channel Secret handler = WebhookHandler('') @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: abort(400) return 'OK'
FlexSendMessage, BubbleContainer, ImageComponent, BoxComponent, TextComponent, SpacerComponent, IconComponent, ButtonComponent, SeparatorComponent, ) app = Flask(__name__) # Channel Access Token line_bot_api = LineBotApi( 'p0XYHyv+vaz/gu4mU2yBjOKCY7s7H/g4kvtBHJ2Ln84/oDHXPQli/UkU3y0Yli+unc+fdZB80n/8d6Ud+U3BVTf6DY71tXkmwiecDHUCTjQT/hT7R8M878XrGzE2TSbX138NGViJlhOOrK4rZm7mawdB04t89/1O/w1cDnyilFU=' ) # Channel Secret handler = WebhookHandler('a635011dbf5f265661ea83c64d0faf52') #===========[ NOTE SAVER ]======================= notes = {} # Post Request @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)
from linebot import LineBotApi, WebhookHandler from linebot.exceptions import InvalidSignatureError from linebot.models import MessageEvent, TextMessage, TextSendMessage, ImageSendMessage from bs4 import BeautifulSoup from threading import Thread import os import random import requests import sqlite3 DATABASE = 'database.db' app = Flask(__name__) line_bot_api = LineBotApi(os.environ['CHANNEL_ACCESS_TOKEN']) handler = WebhookHandler(os.environ['CHANNEL_SECRET']) def initialize_database(): with app.app_context(): connection = get_database() cursor = connection.cursor() cursor.execute( 'CREATE TABLE IF NOT EXISTS links (id INTEGER PRIMARY KEY AUTOINCREMENT, link TEXT NOT NULL, number TEXT NOT NULL)' ) connection.commit() connection.close() def get_database():
FlexSendMessage, BubbleContainer, ImageComponent, BoxComponent, TextComponent, SpacerComponent, IconComponent, ButtonComponent, SeparatorComponent, ) app = Flask(__name__) # Channel Access Token line_bot_api = LineBotApi( 'XvOs71zwF0kEM/IzrJOchDvHUOjIIsCbjIn8RUtGlgW1Qu3EDPSvjoCP61bZhrbmrmjoeGd0wZvT3BQSfftYkUC+S4HMQWmp0rHO0DXb3+B5qwWHNl1nJBACNJGBP8U1OEDjGPHsXGQnhu1vye82gwdB04t89/1O/w1cDnyilFU=' ) # Channel Secret NINO LIFF BOT handler = WebhookHandler('2e49cc936658f2cde43181ec640c18d0') #===========[ NOTE SAVER ]======================= notes = {} tokenz = {} # Post Request @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:
from linebot.models import ( MessageEvent, TextMessage, TextSendMessage, ) # firebase cred = credentials.Certificate("./serviceAccountKey.json") firebase_admin.initialize_app( cred, {'databaseURL': 'https://treat-me-22bff.firebaseio.com/'}) # Flask app should start in global layout app = Flask(__name__) line_bot_api = LineBotApi( 'QiRriK22eidlQYKXbPseOKC9VEoRnR4/Jvo1GMxQMZXkzYoI+wtql1HchBjEdAcwSBrkj9RNBrixAyV9C0Rx1/6AXu/DqNwnVOaZ7b+ouBHvLZUM3NNntPFAz4V6O3gjyDElT/8FslyCkuRJVQd3wAdB04t89/1O/w1cDnyilFU=' ) handler = WebhookHandler('66102e73c1b74719168a8873e307430b') @app.route('/call', methods=['GET']) def call(): database = db.reference() user = database.child("user") #membaca apakah ada data pada firebase snapshot = user.order_by_key().get() #key = userId Line for key, val in snapshot.items(): try:
def __init__(self): secret, access_token = self.check_required_environmental_variables() self.commands = [PingCommand(), JinguReservationStateThisWeek()] self.line_bot_api = LineBotApi(access_token) self.parser = WebhookParser(secret)
class Bot(object): COMMAND_PREFIX = '@bot' def __init__(self): secret, access_token = self.check_required_environmental_variables() self.commands = [PingCommand(), JinguReservationStateThisWeek()] self.line_bot_api = LineBotApi(access_token) self.parser = WebhookParser(secret) def check_required_environmental_variables(self): channel_secret = os.getenv('LINEBOT_TENNIS_LINE_CHANNEL_SECRET', None) channel_access_token = os.getenv( 'LINEBOT_TENNIS_LINE_CHANNEL_ACCESS_TOKEN', None) if channel_secret is None: raise Exception( 'Specify LINEBOT_TENNIS_LINE_CHANNEL_SECRET as environment variable.' ) if channel_access_token is None: raise Exception( 'Specify LINEBOT_TENNIS_LINE_CHANNEL_ACCESS_TOKEN as environment variable.' ) return (channel_secret, channel_access_token) def handle_request(self, request): if request.method != 'POST': return Response('404', status=404) signature = request.headers.get('X_LINE_SIGNATURE') wsgi_input = request.headers.get('wsgi.input') content_length = int(request.headers.get('CONTENT_LENGTH')) #body = wsgi_input.read(content_length).decode('utf-8') body = request.stream.read().decode('utf-8') try: events = self.parser.parse(body, signature) except InvalidSignatureError: return Response('Bad request', status=400) for event in events: if self.is_event_for_connection_test(event): print('Ignore the message because it is connection test') elif event.type == 'message' and event.message.type == 'text': self.handle_message(event.message.text, event.reply_token) return Response('OK', status=200) def send_help_string(self, reply_token): help_string = 'Available commands:\n' + '\n'.join( [c.help() for c in self.commands]) self.line_bot_api.reply_message(reply_token, TextSendMessage(text=help_string)) def is_event_for_connection_test(self, event): return (event.type == 'message' and (event.message.id == '100001' or event.message.id == '100002')) def handle_message(self, message_text, reply_token): if message_text.startswith(self.COMMAND_PREFIX): message_body = message_text[len(self.COMMAND_PREFIX):].strip() for command in self.commands: if command.is_match(message_body): command.reply(message_body, reply_token, self.line_bot_api) return self.send_help_string(reply_token)
class TestLineBotApi(unittest.TestCase): maxDiff = None def setUp(self): self.tested = LineBotApi('channel_secret') self.button_template_message = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate( thumbnail_image_url='https://example.com/image.jpg', title='Menu', text='Please select', actions=[ PostbackTemplateAction( label='postback', text='postback text', data='action=buy&itemid=1' ), MessageTemplateAction( label='message', text='message text' ), URITemplateAction( label='uri', uri='http://example.com/' ) ] ) ) self.button_message = [{ "type": "template", "altText": "Buttons template", "template": { "type": "buttons", "thumbnailImageUrl": "https://example.com/image.jpg", "imageAspectRatio": None, "imageSize": None, "imageBackgroundColor": None, "title": "Menu", "text": "Please select", "actions": [ { "type": "postback", "label": "postback", "text": "postback text", "data": "action=buy&itemid=1" }, { "type": "message", "label": "message", "text": "message text" }, { "type": "uri", "label": "uri", "uri": "http://example.com/" } ] } }] self.confirm_template_message = TemplateSendMessage( alt_text='Confirm template', template=ConfirmTemplate( text='Are you sure?', actions=[ PostbackTemplateAction( label='postback', text='postback text', data='action=buy&itemid=1' ), MessageTemplateAction( label='message', text='message text' ) ] ) ) self.confirm_message = [{ "type": "template", "altText": "Confirm template", "template": { "type": "confirm", "text": "Are you sure?", "actions": [ { "type": "postback", "label": "postback", "text": "postback text", "data": "action=buy&itemid=1" }, { "type": "message", "label": "message", "text": "message text" } ] } }] self.carousel_template_message = TemplateSendMessage( alt_text='Carousel template', template=CarouselTemplate( columns=[ CarouselColumn( thumbnail_image_url='https://example.com' '/item1.jpg', title='this is menu1', text='description1', actions=[ PostbackTemplateAction( label='postback1', text='postback text1', data='action=buy&itemid=1' ), MessageTemplateAction( label='message1', text='message text1' ), URITemplateAction( label='uri1', uri='http://example.com/1' ) ] ), CarouselColumn( thumbnail_image_url='https://example.com' '/item2.jpg', image_background_color='#000000', title='this is menu2', text='description2', actions=[ PostbackTemplateAction( label='postback2', text='postback text2', data='action=buy&itemid=2' ), MessageTemplateAction( label='message2', text='message text2' ), URITemplateAction( label='uri2', uri='http://example.com/2' ) ] ), CarouselColumn( thumbnail_image_url='https://example.com' '/item3.jpg', title='this is menu3', text='description3', actions=[ DatetimePickerTemplateAction( label="datetime picker date", data="action=sell&itemid=2&mode=date", mode="date", initial="2013-04-01", min="2011-06-23", max="2017-09-08" ), DatetimePickerTemplateAction( label="datetime picker time", data="action=sell&itemid=2&mode=time", mode="time", initial="10:00", min="00:00", max="23:59" ), DatetimePickerTemplateAction( label="datetime picker datetime", data="action=sell&itemid=2&mode=datetime", mode="datetime", initial="2013-04-01T10:00", min="2011-06-23T00:00", max="2017-09-08T23:59" ) ] ) ] ) ) self.carousel_message = [{ "type": "template", "altText": "Carousel template", "template": { "type": "carousel", "columns": [ { "thumbnailImageUrl": "https://example.com/item1.jpg", "imageBackgroundColor": None, "title": "this is menu1", "text": "description1", "actions": [ { "type": "postback", "label": "postback1", "text": "postback text1", "data": "action=buy&itemid=1" }, { "type": "message", "label": "message1", "text": "message text1" }, { "type": "uri", "label": "uri1", "uri": "http://example.com/1" } ] }, { "thumbnailImageUrl": "https://example.com/item2.jpg", "imageBackgroundColor": "#000000", "title": "this is menu2", "text": "description2", "actions": [ { "type": "postback", "label": "postback2", "text": "postback text2", "data": "action=buy&itemid=2" }, { "type": "message", "label": "message2", "text": "message text2" }, { "type": "uri", "label": "uri2", "uri": "http://example.com/2" } ] }, { "thumbnailImageUrl": "https://example.com/item3.jpg", "imageBackgroundColor": None, "title": "this is menu3", "text": "description3", "actions": [ { "type": "datetimepicker", "label": "datetime picker date", "data": "action=sell&itemid=2&mode=date", "mode": "date", "initial": "2013-04-01", "min": "2011-06-23", "max": "2017-09-08" }, { "type": "datetimepicker", "label": "datetime picker time", "data": "action=sell&itemid=2&mode=time", "mode": "time", "initial": "10:00", "min": "00:00", "max": "23:59" }, { "type": "datetimepicker", "label": "datetime picker datetime", "data": "action=sell&itemid=2&mode=datetime", "mode": "datetime", "initial": "2013-04-01T10:00", "min": "2011-06-23T00:00", "max": "2017-09-08T23:59" } ] } ], "imageAspectRatio": None, "imageSize": None } }] self.image_carousel_template_message = TemplateSendMessage( alt_text='Image carousel template', template=ImageCarouselTemplate( columns=[ ImageCarouselColumn( image_url='https://example.com/' 'item1.jpg', action=PostbackTemplateAction( label='postback1', data='action=buy&itemid=1' ) ), ImageCarouselColumn( image_url='https://example.com' '/item2.jpg', action=MessageTemplateAction( label='message2', text='message text2' ) ), ImageCarouselColumn( image_url='https://example.com/' 'item3.jpg', action=URITemplateAction( label='uri1', uri='https://example.com/1' ) ) ] ) ) self.image_carousel_message = [{ "type": "template", "altText": "Image carousel template", "template": { "type": "image_carousel", "columns": [ { "imageUrl": "https://example.com/item1.jpg", "action": { "type": "postback", "label": "postback1", "data": "action=buy&itemid=1", "text": None } }, { "imageUrl": "https://example.com/item2.jpg", "action": { "type": "message", "label": "message2", "text": "message text2" } }, { "imageUrl": "https://example.com/item3.jpg", "action": { "type": "uri", "label": "uri1", "uri": "https://example.com/1" } } ] } }] @responses.activate def test_push_buttons_template_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={}, status=200 ) self.tested.push_message('to', self.button_template_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') self.assertEqual( json.loads(request.body), { "to": "to", "messages": self.button_message } ) @responses.activate def test_reply_buttons_template_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', json={}, status=200 ) self.tested.reply_message('replyToken', self.button_template_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') self.assertEqual( json.loads(request.body), { "replyToken": "replyToken", "messages": self.button_message } ) @responses.activate def test_push_confirm_template_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={}, status=200 ) self.tested.push_message('to', self.confirm_template_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') self.assertEqual( json.loads(request.body), { "to": "to", "messages": self.confirm_message } ) @responses.activate def test_reply_confirm_template_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', json={}, status=200 ) self.tested.reply_message('replyToken', self.confirm_template_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply' ) self.assertEqual( json.loads(request.body), { "replyToken": "replyToken", "messages": self.confirm_message } ) @responses.activate def test_push_carousel_template_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={}, status=200 ) self.tested.push_message('to', self.carousel_template_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') self.assertEqual( json.loads(request.body), { "to": "to", "messages": self.carousel_message } ) @responses.activate def test_reply_carousel_template_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', json={}, status=200 ) self.tested.reply_message('replyToken', self.carousel_template_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') self.assertEqual( json.loads(request.body), { "replyToken": "replyToken", "messages": self.carousel_message } ) @responses.activate def test_multicast_carousel_template_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', json={}, status=200 ) self.tested.multicast(['to1', 'to2'], self.carousel_template_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') self.assertEqual( json.loads(request.body), { "to": ['to1', 'to2'], "messages": self.carousel_message } ) @responses.activate def test_push_image_carousel_template_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={}, status=200 ) self.tested.push_message('to', self.image_carousel_template_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') self.assertEqual( json.loads(request.body), { "to": "to", "messages": self.image_carousel_message } ) @responses.activate def test_reply_image_carousel_template_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', json={}, status=200 ) self.tested.reply_message('replyToken', self.image_carousel_template_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') self.assertEqual( json.loads(request.body), { "replyToken": "replyToken", "messages": self.image_carousel_message } ) @responses.activate def test_multicast_image_carousel_template_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', json={}, status=200 ) self.tested.multicast(['to1', 'to2'], self.image_carousel_template_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') self.assertEqual( json.loads(request.body), { "to": ['to1', 'to2'], "messages": self.image_carousel_message } )
class TestLineBotApi(unittest.TestCase): def setUp(self): self.tested = LineBotApi('channel_secret') self.location_message = LocationSendMessage( title='my location', address='Tokyo', latitude=35.65910807942215, longitude=139.70372892916203 ) self.message = [{ "type": "location", "title": "my location", "address": "Tokyo", "latitude": 35.65910807942215, "longitude": 139.70372892916203 }] @responses.activate def test_push_location_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={}, status=200 ) self.tested.push_message('to', self.location_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') self.assertEqual( json.loads(request.body), { "to": "to", "messages": self.message } ) @responses.activate def test_reply_location_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', json={}, status=200 ) self.tested.reply_message('replyToken', self.location_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') self.assertEqual( json.loads(request.body), { "replyToken": "replyToken", "messages": self.message } ) @responses.activate def test_multicast_location_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', json={}, status=200 ) self.tested.multicast(['to1', 'to2'], self.location_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') self.assertEqual( json.loads(request.body), { "to": ['to1', 'to2'], "messages": self.message } )
import requests from datetime import datetime from flask import Flask, request, abort import json, time import pandas as pd from linebot import (LineBotApi, WebhookHandler) from linebot.exceptions import (InvalidSignatureError) from linebot.models import * app = Flask(__name__) # Channel Access Token line_bot_api = LineBotApi( 'k3iyUllSIUQ+ZNKGyI1juMXozfxdoOPamv2Qr0lYXWfPhujjDjQsUzezMDzjeVdseEh/orhbQ5yDxrwr9c1qdDRna8Y3JFvNxW0fPlSPh+oPFg6MOGuD4DfQpv6hZLxnTTxtPdw71cuywB1dH+rqeQdB04t89/1O/w1cDnyilFU=' ) # Channel Secret handler = WebhookHandler('c17402a86b83e6ef25c4f10c6ac46522') user_id = 'user_id' # 監聽所有來自 /callback 的 Post Request @app.route("/", methods=['POST']) def callback(): # get X-Line-Signature header value signature = request.headers['X-Line-Signature'] app.logger.info("signature : %s" % signature) # get request body as text body = request.get_data(as_text=True) app.logger.info("Mark body: %s" % body)
class TestLineBotApi(unittest.TestCase): def setUp(self): self.tested = LineBotApi('channel_secret') self.video_message = VideoSendMessage( original_content_url='https://example.com/original.mp4', preview_image_url='https://example.com/preview.jpg' ) self.message = [{ "type": "video", "originalContentUrl": "https://example.com/original.mp4", "previewImageUrl": "https://example.com/preview.jpg", }] @responses.activate def test_push_video_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={}, status=200 ) self.tested.push_message('to', self.video_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') self.assertEqual( json.loads(request.body), { "to": "to", "messages": self.message } ) @responses.activate def test_reply_video_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', json={}, status=200 ) self.tested.reply_message('replyToken', self.video_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') self.assertEqual( json.loads(request.body), { "replyToken": "replyToken", "messages": self.message } ) @responses.activate def test_multicast_video_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', json={}, status=200 ) self.tested.multicast(['to1', 'to2'], self.video_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') self.assertEqual( json.loads(request.body), { "to": ['to1', 'to2'], "messages": self.message } )
# API bp = Blueprint("motion_detection", __name__) # global variableに睡眠状態持たせておく。 # やりたいことは、友達・家族からLINEで寝ているか?確認する文言が発話されたら、 # 私が寝室でゴロゴロしているかどうかをraspberry Piで検知→その結果をbotに発話させることである。 # (もっといい方法があるはず。友達・家族からの発話を踏まえてrasberryPiで検知が走るようにしたい。) # とりあえずまず作ってみる。 # まずは、LINE botを作成してみる。https://qiita.com/kotamatsuoka/items/c4e651f1cb6c4490f4b8 is_sleep = False LINE_CHANNEL_ACCESS_TOKEN = os.environ["LINE_CHANNEL_ACCESS_TOKEN"] LINE_CHANNEL_SECRET = os.environ["LINE_CHANNEL_SECRET"] line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN) handler = WebhookHandler(LINE_CHANNEL_SECRET) @bp.route("/callback", methods=['POST']) def callback(): signature = request.headers['X-Line-Signature'] logger = current_app.logger body = request.get_data(as_text=True) logger.info("Request body: " + body) try: handler.handle(body, signature) except InvalidSignatureError:
from linebot.exceptions import ( InvalidSignatureError ) from linebot.models import ( MessageEvent, TextMessage, TextSendMessage, ) import os app = Flask(__name__) # 環境変数取得 # LINE Developersで設定されているアクセストークンとChannel Secretをを取得し、設定します。 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) ## 1 ## # Webhookからのリクエストをチェックします。 @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) # handle webhook body
from flask import Flask, request import antolib from linebot import ( LineBotApi, WebhookHandler, ) from linebot.exceptions import ( InvalidSignatureError, LineBotApiError, ) from linebot.models import (MessageEvent, TextMessage, TextSendMessage) line_bot_api = LineBotApi( 'IrN10smd9lGZGp0JtOOoBJpAvSvDPFVNnDbTdxVbnU2Xv9YNaABrfKI2LxXxRH59XxerqJx3otWj0OqohFtMLiwSJy6fEEYarDN9KVKol7CqHo1GzqPST1DJI4hvg04yIDQiNwa2M1UD8K4SRn4XawdB04t89/1O/w1cDnyilFU=' ) handler = WebhookHandler('fb78ff3825406ec91a010e7a55e0af6c') app = Flask(__name__) # username of anto.io account user = '******' # key of permission, generated on control panel anto.io key = 'TLmlVU2Dk1oQIyt0ffFFwJcub5Yhr5ZCX0QgSQ2p' # your default thing. thing = 'myyChannel1' anto = antolib.Anto(user, key, thing) @app.route("/callback", methods=['POST']) def callback():
collect2.append(item.text) num=2 while num<=5: r=requests.get("https://meigen-ijin.com/genki/"+str(num)) soup = BeautifulSoup(r.content, "html.parser") kotoba=soup.select("p.meigen") for item in kotoba: collect.append(item.text) for item in detail: collect2.append(item.text) num += 1 number=0 while number<len(collect): d[collect[number]]=collect2[number] number += 1 ran=random.choice(list(d.items())) message=ran[0]+"\n\n\n"+ran[1] return message line_bot_api = LineBotApi(os.environ["CHANNEL_ACCESS_TOKEN"]) line_bot_api.push_message(os.environ["USER_ID"], TextSendMessage(text=meigen()))
from linebot import (LineBotApi, WebhookHandler) from linebot.exceptions import (InvalidSignatureError, LineBotApiError) from linebot.models import (MessageEvent, TextMessage, TextSendMessage, JoinEvent, SourceGroup, SourceRoom, SourceUser, TemplateSendMessage, ButtonsTemplate, URIAction) from rest_framework.response import Response from rest_framework.views import APIView from .models import (Player, Question) from .utils import (BOT_NAME, BOT_ID, BOT_CHANNEL_SECRET, BOT_CHANNEL_ACCESS_TOKEN, get_cache_prefix, get_player_identity, get_participant_identity) logger = logging.getLogger('django') handler = WebhookHandler(BOT_CHANNEL_SECRET) line_bot_api = LineBotApi(BOT_CHANNEL_ACCESS_TOKEN) class IndexView(TemplateView): template_name = 'app:index.html' page_title = 'Line Bot' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class DashboardView(LoginRequiredMixin, TemplateView): template_name = 'app:dashboard.html' page_title = 'Dashboard'
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( 'zCky2QfMUFjwudA9P1YbErlEoF1t3JvXVD8l739SE78Rx/ruiIZVlAxMGIR96AiemCVSMY+xR86ikrtxUHAap8IjVcuOU7M1C76GbeLhpUtsLJuHDB8y559+VXjNp/bhGVa3e5PHERMDMIgt3JM2iQdB04t89/1O/w1cDnyilFU=' ) handler = WebhookHandler('abc362257ffbeb84d24d162004a82be5') @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( "Invalid signature. Please check your channel access token/channel secret." )
from flask import Flask, request, abort from linebot import LineBotApi, WebhookHandler from linebot.exceptions import InvalidSignatureError from linebot.models import MessageEvent, TextMessage, TextSendMessage # Load data from config.ini file config = configparser.ConfigParser() config.read('config.ini') # Initial Flask app app = Flask(__name__) # Initial bot by line access token & secret line_bot_api = LineBotApi(config['line_bot']['Channel_Access_Token']) handler = WebhookHandler(config['line_bot']['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:
class TestLineBotApi(unittest.TestCase): def setUp(self): self.tested = LineBotApi('channel_secret') self.imagemap_message = ImagemapSendMessage( base_url='https://example.com/base', alt_text='this is an imagemap', base_size=BaseSize(height=1040, width=1040), actions=[ URIImagemapAction( link_uri='https://example.com/', area=ImagemapArea( x=0, y=0, width=520, height=1040 ) ), MessageImagemapAction( text='hello', area=ImagemapArea( x=520, y=0, width=520, height=1040 ) ) ] ) self.message = [{ "type": "imagemap", "baseUrl": "https://example.com/base", "altText": "this is an imagemap", "baseSize": { "height": 1040, "width": 1040 }, "actions": [ { "type": "uri", "linkUri": "https://example.com/", "area": { "x": 0, "y": 0, "width": 520, "height": 1040 } }, { "type": "message", "text": "hello", "area": { "x": 520, "y": 0, "width": 520, "height": 1040 } } ] }] @responses.activate def test_push_imagemap_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={}, status=200 ) self.tested.push_message('to', self.imagemap_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') self.assertEqual( json.loads(request.body), { "to": "to", "messages": self.message } ) @responses.activate def test_reply_imagemap_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', json={}, status=200 ) self.tested.reply_message('replyToken', self.imagemap_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') self.assertEqual( json.loads(request.body), { "replyToken": "replyToken", "messages": self.message } ) @responses.activate def test_multicast_imagemap_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', json={}, status=200 ) self.tested.multicast(['to1', 'to2'], self.imagemap_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') self.assertEqual( json.loads(request.body), { "to": ['to1', 'to2'], "messages": self.message } )
alt_text='ImageCarousel template', template=ImageCarouselTemplate(columns=[ ImageCarouselColumn(image_url='https://i.imgur.com/JHoQ5Xg.png', action=PostbackAction(label='2、3月', data='action=buy&itemid=1')), ImageCarouselColumn(image_url='https://i.imgur.com/PUTvUgG.png', action=PostbackAction(label='4、5月', data='action=buy&itemid=2')), ImageCarouselColumn(image_url='https://i.imgur.com/isntBij.png', action=PostbackAction(label='6、7月', data='action=buy&itemid=2')) ])) app = Flask(__name__) # LINE BOT info line_bot_api = LineBotApi( 'fNUmdwjb36kT5Fv3a2EyPRF+0cIxQIGOz6cqikXxbjsyOg/9zRrna8v3K8VI8etW1eub+ETlBRveDIlCHIA3Nj98aOFUuGhfjparCyovn79K1lq5R7mcZZzwgoy4uCGcShykK9gxJUKp12P64/gS7wdB04t89/1O/w1cDnyilFU=' ) handler = WebhookHandler('5fae52882c597bdfbd02e56959ff34e2') @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) print(body) try: handler.handle(body, signature) except InvalidSignatureError: abort(400) return 'OK'
import os from flask import Flask, request, abort from linebot import (LineBotApi, WebhookHandler) from linebot.exceptions import (InvalidSignatureError) from linebot.models import * from pchome import scrapy import re app = Flask(__name__) # Channel Access Token line_bot_api = LineBotApi(os.environ.get("LINE_BOT_TOKEN")) # Channel Secret handler = WebhookHandler(os.environ.get("LINE_BOT_SECRET")) # 監聽所有來自 /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) except InvalidSignatureError:
import requests import datetime from bs4 import BeautifulSoup from flask import Flask, request, abort from linebot import (LineBotApi, WebhookHandler, exceptions) from linebot.exceptions import (InvalidSignatureError) from linebot.models import * import mongodb import re import json import Standard_Deviation app = Flask(__name__) line_bot_api = LineBotApi( 'yPz5v7f3XGdcsTCyme2hKXbu58fKDgEriFNPSo/NcMNoZPWVZEwYIOlQ2jqNQeXF080NRsgf/jzbYI/VjlJTl2H1Xc9ZXN7wBHLJH82E6uJsab+TuUAaT2G4TZtH5T+uWycR5QSotn6TQiy/ykra4wdB04t89/1O/w1cDnyilFU=' ) # 必須放上自己的Channel Secret handler = WebhookHandler('3bbbb90dbcad8693b66c7d61ff58ba6c') yourid = 'U6c8f2685a2918d7afbd819b12c15a848' line_bot_api.push_message(yourid, 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)
def setUp(self): self.tested = LineBotApi('channel_secret') # test data self.text_message = TextSendMessage(text='Hello, world') self.message = [{"type": "text", "text": "Hello, world"}]
import os 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('9tCt4xaZGm45WAqnWBPs3GdaNt++EDAw2hvGZcCNxVM0BdJhwWmtM6Ut3HWTMB8xhRRg0IaMZ91PXL7fC3zwrlP+rKeMlk23IdzM2OHO1KStqQvOnamzuxVsLNahtVDTYMwruMWu2wZucPJ3iLyD8QdB04t89/1O/w1cDnyilFU=') handler = WebhookHandler('7d4cbf295eaecce53055692d3165cc61') @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)
def setUp(self): self.tested = LineBotApi('channel_secret') self.button_template_message = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate( thumbnail_image_url='https://example.com/image.jpg', title='Menu', text='Please select', actions=[ PostbackTemplateAction( label='postback', text='postback text', data='action=buy&itemid=1' ), MessageTemplateAction( label='message', text='message text' ), URITemplateAction( label='uri', uri='http://example.com/' ) ] ) ) self.button_message = [{ "type": "template", "altText": "Buttons template", "template": { "type": "buttons", "thumbnailImageUrl": "https://example.com/image.jpg", "imageAspectRatio": None, "imageSize": None, "imageBackgroundColor": None, "title": "Menu", "text": "Please select", "actions": [ { "type": "postback", "label": "postback", "text": "postback text", "data": "action=buy&itemid=1" }, { "type": "message", "label": "message", "text": "message text" }, { "type": "uri", "label": "uri", "uri": "http://example.com/" } ] } }] self.confirm_template_message = TemplateSendMessage( alt_text='Confirm template', template=ConfirmTemplate( text='Are you sure?', actions=[ PostbackTemplateAction( label='postback', text='postback text', data='action=buy&itemid=1' ), MessageTemplateAction( label='message', text='message text' ) ] ) ) self.confirm_message = [{ "type": "template", "altText": "Confirm template", "template": { "type": "confirm", "text": "Are you sure?", "actions": [ { "type": "postback", "label": "postback", "text": "postback text", "data": "action=buy&itemid=1" }, { "type": "message", "label": "message", "text": "message text" } ] } }] self.carousel_template_message = TemplateSendMessage( alt_text='Carousel template', template=CarouselTemplate( columns=[ CarouselColumn( thumbnail_image_url='https://example.com' '/item1.jpg', title='this is menu1', text='description1', actions=[ PostbackTemplateAction( label='postback1', text='postback text1', data='action=buy&itemid=1' ), MessageTemplateAction( label='message1', text='message text1' ), URITemplateAction( label='uri1', uri='http://example.com/1' ) ] ), CarouselColumn( thumbnail_image_url='https://example.com' '/item2.jpg', image_background_color='#000000', title='this is menu2', text='description2', actions=[ PostbackTemplateAction( label='postback2', text='postback text2', data='action=buy&itemid=2' ), MessageTemplateAction( label='message2', text='message text2' ), URITemplateAction( label='uri2', uri='http://example.com/2' ) ] ), CarouselColumn( thumbnail_image_url='https://example.com' '/item3.jpg', title='this is menu3', text='description3', actions=[ DatetimePickerTemplateAction( label="datetime picker date", data="action=sell&itemid=2&mode=date", mode="date", initial="2013-04-01", min="2011-06-23", max="2017-09-08" ), DatetimePickerTemplateAction( label="datetime picker time", data="action=sell&itemid=2&mode=time", mode="time", initial="10:00", min="00:00", max="23:59" ), DatetimePickerTemplateAction( label="datetime picker datetime", data="action=sell&itemid=2&mode=datetime", mode="datetime", initial="2013-04-01T10:00", min="2011-06-23T00:00", max="2017-09-08T23:59" ) ] ) ] ) ) self.carousel_message = [{ "type": "template", "altText": "Carousel template", "template": { "type": "carousel", "columns": [ { "thumbnailImageUrl": "https://example.com/item1.jpg", "imageBackgroundColor": None, "title": "this is menu1", "text": "description1", "actions": [ { "type": "postback", "label": "postback1", "text": "postback text1", "data": "action=buy&itemid=1" }, { "type": "message", "label": "message1", "text": "message text1" }, { "type": "uri", "label": "uri1", "uri": "http://example.com/1" } ] }, { "thumbnailImageUrl": "https://example.com/item2.jpg", "imageBackgroundColor": "#000000", "title": "this is menu2", "text": "description2", "actions": [ { "type": "postback", "label": "postback2", "text": "postback text2", "data": "action=buy&itemid=2" }, { "type": "message", "label": "message2", "text": "message text2" }, { "type": "uri", "label": "uri2", "uri": "http://example.com/2" } ] }, { "thumbnailImageUrl": "https://example.com/item3.jpg", "imageBackgroundColor": None, "title": "this is menu3", "text": "description3", "actions": [ { "type": "datetimepicker", "label": "datetime picker date", "data": "action=sell&itemid=2&mode=date", "mode": "date", "initial": "2013-04-01", "min": "2011-06-23", "max": "2017-09-08" }, { "type": "datetimepicker", "label": "datetime picker time", "data": "action=sell&itemid=2&mode=time", "mode": "time", "initial": "10:00", "min": "00:00", "max": "23:59" }, { "type": "datetimepicker", "label": "datetime picker datetime", "data": "action=sell&itemid=2&mode=datetime", "mode": "datetime", "initial": "2013-04-01T10:00", "min": "2011-06-23T00:00", "max": "2017-09-08T23:59" } ] } ], "imageAspectRatio": None, "imageSize": None } }] self.image_carousel_template_message = TemplateSendMessage( alt_text='Image carousel template', template=ImageCarouselTemplate( columns=[ ImageCarouselColumn( image_url='https://example.com/' 'item1.jpg', action=PostbackTemplateAction( label='postback1', data='action=buy&itemid=1' ) ), ImageCarouselColumn( image_url='https://example.com' '/item2.jpg', action=MessageTemplateAction( label='message2', text='message text2' ) ), ImageCarouselColumn( image_url='https://example.com/' 'item3.jpg', action=URITemplateAction( label='uri1', uri='https://example.com/1' ) ) ] ) ) self.image_carousel_message = [{ "type": "template", "altText": "Image carousel template", "template": { "type": "image_carousel", "columns": [ { "imageUrl": "https://example.com/item1.jpg", "action": { "type": "postback", "label": "postback1", "data": "action=buy&itemid=1", "text": None } }, { "imageUrl": "https://example.com/item2.jpg", "action": { "type": "message", "label": "message2", "text": "message text2" } }, { "imageUrl": "https://example.com/item3.jpg", "action": { "type": "uri", "label": "uri1", "uri": "https://example.com/1" } } ] } }]
class LineBotClient(FlaskRestBotClient): def __init__(self, argument_parser=None): FlaskRestBotClient.__init__(self, "line", argument_parser) self.create_line_bot() YLogger.debug(self, "Line Client is running....") def get_description(self): return 'ProgramY AIML2.0 Line Client' def get_client_configuration(self): return LineConfiguration() def get_license_keys(self): self._channel_secret = self.license_keys.get_key("LINE_CHANNEL_SECRET") self._channel_access_token = self.license_keys.get_key("LINE_ACCESS_TOKEN") def create_line_bot(self): self._line_bot_api = LineBotApi(self._channel_access_token) self._parser = WebhookParser(self._channel_secret) def handle_text_message(self, event): question = event.message.text userid = event.source.user_id answer = self.ask_question(userid, question) self._line_bot_api.reply_message(event.reply_token, TextSendMessage(text=answer)) def get_unknown_response(self, userid): if self.configuration.client_configuration.unknown_command_srai is None: unknown_response = self.configuration.client_configuration.unknown_command else: unknown_response = self.ask_question(userid, self.configuration.client_configuration.unknown_command_srai) if unknown_response is None or unknown_response == "": unknown_response = self.configuration.client_configuration.unknown_command return unknown_response def handle_unknown_event(self, event): userid = "" unknown_response = self.get_unknown_response(userid) self._line_bot_api.reply_message(event.reply_token, TextSendMessage(text=unknown_response)) def handle_unknown_message(self, event): userid = "" unknown_response = self.get_unknown_response(userid) self._line_bot_api.reply_message(event.reply_token, TextSendMessage(text=unknown_response)) def handle_message_request(self, body, signature): events = self._parser.parse(body, signature) for event in events: if isinstance(event, MessageEvent): if isinstance(event.message, TextMessage): self.handle_text_message(event) else: self.handle_unknown_message(event) else: self.handle_unknown_event(event) def receive_message(self, request): if self.configuration.client_configuration.debug is True: self.dump_request(request) # get X-Line-Signature header value signature = request.headers['X-Line-Signature'] # get request body as text body = request.get_data(as_text=True) # handle webhook body try: self.handle_message_request(body, signature) except InvalidSignatureError as excep: YLogger.exception(self, "Line error", excep) abort(500) return Response(status=200)
class TestLineBotApi(unittest.TestCase): def setUp(self): self.tested = LineBotApi('channel_secret') self.sticker_message = StickerSendMessage( package_id='1', sticker_id='1' ) self.message = [{ "type": "sticker", "packageId": "1", "stickerId": "1" }] @responses.activate def test_push_sticker_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={}, status=200 ) self.tested.push_message('to', self.sticker_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') self.assertEqual( json.loads(request.body), { "to": "to", "messages": self.message } ) @responses.activate def test_reply_sticker_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', json={}, status=200 ) self.tested.reply_message('replyToken', self.sticker_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') self.assertEqual( json.loads(request.body), { "replyToken": "replyToken", "messages": self.message } ) @responses.activate def test_multicast_sticker_message(self): responses.add( responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', json={}, status=200 ) self.tested.multicast(['to1', 'to2'], self.sticker_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') self.assertEqual( json.loads(request.body), { "to": ['to1', 'to2'], "messages": self.message } )
#!/usr/bin/python # -*- coding: UTF-8 -*- import paho.mqtt.client as mqtt from flask import Flask, request, abort from linebot import (LineBotApi, WebhookHandler) from linebot.exceptions import (InvalidSignatureError) from linebot.models import ( MessageEvent, TextMessage, TextSendMessage, ) line_bot_api = LineBotApi('xxxxxxxxxx') to_group_id = ('xxxxxxxxxx') def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client.subscribe("home/alert") def on_message(client, userdata, msg): msg.payload = str(msg.payload, encoding="utf-8") if msg.payload == ('Unlock'): line_bot_api.push_message(to_group_id, TextSendMessage(u'解鎖')) elif msg.payload == ('Lock'): line_bot_api.push_message(to_group_id, TextSendMessage(u'上鎖')) elif msg.payload == ('Alert!'): line_bot_api.push_message(to_group_id, TextSendMessage(u'遭受入侵')) else:
def setUp(self): self.tested = LineBotApi('channel_secret')
ImageSendMessage) from linebot.models.template import * from linebot import ( LineBotApi, WebhookHandler ) from linebot.exceptions import ( LineBotApiError, InvalidSignatureError ) from web_scraping_the_standard import * from web_scraping_rotten_tomatoes import * app = Flask(__name__) lineaccesstoken = 'CSdgziqlU0NO/Sf3MmAkinm92OOKEUYNwNV9xlzta/Z85ZdUUc6sQ5eHl2aJrCGgmR6nFvtNYhhEOG1kG8B0XxayECT8jqSHdszjg7derd6JKI/fZqVDpA5iv9+qICJxk43PeGbYDoQG3Ph7YVAblAdB04t89/1O/w1cDnyilFU=' linesecret = '74d75448fe78ae3cf293ab1a8cfce9b0' line_bot_api = LineBotApi(lineaccesstoken) handler = WebhookHandler(linesecret) ####################### new ######################## @app.route('/') def index(): return "This is Line Chatbot" @app.route("/callback", methods=['POST']) ## or 'webhook' it's actually the same def callback(): # get X-Line-Signature header value signature = request.headers['X-Line-Signature'] # get request body as text
if Restaurant.Num_of_match > best_Num_of_match: best_Num_of_match = Restaurant.Num_of_match best_Num_of_match_list = [] best_Num_of_match_list.append(Restaurant) elif Restaurant.Num_of_match == best_Num_of_match: best_Num_of_match_list.append(Restaurant) # random.shuffle(best_Num_of_match_list) now = datetime.now() second = now.strftime("%S") index = int(second) % len(best_Num_of_match_list) return best_Num_of_match_list[index] # Channel Access Token line_bot_api = LineBotApi( 'ILh4a91G2sR8bBbfAz9YOi6RvzfousZ+Q+G7PF5Gylx3Re5XaeOI65RH3JdtS/LUxrHx53yG73Nt3uMlry5mL4jqA3g1ajmL83dlrjq6NOIVjPe0FuYFFdOYstlZfntVHycjzMcNiOhyM64SO7GveAdB04t89/1O/w1cDnyilFU=' ) # Channel Secret handler = WebhookHandler("9565a35e1afc821cbe78d714e2cd45c5") # 監聽所有來自 /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:
from urllib.parse import parse_qsl import uuid from config import Config from database import db_session, init_db from models.user import Users from models.product import Products from models.cart import Cart from models.order import Orders from models.item import Items from models.linepay import LinePay app = Flask(__name__) line_bot_api = LineBotApi(Config.CHANNEL_ACCESS_TOKEN) handler = WebhookHandler(Config.CHANNEL_SECRET) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() @app.route("/liff", methods=['GET']) def liff(): redirect_url = request.args.get('redirect_url') return redirect(redirect_url)
def create_line_bot(self): self._line_bot_api = LineBotApi(self._channel_access_token) self._parser = WebhookParser(self._channel_secret)
from google.cloud import storage from flask import Flask, request, abort from linebot import (LineBotApi, WebhookHandler) from linebot.exceptions import (InvalidSignatureError) from linebot.models import ( MessageEvent, TextMessage, TextSendMessage, AudioMessage, ) os.environ["GCLOUD_PROJECT"] = "lalu" app = Flask(__name__) line_bot_api = LineBotApi( 'hKQqH81E7hVz7qTR2atb33XCwxGU7rp26ujip3v07w/zG6Mh/MFAytYQMRQ8REHXKFK83SxYet8CP8V9ToFTsT6ECb7okQaw/Ma3F8kMEe3qgdgA7CeDuNjQ+4UCkJqo7zwtkQEsYfxEYT2LNFB+PwdB04t89/1O/w1cDnyilFU=' ) handler = WebhookHandler('25d6ce598476773ebf878082b36021b5') @app.route("/", methods=['GET']) def hello(): return "Hello World!" @app.route("/", methods=['POST']) def callback(): signature = request.headers['X-Line-Signature'] body = request.get_data(as_text=True) print("Request body: " + body, "Signature: " + signature) try:
TextMessage, TextSendMessage, ) from linebot.exceptions import (InvalidSignatureError) from linebot import (LineBotApi, WebhookHandler) from flask import Flask, request, abort with open("./linebot.json", encoding="utf-8") as f: account_dict = json.loads(f.read()) LINE_ACCESS_TOKEN = account_dict["LINE_ACCESS_TOKEN"] LINE_CHANNEL_SECRET = account_dict["LINE_CHANNEL_SECRET"] app = Flask(__name__) line_bot_api = LineBotApi(LINE_ACCESS_TOKEN) handler = WebhookHandler(LINE_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) msg = request.get_json() app.logger.info("Request body: " + body) # handle webhook body
def __init__(self, channel_access_token): LineBotApi.__init__(self, channel_access_token) self._messages = []