-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsmalltalkbot.py
226 lines (195 loc) · 8.9 KB
/
smalltalkbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# Backward compatibility
from errbot.version import VERSION
from errbot.utils import version2array
if version2array(VERSION) >= [1,6,0]:
from errbot import botcmd, BotPlugin
else:
from errbot.botplugin import BotPlugin
from errbot.jabberbot import botcmd
from myconfig import OpenWeatherMapAPIToken, forecastioAPIKey
import urllib
from pyquery import PyQuery as pq
import datetime
import time
import json
import requests
from pytz import timezone
__author__ = 'Tomas Nunez'
class SmalltalkBot(BotPlugin):
@botcmd
def weather(self, mess, args):
""" Tells the weather in a city
Example: !weather city
"""
#Docu en http://openweathermap.org/api
if not args:
return 'Which city do you want to check?'
args = args.strip()
cityToCheck = str(args)
if cityToCheck == "Uranus":
return "Mine is warm...What about yours?"
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=' + cityToCheck + '&APPID='+ OpenWeatherMapAPIToken +'&units=Metric')
cityFound = r.json()['name']
messagePrefix = ""
if( cityToCheck != cityFound ):
messagePrefix = "The closest city I have data for is " + cityFound + ". "
return messagePrefix + 'According to openweathermap, the weather in ' + cityFound + ' is: ' + r.json()['weather'][0]['description'] + ' and temperature is ' + str(r.json()['main']['temp']) + ' Celsius'
@botcmd
def time(self, mess, args):
""" Tells the time in a city
Example: !time city
"""
if not args:
return 'Which city do you want to check?'
args = args.strip()
if str(args) == "Uranus":
return "Mine is well...What about in yours?"
maps_search = requests.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + str(args) + '&sensor=false')
city_tz = requests.get('https://maps.googleapis.com/maps/api/timezone/json?location=' + str(maps_search.json()["results"][0]["geometry"]["location"]["lat"]) + ',' + str(maps_search.json()["results"][0]["geometry"]["location"]["lng"]) + '×tamp=' + str(int(time.time())) + '&sensor=false')
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
return "I'm guessing you are asking for " + maps_search.json()['results'][0]['formatted_address'] + ". The timezone is " + city_tz.json()['timeZoneName'] + " and time there is " + datetime.datetime.now(timezone(city_tz.json()['timeZoneId'])).strftime(fmt)
@botcmd(split_args_with=None)
def location_setother(self, mess, args):
""" Sets location for another user
Example: !location setother Tomas Jaipur"
"""
if len(args) <= 1:
yield "You need a user AND a location"
return "Example: !location setother Tomas Jaipur"
requester = str(mess.frm)
user = args[0].strip().title()
user_location = " ".join(args[1:]).title()
users = self['users']
if user in self['nicknames']:
user = self['nicknames'][user]
yield "Ok, " + requester + ", trying to set "+ user + " location to " + user_location
try:
users[user] = user_location
self['users'] = users
except Exception:
raise "I can't update that user"
return "Done!"
@botcmd
def location_set(self, mess, args):
""" Sets your location
Example: !location set Jaipur"
"""
requester = str(mess.frm.resource).title()
users = self['users']
user_location = args.strip().title()
if requester in self['nicknames']:
requester = self['nicknames'][requester]
yield "Ok, " + requester + ", trying to set your location to " + user_location
try:
users[requester]=user_location
self['users'] = users
except KeyError:
raise "I can't update that user"
return "Done!"
@botcmd
def location_get(self, mess, args):
""" Gets the location for a user
Example: !location get Tomas"
"""
user = args.strip().title()
if user in self['users']:
return "Location for user " + user + " is " + self['users'][user]
else:
if user in self['nicknames']:
username = self['nicknames'][user]
return "User " + user + " is a nickname for " + username + ". Location for user " + username + " is " + self['users'][username]
else:
return "I have no record for user " + user
@botcmd
def smalltalk(self, mess, args):
""" Gives you a small amount of information to start smalltalk with someone
Example: !smalltalk Tomas
"""
user = args.strip().title()
if user in self['users']:
pass
else:
if user in self['nicknames']:
user = self['nicknames'][user]
else:
return "I have no record for user " + user
try:
user_location = self['users'][user]
yield "Location for user " + user + " is " + user_location
maps_search = requests.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + user_location + '&sensor=false')
location_latitude = maps_search.json()["results"][0]["geometry"]["location"]["lat"]
location_longitude = maps_search.json()["results"][0]["geometry"]["location"]["lng"]
city_tz = requests.get('https://maps.googleapis.com/maps/api/timezone/json?location=' + str(location_latitude) + ',' + str(location_longitude) + '×tamp=' + str(int(time.time())) + '&sensor=false')
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
yield maps_search.json()['results'][0]['formatted_address'] + " is in " + city_tz.json()['timeZoneName'] + " timezone, and now it's " + datetime.datetime.now(timezone(city_tz.json()['timeZoneId'])).strftime(fmt) + " there."
openweathermap = requests.get('http://api.openweathermap.org/data/2.5/weather?q=' + user_location + '&APPID='+ OpenWeatherMapAPIToken +'&units=Metric')
yield 'The closest city I have data is ' + openweathermap.json()['name'] + ' and according to openweathermap, weather is: ' + openweathermap.json()['weather'][0]['description'] + ' and temperature is ' + str(openweathermap.json()['main']['temp']) + ' Celsius'
forecastio = requests.get('https://api.forecast.io/forecast/' + forecastioAPIKey +'/' + str(location_latitude) + ',' + str(location_longitude) + '?units=si')
yield 'According to forecast.io, it\'s ' + forecastio.json()['currently']['summary'] + ' and temperature is ' + str(forecastio.json()['currently']['temperature']) + ' Celsius'
# return "Done!"
except KeyError:
yield "I have no record for user "
@botcmd
def user_del(self, mess, args):
""" Delete location for a user
Example: !user del tomas
"""
user = args.strip().title()
users = self['users']
try:
del users[user]
self['users'] = users
return "User "+ user + " deleted successfully"
except KeyError:
raise "There's no user " + user +" in the database"
@botcmd
def user_list(self, mess, args):
""" Lists all available users
Example: !user list
"""
return self['users']
@botcmd(split_args_with=None)
def nick_add(self, mess, args):
""" Assigns a nickname to a name
Example: !nick add name nickname
"""
if len(args) <= 1:
yield "You need a user AND a nickname"
return "Example: !nick add nunez Tomas"
nicknames = self['nicknames']
users = self['users']
user = args[0].strip().title()
nickname = " ".join(args[1:]).strip().title()
yield "Username " + user + " and nickname " + nickname
if user in users:
pass
else:
yield "Error. User " + user + " doesn't exist in users table"
return
if nickname in nicknames:
yield "Warning: Nickname " + nickname + " was already there with value " + nicknames[nickname] + ". Overwriting..."
nicknames[nickname] = user
self['nicknames'] = nicknames
@botcmd
def nick_list(self, mess, args):
""" Lists all available nicknames
Example: !nick list
"""
return self['nicknames']
@botcmd
def nick_del(self, mess, args):
""" Deletes a nickname
Example: !nick del nickname
"""
nick = args.strip().title()
nicknames = self['nicknames']
try:
del nicknames[nick]
self['nicknames'] = nicknames
return "Nickname " + nick + " deleted successfully"
except KeyError:
raise "There's no nickname " + nick + " in the database"
# @botcmd
# def user_init(self, mess, args):
# self['users'] = {}
# self['nicknames'] = {}