【问题标题】:Sending message to all user (dm off failure)向所有用户发送消息(dm off 失败)
【发布时间】:2021-12-24 12:21:59
【问题描述】:

我在这里遇到的问题是,当机器人在成员之间循环并发送消息时,当用户关闭 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`

谢谢!

【问题讨论】:

    标签: python discord discord.py bots


    【解决方案1】:

    您的代码无法正常工作的原因是,每当您遇到错误时,循环就会中断,并从 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`")
    

    【讨论】:

      【解决方案2】:

      好的!所以我想出了我遇到的问题。我需要搬家

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

      【讨论】:

        猜你喜欢
        • 2022-01-11
        • 2015-01-27
        • 2019-04-29
        • 2017-02-07
        • 1970-01-01
        • 1970-01-01
        • 2021-11-09
        • 1970-01-01
        相关资源
        最近更新 更多