2
votes

I have developed a small bot in python3 thanks to the discord.py plugin which must send a private message to all users present in the Discord server.

@bot.event
async def on_message(message):
    if message.content.startswith('!mmb'):
        channel = message.channel
        x = message.guild.members
        text = 'Test'
        for member in x:
            print(member)
            if member.bot == "True":
                print(f"Message non envoyé à {member.name}.")
            else :
                await member.send(text)
                print(f"Messages envoyé à {member.name}")
        print("Tous les messages ont été envoyés.")

So I create a list of all the users present on the server and then I make a loop which sends the said message to all the users by removing the bot. The problem is that in this user list, there are some who have disabled private messages on the server so the bot cannot send the message and generates an error :

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\antoi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "./main.py", line 31, in on_message
    await member.send(text)
  File "C:\Users\antoi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\abc.py", line 856, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, nonce=nonce)
  File "C:\Users\antoi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\http.py", line 221, in request
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user

So I would like the bot to continue the list despite the error. We can therefore either find the parameter and remove the users who have disabled private messages with a condition or ignore the error it generates and continue to execute the loop.

No need to tell you that I did not find a solution by myself. Thank you in advance for all your answers.

PS = I am Belgian (speaks French) so the above English should not be optimal, I apologize. Thank you Google Translate (=

1
discordpy.readthedocs.io/en/latest/… it raises Forbidden which you can catch. You can also use the discord.DMChannel and preemptively check if you have permission.Tin Nguyen

1 Answers

1
votes

Using a try/catch can solve your issue here. As someone pointed out in the comment, it raises a Forbidden error, so something along the lines of this would work, where it catches the error and moves on if DMs are disabled:

try:
    await member.send(text)
    print(f"Messages envoyé à {member.name}")
except discord.Forbidden:
    print("User has DMs disabled.")

Note that it can also throw a HTTPException error, so including that might be a good idea as well.