Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

python - Discord.py - Sending messages to every member

Before everyone starts assuming, I have permissions to do this command.

@bot.command()
@commands.has_permissions(administrator=True)
async def dm(ctx, *, message=None):
    await ctx.message.delete()
    if message:
        for guilds in bot.guilds:
            members = guilds.members
            for m in members:
                await m.send(message)
                print("Message sent to all")

I receive an error:

Command raised an exception: HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user

Because I'm dm-ing every member, some members do have their dms open (I have personally dm'd some members using their ID and it worked)

How do I fix this error?

question from:https://stackoverflow.com/questions/65894104/discord-py-sending-messages-to-every-member

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're getting this error because the bot is unable to send the DM because the user has their DMs disabled or friends only, You can list the users who didn't get the DMs.

Here is how you can see who didn't get the DMs.

@bot.command()
@commands.has_permissions(administrator=True)
async def dm(ctx, *, message=None):
    await ctx.send(f"{ctx.author.mention} Message sent to all users in this server except the users listed below.")
    await ctx.message.delete()
    if message:
        for guilds in bot.guilds:
            members = guilds.members
            for m in members:
                try:
                    await m.send(message)
                except discord.Forbidden: # discord.Forbidden means that the bot can't be sent.
                    await ctx.send(f"{m.name}#{m.discriminator}")

I hope this helped, I felt like Kelo's answer wasn't really explaining much so I tried to help and improve the code.

Have a nice day!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...