Discord Python Bot具有不同的源文件

问题描述 投票:0回答:2

所以我在使用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 discord.py
2个回答
0
投票

假设你的主要python文件名为from __main__ import client,尝试用from main import client替换main.py

你需要这样做,因为python在导入另一个脚本时只需要文件名。我还建议将主文件名更改为其他内容,因为python中的__main__是为其他内容保留的。


1
投票

我有同样的问题。问题是你在await函数之外使用async。我不知道为什么抛出错误的真正原因。您也不一定需要从client导入__main__。您可以使用

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!')

对不起,如果我有任何语法错误或拼写错误。英语不是我的母语(unfortunataly D:)希望这对你也有帮助

© www.soinside.com 2019 - 2024. All rights reserved.