2017-09-16 42 views
0

因此,我在使用Python中的Discord Bot時遇到了問題。不同源文件不一致的Python Bot

對於它的代碼變得太簡單了,所以我想把它分成不同的源文件。

(主文件)

...   
import second_file 
if message.content.lower().startswith("!Hi"): 
    second_file.hello() 

(第二文件)

... 
from __main__ import client 
def hello(): 
    await client.send_message(message.channel, "Hiii <3!") 

我得到的錯誤是name "client" is not defined

我該怎麼辦? 謝謝:)

+0

如果我的答案奏效,請將其標記爲正確,以便將來任何人都可以解決他們的問題。 – James

+0

你應該看看創建Cog。使用Cogs將使您的生活變得如此簡單。編輯:你也需要看在commands.ext – xNinjaKittyx

回答

0

嘗試用from main import client假設你的主要的Python文件替換from __main__ import client被稱爲main.py

你需要這樣做,因爲python在導入另一個腳本時只需要文件名。我還建議將你的主文件名改爲其他東西,因爲python中的__main__是爲其他東西保留的。

+0

可悲的是,沒有解決它... 現在它只是說: 「無效的語法」在client.send_message(message.channel,「Hiii <3!」) 「 指針由客戶端的」t「代替 – itzFlubby

+0

它被命名爲」__main__「,因爲我聽說Python使用」__main__「作爲調用腳本 – itzFlubby

+0

將該文件重命名爲其他內容並嘗試再次執行該操作 – James

1

我有同樣的問題。 問題是您在async函數之外使用await。 我不知道爲什麼會拋出錯誤的真正原因。 您也不一定需要從__main__導入client。 您可以使用

await __main__.client.send_message(__main__.message.channel, 'Hello')` 

就好。 但試試這個代碼:

(Main-file) 
import second_file 
if message.content.lower().startswith('!hi'): 
    second_file.hello() 

(Second-file) 

async def hello(): 
    await __main__.client.send_message(__main__.message.channel, 'Hello!') 

很抱歉,如果我有任何語法或拼寫錯誤。英語不是我的母語(不幸的是D:) 希望這對你有所幫助