Google App EngineのPythonで無料でLINE Botを作るというチャレンジをしているのですが、GitHubで公開されているLineのline-bot-sdk-pythonがflask前提となっていたので、flaskを使わないようなプログラムがほしいなと思い、急遽自作することに。
そこで、今回は、Template ActionのPostback Actionを作るメソッドを書きたいと思います。
linebot.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class LineTemplateActionClass(object):
def __init__(self):
pass
@classmethod
def postbackAction(cls,label,data,text):
_label = label
_label_max_length = 20
_text = text
_text_max_length = 300
_data = data
_data_max_length = 300
#string型ではない場合
if not isinstance(_label,unicode):
return None
#20文字より大きい場合は、20文字に変更する
if len(_label) > _label_max_length:
_label = _label[0:_label_max_length]
#string型ではない場合
if not isinstance(_text,unicode):
return None
#20文字より大きい場合は、20文字に変更する
if len(_text) > _text_max_length:
_text = _text[0:_text_max_length]
#string型ではない場合
if not isinstance(_data,unicode):
return None
#20文字より大きい場合は、20文字に変更する
if len(_data) > _data_max_length:
_data = _data[0:_data_max_length]
return {
"type":"postback",
"label":_label,
"text":_text,
"data":_data
}
@classmethod
def uriAction(cls,label,uri):
_label = label
_label_max_length = 20
_uri = uri
_uri_max_length = 1000
#string型ではない場合
if not isinstance(_label,unicode):
return None
#20文字より大きい場合は、20文字に変更する
if len(_label) > _label_max_length:
_label = _label[0:_label_max_length]
#string型ではない場合
if not isinstance(uri,unicode):
return None
#1000文字より大きい場合は Noneを返す
if len(_uri) > _uri_max_length:
return None
return {
"type":"uri",
"label":_label,
"uri":_uri
}
@classmethod
def messageAction(cls,label,text):
_label = label
_label_max_length = 20
_text = text
_text_max_length = 300
#string型ではない場合
if not isinstance(_label,unicode):
return None
#20文字より大きい場合は、20文字に変更する
if len(_label) > _label_max_length:
_label = _label[0:_label_max_length]
#string型ではない場合
if not isinstance(_text,unicode):
return None
#20文字より大きい場合は、20文字に変更する
if len(_text) > _text_max_length:
_text = _text[0:_text_max_length]
return {
"type":"message",
"label":_label,
"text":_text
}
使い方は、from linebot import LineTemplateActionClass hoge = LineTemplateActionClass.postbackAction(u"ラベル",u"foo",u"hoge") print hoge
0 コメント:
コメントを投稿