本文整理匯總了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)
示例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.'
示例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))
示例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)
示例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:
#.........這裏部分代碼省略.........