【问题标题】:discrod.py Text channel history to HTML filediscrod.py 文本频道历史到 HTML 文件
【发布时间】:2021-02-26 20:12:18
【问题描述】:

我正在寻找一种导出文本通道的方法。到一个 HTML,以便我可以删除频道。

我在另一个机器人上看到了这个,这是一张照片。

@bot.command()
async def export(ctx):
    # get the html here for ctx.channel
 
    await ctx.send(file=HTML)

【问题讨论】:

    标签: python html discord discord.py


    【解决方案1】:
    @bot.command()
    async def export(ctx): 
        messages = await ctx.channel.history(limit=None).flatten()
    
        file = open("file.html", "a")
        for i in messages:
            file.write(f'[{i.created_at}]{i.author} | {i.channel.name} | {i.content}<br> \n')
        file.close()
        await ctx.channel.send(file='file.html')
    

    无论何时调用export 命令!机器人开始存储特定通道中的所有消息并存储在messages变量n中转换为list

    open()函数的帮助下,我们打开了HTML文件并编写了\

    "[message time] user_name | channel_name | message"
    

    [documentation:TextChannel.history]

    确保机器人必须拥有READ MESSAGE HISTORY 的权限。

    【讨论】:

    • [This ](imgur.com/a/RT9ijSE) 与照片中显示的不和谐布局不同,嵌入也无法正确显示。另外考虑使用with open("file.html", "a" as f:,以便它自行关闭文件。
    • 如果有一些(html,css)专家,我们可以让它看起来像那个图像。我的代码只是给出了时间、用户、消息等。使用 html css 你可以让它看起来像那样!。
    • 实际上我找到了this,它在照片中使用。我会将此标记为答案。谢谢
    【解决方案2】:

    使用chat-exporter

    # import chat_exporter
    # import io
    async def archive(channel, archive_channel):
        # channels are not None
        if channel and archive_channel:
            transcript = await chat_exporter.export(channel, set_timezone='UTC')
            transcript_file = discord.File(io.BytesIO(transcript.encode()),
                                           filename=f"{channel.name}.html")
    
            await archive_channel.send(file=transcript_file)
            # await channel.delete()
    

    使用Tyrrrz's DiscordChatExporter(不推荐)

    从GtiHub下载cli并导出到同一路径

    获取聊天导出器的路径:

    def get_chat_exporter_path():
        if os.name == 'nt': # windows environment
            return f'.{os.sep}DiscordChatExporter.CLI{os.sep}DiscordChatExporter.Cli.exe'
        elif os.name == 'posix': # linux environment
            return f'dotnet .{os.sep}DiscordChatExporter.CLI{os.sep}DiscordChatExporter.Cli.dll'
        else:
            return
    

    存档频道

    # import subprocess
    
    async def archive(channel, archive_channel):
        path = get_chat_exporter_path()
        if not path:
            return
    
        file_path = f'.{os.sep}archive{os.sep}{channel.name}.html'
        subprocess.Popen([path, 'export', '-t', DISCORD_TOKEN, '-b', '-c', str(channel.id), '-o', file_path, '--dateformat', 'u'], shell=True).wait()
        await archive_channel.send(file=discord.File(file_path))
        await channel.delete()
    

    【讨论】:

      猜你喜欢
      • 2011-03-09
      • 2013-05-27
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多