Discord Python 具有不同源文件的机器人
Discord Python Bot With Different Source Files
所以我在 Python 中遇到了我的 Discord 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
。
我该怎么办?
谢谢 :)
假设您的 python 主文件名为 main.py
.
,请尝试将 from __main__ import client
替换为 from main import client
您需要这样做,因为 python 在导入另一个脚本时只需要文件名。我还建议将您的主文件名更改为其他名称,因为 python 中的 __main__
保留用于其他名称。
我遇到了同样的问题。
问题是您在 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: )
希望这对你也有帮助
所以我在 Python 中遇到了我的 Discord 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
。
我该怎么办? 谢谢 :)
假设您的 python 主文件名为 main.py
.
from __main__ import client
替换为 from main import client
您需要这样做,因为 python 在导入另一个脚本时只需要文件名。我还建议将您的主文件名更改为其他名称,因为 python 中的 __main__
保留用于其他名称。
我遇到了同样的问题。
问题是您在 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: ) 希望这对你也有帮助