discord.py 1.7.2 - 如何私信用户

Posted

技术标签:

【中文标题】discord.py 1.7.2 - 如何私信用户【英文标题】:discord.py 1.7.2 - How to private message user 【发布时间】:2021-07-27 08:07:06 【问题描述】:

discord.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

如何给用户发私信?谢谢

【问题讨论】:

discordpy.readthedocs.io/en/stable/… 这能回答你的问题吗? AttributeError: 'Client' object has no attribute 'send_message' (Discord Bot) @SuperStormer 感谢您的回复,可惜没有。我遇到的大多数示例都是基于用户是否刚刚发送了一条新消息并且您想立即回复他们或立即给他们发送私人消息,您可以使用 cxt 对象。但是,如果您想通过私人消息回复,几天、几周或几小时后。如果您有他们的 discord_id,似乎零示例或用例可用 啊,那你要***.com/questions/57336369/… @SuperStormer 是的,我试了一下,得到了AttributeError: 'NoneType' object has no attribute 'send' client.get_user 返回 None。 【参考方案1】:

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

【讨论】:

【参考方案2】:

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

await member.send("message")

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

【讨论】:

以上是关于discord.py 1.7.2 - 如何私信用户的主要内容,如果未能解决你的问题,请参考以下文章

如何检查用户是不是提供了参数 discord.py

如何使用 discord.py 让 discord bot ping 用户 [关闭]

如何使用 Discord.py 对特定用户进行 dm?

如何使用 discord.py 获取不和谐用户的用户 ID

Discord.py:如何从 UserID 获取用户?

Discord.py - 如何检测用户是不是提到/ping 机器人