在 discord.py 中获取 DM 消息

时间:2021-04-28 20:48:17

标签: python discord discord.py

所以我有这个代码

import discord
from discord.ext.commands import Bot
from discord import DMChannel
TOKEN = "bot token"
client = Bot (command_prefix='!')
@client.command(name='dm', pass_context=True)
async def dmsend(ctx):
    user = await client.fetch_user("user ID")
    await DMChannel.send(user, "Hello there!")
client.run(TOKEN)

如果用户写了 !dm,它基本上会向特定用户发送一条消息。但是有没有办法通过 dms 做到这一点?因此,每次我在 dms 下收到带有 !dm 的消息时,它都会在 #general 频道中执行吗?

1 个答案:

答案 0 :(得分:1)

您可以在某些地方添加一些约束并使代码更简单。

首先:使用 @commands.dm_only() 从而确保或仅允许在私人消息中执行该命令。

第二:您查询消息作者的方式有点复杂,不应为此使用 fetch,否则您可能会受到速率限制。最好的方法是使用以下内容:user = ctx.author

第三:要定义一个 general 频道或其他东西,您可以使用 client.get_channel(ChannelID)

查看完整代码:

@client.command()
@commands.dm_only() # Can only be used in the bots DMs
async def dmsend(ctx):
    user = ctx.author
    await user.send("Hello there!") # Send a DM to the author of the command
    general = client.get_channel(ChannelID) # Define the general channel
    await general.send(f"Sent a DM to {ctx.author}") # Your text after a DM

另请参阅 docs 了解更多信息