So in the GroupMe Bot I'm working on - I've gotten the bot to respond by passing messages with an if statement in the webhooks.
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())
Now below is the function for get_weather
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'])
If a phrase is "in message['text']" it will trigger an action because it is in the message.
What if I was trying to get it to parse this message.
"Whats the weather in Austin this weekend"
The key part of that phrase is "weather in Austin"
So I want to take the word after "in" and parse that to get_weather(city)
Expected workflow: person in chat says phrase with "weather in {CITY}" in the message bot triggers, filters city out of the string to call get_weather function
You coud use regular expression for that but that's not so obvious. The case you described is easily catched by
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
But not all the cities have the name of one word. So the trick is to tell when does the city name end ands "the rest of the sentence" begins. You can rely for example that all words starting with capital letters are part of the city name
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
But as it's a chat bot you're trying to create, well, how many people bother themselves to use capital letters and punctuation in chats?..
So you would probably need to align with some predefined list of city names (it shouldn't be that big I suppose) after your captured what you suppose to be a city name.