簡體   English   中英

如何顯示我的機器人是誰在私信,誰不能私信。 (discord.py)

[英]How can I show who my bot is DMing and cannot DM. (discord.py)

我知道這個問題的措辭不正確或可能沒有任何意義,所以我將提供一些關於我正在嘗試做的事情的背景和信息......

語境

我正在嘗試創建一個機器人,它可以向我服務器中的每個人發送消息以提醒他們某事,我已經掌握了如何執行此操作的代碼,但我無法弄清楚如何讓它顯示,該機器人是誰在 DMing 和誰不是DMing。 我進行了相當多的研究,但還沒有找到將我帶到這里的解決方案。

問題我如何顯示我的機器人正在 DMing 並且不能 DM。 (機器人確實做了它應該做的事情,根據請求向服務器中的每個人發送消息,但我希望它通過終端/pycharm/IDE 顯示。

例如:用戶#1000 已成功向用戶#2000 發送消息!

import discord
import os, time, random
from discord.ext import commands
from lol import token
client = discord.Client()

intents = discord.Intents.all()
client = commands.Bot(command_prefix="!", intents=intents, self_bot = True)

@client.event
async def on_ready():
    print("Ready!")
    
@client.command()
async def dm_all(ctx, *, args=None):
    if args != None:
        members = ctx.guild.members
        for member in members:
            try:
                await member.send(args)
                await print(ctx.discriminator.author)
            except:
                print("Unable to DM user because the user has DMs off or this is a bot account!")
    else: 
        await ctx.send("Please provide a valid message.")


client.run(token, bot=True)

以下是一些需要了解的重要事項:

  1. 如果用戶無法收到 DM,則會收到Forbidden錯誤。

  2. 您可以使用except語句來記錄這些錯誤並在控制台中顯示它們。

  3. 大多數情況下,您無法向機器人發送直接消息,然后您會收到HTTPException錯誤。

看看下面的代碼:

@client.command()
async def dm_all(ctx, *, args=None):
    if args is not None:
        members = ctx.guild.members
        for member in members:
            try:
                await member.send(args)
                print(f"Sent a DM to {member.name}")
            except discord.errors.Forbidden:
                print(f"Could not send a DM to: {member.name}")
            except discord.errors.HTTPException:
                print(f"Could not send a DM to: {member.name}")

    else:
        await ctx.send("Please provide a valid message.")

Output:

Sent a DM to Dominik
Could not send a DM to: BotNameHere
  • 當然,您可以根據自己的意願自定義member.name

參考: https://discordpy.readthedocs.io/en/latest/api.html?highlight=forbidden#discord.Forbidden

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM