【发布时间】:2018-07-21 08:18:02
【问题描述】:
我一直在用 Python 编写我的第一个 Discord 机器人,它运行良好。我决定将我的代码重构为两个模块,而不仅仅是一个。它看起来像这样:
Proj
- src
-- __init_.py
-- eve.py
-- event.py
我的 eve.py 看起来像这样:
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
from src.event import eventCall
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print ("Booting up your system")
print ("I am running on " + bot.user.name)
print ("With the ID: " + bot.user.id)
@bot.command(pass_context=True)
async def event(ctx):
await eventCall(ctx)
bot.run(<client ID>)
我的 event.py 看起来里面有这个标签:
async def eventCall(ctx):
member = ctx.message.author
message = await bot.send_message(member, "Hi " + member.display_name + "!")
channel = message.channel
(continues)
我一直在努力让 eve.py 导入 event.py,所以我将所有内容都移到了 src 文件夹,然后我不再出现编译器错误。
但是现在当我运行 eve.py 时,on_ready 不再触发(我在控制台中看不到任何文本),并且 !event 命令在 Discord 中不起作用。
我认为我的文件夹结构和我使用 import 的语法都可能是错误的,但我不确定如何最好地解决这个问题。
【问题讨论】:
-
注释掉
from src.event import eventCall行(可能还有所有引用eventCall的行)。如果未找到该模块,您应该会看到异常。src.event中执行的代码是否不在函数中?它会在文件导入时运行,所以可能有一个循环需要很长时间? -
成功了! event.py 中有很多定义,但是当它全部在一个模块中时,没有什么不存在。我更新了上面的帖子以显示其中的所有内容。
-
如果
eve.py和event.py在同一个目录中,那么你不应该用from event import eventCall导入它吗? -
每当我这样做时,Eclipse 似乎都不喜欢它。我也试过 .event 并没有给我一个 Eclipse 错误,但我最终得到一个: ModuleNotFoundError: No module named 'main.event'; 'main' 不是包
标签: python discord.py