Tony_I
Tony_I

Reputation: 87

How to copy all messages from the channel in discord.py

import discord
file = open("file.txt", "w+", encoding = "utf-8")

bot = commands.Bot(command_prefix = "{")

@bot.command( pass_context = True )
async def copy(ctx):
    chId = "putIdHere"   #channel id
    for ? in ???  #for "lines of messages" in "channel with id = chId"
        file.write(str(?) + "\n")

First question: How to use Id of something in code? For example in case of printing() a message with Id that you wrote, where to put the id?

Second question: What to put instead of question marks in code that is above? Or what is the better way to copy messages?

Upvotes: 2

Views: 5396

Answers (1)

BluePigeon
BluePigeon

Reputation: 1812

Here is a solution:

import discord
from discord.ext import commands
import asyncio

bot = commands.Bot(command_prefix = "{")

@bot.command()
async def copy(ctx):
    with open("file.txt", "w") as f:
        async for message in ctx.history(limit=1000):
            f.write(message.content + "\n")

    await ctx.send("Done!")

Note: use open("file.txt", "r+") instead of open("file.txt", "w") if you want to keep the file's content. You can learn more about the open function by clicking on the link.

Upvotes: 2

Related Questions