Discord.py:将消息从一个频道转发到另一个

时间:2021-03-24 12:28:45

标签: python python-3.x 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)

1 个答案:

答案 0 :(得分:0)

最简单的方法如下:

@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])

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

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