Discord机器人pi命令模块导入失败,请求技术帮助
Discord机器人Cog导入问题解决方法
问题背景
将Discord机器人的命令拆分到cogs文件夹下的单独文件(如pi.py)后,运行main.py出现ModuleNotFoundError: No module named 'pi'错误,同时pi.py的Cog代码也存在规范问题。
核心问题分析
- 导入路径错误:
pi.py位于cogs文件夹内,直接使用from pi.py import Pi会导致Python无法在当前目录找到目标模块。 - Cog代码不规范:
pi.py中重复创建了Bot实例,且命令装饰器使用错误,不符合Discord.py的Cog开发规范。
修复步骤
1. 修正main.py的扩展加载逻辑
删除错误的导入语句,改用Discord.py官方推荐的扩展加载方式,同时确保cogs文件夹被识别为Python模块(需添加空的__init__.py文件)。
修改后的main.py代码:
import discord from discord.ext import commands import asyncio token = "hidden for saftey lol" intents = discord.Intents.all() bot = commands.Bot(command_prefix="?", intents=intents) @bot.event async def on_ready(): await bot.change_presence(activity=discord.Game(name=f"?help")) await asyncio.sleep(1) print("\n Bot has successfully logged in as: {}".format(bot.user)) print("Bot ID: {}\n".format(bot.user.id)) # 加载cogs文件夹中的pi扩展 async def load_cogs(): await bot.load_extension("cogs.pi") async def main(): async with bot: await load_cogs() await bot.start(token) try: asyncio.run(main()) except discord.HTTPException as e: if e.status == 429: print("The Discord servers denied the connection for making too many requests") else: raise e
2. 修正pi.py的Cog代码
删除重复创建的Bot实例,将命令装饰器改为@commands.command(),并为命令方法添加self参数(类方法必需)。
修改后的pi.py代码:
import discord from discord.ext import commands import decimal class Pi(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def pi(self, ctx, num_decimals: int): if num_decimals > 10000: await ctx.send("Sorry, I can only print up to 10000 decimal places.") return decimal.getcontext().prec = num_decimals + 1 pi_value = decimal.Decimal(0) for i in range(num_decimals + 1): pi_value += (decimal.Decimal(1) / 16 ** i) * ((decimal.Decimal(4) / (8 * i + 1)) - (decimal.Decimal(2) / (8 * i + 4)) - (decimal.Decimal(1) / (8 * i + 5)) - (decimal.Decimal(1) / (8 * i + 6))) pi_str = str(pi_value)[:num_decimals + 1] await ctx.send(f"The value of pi to {num_decimals} decimal places is: {pi_str}") async def setup(bot): await bot.add_cog(Pi(bot))
3. 配置cogs文件夹为Python模块
在cogs文件夹中创建一个空的__init__.py文件,让Python将该文件夹识别为可导入的模块。
完成以上步骤后,运行main.py即可正确加载pi命令的Cog模块。
内容的提问来源于stack exchange,提问作者user19932233
相关产品推荐
相关产品推荐

