-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
221 lines (189 loc) · 8.45 KB
/
main.py
File metadata and controls
221 lines (189 loc) · 8.45 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
Basic example for a bot that uses inline keyboards.
"""
import logging,requests,json,os,datetime,pytz
from telegram import InlineKeyboardButton, InlineKeyboardMarkup,ParseMode,TelegramError
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler,MessageHandler,Filters
from time import sleep
##鍵盤設定
keyboardNow = [
[
InlineKeyboardButton("宜蘭縣", callback_data='宜蘭縣 now'),
InlineKeyboardButton("花蓮縣", callback_data='花蓮縣 now'),
InlineKeyboardButton("臺東縣", callback_data='臺東縣 now'),
],
[
InlineKeyboardButton("澎湖縣", callback_data='澎湖縣 now'),
InlineKeyboardButton("金門縣", callback_data='金門縣 now'),
InlineKeyboardButton("連江縣", callback_data='連江縣 now'),
],
[
InlineKeyboardButton("臺北市", callback_data='臺北市 now'),
InlineKeyboardButton("新北市", callback_data='新北市 now'),
InlineKeyboardButton("桃園市", callback_data='桃園市 now'),
],
[
InlineKeyboardButton("臺中市", callback_data='臺中市 now'),
InlineKeyboardButton("臺南市", callback_data='臺南市 now'),
InlineKeyboardButton("高雄市", callback_data='高雄市 now'),
],
[
InlineKeyboardButton("基隆市", callback_data='基隆市 now'),
InlineKeyboardButton("新竹縣", callback_data='新竹縣 now'),
InlineKeyboardButton("新竹市", callback_data='新竹市 now'),
],
[
InlineKeyboardButton("苗栗縣", callback_data='苗栗縣 now'),
InlineKeyboardButton("彰化縣", callback_data='彰化縣 now'),
InlineKeyboardButton("南投縣", callback_data='南投縣 now'),
],
[
InlineKeyboardButton("雲林縣", callback_data='雲林縣 now'),
InlineKeyboardButton("嘉義縣", callback_data='嘉義縣 now'),
InlineKeyboardButton("嘉義市", callback_data='嘉義市 now'),
InlineKeyboardButton("屏東縣", callback_data='屏東縣 now'),
],
]
keyboardNotify = [
[
InlineKeyboardButton("宜蘭縣", callback_data='宜蘭縣 notify'),
InlineKeyboardButton("花蓮縣", callback_data='花蓮縣 notify'),
InlineKeyboardButton("臺東縣", callback_data='臺東縣 notify'),
],
[
InlineKeyboardButton("澎湖縣", callback_data='澎湖縣 notify'),
InlineKeyboardButton("金門縣", callback_data='金門縣 notify'),
InlineKeyboardButton("連江縣", callback_data='連江縣 notify'),
],
[
InlineKeyboardButton("臺北市", callback_data='臺北市 notify'),
InlineKeyboardButton("新北市", callback_data='新北市 notify'),
InlineKeyboardButton("桃園市", callback_data='桃園市 notify'),
],
[
InlineKeyboardButton("臺中市", callback_data='臺中市 notify'),
InlineKeyboardButton("臺南市", callback_data='臺南市 notify'),
InlineKeyboardButton("高雄市", callback_data='高雄市 notify'),
],
[
InlineKeyboardButton("基隆市", callback_data='基隆市 notify'),
InlineKeyboardButton("新竹縣", callback_data='新竹縣 notify'),
InlineKeyboardButton("新竹市", callback_data='新竹市 notify'),
],
[
InlineKeyboardButton("苗栗縣", callback_data='苗栗縣 notify'),
InlineKeyboardButton("彰化縣", callback_data='彰化縣 notify'),
InlineKeyboardButton("南投縣", callback_data='南投縣 notify'),
],
[
InlineKeyboardButton("雲林縣", callback_data='雲林縣 notify'),
InlineKeyboardButton("嘉義縣", callback_data='嘉義縣 notify'),
InlineKeyboardButton("嘉義市", callback_data='嘉義市 notify'),
InlineKeyboardButton("屏東縣", callback_data='屏東縣 notify'),
],
]
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
##查詢縣市目前往後推36小時的溫度資料
def now(update, context):
reply_markup = InlineKeyboardMarkup(keyboardNow)
update.message.reply_text('請選擇要查詢的區域:', reply_markup=reply_markup)
##now按下按鈕事件
def nowCallback(update, context):
query = update.callback_query
# CallbackQueries need to be answered, even if no notification to the user is needed
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
query.edit_message_text(text=getTempStr(query.data.split(" ")[0]),parse_mode=ParseMode.HTML)
##排程
def dailyTemp(context):
job = context.job
context.bot.send_message(job.context[0], text=getTempStr(job.context[1]),parse_mode=ParseMode.HTML)
##設定每天早上六點要通知哪個縣市的溫度資料
def notify(update, context):
reply_markup = InlineKeyboardMarkup(keyboardNotify)
update.message.reply_text('請選擇要設定的區域:', reply_markup=reply_markup)
##notify按下按鈕事件
def notifyCallback(update, context):
query = update.callback_query
query.answer()
chat_id = query.message.chat.id
remove_job_if_exists(str(chat_id), context)
context.job_queue.run_daily(dailyTemp, datetime.time(8,30,tzinfo=pytz.timezone('Asia/Taipei')), context=[chat_id,query.data.split(" ")[0]], name=str(chat_id))
query.edit_message_text('設定完成')
##移除原本存在的排程
def remove_job_if_exists(name, context):
"""Remove job with given name. Returns whether job was removed."""
current_jobs = context.job_queue.get_jobs_by_name(name)
for job in current_jobs:
job.schedule_removal()
##取得回覆字串
def getTempStr(city):
rs = requests.session()
res = rs.get("https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization={}&locationName={}".format(os.getenv("WEATHER_TOKEN"),city))
rsJson = json.loads(res.text)
desc = rsJson["records"]["datasetDescription"]
weatherElementList = rsJson["records"]["location"][0]["weatherElement"]
text = "<b>目前區域</b>\n" + city+desc+"\n\n"
for weatherElement in weatherElementList:
if(weatherElement["elementName"] == "Wx"):
text += "<b>天氣現象</b>\n"
elementType = "a"
elif (weatherElement["elementName"] == "PoP"):
text += "<b>降雨機率</b>\n"
elementType = "b"
elif (weatherElement["elementName"] == "MinT"):
text += "<b>最低溫</b>\n"
elementType = "b"
elif (weatherElement["elementName"] == "CI"):
text += "<b>舒適度</b>\n"
elementType = "a"
elif (weatherElement["elementName"] == "MaxT"):
text += "<b>最高溫</b>\n"
elementType = "b"
if(elementType == "a"):
for item in weatherElement["time"]:
text += item["startTime"] + " <b>" + item["parameter"]["parameterName"]+"</b>\n"
else:
for item in weatherElement["time"]:
text += item["startTime"] + " <b>" + item["parameter"]["parameterName"]+"</b> "+item["parameter"]["parameterUnit"]+"\n"
return text
def echo(update, context):
"""Echo the user message."""
update.message.reply_text(update.message.text,parse_mode=ParseMode.HTML)
def help_command(update, context):
update.message.reply_text(text =
"""*/now* 查詢縣市目前往後推36小時的溫度資料\n
*/notify* 設定每天早上六點要通知哪個縣市的溫度資料
""",parse_mode=ParseMode.MARKDOWN)
def main():
try:
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater(os.getenv("TELEGRAM_KEY"), use_context=True)
updater.dispatcher.add_handler(CommandHandler('now', now))
updater.dispatcher.add_handler(CallbackQueryHandler(nowCallback,pattern='....now$'))
updater.dispatcher.add_handler(CommandHandler('notify', notify))
updater.dispatcher.add_handler(CallbackQueryHandler(notifyCallback,pattern='....notify$'))
updater.dispatcher.add_handler(CommandHandler('help', help_command))
# on noncommand i.e message - echo the message on Telegram
updater.dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
# Start the Bot
updater.start_polling()
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT
updater.idle()
except TelegramError as e:
# These are network problems with Telegram.
if e.message in ("Bad Gateway", "Timed out"):
sleep(1)
else:
raise e
if __name__ == '__main__':
main()