糾團的功能我把它切成兩個部分
這個部分主要是讓程式持續讀取資料庫裡的任務時間與現在時間相減是否在一小時以內
要讓程式持續讀取資料有兩個辦法
一個是用While迴圈另一個是用discord裡的tasks.loop()這函式記得要import進去:
from discord.ext import commands,tasks
函式裡面可以設定要多久時間執行一次程式碼,相當方便
這邊要特別注意時區轉換的部分
還記得先前我們在執行GCP時我們的服務是架在美國那邊,所以我們還需要把美國時區轉成台灣時區
轉換寫法如下:
from datetime import datetime,timezone,timedelta
now_time = datetime.utcnow().replace(tzinfo=timezone.utc)
now_time = now_time.astimezone(timezone(timedelta(hours=8)))
now_time = now_time.strftime('%m/%d-%H:%M')
接著就是判斷任務時間與現在時間相減是否在一小時以內
json檔裡會有多個任務存在所以需要用for迴圈遍歷每個任務時間
附上背景執行程式碼
class tasktiming(Cog_Extension):
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.tasktime.start()
        self.count=0
        self.id = 0
    @tasks.loop(seconds=10)
    async def tasktime(self):
        embed = discord.Embed()
        self.generalchannel = self.bot.get_channel(779782707080069193)#記得改成功會generalID
        
        self.channel = self.bot.get_channel(887264861510328340)#記得改糾團頻道ID
        #由於伺服器架在美國所以要轉時區
        now_time = datetime.utcnow().replace(tzinfo=timezone.utc)
        now_time = now_time.astimezone(timezone(timedelta(hours=8)))
        now_time = now_time.strftime('%m/%d-%H:%M')
        # print(now_time)
        with open("setting.json",'r',encoding="utf8") as jfile:
            jdata = json.load(jfile)
        # print(len(jdata))
        if len(jdata) >0:
            #遍例每筆資料確認每筆時間
            for key in list(jdata):
                # print(key, ":", jdata[key])
                if datetime.strptime(now_time, '%m/%d-%H:%M') < datetime.strptime(jdata[key]["time"], '%m/%d-%H:%M'):
                    remain_hour = datetime.strptime(jdata[key]["time"], '%m/%d-%H:%M')-datetime.strptime(now_time, '%m/%d-%H:%M')
                    remain_hour = remain_hour.seconds/3600#轉成小時
                    # print(remain_hour)
                    #剩餘時間小於一小時執行下面動作
                    if remain_hour < 1 :
                        # print("complete")
                        #在general頻道發通知
                        user_wordlist = ["有任務快開始囉~趕快來參加",f'任務名稱 : {jdata[key]["task"]}']+[f'時間 : {jdata[key]["time"]}']+[f'備註 : {jdata[key]["condition"]}' if "condition" in jdata[key] else '備註 : 無']+[f'[傳送門]( {jdata[key]["url"]})']
                        embed.description = "\n".join(user_wordlist)
                        await self.generalchannel.send(embed=embed)
                        self.count=1
                        del jdata[key]
                        with open("setting.json",'w',encoding="utf8") as jfile:
                            jdata = json.dump(jdata,jfile,indent=4)
                    else:
                        pass
                else:
                    del jdata[key]
                    with open("setting.json",'w',encoding="utf8") as jfile:
                            jdata = json.dump(jdata,jfile,indent=4)
最後呈現結果如下:
