pythondiscorddiscord.pybots

How to send messages on threads?


I currently have code for a command that takes in a channel ID followed by some text message as input. The code then finds the channel and sends the message on it. However, Discord has just released a new thread feature, and currently, no update has been made to the official Discord API docs regarding how bots can interact with threads. So, how can a bot send messages to threads? Please leave down answers as new information is released by Discord. Here's the code I was talking about before:

@bot.command()
async def text(ctx, channel_id, *, msg):
    channel = bot.get_channel(int(channel_id))
    try:
        await channel.send(ctx.message.attachments[0].url)
    except IndexError:
        pass
    await channel.trigger_typing()
    await channel.send(msg)

Solution

  • Since discord.py 2.0, threads are supported with discord.Thread.

    get_thread method

    1. Using the guild
    @bot.command()
    async def test(ctx):
        thread = ctx.guild.get_thread(thread_id)
    

    There is also the method get_channel_or_thread which returns either a channel or a thread.

        channel_or_thread = ctx.guild.get_channel_or_thread(channel_id)
    
    2. Using the text channel
    @bot.command()
    async def test(ctx):
        thread = ctx.channel.get_thread(thread_id)
    

    threads list

    1. Using the guild
    @bot.command()
    async def test(ctx):
        threads = ctx.guild.threads
    

    There is also the coroutine active_threads which returns all active threads which the bot can see

        active_threads = await ctx.guild.active_threads()
    
    2. Using the text channel
    @bot.command()
    async def test(ctx):
        threads = ctx.channel.threads
    

    There is also the async iterator archived_threads that iterates over all archived threads in this text channel

        async for thread in ctx.channel.archived_threads():
            # ...