'Discord.py message pinning?

I've tried multiple different ways to pin (I also want to try unpinning it) a certain message (it has already been sent) using a bot / selfbot with discord.py, here a few examples:

@pinner.event
async def on_message():
    if message.content == 'message im trying to pin':
    message.pin


@tasks.loop(seconds=1)
async def pin_message():
    message = ('message id ')
    await message.pin(message id)

I'm using Python 3.8 and the latest version of discord.py API.



Solution 1:[1]

In order to pin a message you must first have the message, once you have it you can await message.pin()

To unpin you can use await message.unpin()

The bot must also have manage_messages permisson in order to pin or unpin messages.

This would pin the message that the user triggered the command with

@bot.command()
async def pin_message(ctx):
  await ctx.message.pin()

If you want to pin a specific message you must fetch it with either ctx.fetch_message(message_id) or if you have the text channel textchannel.fetch_message(message_id)

This will pin a message that the user wants:

@bot.command()
async def pin_this(ctx, message_id: int):
  message = await ctx.fetch_message(message_id)
  await message.pin()

Optional: You can also specify a reason with await message.pin(reason="your reason here")

Documentation:

Solution 2:[2]

For pinning messages, you use:

await message.pin(reason=None)

For unpinning:

await message.unpin(reason=None)

From your example:

@client.event
async def on_message(message):
    if message.content == 'message im trying to pin':
        await message.pin()

Go to the API: https://docs.pycord.dev/en/master/api.html?highlight=pin#discord.Message.pin for more.

Note that the bot needs Manage Messages to do this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yunnosch
Solution 2 NevergonnagiveuupL