【问题标题】:How do functions work in cogs (discord.py)?函数如何在 cogs (discord.py) 中工作?
【发布时间】:2020-12-12 17:34:09
【问题描述】:

使用此代码时发生错误,提示未定义机器人。我不太了解cogs,但我也了解一些类。我想知道函数在 cog 中是如何工作的,以及变量是如何分配的,如下面的guildstats = ...

这是我的代码:(我正在尝试使用公会中的不和谐机器人创建数据库。该代码无需使用 cogs 即可工作,但我希望更容易调试任何错误,因此我选择了 cogs。)

class Boot(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    guildstats = pd.read_excel('DiscordStats.xlsx',sheet_name=0)
    userstats = pd.read_excel('DiscordStats.xlsx',sheet_name=1)

    def dataframe_to_excel(df1 = guildstats, df2 = userstats):
        with pd.ExcelWriter('DiscordStats.xlsx', mode = 'w') as writer:
            df1.to_excel(writer, index=False, sheet_name = 'GuildStats')
            df2.to_excel(writer, index=False, sheet_name = 'UserStats')

    def guildstats_writer():
        guild_row_data = []
        for guild in self.bot.guilds:
            if '\''+str(guild.id) not in guildstats['GuildID'].to_list():
                guild_row_data.append([guild.name,'\''+str(guild.id),'','',False])
            else:
                pass
        guild_row = pd.DataFrame(guild_row_data,columns = guildstats.columns.to_list())
        guildstats1 = guildstats.append(guild_row,ignore_index=True)
        Boot.dataframe_to_excel(df1=guildstats1)

    @commands.Cog.listener()
    async def on_ready(self):
        Boot.guildstats_writer(self)
        await sbot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="for MeepMop ~help"))
        print(f'{bot.user} is connected to the following guild:')
        for guild in bot.guilds:
            print(f'{guild.name} (id: {guild.id})')

def setup(bot):
    bot.add_cog(Boot(bot))

【问题讨论】:

    标签: discord discord.py


    【解决方案1】:

    你试图调用变量 bot,但你从未定义它,你的程序不知道变量“bot”是什么,试着改变你调用 bot 的所有时间,而不是调用 self.bot 而不是

    例如,您的 on_ready 函数应如下所示:

        @commands.Cog.listener()
        async def on_ready(self):
            Boot.guildstats_writer(self)
            await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="for MeepMop ~help"))
            print(f'{self.bot.user} is connected to the following guild:')
            for guild in self.bot.guilds:
                print(f'{guild.name} (id: {guild.id})')
    

    【讨论】:

    猜你喜欢
    • 2019-04-30
    • 2020-11-13
    • 1970-01-01
    • 2019-11-16
    • 2021-04-19
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 2020-09-27
    相关资源
    最近更新 更多