예제 #1
0
    def __init__(self,
                 bot=None,
                 *,
                 debug=False,
                 application_id=None,
                 default_language=None,
                 **kwargs):
        """
        Parameters
        ----------
        bot : minette.Minette, default None
            Instance of Minette.
            If None, create new instance of Minette by using `**kwargs`
        application_id : str or None, default None
            Application ID for your Clova Skill
        default_language : str or None, default None
            Default language. ("en" / "ja" / "ko")
            If None, "ja" is set to Clova Extensions Kit API object
        debug : bool, default False
            Debug mode
        """
        super().__init__(bot=bot, threads=0, debug=debug, **kwargs)
        self.application_id = application_id or \
            self.config.get(section="clova_cek", key="application_id")
        self.default_language = default_language or \
            self.config.get(section="clova_cek", key="default_language") or "ja"
        self.clova = Clova(application_id=self.application_id,
                           default_language=self.default_language,
                           debug_mode=debug)

        # handler for all types of request
        @self.clova.handle.default
        def default(clova_request):
            return clova_request
예제 #2
0
 def test_wrong_language(self):
     # Tets builders
     for lang in ["es", "jp"]:
         with self.assertRaises(ValueError):
             clova.response(cek.Message("Hola", lang))
         with self.assertRaises(ValueError):
             Clova(application_id="",
                   default_language=lang,
                   debug_mode=True)
예제 #3
0
import os
from flask import request
from cek import Clova

# clova application_id
application_id = os.environ["APPLICATION_ID"]
# Set debug_mode=True if you are testing your extension. If True, this disables request verification
clova = Clova(application_id=application_id,
              default_language="ja",
              debug_mode=False)

hintList = ['モンゲー', '非日常', 'まり、、、なんとか']


class LineBotController:
    def action(request):

        resp = clova.route(request.data, request.headers)
        resp = jsonify(resp)
        # make sure we have correct Content-Type that CEK expects
        resp.headers['Content-Type'] = 'application/json;charset-UTF-8'
        return resp


# ----------------------------------------------
# メッセージを受信
@clova.handle.launch
def launch_request_handler(clova_request):
    return clova.response("こんにちは世界。スキルを起動します")

예제 #4
0
logger.setLevel(logging.DEBUG)

# Flask
app = Flask(__name__)

# Clova
application_id = os.environ.get('CLOVA_APPLICATION_ID')
channel_secret = os.environ.get('CHANNEL_SECRET')
channel_access_token = os.environ.get('CHANNEL_ACCESS_TOKEN')
channel_push_url = os.environ.get('CHANNEL_PUSH_URL')
log_push_user_token = os.environ.get('LOG_PUSH_USER_TOKEN')
channel_reply_url = os.environ.get('CHANNEL_REPLY_URL')
yeahma10_table = os.environ.get('DYNAMO_YEAHMA10_TABLE')
topic_arn = os.environ.get('SNS_TOPIC_ARN') 
clova = Clova(
            application_id=application_id,
            default_language='ja',
            debug_mode=True)
speech_builder = SpeechBuilder(default_language='ja')
response_builder = ResponseBuilder(default_language='ja')
resp_attributes = {}
debugbot = False
debuglog = False

#mp3
drumrole_mp3 = "http://ikegami.tokyo/wp-content/uploads/2018/10/tympani-roll1.mp3"
question_mp3 = "http://ikegami.tokyo/wp-content/uploads/2018/10/question1.mp3"
correct_mp3 = "http://ikegami.tokyo/wp-content/uploads/2018/10/correct2.mp3"
incorrect_mp3 = "http://ikegami.tokyo/wp-content/uploads/2018/10/incorrect1.mp3"

# Quiz
import data
예제 #5
0
class ClovaAdapter(Adapter):
    """
    Adapter for Clova Extensions Kit

    Attributes
    ----------
    bot : minette.Minette
        Instance of Minette
    application_id : str
        Application ID of Clova Skill
    default_language : str
        Default language of Clova Skill
    clova : Clova
        Clova Extensions Kit API
    config : minette.Config
        Configuration
    timezone : pytz.timezone
        Timezone
    logger : logging.Logger
        Logger
    debug : bool
        Debug mode
    """
    def __init__(self,
                 bot=None,
                 *,
                 debug=False,
                 application_id=None,
                 default_language=None,
                 **kwargs):
        """
        Parameters
        ----------
        bot : minette.Minette, default None
            Instance of Minette.
            If None, create new instance of Minette by using `**kwargs`
        application_id : str or None, default None
            Application ID for your Clova Skill
        default_language : str or None, default None
            Default language. ("en" / "ja" / "ko")
            If None, "ja" is set to Clova Extensions Kit API object
        debug : bool, default False
            Debug mode
        """
        super().__init__(bot=bot, threads=0, debug=debug, **kwargs)
        self.application_id = application_id or \
            self.config.get(section="clova_cek", key="application_id")
        self.default_language = default_language or \
            self.config.get(section="clova_cek", key="default_language") or "ja"
        self.clova = Clova(application_id=self.application_id,
                           default_language=self.default_language,
                           debug_mode=debug)

        # handler for all types of request
        @self.clova.handle.default
        def default(clova_request):
            return clova_request

    def handle_http_request(self, request_data, request_headers):
        """
        Interface to chat with Clova Skill

        Parameters
        ----------
        request_data : bytes
            Request data from Clova as bytes
        request_headers : dict
            Request headers from Clova as dict

        Returns
        -------
        response : Response
            Response from chatbot. Send back `json` attribute to Clova API
        """
        clova_request = self.clova.route(request_data, request_headers)
        return self.handle_event(clova_request)

    def handle_event(self, clova_request):
        # execute bot
        channel_messages, _ = super().handle_event(clova_request)

        # print response for debug
        for msg in channel_messages:
            if self.debug:
                self.logger.info(msg)
            else:
                self.logger.info("Minette> {}".format(msg["speech_value"]))

        # build response message
        speech_values = [msg["speech_value"] for msg in channel_messages]
        end_session = channel_messages[-1]["end_session"]
        reprompt = channel_messages[-1]["reprompt"]
        if len(speech_values) == 1:
            return dumps(
                self.clova.response(speech_values[0],
                                    end_session=end_session,
                                    reprompt=reprompt))
        else:
            return dumps(
                self.clova.response(speech_values,
                                    end_session=end_session,
                                    reprompt=reprompt))

    @staticmethod
    def _to_minette_message(clova_request):
        """
        Convert ClovaRequest object to Minette Message object

        Parameters
        ----------
        clova_request : cek.Request
            Request from clova

        Returns
        -------
        message : minette.Message
            Request converted into Message object
        """
        msg = Message(type=clova_request.type,
                      channel="LINE",
                      channel_detail="Clova",
                      channel_user_id=clova_request.session.user.id
                      if clova_request.session._session else "",
                      channel_message=clova_request)

        # Set intent and entities when IntentRequest
        if isinstance(clova_request, IntentRequest):
            msg.intent = clova_request.name
            # if clova_request.slots: <- Error occures when no slot values
            if clova_request._request["intent"]["slots"]:
                msg.entities = clova_request.slots
        return msg

    @staticmethod
    def _to_channel_message(message):
        """
        Convert Minette Message object to LINE SendMessage object

        Parameters
        ----------
        response : Message
            Response message object

        Returns
        -------
        response : SendMessage
            SendMessage object for LINE Messaging API
        """
        return {
            "speech_value":
            URL(message.text) if message.type == "url" else message.text,
            "end_session":
            message.entities.get("end_session", True),
            "reprompt":
            message.entities.get("reprompt", None)
        }
예제 #6
0
#   https://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.

import unittest
from cek import Clova
import cek

from data.requests import LAUNCH_REQUEST_BODY, INTENT_REQUEST_BODY, END_REQUEST_BODY, DEFAULT_REQUEST_BODY, GUIDE_REQUEST_BODY, NO_REQUEST_BODY

clova = Clova(application_id="com.line.myApplication",
              default_language="en",
              debug_mode=True)

mocked_header = {"": ""}


@clova.handle.launch
def launch_request_handler(clova_request):
    return clova.response("Hello! Welcome to my Service!")


@clova.handle.intent("TurnOn")
def turn_on_handler(clova_request):
    return clova.response(message="Turned on Something!",
                          reprompt="Reprompt Message.")
예제 #7
0
# coding:utf-8
from flask import Flask, request, jsonify
import os
from cek import Clova
import datetime

app = Flask(__name__)

application_id = os.environ.get("APPLICATION_ID")
clova = Clova(application_id, debug_mode=True)


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


@app.route('/app', methods=['POST'])
def my_service():
    resp = clova.route(request.data, request.headers)
    resp = jsonify(resp)
    resp.headers['Content-Type'] = 'application/json;charset-UTF-8'
    return resp


@clova.handle.launch
def launch_request_handler(clova_request):
    return clova.response("こんにちは世界。スキルを起動します")


@clova.handle.default