首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Groupme Bot中通过从JSON消息请求中传递变量调用函数

在Groupme Bot中通过从JSON消息请求中传递变量调用函数
EN

Stack Overflow用户
提问于 2018-05-02 20:34:38
回答 1查看 108关注 0票数 0

因此,在我正在开发的GroupMe机器人中,我让机器人通过在webhooks中传递消息来响应。

代码语言:javascript
复制
def webhook():

# 'message' is an object that represents a single GroupMe message.
message = request.get_json()
speaker = message['name'] 


# If hypefact! is spoken, return random fact
# This code replies once and then calls another function that replies again
if 'hypefact!' in message['text'].lower() and not sender_is_bot(message):
    reply(speaker + ' - Here is your Hype Fact: ')
    reply(fact_delivery())

下面是get_weather的函数

代码语言:javascript
复制
def get_weather(city):

## Bunch of stuff happens

reply(weatherData['currently']['summary'] + ', ' + str(
    weatherData['currently']['apparentTemperature']) + degree_sign + 'F. ' + weatherData['hourly'][
          'summary'] + '\n\n' + weatherData['daily']['summary'])

如果一个短语是"in message‘’text‘“,它将触发一个动作,因为它在消息中。

如果我想让它解析这条信息。

“这个周末奥斯汀的天气怎么样?”

这句话的关键部分是“奥斯汀的天气”。

所以我想把"in“后面的单词解析为get_weather(城市)

预期工作流程:聊天人员在message触发器中用“天气在{ city }”表示短语,从字符串中筛选出城市以调用get_weather函数

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-02 20:54:02

您可以使用正则表达式,但这并不明显。你描述的这个案子很容易被抓住。

代码语言:javascript
复制
import re

text = "Whats the weather in Austin this weekend"
match = re.search('[Ww]eather in (?P<city>\w+)', text)

if match:
    print(match.groupdict())  #  {'city': 'Austin'}
else:
    pass # the text does not contain "weather in {CITY}" pattern

但并不是所有的城市都有一个词的名字。所以,诀窍是告诉城市的名字何时结束和“其余的句子”开始。例如,您可以依赖以大写字母开头的所有单词都是城市名称的一部分。

代码语言:javascript
复制
text2 = "Whats the weather in New York this weekend"
match2 = re.search('[Ww]eather in (?P<city>([A-Z]\w+\W+)+)', text2)

if match2:
    print(match2.groupdict())  #  {'city': 'New York '}
else:
    pass # the text does not contain "weather in {CITY}" pattern

但是当你想创造一个聊天机器人的时候,有多少人会在聊天中使用大写字母和标点符号呢?

因此,您可能需要在捕获到的城市名称之后,与一些预定义的城市名称列表(我认为不应该太大)对齐。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50143155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档