Home > Software design >  Sending message to all user (dm off failure)
Sending message to all user (dm off failure)

Time:11-12

The issue im having here is when the bot is cycling through the members and its sending the message, when a user has the dms off it just stops going through them.

I would like it so it keeps going through the members after hitting a member with dms off.

CODE:

@client.command()
async def pd(ctx):
  try:
    for m in client.get_all_members():
        await m.send(ad)
        print(f"received the ad")
  except:
    print(f" has [DM] `off`")

This is what it looks like after hitting a member with dms off. TERMINAL:

bot is now online
received the ad
received the ad
received the ad
received the ad
 has [DM] `off`

Thank you!

CodePudding user response:

The reason your code is not working is because whenever you get an error, the loop is broken, and execution continues from the except: block.

You can fix this simply by putting the try: and except: inside the loop.

@client.command()
async def pd(ctx):

  # Iterates over each member
  for m in client.get_all_members():

    # Try sending the message to the member
    try:
      await m.send(ad)
      print(f"received the ad")

    # If an error is produced, log it.
    # After this, the loop will continue onto
    # the next member.
    except:
      print(f" has [DM] `off`")

CodePudding user response:

OK! So I figured out the issue I had. I needed to move

try:

Down a line to make it inside the loop

EXAMPLE:

@client.command()
async def pd(ctx):
  
    for m in client.get_all_members():
       try:
        await m.send(ad)
        print(f"received the ad")
       except:
        print(f" has [DM] `off`")
    print("finished sending ads")

  • Related