如何显示谁是我的机器人正在管理,谁不能管理。(discord.py)

2024-05-13 18:11:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我理解这个问题的措辞不正确,或者可能没有任何意义,所以我将提供一些上下文和信息,说明我正在尝试做什么

上下文

我试图创建一个机器人,DMs我的服务器中的每个人,以提醒他们这样或那样,我已经掌握了如何做到这一点的代码,但我有困难,如何使它显示,谁是机器人的DMing和谁不是DMing。 我已经研究了相当多的时间,还没有找到一个解决方案,导致我在这里

问题 如何显示谁是我的机器人正在管理,谁不能管理。(bot做它应该做的事情,根据请求对服务器中的每个人进行DM,但我希望它通过terminal/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)

Tags: import服务器clientbotargs机器人dmsdm
1条回答
网友
1楼 · 发布于 2024-05-13 18:11:54

这里有一些重要的事情需要知道:

  1. 如果用户无法接收DM,则会出现Forbidden错误

  2. 您可以使用except语句记录这些错误并在控制台中显示它们

  3. 大多数情况下,您无法向bot发送直接消息,然后会出现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.")

输出:

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

相关问题 更多 >