forked from mustafababil/Telegram-Weather-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
responseController.py
194 lines (143 loc) · 6.59 KB
/
responseController.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
import urllib
import urllib2
import json
import StringIO
# standard app engine imports
import logging
# Openweathermap Weather codes and corressponding emojis
thunderstorm = u'\U0001F4A8' # Code: 200's, 900, 901, 902, 905
drizzle = u'\U0001F4A7' # Code: 300's
rain = u'\U00002614' # Code: 500's
snowflake = u'\U00002744' # Code: 600's snowflake
snowman = u'\U000026C4' # Code: 600's snowman, 903, 906
atmosphere = u'\U0001F301' # Code: 700's foogy
clearSky = u'\U00002600' # Code: 800 clear sky
fewClouds = u'\U000026C5' # Code: 801 sun behind clouds
clouds = u'\U00002601' # Code: 802-803-804 clouds general
hot = u'\U0001F525' # Code: 904
defaultEmoji = u'\U0001F300' # default emojis
###
TOKEN = '58737283:AAGB3v1c27r_rgsur5nCfc53gndhKg9iR_8'
BASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/'
WEATHER_BASE_URL = 'http://api.openweathermap.org/data/2.5/weather?'
WEATHER_API_KEY = '04f9cff3a5fbb8c457e31444bae05328'
WEATHER_CITY_NAME = 'q='
WEATHER_CITY_LAT = 'lat='
WEATHER_CITY_LNG = 'lon='
WEATHER_UNIT = 'metric'
WEATHER_DAY_CNT = 1
degree_sign= u'\N{DEGREE SIGN}'
################################################
"""
Handles location inputs.
Parses Openweathermap @response and sends the information to user at specified @chat_id
"""
def locationInputHandler(chat_id, response):
resultCode = response.get('cod')
if resultCode == 200: # Success city found
cityName = response.get('name')
countryName = response.get('sys').get('country')
temp_current = response.get('main').get('temp')
temp_max = response.get('main').get('temp_max')
temp_min = response.get('main').get('temp_min')
description = response.get('weather')[0].get('description')
description_brief = response.get('weather')[0].get('main')
weatherID = response.get('weather')[0].get('id') # gets ID of weather description, used for emoji
emoji = getEmoji(weatherID)
message = cityName + ', ' + countryName + ': ' + str(temp_current) + degree_sign + 'C\n' + 'Max: ' + str(temp_max) + degree_sign + 'C - ' + 'Min: ' + str(temp_min) + degree_sign + 'C\n' + description_brief + ' - ' + description + emoji + emoji
sendTextMessage(chat_id, message)
else: # Not found city
errorCode = response.get('message')
sendTextMessage(chat_id, str(resultCode) + ' - ' + errorCode)
"""
Location input request
Makes request to Openweathermap to fetch weathercast
"""
def locationInputRequest(latitude, longitude):
if not latitude or not longitude:
logging.warning('Error: - responseController.locationInputRequest: No lat or lng input')
try:
urlEncodePairs = { 'lat': str(latitude), 'lon': str(longitude), 'APPID': WEATHER_API_KEY, 'units': WEATHER_UNIT, 'cnt': WEATHER_DAY_CNT }
encodedURL = urllib.urlencode(urlEncodePairs)
WEATHER_URL_COORD = WEATHER_BASE_URL + encodedURL
weatherResponse = json.load(urllib2.urlopen(WEATHER_URL_COORD))
return weatherResponse
except Exception, e:
logging.warning('Error: - responseController.locationInputRequest: ' + str(e))
"""
Text response handler
Parses Openweathermap @response and sends the information to user at specified @chat_id
"""
def textInputHandler(chat_id, response):
resultCode = response['cod']
if resultCode == 200: # Success city found
cityName = response.get('name')
countryName = response.get('sys').get('country')
temp_current = response.get('main').get('temp')
temp_max = response.get('main').get('temp_max')
temp_min = response.get('main').get('temp_min')
description = response.get('weather')[0].get('description')
description_brief = response.get('weather')[0].get('main')
weatherID = response.get('weather')[0].get('id') # gets ID of weather description, used for emoji
emoji = getEmoji(weatherID)
message = cityName + ', ' + countryName + ': ' + str(temp_current) + degree_sign + 'C\n' + 'Max: ' + str(temp_max) + degree_sign + 'C - ' + 'Min: ' + str(temp_min)+ degree_sign + 'C\n' + description_brief + ' - ' + description + emoji + emoji
sendTextMessage(chat_id, message)
else: # Not found city
errorCode = response.get('message')
sendTextMessage(chat_id, str(resultCode) + ' - ' + errorCode)
"""
Text input request
Makes request to Openweathermap to fetch weathercast
"""
def textInputRequest(text):
if not text:
logging.warning('Error: - responseController.textInputRequest: No text input')
try:
urlEncodePairs = { 'q': text, 'APPID': WEATHER_API_KEY, 'units': WEATHER_UNIT, 'cnt': WEATHER_DAY_CNT }
encodedURL = urllib.urlencode(urlEncodePairs)
WEATHER_URL_TEXT = WEATHER_BASE_URL + encodedURL
weatherResponse = json.load(urllib2.urlopen(WEATHER_URL_TEXT))
return weatherResponse
except Exception as e:
logging.warning('Error: - responseController.textInputRequest: ' + str(e))
"""
Send text message to user
"""
def sendTextMessage(chat_id, text=None):
if(not chat_id or not text):
logging.warning('chat_id or text is not entered')
try:
message = urllib.urlencode({ 'chat_id': format(chat_id), 'text': text.encode('utf-8', 'strict'), 'disable_web_page_preview': True })
response = urllib.urlopen(BASE_URL + 'sendMessage', message.encode('utf-8'))
logging.info('send response:')
logging.info(response.read())
except Exception as e:
logging.warning('Error - responseController.sendTextMessage: ' + str(e))
return
"""
Return related emojis according to weather
"""
def getEmoji(weatherID):
if weatherID:
if str(weatherID)[0] == '2' or weatherID == 900 or weatherID==901 or weatherID==902 or weatherID==905:
return thunderstorm
elif str(weatherID)[0] == '3':
return drizzle
elif str(weatherID)[0] == '5':
return rain
elif str(weatherID)[0] == '6' or weatherID==903 or weatherID== 906:
return snowflake + ' ' + snowman
elif str(weatherID)[0] == '7':
return atmosphere
elif weatherID == 800:
return clearSky
elif weatherID == 801:
return fewClouds
elif weatherID==802 or weatherID==803 or weatherID==803:
return clouds
elif weatherID == 904:
return hot
else:
return defaultEmoji # Default emoji
else:
return defaultEmoji # Default emoji