向所有用户发送消息(dm 关闭失败)

Sending message to all user (dm off failure)

我在这里遇到的问题是,当机器人在成员之间循环并发送消息时,当用户关闭 dms 时,它就会停止通过它们。

我想要它,所以它会在关闭 dms 的情况下击中会员后继续通过会员。

代码:

@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`")

这是关闭 dms 击中成员后的样子。 终端机:

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

谢谢!

您的代码无法运行的原因是,每当您遇到错误时,循环就会中断,并从 except: 块继续执行。

您只需将 try:except: 放在循环中即可解决此问题。

@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`")

好的!所以我弄清楚了我遇到的问题。我需要移动

try:

向下一行使其进入循环

示例:

@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")