xia的小窩

一起來coding和碼字吧

0%

python-Discord-bot,從0開始到做出一個機器人系列-17

關於match的檔案管理

第一,我們需要做刪除的動作

第二,或者說,自訂排程

刪除檔案 + 新增檔案

建立remove_create的python檔

1
2
3
4
5
from pathlib import Path
import os

# 路徑
fileTest = r"C:\Users\a9132\Desktop\乁( ◔ ౪◔)「\match.json"

建立一個class

1
class RemoveCreate:

刪除match

1
2
3
4
5
6
7
def fileremove_match_json():
try:
os.remove(fileTest)
except OSError as e :
print(e)
else:
print("File is delete successfully")

寫新檔案

1
2
3
4
5
6
def filecreate_match_json():
match_json_file = Path("match.json")
match_json_file.touch(exist_ok = True)
File = open(match_json_file)
file = open("match.json", "w+")
file.write("{}")

在最底下加上

1
2
3
if __name__ == "__main__":
RemoveCreate.fileremove_match_json()
RemoveCreate.filecreate_match_json()

pathlib模組的path.touch()方法在path.touch()的 path中指定的路徑上建立檔案。
如果我們將exist_ok設定為 True,如果檔案存在,該函式將不做任何操作。
os.remove()函式用來刪除存在的給定檔案,
假如給定的檔案不存在或者不是一個檔案(比如說是資料夾)或者你沒有刪除許可權的話,將會觸發相應的錯誤資訊

這時候回到主檔案

1
2
3
4
5
6
7
8
9
10
11
from remove_create import RemoveCreate

# 省略

if __name__ == '__main__':
# New
RemoveCreate.fileremove_match_json()
# New
RemoveCreate.filecreate_match_json()
# ......省略
bot.run(data['token'])

第二種方式

可以使用工作排程
在Windows系統管理工具中有一個工作排程器

建立工作

新增觸發程序

新增動作

這樣應該就可以完成目標了

2.0部分更改

好的,一樣來更新小部分

1
2
3
4
5
6
7
8
9
# bot.py 省略前段

if __name__ == '__main__':
# New
await RemoveCreate.fileremove_match_json()
# New
await RemoveCreate.filecreate_match_json()
# ......省略
asyncio.run(main())

其實這時候往以前的文章看…需要更改的東西會有點多,思路也可以調整,寫一個tasks刪除檔案新增檔案就可以啦…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from discord.ext import commands
import asyncio
import discord
import os

class deletefile(commands.Cog):
# 東八區
tz = datetime.timezone(datetime.timedelta(hours = 8))
# 每天0000
everyday_time = datetime.time(hour = 0, minute = 0, tzinfo = tz)

def __init__(self, bot: commands.Bot):
self.bot = bot
# 函式 啟動
self.delfile.start()

@tasks.loop(time = everyday_time)
async def delfile(self):
os.remove('match.json')
file = open("match.json", "w+")
file.write("{}")

async def setup(bot: commands.Bot):
await bot.add_cog(deletefile(bot))

這樣就可以完成每天定時刪除與新增一個json了(空的)。