首页 > 解决方案 > discord.py 1.7.2 - 如何私信用户

问题描述

不和谐.py 1.7.2

用例:

当用户加入我的频道时,我将他们的 discord id 保存在我的数据库中。如果用户发送了一条消息,其中包含$sub foo他们订阅我的一项服务的词。当他们订阅此服务时。他们的想法是让他们根据类型不时地收到一条私人消息

代码

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

我怎样才能给用户发私信?谢谢

标签: pythonpython-3.xdiscorddiscord.pybackground-task

解决方案


感谢 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


推荐阅读