首页 > 解决方案 > 无法在 discord.py 中导入 main

问题描述

我有一个小问题,你可以跳过它,并且不会给你一个大错误,不会让你运行机器人,因为它非常令人沮丧。

代码:

    import asyncio
    import discord
    from discord.ext import commands
    from main import db
         ^^^^ Unable to import 'main' [pylint(import-error)]
    import datetime
    import random

我正在使用 cogs,所以这就是我从main.

标签: pythondiscord.py

解决方案


如果您使用的是 cogs,则不必导入 main。只需看一下 discord.py 文档,您就会发现 cogs 必须是这样的:

import discord

from discord.ext import commands
class MembersCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    @commands.guild_only()
    async def joined(self, ctx, *, member: discord.Member):
        """Says when a member joined."""
        await ctx.send(f'{member.display_name} joined on {member.joined_at}')

    @commands.command(name='coolbot')
    async def cool_bot(self, ctx):
        """Is the bot cool?"""
        await ctx.send('This bot is cool. :)')

    @commands.command(name='top_role', aliases=['toprole'])
    @commands.guild_only()
    async def show_toprole(self, ctx, *, member: discord.Member=None):
        """Simple command which shows the members Top Role."""

        if member is None:
            member = ctx.author

        await ctx.send(f'The top role for {member.display_name} is {member.top_role.name}')    
    def setup(bot):
        bot.add_cog(MembersCog(bot))

在 main.py 中:bot.load_extension('folder_name.file_name') 这只是一个示例。


推荐阅读