[英]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")
第一個問題:如何在代碼中使用某物的 Id? 例如,在 print() 的情況下,您編寫的帶有 Id 的消息,將 id 放在哪里?
第二個問題:在上面的代碼中用什么代替問號? 或者復制消息的更好方法是什么?
這是一個解決方案:
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!")
注意:如果要保留文件的內容,請使用open("file.txt", "r+")
而不是open("file.txt", "w")
。 您可以通過單擊鏈接了解有關open
function 的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.