This is my code. I’ve tested it on my computer, and everything operates as intended. Every minute, it fetches data from my Google Sheet and checks for alarm reminders. If I haven’t added my LINE BOT to a group, it logs “Group ID is not set. Reminders cannot be sent.” every minute. However, after deploying the program to Render.com, I no longer receive the log “Group ID is not set. Reminders cannot be sent.” Does this mean that my program is not running main
? I would greatly appreciate any insights or solutions.
import os
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from linebot import LineBotApi, WebhookHandler
from linebot.models import MessageEvent, TextMessage, TextSendMessage, JoinEvent
from datetime import datetime, timedelta
import time
import logging
import threading
from flask import Flask, request, abort
from dotenv import load_dotenv
import json
load_dotenv()
設置 Flask
app = Flask(name)
Google 試算表 API 設定
scope = [‘XXX’, 'XXX]
creds = ServiceAccountCredentials.from_json_keyfile_dict(json.loads(os.getenv(‘CREDENTIALS_JSON’)), scope)
client = gspread.authorize(creds)
從環境變數讀取 LINE BOT API 設定
line_bot_api = LineBotApi(os.getenv(‘LINE_CHANNEL_ACCESS_TOKEN’))
handler = WebhookHandler(os.getenv(‘LINE_CHANNEL_SECRET’))
試算表和工作表設定
spreadsheet_name = ‘提醒事項’
sheet_name = ‘內容’
spreadsheet = client.open(spreadsheet_name)
sheet = spreadsheet.worksheet(sheet_name)
內存紀錄
reminders =
group_id = None
定义时间偏移
time_offset = timedelta(hours=0)
建立星期對應字典
day_map = {
‘星期一’: ‘Monday’,
‘星期二’: ‘Tuesday’,
‘星期三’: ‘Wednesday’,
‘星期四’: ‘Thursday’,
‘星期五’: ‘Friday’,
‘星期六’: ‘Saturday’,
‘星期日’: ‘Sunday’
}
def update_reminders():
global reminders
reminders =
data = sheet.get_all_records()
current_time = datetime.now() + time_offset
today = current_time.strftime(‘%A’)
for item in data:
if item[‘頻率’] == ‘每天’:
reminders.append((item[‘時間’], item[‘內容’]))
elif item[‘頻率’] in day_map and day_map[item[‘頻率’]] == today:
reminders.append((item[‘時間’], item[‘內容’]))
def send_reminders_at_time():
if group_id is None:
app.logger.info(“Group ID is not set. Reminders cannot be sent.”)
return
current_time = (datetime.now() + time_offset).strftime('%H:%M')
messages = [msg for time, msg in reminders if time == current_time]
if messages:
message = "\n".join([f"{i+1}. {msg}" for i, msg in enumerate(messages)])
line_bot_api.push_message(group_id, TextSendMessage(text=message))
app.logger.info(f"Sent reminders at {current_time}: {message}") # 新增日誌輸出
else:
app.logger.info(f"No reminders to send at {current_time}") # 新增日誌輸出
@app.route(“/callback”, methods=[‘POST’])
def callback():
signature = request.headers[‘X-Line-Signature’]
body = request.get_data(as_text=True)
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return ‘OK’
@handler.add(JoinEvent)
def handle_join(event):
global group_id
group_id = event.source.group_id
app.logger.info(f"Joined group: {group_id}")
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
# 不回應使用者訊息,只處理提醒發送
pass
@app.route(“/”)
def index():
threading.Thread(target=main).start()
return ‘Reminder service has started.’
def main():
while True:
update_reminders() # 每分鐘更新一次試算表到內存
send_reminders_at_time()
time.sleep(60) # 每分鐘檢查一次
if name == “main”:
# 設定日誌紀錄等級為 INFO 等級,並將日誌輸出到控制台
logging.basicConfig(level=logging.INFO)
# 設定PORT為10000
port = int(os.getenv('PORT', 10000))