Discord.py使bot复制每条消息,包括文件

2024-05-21 00:59:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是创建一个discord bot,该bot使用用户发送的相同消息进行响应,如果用户发送文件,则bot将发送该文件的链接

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

我的代码:

@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错误


Tags: 文件代码用户文本clienteventsend消息
1条回答
网友
1楼 · 发布于 2024-05-21 00:59:15

正如@fireyspectre指出的,您正在覆盖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

相关问题 更多 >