基本上我想让我的机器人从特定频道接收我的消息。
示例:
#general contains:
Hello
Hi
Welcome
机器人应该能够在收到类似命令后输出 您好,您好,欢迎您
我尝试了 ctx.history,但结果非常糟糕,它给了我一长串除了消息之外的所有内容。
答案 0 :(得分:0)
我编写了一个简短的命令来获取给定频道的历史记录并将其输出到一个 .txt 文件中:
@bot.command
async def log_channel(self, ctx):
filename = str(ctx.channel.name)
with open(f"{filename}.txt", "w+") as fp:
async for msg in ctx.channel.history(limit=None):
try:
towrite = f"[{msg.author.name}] @ [{msg.created_at}] said: {msg.clean_content} \n"
except:
towrite = "message unreadable. likely an image?"
fp.write(towrite)
await ctx.send(file=discord.File(f"{filename}.txt"))
您在调用 ctx.history
时可能做错的是,您期望它以文本形式返回消息列表 - 它没有这样做,它返回消息 objects .您可以阅读有关 discord.Message
here 的更多信息。有两种方法可以从消息对象中获取文本,您可以调用 discord.Message.content
,也可以调用 discord.Message.clean_content
。就个人而言,我发现 clean_content
对于日志记录等应用程序更有用,在这些应用程序中,消息不一定会以不和谐的方式保存,而提及可以适当呈现。 clean_content
删除所有提及并用他们自己的文本版本替换它们,因此例如 <#id> turns into #name. discord.Message.content
另一方面以 <#id> 保留 <#id> 的形式返回所有内容.它不会变成#name。选择您认为更适合您正在做的事情的一种,然后使用它。