如何从另一个函数获取消息id

2024-06-02 13:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个bot,当一名工作人员单击某个特定消息的反应时,它会给用户一个静音角色,但我有一个问题,我想从另一个函数获取消息id,并检查它是否与该工作人员在其中反应的消息具有相同的id。 我该怎么做

这是我的代码:

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

    @commands.has_role("Staff")
    @commands.command()
    async def mute(self,ctx,member:discord.Member=None):
        role = discord.utils.get(ctx.guild.roles, name="Muted")
        reasons = discord.Embed(title="قم بأختيار سبب الميوت",color=0x00ff00,description="1-\n2-\n3-\n4-")
        reasons.set_footer(text=member,icon_url=member.avatar_url)
        msg = await ctx.send(embed=reasons)
        await msg.add_reaction(str("1️⃣"))
        await msg.add_reaction(str("2️⃣")) 
        await msg.add_reaction(str("3️⃣"))
        await msg.add_reaction(str("4️⃣"))
        await msg.add_reaction(str("5️⃣"))
        await msg.add_reaction(str("6️⃣"))
        await msg.add_reaction(str("7️⃣"))
        await msg.add_reaction(str("8️⃣"))
        await msg.add_reaction(str("9️⃣"))
        await msg.add_reaction(str("🔟"))

    @commands.Cog.listener()
    async def on_reaction_add(self,reaction, user):
        if user.id == self.client.user.id:
            return
        if reaction.message.id == self.mute.msg.id:
            print("correct message")

Tags: selfclientaddid消息defmsgawait
1条回答
网友
1楼 · 发布于 2024-06-02 13:28:24

无法访问函数中的变量,因为它们是局部变量。你可以使用全局变量,但那真的很昂贵而且难看。那你能做什么呢? 您可以在mute的对象上创建一个属性,并保存消息的对象或ID

举个例子

def __init__(self, client):
    self.client = client
    self.msgs = {}

...
async def mute(self, ctx, ...):
    msg = await ctx.send(...)
    self.msgs[ctx.author] = msg

...
async def on_reaction_add(self, ctx, ...):
    try:
        msg = self.msgs[ctx.author]
    except KeyError:
        return

    if ctx.message.id == msg.id:
        #correct message

相关问题 更多 >