当前位置: 首页>>代码示例>>Python>>正文


Python Wit.message方法代码示例

本文整理汇总了Python中wit.Wit.message方法的典型用法代码示例。如果您正苦于以下问题:Python Wit.message方法的具体用法?Python Wit.message怎么用?Python Wit.message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在wit.Wit的用法示例。


在下文中一共展示了Wit.message方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: chat

# 需要导入模块: from wit import Wit [as 别名]
# 或者: from wit.Wit import message [as 别名]
def chat(bot, update):
    user_id = update.message.from_user.id
    answer = update.message.text

    if answer == 'О марафонах':
        text = "Марафоны - это круто!"
        bot.sendMessage(user_id, text=text, reply_markup=main_kbd)     
    elif answer == 'Категории':
        text = "Пока категории вопросов не созданы. Вы можете ввести вопрос самостоятельно"
        bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
    elif answer == 'Моя программа':
        text = "Подождите, какая еще программа? Вы же даже не знаете, что такое марафон. Сначала узнайте, а потом уже спрашивайте про программу!"
        bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
    elif answer == 'INFO':
        text = "Появление информации ожидается в скором времени"
        bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
    else:
        actions = dict()
        client = Wit(access_token=wit_token, actions=actions)
        client_answer = client.message(answer)
        try:
            if client_answer['entities']['intent'][0]['confidence'] < 0.6:
                text = "К сожалению, ответ на этот вопрос мне не известен. Попробуйте другой вопрос."
                bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
            else:
                codec = client_answer['entities']['intent'][0]['value']
                text = dictionary[codec]
                bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
        except KeyError:
            text = "К сожалению, ответ на этот вопрос мне не известен. Попробуйте другой вопрос."
            bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
开发者ID:EremeykinS,项目名称:MaraphonBot,代码行数:33,代码来源:bot.py

示例2: do

# 需要导入模块: from wit import Wit [as 别名]
# 或者: from wit.Wit import message [as 别名]
def do(text):
    witClient = Wit(access_token='Z2M5NG4DUAOD3IH24BNQSXGM4LGIK4PU')
    wolframClient = wolframalpha.Client('5G696A-TT6AEK7L74')
    response = witClient.message(text)
    intent = response['entities']['intent'][0]['value']
    if intent == 'weather':
        loc = Nominatim()
        loc = loc.geocode(response['entities']['location'][0]['value'])
        forecast = forecastio.load_forecast('17e86a360729736b727899a8135e33ad',loc.latitude, loc.longitude)
        return forecast.hourly().summary
    elif intent == 'greeting':
        return random.choice(greetings)
    elif intent == 'wikipedia':
        return wikipedia.summary(response['entities']['contact'][0]['value'], sentences=1)
    elif intent == 'curse':
        return 'Fuck you too!'
    else:
        return 'I did not understand what you said.'
开发者ID:thephantomblu,项目名称:jarvis,代码行数:20,代码来源:jarvis.py

示例3: open

# 需要导入模块: from wit import Wit [as 别名]
# 或者: from wit.Wit import message [as 别名]
from wit import Wit
import json

try:
    with open("config.json") as f :
        access_token = json.load(f)['witai']
except:
    print("open config.json error")

def send(request, response):
    print(response['text'])

actions = {
    'send': send,
}

client = Wit(access_token=access_token, actions=actions)
resp = client.message('Turn on the light in my bedroom')
print('Yay, got Wit.ai response: ' + str(resp))
开发者ID:sxwei123,项目名称:AIlightControl,代码行数:21,代码来源:witai.py

示例4: WitRos

# 需要导入模块: from wit import Wit [as 别名]
# 或者: from wit.Wit import message [as 别名]
class WitRos(object):
    def __init__(self, api_key):
        self.wit = Wit(api_key)
        self.pub = rospy.Publisher('stt', Outcome, queue_size=1)

    def start(self):
        rospy.Service('wit/interpret', Interpret, self.interpret)
        # rospy.Service('wit/listen_interpret', ListenAndInterpret, self.listen_and_interpret)

    def parse_response(self, response, klass):
        rospy.logdebug("Data: '{0}'".format(json.dumps(response, indent=4, separators=(',', ': '))))
        ros_entities = []

        if "WARNING" in response:
            rospy.logwarn("Response contains a warning: {warn}".format(warn=response["WARNING"]))

        outcome = None
        entities = []

        if "entities" in response:
            entities = response["entities"]
        elif "outcomes" in response:
            outcome = response["outcomes"][0]
            entities = outcome["entities"]

        for entity_name, entity_properties in entities.iteritems():
            entity_properties = entity_properties[0]
            rospy.logdebug("Entity '{name}' has properties{prop}".format(name=entity_name, prop=entity_properties))

            entity = Entity(name=str(entity_name))
            if 'type' in entity_properties:
                entity.type = str(entity_properties["type"])
            if 'value' in entity_properties:
                entity.value = str(entity_properties["value"])
            if 'unit' in entity_properties:
                entity.unit = str(entity_properties["unit"])
            if 'suggested' in entity_properties:
                entity.suggested = str(entity_properties["suggested"])
            if 'confidence' in entity_properties:
                entity.confidence = float(entity_properties["confidence"])
            rospy.logdebug("Adding {ent}".format(ent=entity))
            ros_entities += [entity]

        outcome = Outcome(entities = ros_entities,
                          intent   = str(outcome["intent"]) if outcome else None,
                          text     = str(response["_text"]))

        response = klass(   msg_body    = str(response),
                            msg_id      = str(response["msg_id"]),
                            outcome     = outcome)
        self.pub.publish(outcome)

        return response

    def interpret(self, rosrequest):
        sentence = rosrequest.sentence
        rospy.logdebug("Interpreting '{0}'".format(sentence))
        wit_response = self.wit.message(sentence)
        rospy.logdebug("WitResponse: {0}".format(wit_response))
        #response = json.loads(wit_response)
        #rospy.logdebug("Response: {0}".format(response))

        return self.parse_response(wit_response, InterpretResponse)
开发者ID:LoyVanBeek,项目名称:wit_ros,代码行数:65,代码来源:wit_node.py

示例5: ExternalApiParser

# 需要导入模块: from wit import Wit [as 别名]
# 或者: from wit.Wit import message [as 别名]
class ExternalApiParser(object):
    """
        This calls external APIs for responses.
        api.ai  for conversational queries
        wit.ai for entities and intents
            - each entity gets a confidence value from 0 to 1.
                "1 is extremely confident. Lower than 0.5 is considered very low confidence."
            - can add intents using api:
            https://wit.ai/docs/http/20160330#get-intent-via-text-link
            - self.actions : this is for merge and context functionality
    """

    def __init__(self, wit_key, rive, bot, nyt_api, mongo):
        self.BOT = bot
        self.NYT_API = nyt_api

        self.wit_actions = {}
        self.wit_client = Wit(access_token=wit_key, actions=self.wit_actions)
        self.wit_empty_response = {'entities': []}
        self.WIT_SEARCH_QUERY_CONFIDENCE_THRESH = 0.5

        self.RIVE = rive

        self.MONGO = mongo

        self.emojis = pickle.load(open("message_processor/unicode_emoji.pickle", "rb"))

    def wit_api_call(self, text):
        try:
            wit_response = self.wit_client.message(text)
        except WitError as we:
            print(we)
            # the Wit API call failed due to a WitError, so let's make the response empty
            wit_response = self.wit_empty_response

        wit_parsed_message = self.parse_wit_response(wit_response)
        return wit_parsed_message

    def parse_wit_response(self, wit_return_dict):
        """
            Takes a Wit response dict and converts into a WitParsedMessage object
        """

        wit_entities = wit_return_dict['entities']
        wit_parsed_message = WitParsedMessage()

        intent = None
        if 'intent' in wit_entities:
            intent = (wit_entities['intent'][0]['value'], wit_entities['intent'][0]['confidence'])
        wit_parsed_message.intent = intent

        search_queries = []
        if 'search_query' in wit_entities:
            for search_query in wit_entities['search_query']:
                search_queries.append((search_query['value'], search_query['confidence']))
        wit_parsed_message.search_queries = search_queries

        locations = []
        if 'location' in wit_entities:
            for loc in wit_entities['location']:
                locations.append((loc['value'], loc['confidence']))
        wit_parsed_message.locations = locations

        return wit_parsed_message

    def take_external_action(self, message_text, recipient_id, num_articles=3,
                             wit_parsed_message=None, rive_parsed_message=None):
        """
            Sends messages to the user.
            if Wit Parser finds intent, return on behalf of wit.ai
            else returns on behalf of api.ai
            else returns helper callback

            params:
                message_text: str or unicode
                recipient_id: str
                num_articles: int
                wit_parsed_message: WitParsedMessage
                api_ai_parsed_message: ApiAIParsedMessage - DEPRECATED
                rive_parsed_message: str

            returns:
                http response
        """

        # Search RIVE for a valid response
        if rive_parsed_message is None:
            # get user info from the db
            user = User()
            user_dict = self.MONGO.db.users.find_one({'recipient_id': recipient_id})

            if user_dict is None:
                # get user information from Facebook
                fb_user_profile_info = self.BOT.get_user_profile_info(recipient_id)
                user.set_user_dict(recipient_id, fb_user_profile_info, timestamp=int(time.time()))

                # write the user information to our database
                self.MONGO.db.users.insert_one(user.user_dict)
                user_dict = user.user_dict
            else:
#.........这里部分代码省略.........
开发者ID:innainu,项目名称:climatechangebot,代码行数:103,代码来源:message_processor.py


注:本文中的wit.Wit.message方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。