discord.py 1.7.2
use case:
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
Code
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'))
I have tried the follow
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
how can I private message the user? Thank you
Thanks to Rapptz from the discord.py github who answered this question. All credit goes to him.
In v1.7 you need to fetch the user first:
user = bot.get_user(user_id) or await bot.fetch_user(user_id)
await user.send('whatever')
In the future in v2.0 (still in development) you'll be able to open a DM directly via user ID:
dm = await client.create_dm(user_id)
await dm.send('whatever')
the actual method which works is the fetch_user