Python类自变量未传输到函数(discord.py)

时间:2019-09-20 07:35:41

标签: python python-3.x discord.py

在此代码中,on_raw_reaction_add()得到的self.serverNone,但是在on_raw_reaction_remove()中却得到了我在__init__()中所要求的。简便的解决方案是在该函数中执行同一行,但是我想了解为什么它不起作用,据我所知。

编辑:尝试过self.client.server_id也不起作用

编辑II:就像我之前说的那样,它在on_raw_reaction_remove()中也不起作用

  

编辑III:找出原因。该机器人在被调用时尚未运行,因此get_guildNone。 h

class reactionsCog(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.server = self.client.get_guild(client.server_id)

    @commands.Cog.listener()
    async def on_raw_reaction_add(self, reaction):
        #Private events
        for i in range(2):
            if reaction.message_id == self.client.pri_message[i].id:
                print('Someone reacted to pri_message ', i, ' with ', str(reaction.emoji))
                if str(reaction.emoji) == '✅':
                    if reaction.user_id != self.client.user.id:
                        member = self.server.get_member(reaction.user_id)
                        userstr = member.display_name
                        if userstr in self.client.pri_not_sure[i]:
                            await self.client.pri_message[i].remove_reaction('❔', member)
                        self.client.pri_attending[i].append(userstr)
                        try:
                            await self.client.pri_message[i].remove_reaction('❌', member)
                        except:
                            pass
                        print(member.name, ' added to pri_attending ', i)

    @commands.Cog.listener()
    async def on_raw_reaction_remove(self, reaction):
        #Private events
        for i in range(2):
            if reaction.message_id == self.client.pri_message[i].id:
                if str(reaction.emoji) == '✅':
                    member = self.server.get_member(reaction.user_id)
                    print(member.name, ' removed from pri_attending ', i)
                    userstr = member.display_name
                    self.client.pri_attending[i].remove(userstr)

1 个答案:

答案 0 :(得分:0)

正如您所发现的,发生这种情况是因为在机器人连接到Discord API服务之前调用了get_guild。您可以通过添加on_ready事件来解决此问题,该事件将在机器人连接时触发:

class reactionsCog(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_ready(self):
        await self.client.wait_until_ready()
        self.server = self.client.get_guild(client.server_id)

    ...