Search code examples
pythondiscorddiscord.pybots

Getting all the messages of a channel


Getting all the messages of a channel. I want to get messages from a announcement channel in my server and show it in a embed . My idea is that i announce updates in my server's channel and i have made a command updates for now i am doing it manually but is there a way to do it ? I know to get the last message using this code but what about all messages

@client.command(
    name='getlastmessage')
async def client_getlastmessage( ctx, ID):
    """Get the last message of a text channel."""
    channel = bot.get_channel(int(ID))
    if channel is None:
        await ctx.send('Could not find that channel.')
        return
    # NOTE: get_channel can return a TextChannel, VoiceChannel,
    # or CategoryChannel. You may want to add a check to make sure
    # the ID is for text channels only

    message = await channel.fetch_message(
        channel.last_message_id)
    # NOTE: channel.last_message_id could return None; needs a check

    await ctx.send(
        f'Last message in {channel.name} sent by {message.author.name}:\n'
        + message.content
    )

EDIT : After getting two answers I tried this

channel=client.get_channel(929329917894737970)
async for message in channel.history(limit=2):
    # do something with all messages
    content = message.content # get content
    await ctx.send(content)

This works fine unless there is an embed in the channel , how can i send something if it is a embed or send it's description . 2. Another method I tried

history = await ctx.channel.history(limit=3).flatten()
await ctx.send(history)

Result [<Message id=x channel=<TextChannel id=0000 name='terrasect' position=5 nsfw=False news=False category_id=jjjj> type=<MessageType.default: 0> author=000<Member id=00000 name='SniperXi199' discriminator='0000' bot=False nick=None guild=<Guild id=912559425921892392 name='Zionic BOT TESTERS' shard_id=None chunked=True member_count=4>> flags=<MessageFlags value=0> components=[]>] Note I have removed some crucial information like id etc.


Solution

  • I think you might be looking for this command, channel.history()

    async for message in channel.history(limit=200):
        # do something with all messages
        content = message.content # get content