Python找不到“__main__”模块

3
当我尝试运行我的代码时,出现以下错误:\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe: can't find '__main__' module in ''
我不知道如何解决它。我已经查看了类似于我问题的帖子,但它们的修复方法似乎没有起作用。这是我所有的代码:
import discord

client = discord.client()

@client.event  
async def on_ready():
    print(f"we have logged in as {client.user}")

client.run("my bot token would be here")

@client.event
async def on_message(message):  # event that happens per any message.

    # each message has a bunch of attributes. Here are a few.
    # check out more by print(dir(message)) for example.
    print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")


client.run(token)  # recall my token was saved!

@client.event
async def on_message(message):  # event that happens per any message.
    print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")
    if str(message.author) == "hello" in message.content.lower():
        await message.channel.send('hi')
        

你安装了Discord库和Python吗? 你能提供更多关于你的环境和执行的信息吗?此外,我强烈建议你改用Unix环境。 - heron J
Discord库和Python都已经安装好了。我使用Sublime Text,所以只需编写代码并运行,其余的工作都由它来完成。我对编程还比较新手。 - NoHaxJustEncrypted
请发布完整的回溯信息。我们需要详细了解情况。 - tdelaney
我不太确定你的意思,我的所有代码都在那里。如果你是指这个,这是完整的错误信息。C:\Users\zorbs\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe: 在''中找不到'main'模块。 - NoHaxJustEncrypted
@NoHaxJustEncrypted - 有意思。这表明脚本从未运行,问题出在您的安装上。 - tdelaney
是的,我修好了,原来我忘记把代码放在正确的文件夹里。我很烦恼,但这都是编程的一部分。 - NoHaxJustEncrypted
1个回答

1
非常简单的修复。您已经包含了两个 client.events。discord.py 不允许这样做,人们最终会得到最随机的错误。我也遇到过这个问题一段时间了。您需要指定 discord 机器人正在寻找什么。下面是调整后的代码,您可以根据自己的需求进行更改。 在代码结尾处,您需要添加 await client.process_commands(message),因为这将确保机器人考虑所有可能性,并且您的命令以及事件将起作用。
import discord

client = discord.client()

@client.event  
async def on_ready():
    print(f"we have logged in as {client.user}")

client.run("my bot token would be here")

@client.event
async def on_message(message):  # event that happens per any message.

    # each message has a bunch of attributes. Here are a few.
    # check out more by print(dir(message)) for example.

    if " " in message.content: #Basically it'll work if the message contains " "
        print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")

    if str(message.author) == "hello" in message.content.lower(): #This is good because you are specifying what the bot should be looking for ("hello")
        await message.channel.send('hi')
    await client.process_commands(message)


client.run(token)  # recall my token was saved!

另一种可能性:client.run 应该在你的代码结尾处且仅在结尾处。从 on_ready 函数中移除它,那里不需要它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接