简体   繁体   English

Discord.py - 向每个成员发送消息

[英]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)因为我在给每个成员发消息,所以有些成员确实打开了他们的 dms(我个人使用他们的 ID 给一些成员发了 dm 并且它有效)

How do I fix this error?如何修复此错误?

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.您收到此错误是因为机器人无法发送 DM,因为用户禁用了他们的 DM 或只有朋友,您可以列出没有收到 DM 的用户。

Here is how you can see who didn't get the DMs.您可以通过以下方式查看谁没有收到 DM。

@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.我希望这会有所帮助,我觉得 Kelo 的回答并没有真正解释太多,所以我试图帮助和改进代码。

Have a nice day!祝你今天过得愉快!

You could use a try-except to avoid the error.您可以使用 try-except 来避免错误。

try:
    await m.send(message)
except:
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM