我正在制作一個為我的網站發送 api 密鑰的命令,但我不希望它被濫用,所以我需要在 3 天(72 小時)內使用一次命令,或者在 2 天甚至 1 天使用一次我只是不不希望它每秒重新生成
這是我的代碼 atm
@bot.command()
async def key(ctx):
await ctx.send(next(keys))
順便說一句,如果您好奇,api 密鑰在 txt 檔案中。
uj5u.com熱心網友回復:
你可以看看這個 repo:https ://github.com/gawel/aiocron
這允許您使用 discord bot 運行 crontab 作業,如果您想每三天運行一次,您只需使用它:
0 12 */3 * *
每 3 天 12:00 運行(您可以更改時間)
uj5u.com熱心網友回復:
您可以將上次訪問時間戳保存到檔案中,并使用datetime.timedelta檢查冷卻時間是否已經過去。 您可以這樣做:
from datetime import datetime, timedelta
@bot.command()
async def key(ctx):
def save_timestamp(timestamp): # Function to save the timestamp to file
timestamp = int(timestamp)
with open("last_credentials.txt", 'w') as f:
f.write(str(timestamp))
try: # Try reading last credentials usage from file 'last_credentials.txt'
with open("last_credentials.txt", 'r') as f:
timestamp = int(f.read())
except FileNotFoundError:
# Create new timestamp if the file does not exist
timestamp = datetime(year=1970, day=1, month=1).timestamp()
creds_datetime = datetime.fromtimestamp(timestamp)
if datetime.now() - creds_datetime > timedelta(hours=72): # check if 3 days have passed from last usage. You could also use days=3 instead of hours=72
save_timestamp(datetime.now().timestamp())
await ctx.send(next(keys))
您也可以將此時間戳存盤在記憶體中,但不會保留最后一個時間戳,以防您重新啟動程式
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/465173.html
標籤:Python python-3.x 不和谐 不和谐.py
下一篇:如何通過公式制作串列編號
