我基本上是在做一件事,它將接收用戶的內容,然后把它放在串列中。我想將其存盤在另一個名為 "問題 "的檔案中,我該怎么做呢?這是我的主Discord Bot的代碼
。import Discord
import random
import problems
TOKEN = "SECRET"/span>
client = discord.Client()
@client.event[/span]。
async def on_ready() 。
print("Bot is ready!"/span>)
@client.event("Bot is ready!
async def on_message(message)。
username = str(message.author).split('#'/span>)[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f"{username}: {user_message} ({channel}) ")
if message.author == client.user。
回傳。
if message.channel.name == 'test':
if user_message.lower() == 'hello':
await message.channel.send(f "Hello {username}!")
return
elif user_message.lower() == 'bye'。
等待 message.channel.send(f "bye!")
return return
elif message.content.startinwith("! store")。
a = message.content[6:] 。
await message.channel.send("Storeed!")
problemlist = problems.problem.append(a)
print(problemlist)
if user_message.lower() == '!code':
await message.channel.send()
client.run(TOKEN)
這是我的problem.py里面的內容
problem = []
基本上是一個空串列
當它列印出problemlist時,我得到的是無
另外,我希望這個串列在機器人重新啟動后能夠持續存在。
uj5u.com熱心網友回復:
在python中(以及我所知道的所有其他語言),當你匯入另一個python檔案時,它會將其作為代碼加載,所以如果你的problems.py如你上面所說,它在每次腳本啟動時都會執行problems = [],而一旦腳本啟動,這些內容就從記憶體中清除了。
如果你正在做一些非常簡單的事情,這里最好的方法是將變數寫入一個檔案,使用pickle或json。我在下面給出了一個讀和寫的例子。
import json
def read(filename)。
""打開檔案,讀取它并決議json""。
try:
with open(filename, 'r) as json_file:
return json.load(json_file.read() )
except FileNotFoundError:
return {}。
def write(filename, save_object)。
""打開檔案,并把物件寫成json""。
with open(filename, 'w') as json_file。
json_file.write(json.dumps(save_object))
# 獲取問題串列,如果它存在的話。
problems = read('persons.json').get('persons', None)
# 如果它不創建它。
if problems is None:
問題 = []
problems.append("issue")
write('persons.json', {'persons': problems})
這將意味著problems.json檔案將看起來像這樣:
{}。
"問題"。 [ "1", "2"。 "3", "4"]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/325373.html
標籤:
