首页 > 解决方案 > Discord.py :将消息从一个频道转发到另一个频道

问题描述

我正在尝试使用以“//”为前缀的机器人发出某种说命令。

在管理命令通道中输入//say_next #some_channel时,我希望在发送第二条消息时将其复制并发送到#some_channel

这是我的代码

@commands.command()
@commands.has_permissions(administrator=True)
async def say_next(self, ctx: Context, channel: discord.TextChannel):
    if ctx.channel.id != get_from_config("admin_commands_channel_id"):
        return

    def message_check(m: discord.Message):
        return m.author == ctx.author

    try:
        message_to_send: discord.Message = await self.bot.wait_for("message", check=message_check, timeout=15)
    except asyncio.TimeoutError:
        await ctx.send(content="Cancelled")
    else:
        await channel.send(content=message_to_send.content)

问题在于,这将转发的消息限制为仅复制原始消息文本。

我希望转发复制消息的所有元素,即未定义的嵌入数量、文件或无文件等......但这无法完成,因为该Messageable.send方法不能与Message对象一起使用,这是我的message_to_send变量.

如果没有像这样Messageable.send的属性的每个参数都没有这样的属性,如何进行这种转发?message_to_send

content = message_to_send.content
embed = None if len(message_to_send.embeds) == 0 else message_to_send.embeds[0]
tts = message_to_send.tts
attachments = message_to_send.attachments
file = files = None
if len(attachments) > 1:
    files = attachments
else:
    file = attachments[0]
await channel.send(content=content, tts=tts, file=file, files=files, embed=embed)

标签: pythonpython-3.xdiscord.py

解决方案


最简单的方法如下:

@commands.command()
@commands.has_permissions(administrator=True)
async def say_next(self, ctx, channel: discord.TextChannel):
    if ctx.channel.id != get_from_config("admin_commands_channel_id"):
        return

    def check(m):
        return m.author == ctx.author

    try:
        msg = await self.bot.wait_for("message", check=check, timeout=15.0)
    except asyncio.TimeoutError:
        await ctx.send("Cancelled")
    else:
        await channel.send(msg.content, tts=msg.tts, files=[await attch.to_file() for attch in msg.attachments])

我没有包含嵌入,因为普通用户无法发送嵌入。

关于这段代码,我真的没什么可说的,唯一的就是kwarg,它只是将实例转换为实例files的一些列表理解。如果您只发送一个文件(或零个文件),您可能会认为它不起作用,我也这么认为,但显然它有效。discord.Attachmentdiscord.File


推荐阅读