discord.py 1.7.2 - 如何私信用户

discord.py 1.7.2 - How to private message user

discord.py 1.7.2

用例:

When a user joins my channel, I save their discord id in my database. If a user sent a message with the word $sub foo they subscribe to one of my services. When they subscribe to this service. They idea is for them to get a private message every now and again based on the type

代码

import discord,os,asyncio
from discord.ext import commands, tasks
from Entity.notifications import Notification
from dotenv import load_dotenv

from discord.utils import get
bot = commands.Bot(command_prefix='$')

@bot.event
async def on_ready():
    print('Bot is ready')

@tasks.loop(seconds=10)
async def user_notification():
    print("foo") ##terminal shows the word foo
    await bot.wait_until_ready()
    user_sub_notifications= Notification().get_active_user_sub_notification()

    if user_sub_notifications:
        for notification in user_sub_notifications:
            if "user_discord_id" in notification:
                #get user
                user = get(bot.get_all_members(), id=notification['user_discord_id'])
                #get the message to sent to the user
                message = notification['message']
                #private message the user
                #bot.send_message(user, message)
                
    await asyncio.sleep(10)

load_dotenv() 
user_notificarion.start()
bot.run(os.getenv('DISCORD_TOKEN'))

我已经试过了

user = get(bot.get_all_members(), id=notification['discord_id']) #got NONE
bot.send_message(notification['user_discord_id'], message) ##bot has not attribute send_message

如何给用户私信?谢谢

感谢 discord.py github 的 Rapptz 回答了这个问题。所有的功劳都归于他。

在 v1.7 中,您需要先获取用户:

user = bot.get_user(user_id) or await bot.fetch_user(user_id)
await user.send('whatever')

将来在 v2.0 中(仍在开发中)您将可以通过用户 ID 直接打开 DM:

dm = await client.create_dm(user_id)
await dm.send('whatever')

实际有效的方法是 fetch_user

我想说的最好和最简单的方法是:

await member.send("{message}")

这将自动打开与使用该命令的成员的 dm,您可以输入任何您想要的消息,类似于 ctx.send