Discord.py 使机器人复制每条消息,包括文件

时间:2021-02-07 23:41:03

标签: python discord discord.py

我的目标是制作一个不和谐机器人,它以用户发送的相同消息进行响应,如果此人发送了一个文件,机器人就会发送它的链接。

我可以让这两个部分单独工作,但一起工作时我遇到了问题(见底部),在我当前的代码中,只有“独立”文件发送有效,短信无效,如果你有文本 + 文件,文件链接将由机器人发送,但文本不会。如果我把第二部分放在上面,那么我得到的结果基本上完全相反,只有文本被发送,没有文件。

我的代码:

@client.event # Clone message
async def on_message(message):
    await client.process_commands(message)
    if message.author == client.user:
        return
    ch = message.channel
    await ch.send(message.content)

@client.event # Clone file
async def on_message(message):
    await client.process_commands(message)
    if message.author == client.user:
        return
    url = message.attachments[0].url
    ch = message.channel
    await ch.send(url)

底部的克隆文件总是出现 IndexError: list index out of range 错误

底部的克隆消息总是出现 400 Bad Request (error code: 50006): Cannot send an empty message 错误

1 个答案:

答案 0 :(得分:1)

正如@FierySpectre 所指出的,您正在覆盖 on_message 函数。您可以将您想做的事情合并到一个功能中。

@client.event
async def on_message(message):
    await client.process_commands(message)
    if message.author == client.user:
        return
    ch = message.channel
    try: # tries to send the url of the file
        await ch.send(message.attachments[0].url)
    except IndexError: # if index error is received, that means the user entered a regular message
        pass
    await ch.send(message.content) # prints out the message