def create_rich_menu():

    print("INFO: Creating rich menu")

    line_bot_api = LineBotApi(channel_access_token)

    display_text = str(
        capture_seconds) + "秒の録画が始まりました!\nスマホをしまっても大丈夫です。\n2分程たったら動画が届きます。"

    rich_menu_to_create = RichMenu(
        size=RichMenuSize(width=2500, height=1204),
        selected=True,
        name="Nice richmenu",
        chat_bar_text="録画ボタン",
        areas=[
            RichMenuArea(bounds=RichMenuBounds(x=0,
                                               y=0,
                                               width=2500,
                                               height=1408),
                         action=PostbackAction(data=twitch_username,
                                               display_text=display_text))
        ])

    rich_menu_id = line_bot_api.create_rich_menu(rich_menu=rich_menu_to_create)

    with open("record_button.png", 'rb') as f:
        line_bot_api.set_rich_menu_image(rich_menu_id, 'image/png', f)

    line_bot_api.set_default_rich_menu(rich_menu_id)

    print("INFO: Finished creating rich menu")
Exemple #2
0
def createRichmenu(event, context):
    # LineBotAPIオブジェクトを作成する
    token = os.getenv('LINE_ACCESS_TOKEN')
    line_bot_api = LineBotApi(token)

    result = False
    try:
        # define a new richmenu
        rich_menu_to_create = RichMenu(
            size=RichMenuSize(width=2500, height=843),
            selected=False,
            name='richmenu for Link',
            chat_bar_text='MENU',
            areas=[
                RichMenuArea(
                    bounds=RichMenuBounds(x=15, y=0, width=800, height=843),
                    action=URIAction(uri='https://www.matsuokamayu.jp/')
                ),
                RichMenuArea(
                    bounds=RichMenuBounds(x=845, y=0, width=800, height=843),
                    action=URIAction(uri='https://twitter.com/hiratahirata14/')
                ),
                RichMenuArea(
                    bounds=RichMenuBounds(x=1660, y=0, width=800, height=843),
                    action=URIAction(
                        uri='https://www.instagram.com/mayu_matsuoka_koushiki/')
                )
            ]
        )
        richMenuId = line_bot_api.create_rich_menu(
            rich_menu=rich_menu_to_create)

        # upload an image for rich menu
        path = './images/rich_image.jpg'

        with open(path, 'rb') as f:
            line_bot_api.set_rich_menu_image(richMenuId, "image/png", f)

        # set the default rich menu
        line_bot_api.set_default_rich_menu(richMenuId)

        result = True

    except Exception:
        result = False

    return result
Exemple #3
0
            "x": 1763,
            "y": 848,
            "width": 545,
            "height": 520
        },
        "action": {
            "type":
            "postback",
            "data":
            '{"kind":"menu","level":"%d","choice":"%d","item":"%d"}' %
            (0, 6, 0)
        }
    }]
}
rich_menu_list = line_bot_api.get_rich_menu_list()
if rich_menu_list:
    print('rich_menu_list', rich_menu_list)
    line_bot_api.delete_rich_menu(line_bot_api.get_default_rich_menu())
else:
    myRichMenu_Id = line_bot_api.create_rich_menu(
        rich_menu=RichMenu.new_from_json_dict(rich_menu_initial))
    print('myRichMenu_Id:', myRichMenu_Id)
    uploadImageFile = open('D:/rich_menu_forallusers.jpg', 'rb')
    setImageResponse = line_bot_api.set_rich_menu_image(
        myRichMenu_Id, 'image/jpeg', uploadImageFile)
    if setImageResponse:
        print('setImageResponse:', setImageResponse)
    setImageResponse = line_bot_api.set_default_rich_menu(myRichMenu_Id)
    default_rich_menu = line_bot_api.get_default_rich_menu()
    print('default_rich_menu', default_rich_menu)
Exemple #4
0
                     action=PostbackAction(data="社会論")),
        RichMenuArea(bounds=RichMenuBounds(x=1250,
                                           y=843,
                                           width=575,
                                           height=750),
                     action=PostbackAction(data="社会科学")),
        RichMenuArea(bounds=RichMenuBounds(x=1825, y=93, width=675,
                                           height=750),
                     action=PostbackAction(data="外国語")),
        RichMenuArea(bounds=RichMenuBounds(x=1825,
                                           y=843,
                                           width=675,
                                           height=750),
                     action=PostbackAction(data="ヘルプ"))
    ])
richMenuId = line_bot_api.create_rich_menu(rich_menu=rich_menu_to_create)

# upload an image for rich menu
# path_default = "job_hisyo_woman_kochira__.png"
# path = "rich_menu.jpg"
with open("static/rich_menu.jpg", 'rb') as f:
    line_bot_api.set_rich_menu_image(richMenuId, "image/jpeg", f)

#########################################################################################

# set the default rich menu----------------------------------------------------------------------------
line_bot_api.set_default_rich_menu(richMenuId)
#--------------------------------------------------------------------------------------------------------

#ngrokでデバック用
# if __name__ == "__main__":
Exemple #5
0
# get channel_secret and channel_access_token from your environment variable
channel_secret = os.getenv('YOUR_CHANNEL_SECRET', None)
channel_access_token = os.getenv('YOUR_CHANNEL_ACCESS_TOKEN', None)
if channel_secret is None:
    print('Specify YOUR_CHANNEL_SECRET as environment variable.')
    sys.exit(1)
if channel_access_token is None:
    print('Specify YOUR_CHANNEL_ACCESS_TOKEN as environment variable.')
    sys.exit(1)

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

rich_menu_id = line_bot_api.create_rich_menu(rich_menu=font_richmenu())
with open("img/menu.png", "rb") as f:
    line_bot_api.set_rich_menu_image(rich_menu_id, 'image/png', f)

line_bot_api.set_default_rich_menu(rich_menu_id)


@app.route('/')
def hello():
    name = "Hello world"
    return name


@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
Exemple #6
0
class TestLineBotApi(unittest.TestCase):
    maxDiff = None

    def setUp(self):
        self.tested = LineBotApi('channel_secret')

        self.rich_menu_id = 'richmenu-0000000000'
        self.user_id = 'userid'
        self.rich_menu = RichMenu(
            size=RichMenuSize(width=2500, height=1686),
            selected=False,
            name="nice richmenu",
            chatBarText="touch me",
            areas=[
                RichMenuArea(
                    RichMenuBounds(x=0, y=0, width=833, height=843),
                    URITemplateAction(uri='https://line.me/R/nv/location/'))
            ])

    @responses.activate
    def test_get_rich_menu(self):
        responses.add(responses.GET,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/richmenu/rich_menu_id',
                      json={
                          "richMenuId":
                          "rich_menu_id",
                          "size": {
                              "width": 2500,
                              "height": 1686
                          },
                          "selected":
                          False,
                          "name":
                          "name",
                          "chatBarText":
                          "chatBarText",
                          "areas": [{
                              "bounds": {
                                  "x": 0,
                                  "y": 0,
                                  "width": 2500,
                                  "height": 1686
                              },
                              "action": {
                                  "type": "postback",
                                  "data": "action=buy&itemid=123"
                              }
                          }]
                      },
                      status=200)

        rich_menu = self.tested.get_rich_menu('rich_menu_id')
        print(rich_menu)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'GET')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/rich_menu_id')

        self.assertEqual(rich_menu.rich_menu_id, 'rich_menu_id')
        self.assertEqual(rich_menu.size.width, 2500)
        self.assertEqual(rich_menu.size.height, 1686)
        self.assertEqual(rich_menu.selected, False)
        self.assertEqual(rich_menu.name, 'name')
        self.assertEqual(rich_menu.chat_bar_text, 'chatBarText')
        self.assertEqual(rich_menu.areas[0].bounds.x, 0)
        self.assertEqual(rich_menu.areas[0].bounds.y, 0)
        self.assertEqual(rich_menu.areas[0].bounds.width, 2500)
        self.assertEqual(rich_menu.areas[0].bounds.height, 1686)
        self.assertEqual(rich_menu.areas[0].action.type, 'postback')
        self.assertEqual(rich_menu.areas[0].action.data,
                         'action=buy&itemid=123')

    @responses.activate
    def test_create_rich_menu(self):
        responses.add(responses.POST,
                      LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu',
                      json={"richMenuId": "richMenuId"},
                      status=200)

        rich_menu = RichMenu(
            size=RichMenuSize(width=2500, height=1686),
            selected=False,
            name="nice richmenu",
            chatBarText="touch me",
            areas=[
                RichMenuArea(
                    RichMenuBounds(x=0, y=0, width=833, height=843),
                    URITemplateAction(uri='https://line.me/R/nv/location/'))
            ])

        result = self.tested.create_rich_menu(rich_menu)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(request.url,
                         LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu')
        self.assertEqual(result, "richMenuId")

    @responses.activate
    def test_delete_rich_menu(self):
        responses.add(responses.DELETE,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/richmenu/rich_menu_id',
                      json={},
                      status=200)

        self.tested.delete_rich_menu('rich_menu_id')

        request = responses.calls[0].request
        self.assertEqual(request.method, 'DELETE')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/rich_menu_id')

    @responses.activate
    def test_get_rich_menu_id_of_user(self):
        responses.add(responses.GET,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/user/user_id/richmenu',
                      json={"richMenuId": "richMenuId"},
                      status=200)

        result = self.tested.get_rich_menu_id_of_user('user_id')

        request = responses.calls[0].request
        self.assertEqual(request.method, 'GET')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/user_id/richmenu')
        self.assertEqual(result, "richMenuId")

    @responses.activate
    def test_link_rich_menu_to_user(self):
        responses.add(responses.POST,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/user/user_id/richmenu/rich_menu_id',
                      json={},
                      status=200)

        self.tested.link_rich_menu_to_user('user_id', 'rich_menu_id')

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url, LineBotApi.DEFAULT_API_ENDPOINT +
            '/v2/bot/user/user_id/richmenu/rich_menu_id')

    @responses.activate
    def test_unlink_rich_menu_from_user(self):
        responses.add(responses.DELETE,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/user/user_id/richmenu',
                      json={},
                      status=200)

        self.tested.unlink_rich_menu_from_user('user_id')

        request = responses.calls[0].request
        self.assertEqual(request.method, 'DELETE')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/user_id/richmenu')

    @responses.activate
    def test_get_rich_menu_list(self):
        responses.add(responses.GET,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/richmenu/list',
                      json={
                          "richmenus": [{
                              "richMenuId":
                              "rich_menu_id",
                              "size": {
                                  "width": 2500,
                                  "height": 1686
                              },
                              "selected":
                              False,
                              "name":
                              "name",
                              "chatBarText":
                              "chatBarText",
                              "areas": [{
                                  "bounds": {
                                      "x": 0,
                                      "y": 0,
                                      "width": 2500,
                                      "height": 1686
                                  },
                                  "action": {
                                      "type": "postback",
                                      "data": "action=buy&itemid=123"
                                  }
                              }]
                          }]
                      },
                      status=200)

        rich_menus = self.tested.get_rich_menu_list()

        request = responses.calls[0].request
        self.assertEqual(request.method, 'GET')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/list')
        self.assertEqual(rich_menus[0].rich_menu_id, 'rich_menu_id')
        self.assertEqual(rich_menus[0].size.width, 2500)
        self.assertEqual(rich_menus[0].size.height, 1686)
        self.assertEqual(rich_menus[0].selected, False)
        self.assertEqual(rich_menus[0].name, 'name')
        self.assertEqual(rich_menus[0].chat_bar_text, 'chatBarText')
        self.assertEqual(rich_menus[0].areas[0].bounds.x, 0)
        self.assertEqual(rich_menus[0].areas[0].bounds.y, 0)
        self.assertEqual(rich_menus[0].areas[0].bounds.width, 2500)
        self.assertEqual(rich_menus[0].areas[0].bounds.height, 1686)
        self.assertEqual(rich_menus[0].areas[0].action.type, 'postback')
        self.assertEqual(rich_menus[0].areas[0].action.data,
                         'action=buy&itemid=123')

    @responses.activate
    def test_link_rich_menu_to_users(self):
        responses.add(responses.POST,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/richmenu/bulk/link',
                      json={},
                      status=202)

        self.tested.link_rich_menu_to_users(['user_id1', 'user_id2'],
                                            'rich_menu_id')

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/bulk/link')
        self.assertEqual(json.loads(request.body), {
            "richMenuId": "rich_menu_id",
            "userIds": ["user_id1", "user_id2"],
        })

    @responses.activate
    def test_unlink_rich_menu_to_users(self):
        responses.add(responses.POST,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/richmenu/bulk/unlink',
                      json={},
                      status=202)

        self.tested.unlink_rich_menu_from_users(['user_id1', 'user_id2'],
                                                'rich_menu_id')

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/bulk/unlink')
        self.assertEqual(json.loads(request.body), {
            "userIds": ["user_id1", "user_id2"],
        })

    @responses.activate
    def test_set_default_rich_menu(self):
        responses.add(responses.POST,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/user/all/richmenu/rich_menu_id',
                      json={},
                      status=200)

        self.tested.set_default_rich_menu('rich_menu_id')

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url, LineBotApi.DEFAULT_API_ENDPOINT +
            '/v2/bot/user/all/richmenu/rich_menu_id')

    @responses.activate
    def test_get_default_rich_menu(self):
        responses.add(responses.GET,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/user/all/richmenu',
                      json={"richMenuId": "richMenuId"},
                      status=200)

        result = self.tested.get_default_rich_menu()

        request = responses.calls[0].request
        self.assertEqual(request.method, 'GET')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/all/richmenu')
        self.assertEqual(result, "richMenuId")

    @responses.activate
    def test_cancel_default_rich_menu(self):
        responses.add(responses.DELETE,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/user/all/richmenu',
                      json={},
                      status=200)

        self.tested.cancel_default_rich_menu()

        request = responses.calls[0].request
        self.assertEqual(request.method, 'DELETE')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/all/richmenu')

    @responses.activate
    def test_get_rich_menu_image(self):
        rich_menu_id = '1234'
        body = b'hogieoidksk'
        responses.add(responses.GET,
                      LineBotApi.DEFAULT_API_DATA_ENDPOINT +
                      '/v2/bot/richmenu/{rich_menu_id}/content'.format(
                          rich_menu_id=rich_menu_id),
                      body=body,
                      status=200)

        res = self.tested.get_rich_menu_image(rich_menu_id)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'GET')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_DATA_ENDPOINT +
            '/v2/bot/richmenu/{rich_menu_id}/content'.format(
                rich_menu_id=rich_menu_id),
        )
        self.assertEqual(body, res.content)

    @responses.activate
    def test_set_rich_menu_image(self):
        rich_menu_id = '1234'
        body = b'hogieoidksk'
        responses.add(responses.POST,
                      LineBotApi.DEFAULT_API_DATA_ENDPOINT +
                      '/v2/bot/richmenu/{rich_menu_id}/content'.format(
                          rich_menu_id=rich_menu_id),
                      json={},
                      status=200)

        self.tested.set_rich_menu_image(rich_menu_id=rich_menu_id,
                                        content_type='image/jpeg',
                                        content=body)

        request = responses.calls[0].request
        self.assertEqual('POST', request.method)
        self.assertEqual(
            LineBotApi.DEFAULT_API_DATA_ENDPOINT +
            '/v2/bot/richmenu/{rich_menu_id}/content'.format(
                rich_menu_id=rich_menu_id), request.url)
Exemple #7
0
        rich_menu_path = os.path.join(rich_menu_folder, rich_menu)
        if os.path.isdir(rich_menu_path):
            anything = os.listdir(rich_menu_path)
            file_path = ''
            jpg_path = ''
            for file in anything:
                if file == 'rich_menu.json':
                    file_path = os.path.join(rich_menu_path, file)
                elif file == 'rich_menu.jpg':
                    jpg_path = os.path.join(rich_menu_path, file)

        with open(file_path, 'r') as f:
            rich_menu_json = json.loads(f.read())

        # 創建菜單,取得menuId
        lineRichMenuId = line_bot_api.create_rich_menu(
            rich_menu=RichMenu.new_from_json_dict(rich_menu_json))
        print('設定檔上傳結果')
        print(lineRichMenuId)

        #id寫入指定資料夾端
        id_folder = os.path.join(rich_menu_path, 'rich_menu_id.txt')

        with open(id_folder, 'w') as rich_id:
            rich_id.write(lineRichMenuId)

        # 上傳照片至該menu-id
        with open(jpg_path, 'rb') as f:
            set_image_response = line_bot_api.set_rich_menu_image(
                lineRichMenuId, 'image/jpeg', f)
        print("-圖片上傳結果")
        print(set_image_response)
line_bot_api = LineBotApi(channel_access_token)

# 讀取選單 json、jpg,json 利用 Line bot Designer 設計出來
json_path_list = glob.glob(r'.\menu\*.json')
jpg_path_list = glob.glob(r'.\menu\*.jpg')

# 檔案上傳順序確認
print(json_path_list)
print(jpg_path_list)

# 依序上傳
for index in range(len(json_path_list)):
    print(f'上傳第 {index + 1} 組')
    # 創建菜單,取得 menuId
    try:
        lineRichMenuId = line_bot_api.create_rich_menu(
            rich_menu=RichMenu.new_from_json_dict(
                json.load(open(json_path_list[index], 'r', encoding='utf8'))))
        print(lineRichMenuId)
    except:
        print('建立 json 失敗')

    # 上傳照片至該id
    try:
        with open(jpg_path_list[index], 'rb') as f:
            set_image_response = line_bot_api.set_rich_menu_image(
                lineRichMenuId, 'image/jpeg', f)
    except:
        print('上傳失敗')

print('上傳完成')
class TestLineBotApi(unittest.TestCase):
    maxDiff = None

    def setUp(self):
        self.tested = LineBotApi('channel_secret')

        self.rich_menu_id = 'richmenu-0000000000'
        self.user_id = 'userid'
        self.rich_menu = RichMenu(
            size=RichMenuSize(width=2500, height=1686),
            selected=False,
            name="nice richmenu",
            chatBarText="touch me",
            areas=[
                RichMenuArea(RichMenuBounds(x=0, y=0, width=833, height=843),
                             URITemplateAction(uri='line://nv/location'))
            ])

    @responses.activate
    def test_get_rich_menu(self):
        responses.add(responses.GET,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/richmenu/rich_menu_id',
                      json={
                          "richMenuId":
                          "rich_menu_id",
                          "size": {
                              "width": 2500,
                              "height": 1686
                          },
                          "selected":
                          False,
                          "name":
                          "name",
                          "chatBarText":
                          "chatBarText",
                          "areas": [{
                              "bounds": {
                                  "x": 0,
                                  "y": 0,
                                  "width": 2500,
                                  "height": 1686
                              },
                              "action": {
                                  "type": "postback",
                                  "data": "action=buy&itemid=123"
                              }
                          }]
                      },
                      status=200)

        rich_menu = self.tested.get_rich_menu('rich_menu_id')
        print(rich_menu)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'GET')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/rich_menu_id')

        self.assertEqual(rich_menu.rich_menu_id, 'rich_menu_id')
        self.assertEqual(rich_menu.size.width, 2500)
        self.assertEqual(rich_menu.size.height, 1686)
        self.assertEqual(rich_menu.selected, False)
        self.assertEqual(rich_menu.name, 'name')
        self.assertEqual(rich_menu.chat_bar_text, 'chatBarText')
        self.assertEqual(rich_menu.areas[0].bounds.x, 0)
        self.assertEqual(rich_menu.areas[0].bounds.y, 0)
        self.assertEqual(rich_menu.areas[0].bounds.width, 2500)
        self.assertEqual(rich_menu.areas[0].bounds.height, 1686)
        self.assertEqual(rich_menu.areas[0].action.type, 'postback')
        self.assertEqual(rich_menu.areas[0].action.data,
                         'action=buy&itemid=123')

    @responses.activate
    def test_create_rich_menu(self):
        responses.add(responses.POST,
                      LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu',
                      json={"richMenuId": "richMenuId"},
                      status=200)

        rich_menu = RichMenu(
            size=RichMenuSize(width=2500, height=1686),
            selected=False,
            name="nice richmenu",
            chatBarText="touch me",
            areas=[
                RichMenuArea(RichMenuBounds(x=0, y=0, width=833, height=843),
                             URITemplateAction(uri='line://nv/location'))
            ])

        result = self.tested.create_rich_menu(rich_menu)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(request.url,
                         LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu')
        self.assertEqual(result, "richMenuId")

    @responses.activate
    def test_delete_rich_menu(self):
        responses.add(responses.DELETE,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/richmenu/rich_menu_id',
                      json={},
                      status=200)

        self.tested.delete_rich_menu('rich_menu_id')

        request = responses.calls[0].request
        self.assertEqual(request.method, 'DELETE')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/rich_menu_id')

    @responses.activate
    def test_get_rich_menu_id_of_user(self):
        responses.add(responses.GET,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/user/user_id/richmenu',
                      json={"richMenuId": "richMenuId"},
                      status=200)

        result = self.tested.get_rich_menu_id_of_user('user_id')

        request = responses.calls[0].request
        self.assertEqual(request.method, 'GET')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/user_id/richmenu')
        self.assertEqual(result, "richMenuId")

    @responses.activate
    def test_link_rich_menu_to_user(self):
        responses.add(responses.POST,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/user/user_id/richmenu/rich_menu_id',
                      json={},
                      status=200)

        self.tested.link_rich_menu_to_user('user_id', 'rich_menu_id')

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url, LineBotApi.DEFAULT_API_ENDPOINT +
            '/v2/bot/user/user_id/richmenu/rich_menu_id')

    @responses.activate
    def test_unlink_rich_menu_from_user(self):
        responses.add(responses.DELETE,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/user/user_id/richmenu',
                      json={},
                      status=200)

        self.tested.unlink_rich_menu_from_user('user_id')

        request = responses.calls[0].request
        self.assertEqual(request.method, 'DELETE')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/user_id/richmenu')

    @responses.activate
    def test_get_rich_menu_list(self):
        responses.add(responses.GET,
                      LineBotApi.DEFAULT_API_ENDPOINT +
                      '/v2/bot/richmenu/list',
                      json={
                          "richmenus": [{
                              "richMenuId":
                              "rich_menu_id",
                              "size": {
                                  "width": 2500,
                                  "height": 1686
                              },
                              "selected":
                              False,
                              "name":
                              "name",
                              "chatBarText":
                              "chatBarText",
                              "areas": [{
                                  "bounds": {
                                      "x": 0,
                                      "y": 0,
                                      "width": 2500,
                                      "height": 1686
                                  },
                                  "action": {
                                      "type": "postback",
                                      "data": "action=buy&itemid=123"
                                  }
                              }]
                          }]
                      },
                      status=200)

        rich_menus = self.tested.get_rich_menu_list()

        request = responses.calls[0].request
        self.assertEqual(request.method, 'GET')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/list')
        self.assertEqual(rich_menus[0].rich_menu_id, 'rich_menu_id')
        self.assertEqual(rich_menus[0].size.width, 2500)
        self.assertEqual(rich_menus[0].size.height, 1686)
        self.assertEqual(rich_menus[0].selected, False)
        self.assertEqual(rich_menus[0].name, 'name')
        self.assertEqual(rich_menus[0].chat_bar_text, 'chatBarText')
        self.assertEqual(rich_menus[0].areas[0].bounds.x, 0)
        self.assertEqual(rich_menus[0].areas[0].bounds.y, 0)
        self.assertEqual(rich_menus[0].areas[0].bounds.width, 2500)
        self.assertEqual(rich_menus[0].areas[0].bounds.height, 1686)
        self.assertEqual(rich_menus[0].areas[0].action.type, 'postback')
        self.assertEqual(rich_menus[0].areas[0].action.data,
                         'action=buy&itemid=123')
Exemple #10
0
Fichier : app.py Projet : tdtk/milk
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage, PostbackAction, PostbackEvent, TemplateSendMessage, ButtonsTemplate
)

from milk.module.greeting import is_greeting, greeting
from milk.module.purchase import pay, get_total, get_latest_data, clear_purchase_data, get_total_until_date, get_sheet_url
from milk.util.handle_action import action_data2dict
from milk.module.rich_menu import milk_rich_menu

app = Flask(__name__)

line_bot_api = LineBotApi(os.getenv('LINE_CHANNEL_ACCESS_TOKEN'))
handler = WebhookHandler(os.getenv('LINE_CHANNEL_SECRET'))

rich_menu_id = line_bot_api.create_rich_menu(rich_menu=milk_rich_menu)

with open("./image/milk-rich-menu.png", "rb") as f:
  line_bot_api.set_rich_menu_image(rich_menu_id, "image/png", f)
  line_bot_api.set_default_rich_menu(rich_menu_id)


@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)
rich_menu的本地列表
'''
rich_menu_array = ['rich_menu_0', 'rich_menu_1', 'rich_menu_2', 'rich_menu_3']

# 載入安全設定檔
secretFileContentJson = json.load(
    open("./line_secret_key", 'r', encoding='utf8'))
line_bot_api = LineBotApi(secretFileContentJson.get("channel_access_token"))

from linebot.models import RichMenu

for rich_menu_name in rich_menu_array:
    # 創建菜單,取得menuId
    lineRichMenuId = line_bot_api.create_rich_menu(
        rich_menu=RichMenu.new_from_json_dict(
            json.load(
                open("素材/" + rich_menu_name + '/rich_menu.json',
                     'r',
                     encoding='utf8'))))
    print("-設定檔上傳結果")
    print(lineRichMenuId)

    # id寫入本地端
    f = open("素材/" + rich_menu_name + "/rich_menu_id", "w", encoding='utf8')
    f.write(lineRichMenuId)
    f.close()

    # 上傳照片至該id
    set_image_response = ''
    with open("素材/" + rich_menu_name + '/rich_menu.jpg', 'rb') as f:
        set_image_response = line_bot_api.set_rich_menu_image(
            lineRichMenuId, 'image/jpeg', f)
Exemple #12
0
# print(res)

# create richmenu
rich_menu_to_create = RichMenu(
    size=RichMenuSize(width=2500, height=843),
    selected=True,
    name="none_room",
    chat_bar_text="メニューを開く・閉じる",
    areas=[
        RichMenuArea(bounds=RichMenuBounds(x=0, y=0, width=1250, height=843),
                     action=MessageAction(text='部屋を作る')),
        RichMenuArea(bounds=RichMenuBounds(x=1250, y=0, width=1250,
                                           height=843),
                     action=MessageAction(text='部屋に入る'))
    ])
rich_menu_id = line_bot_api.create_rich_menu(rich_menu=rich_menu_to_create)

# upload image
with open('static/none_room.png', 'rb') as f:
    line_bot_api.set_rich_menu_image(rich_menu_id, 'image/png', f)

print(f'richmenu_id = "{rich_menu_id}"')

# create richmenu
rich_menu_to_create = RichMenu(
    size=RichMenuSize(width=2500, height=843),
    selected=True,
    name="with_room",
    chat_bar_text="メニューを開く・閉じる",
    areas=[
        RichMenuArea(bounds=RichMenuBounds(x=0, y=0, width=1250, height=843),
Exemple #13
0
class TestLineBotApi(unittest.TestCase):

    maxDiff = None

    def setUp(self):
        self.tested = LineBotApi('channel_secret')

        self.rich_menu_id = 'richmenu-0000000000'
        self.user_id = 'userid'
        self.rich_menu = RichMenu(
                size=RichMenuBound(
                    width=2500,
                    height=1686
                ),
                selected=False,
                name="nice richmenu",
                chatBarText="touch me",
                areas=[
                    RichMenuArea(
                        RichMenuBound(
                            x=0,
                            y=0,
                            width=833,
                            height=843
                        ),
                        URITemplateAction(
                            uri='line://nv/location'
                        )
                    )
                ]
            )

    @responses.activate
    def test_delete_rich_menu(self):
        responses.add(
            responses.DELETE,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/{rich_menu_id}'.format(
                rich_menu_id=self.rich_menu_id
            ),
            json={}, status=200
        )

        self.tested.delete_rich_menu(self.rich_menu_id)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'DELETE')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/{rich_menu_id}'.format(
                rich_menu_id=self.rich_menu_id
            )
        )

    @responses.activate
    def test_link_rich_menu_to_user(self):
        responses.add(
            responses.POST,
            LineBotApi.DEFAULT_API_ENDPOINT +
            '/v2/bot/user/{user_id}/richmenu/{rich_menu_id}'.format(
                user_id=self.user_id,
                rich_menu_id=self.rich_menu_id
            ),
            json={}, status=200
        )

        self.tested.link_rich_menu_to_user(self.user_id, self.rich_menu_id)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT +
            '/v2/bot/user/{user_id}/richmenu/{rich_menu_id}'.format(
                user_id=self.user_id,
                rich_menu_id=self.rich_menu_id
            )
        )

    @responses.activate
    def test_unlink_rich_menu_from_user(self):
        responses.add(
            responses.DELETE,
            LineBotApi.DEFAULT_API_ENDPOINT +
            '/v2/bot/user/{user_id}/richmenu'.format(user_id=self.user_id),
            json={}, status=200
        )

        self.tested.unlink_rich_menu_from_user(self.user_id)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'DELETE')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT +
            '/v2/bot/user/{user_id}/richmenu'.format(user_id=self.user_id)
        )

    @responses.activate
    def test_get_rich_menu_id_of_user(self):
        responses.add(
            responses.GET,
            LineBotApi.DEFAULT_API_ENDPOINT +
            '/v2/bot/user/{user_id}/richmenu'.format(user_id=self.user_id),
            json={}, status=200
        )

        self.tested.get_rich_menu_id_of_user(self.user_id)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'GET')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT +
            '/v2/bot/user/{user_id}/richmenu'.format(user_id=self.user_id)
        )

    @responses.activate
    def test_get_rich_menu_list(self):
        responses.add(
            responses.GET,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/list',
            json={'richmenus': []}, status=200
        )

        self.tested.get_rich_menu_list()

        request = responses.calls[0].request
        self.assertEqual(request.method, 'GET')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/list'
        )

    @responses.activate
    def test_create_rich_menu(self):
        responses.add(
            responses.POST,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu',
            json={}, status=200
        )

        self.tested.create_rich_menu(self.rich_menu)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu'
        )
Exemple #14
0
def handler(event, context):
    """
    リッチメニューを作成します

    使用するサンプル画像は files/richmenu_tmp.png にあります(必要に応じて差し替えてください)
    コード中の座標・サイズの数値は、サンプル画像に合わせた数値となっています
    """

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

    # リッチメニューの作成
    rich_menu_to_create = RichMenu(
        size=RichMenuSize(width=2500, height=1658),
        selected=False,
        name="tmp richmenu",
        chat_bar_text="メニューはこちらをタップ",
        areas=[
            # 設定時間の確認
            RichMenuArea(
                bounds=RichMenuBounds(x=133, y=350, width=1400, height=300),
                action=PostbackAction(
                    display_text=None, 
                    label='設定時間の確認', 
                    data='action=check'
                )
            ),
            # 当日の通知時間(設定)
            RichMenuArea(
                bounds=RichMenuBounds(x=0, y=1033, width=625, height=625),
                action=DatetimePickerAction(
                    label='gomi_today', 
                    data='action=set&target=gomi_today', 
                    mode='time', 
                    initial='07:00', 
                    max='07:59', 
                    min='00:00'
                )
            ),
            # 当日の通知時間(削除)
            RichMenuArea(
                bounds=RichMenuBounds(x=625, y=1033, width=625, height=625),
                action=PostbackAction(
                    display_text=None, 
                    label='Postback action', 
                    data='action=remove&target=gomi_today'
                )
            ),
            # 前日の通知時間(設定)
            RichMenuArea(
                bounds=RichMenuBounds(x=1250, y=1033, width=625, height=625),
                action=DatetimePickerAction(
                    label='gomi_day_before', 
                    data='action=set&target=gomi_day_before', 
                    mode='time', 
                    initial='18:00', 
                    max='23:59', 
                    min='16:00'
                )
            ),
            # 前日の通知時間(削除)
            RichMenuArea(
                bounds=RichMenuBounds(x=1875, y=1033, width=625, height=625),
                action=PostbackAction(
                    display_text=None, 
                    label='Postback action', 
                    data='action=remove&target=gomi_day_before'
                )
            ),
            # フリースペース(例: テキストを出すだけ)
            RichMenuArea(
                bounds=RichMenuBounds(x=1667, y=0, width=833, height=833),
                action=MessageAction(label='hogehoge', text='hogehoge') 
            ),
            # フリースペース(例: アプリ内ブラウザで指定URLにアクセス)
            RichMenuArea(
                bounds=RichMenuBounds(x=1667, y=0, width=833, height=833),
                action=URIAction(label='URI', uri='https://heptagon.co.jp/')
            ),
        ]
    )

    new_richmenu_id = line_bot_api.create_rich_menu(rich_menu=rich_menu_to_create)

    # リッチメニュー用の画像をアップロード
    with open('files/richmenu_tmp.png', 'rb') as f:
        line_bot_api.set_rich_menu_image(new_richmenu_id, 'image/png', f)

    # リッチメニューをデフォルトに
    line_bot_api.set_default_rich_menu(new_richmenu_id)

    # デフォルトのリッチメニュー以外は削除する
    menu_list = line_bot_api.get_rich_menu_list()

    for menu in menu_list:
        if menu.rich_menu_id != new_richmenu_id:
            line_bot_api.delete_rich_menu(menu.rich_menu_id)

    return {
        "rich_menu_id": new_richmenu_id
    }
Exemple #15
0
app = Flask(__name__)

line_bot_api = LineBotApi(os.environ['LINE_BOT_TOKEN'])
handler = WebhookHandler(os.environ['LINE_BOT_SECRET'])

db_url = os.environ['DATABASE_URL']

# init

rich_menu_ids = {}
rich_menu_ids['main'] = line_bot_api.create_rich_menu(rich_menu=RichMenu(
    size=RichMenuSize(width=1200, height=600),
    selected=False,
    name="main",
    chat_bar_text="Tap here",
    areas=[
        RichMenuArea(bounds=RichMenuBounds(x=0, y=0, width=540, height=600),
                     action=MessageAction(text="即時狀態查詢")),
        RichMenuArea(bounds=RichMenuBounds(x=660, y=0, width=540, height=600),
                     action=MessageAction(text="登錄機器狀態"))
    ]))
with open("img/rich_menu/main.png", 'rb') as f:
    line_bot_api.set_rich_menu_image(rich_menu_ids['main'], 'image/png', f)
line_bot_api.set_default_rich_menu(rich_menu_ids['main'])


@app.route("/")
def root():
    return 'OK'