def download_json(file_name_t): save_file_path = "schedule_json/{}".format(file_name_t) if not os.path.exists(save_file_path): log.TWR_INFO("Download the file {}...".format(file_name_t)) file_url = get_json_file_url(file_name_t) urllib.request.urlretrieve(file_url, save_file_path) log.TWR_INFO("Done.") else: log.TWR_INFO("File {} exists.".format(save_file_path)) return 0
def shutdown_notification(bot, e): if not USE_NOTIFY_BOT: return 0 msg = "[TWR crash] {} was shut down.".format(PROGRAM_NAME) msg += "\n{}".format(e) log.TWR_INFO(msg, "main.main") bot.send_message(chat_id=Author_UID, text=msg) return 0
def echo(update, date_str, table_name2code, json_list_t, table_car_class_dict): """Echo the message the user sent.""" ret = 0 if type(table_name2code) != type({}): log.TWR_ERR("Wrong table_name2code type.", "main.echo") ret = -1 elif type(json_list_t) != type([]): log.TWR_ERR("Wrong json_list_t type.", "main.echo") ret = -1 elif update.message: # your bot can receive updates without messages received_uid = update.message.chat.id received_username = update.message.chat.username received_firstname = update.message.chat.first_name log_msg_postfix = ", UID: {}, username: {}, First name: {}".format( received_uid, received_username, received_firstname) received_msg = update.message.text if received_uid < 0: msg = "不支援群組" # update.message.reply_text(msg) log.TWR_INFO(msg + log_msg_postfix, "main.echo") return 0 if received_msg is None: msg = "奇怪的訊息" update.message.reply_text(msg) log.TWR_INFO(msg + log_msg_postfix, "main.echo") return 0 if received_msg == "/help" or received_msg == "/start": log.TWR_INFO(received_msg + log_msg_postfix, "main.echo") update.message.reply_text(help_msg) ret = 0 else: # Reply to the message input_stations = received_msg.split(' ') len_input_stations = len(input_stations) if len_input_stations > 2 or len_input_stations < 2: msg = "車站數不正確,請輸入兩個車站名。訊息: {}".format(received_msg) update.message.reply_text(msg) log_msg = msg + log_msg_postfix log.TWR_ERR(log_msg, "main.echo") ret = 0 elif input_stations[0] not in table_name2code or input_stations[ 1] not in table_name2code: msg = "查無車站名稱,請輸入兩站正確的車站。訊息: {}".format(received_msg) update.message.reply_text(msg) log_msg = msg + log_msg_postfix log.TWR_ERR(log_msg, "main.echo") ret = 0 elif table_name2code[input_stations[0]] == table_name2code[ input_stations[1]]: msg = "相同的車站,請輸入兩個不同車站。訊息: {}".format(received_msg) update.message.reply_text(msg) log_msg = msg + log_msg_postfix log.TWR_ERR(log_msg, "main.echo") ret = 0 else: msg = "收到訊息: {}".format(received_msg) log_msg = msg + log_msg_postfix log.TWR_INFO(log_msg, "main.echo") len_json_list_t = len(json_list_t) src_station_name = input_stations[0] dst_station_name = input_stations[1] src_station_code = table_name2code[src_station_name] dst_station_code = table_name2code[dst_station_name] reply_train_msg_list = [] reply_train_msg_str = "" for train_info in json_list_t: reply_train_single_str = "" src_station_time_info = None dst_station_time_info = None for time_info in train_info["TimeInfos"]: reply_train_single_line_str = "" if src_station_time_info is None and time_info[ "Station"] == src_station_code: src_station_time_info = time_info elif src_station_time_info and dst_station_time_info is None and time_info[ "Station"] == dst_station_code: dst_station_time_info = time_info break if src_station_time_info and dst_station_time_info: reply_train_single_str += "{} {} ".format( src_station_time_info["DEPTime"][:-3], dst_station_time_info["ARRTime"][:-3]) car_class_result = (table_car_class_dict.get( train_info.get("CarClass"))) if car_class_result is None: # log.TWR_ERR("Unknown car class code: {}".format(train_info.get("CarClass")), "main.echo") car_class_code_str = train_info.get("CarClass") reply_train_single_str += car_class_code_str # print(train_info.get("CarClass")) else: car_class_name_str = car_class_result.get( KEY_CAR_CLASS_NAME_ZH_TW) reply_train_single_str += car_class_name_str # print( car_class_result.get(KEY_CAR_CLASS_NAME_ZH_TW) ) reply_train_msg_list.append(reply_train_single_str) sorted_reply_train_msg_list = reply_train_msg_list_to_dict( reply_train_msg_list) if not sorted_reply_train_msg_list: msg = "查無班次" log.TWR_INFO(msg) update.message.reply_text(msg) ret = 0 else: head_str = "{}/{}/{}\n{} -> {}\n".format( date_str[0:4], date_str[4:6], date_str[6:], src_station_name, dst_station_name) log.TWR_INFO("Reply the train info: ") len_reply_train_msg_list = len(sorted_reply_train_msg_list) for index in range(len_reply_train_msg_list): if index and index % 20 == 0: reply_train_msg_str = reply_train_msg_str[:-1] log.TWR_INFO("\n{}".format(head_str + reply_train_msg_str)) update.message.reply_text(head_str + reply_train_msg_str) reply_train_msg_str = "" reply_train_msg_str += ( sorted_reply_train_msg_list[index] + "\n") if reply_train_msg_str: reply_train_msg_str = head_str + reply_train_msg_str[: -1] log.TWR_INFO("\n{}".format(reply_train_msg_str)) update.message.reply_text(reply_train_msg_str) ret = 0 return ret
def release(): log.TWR_INFO("Release.", "main.release")
def main(): """Run the bot.""" update_id = None station_name2code = {} car_class_dict = {} # Telegram Bot Authorization Token bot = telegram.Bot( 'xxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') # BotToken # get the first pending update_id, this is so we can skip over it in case # we get an "Unauthorized" exception. update_result = bot.get_updates() if not len(update_result): update_id = None else: update_id = update_result[0].update_id #update_id = bot.get_updates()[0].update_id schedule_json_list, today_date = get_json_list() if initial(station_name2code, car_class_dict) < 0: log.TWR_ERR("initial() failed.", "main.main") release() return -1 log.TWR_INFO("Start get_updates...") while True: try: time_int = int(time.strftime("%M")) new_today_date = datetime.datetime.now().strftime("%Y%m%d") if new_today_date != today_date: log.TWR_INFO("Start to re-initial.", "main.main") schedule_json_list, today_date = get_json_list() if initial(station_name2code, car_class_dict) < 0: log.TWR_ERR("re-initial() failed.", "main.main") release() return -1 # Request updates after the last update_id for update in bot.get_updates(offset=update_id, timeout=10): update_id = update.update_id + 1 if echo(update, today_date, station_name2code, schedule_json_list, car_class_dict) < 0: log.TWR_ERR("echo() failed.", "main.main") release() return -1 except NetworkError: log.TWR_ERR("Network error.", "main.main") sleep(1) except Unauthorized: # The user has removed or blocked the bot. log.TWR_INFO("The user has removed or blocked the bot.", "main.main") update_id += 1 except KeyboardInterrupt: print("") log.TWR_INFO("Keyboard Exit.") break except Exception as e: shutdown_notification(bot, e) break release() return 0