【问题标题】:Discord Bot to DM specific rolesDiscord Bot 到 DM 特定角色
【发布时间】:2020-09-02 11:40:06
【问题描述】:

一直在尝试从另一个人那里获得有关此代码的解决方法,但我无法使其正常工作...这是代码:

import discord
from discord.ext.commands import bot
from discord import game
from discord.ext import commands
import asyncio
import platform
import colorsys
import random
import time

client = commands.Bot(command_prefix = '!', case_insensitive=True)
Client = discord.client
Clientdiscord = discord.Client()

@client.event
async def on_ready():
    print('Logged in as '+client.user.name+' (ID:'+client.user.id+') | Connected to '+str(len(client.servers))+' servers | Connected to '+str(len(set(client.get_all_members())))+' users')
    print('--------')
    print('--------')

@client.command(pass_context = True)
@commands.has_permissions(kick_members=True)     
async def userinfo(ctx, user: discord.Member):
    r, g, b = tuple(int(x * 255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1))
    embed = discord.Embed(title="{}'s info".format(user.name), description="Here's what I could find.", color = discord.Color((r << 16) + (g << 8) + b))
    embed.add_field(name="Name", value=user.name, inline=True)
    embed.add_field(name="ID", value=user.id, inline=True)
    embed.add_field(name="Status", value=user.status, inline=True)
    embed.add_field(name="Highest role", value=user.top_role)
    embed.add_field(name="Joined", value=user.joined_at)
    embed.set_thumbnail(url=user.avatar_url)
    await client.say(embed=embed)

@commands.has_permissions(administrator=True)
@client.command(pass_context = True)
async def send(ctx, *, content: str):
        for member in ctx.message.server.members:
            try:
                await client.send_message(member, content)
                await client.say("DM Sent To : {} :white_check_mark:  ".format(member))
            except:
                print("can't")
                await client.say("DM can't Sent To : {} :x: ".format(member))


client.run("TOKEN") 

该代码用于向 Discord 服务器中的每个人发送 DM,但我想要将 DM 发送给特定角色,即:!send role message。

提前感谢您的帮助

PS:它不是公共发布的机器人,我只是想为我的公会制作一个高效的公告系统。

【问题讨论】:

    标签: python bots discord


    【解决方案1】:

    看起来您正在使用旧版本 discord.py 的教程,或者两个版本之间的某种网格。

    从那时到现在,在最近的 - 重写 - 版本中,有一些 major changes

    你的命令重写了:

    bot = commands.Bot(command_prefix="!", case_insensitive=True)
    # you don't need discord.Client()
    
    # this is dming users with a certain role
    @commands.has_permissions(administrator=True)
    @bot.command()
    async def announce(ctx, role: discord.Role, *, msg): # announces to the specified role
        global members
        members = [m for m in ctx.guild.members if role in m.roles]
        for m in members:
            try:
                await m.send(msg)
                await ctx.send(f":white_check_mark: Message sent to {m}")
            except:
                await ctx.send(f":x: No DM could be sent to {m}")
        await ctx.send("Done!")
    @announce.error
    # feel free to add another decorator here if you wish for it to send the same messages
    # for the same exceptions: e.g. @userinfo.error
    async def _announcement_error(ctx, error):
        if isinstance(error, commands.BadArgument):
            await ctx.send(":x: Role couldn't be found!")
        elif isinstance(error, commands.MissingPermissions):
            await ctx.send(f":x: {ctx.author.mention}, you don't have sufficient permissions.")
        else:
            await ctx.send(error)
    

    参考资料:

    【讨论】:

    • 使用您的解决方案并使其工作,但现在我遇到了另一个问题。当尝试发送 DM 并且用户阻止了机器人时,而不是得到“:x:消息无法发送到 {m}”我得到“命令引发异常:禁止:403 禁止(错误代码 50007 ):无法向该用户发送消息。我希望它告诉用户是谁,显然“等待 ctx.send(f”:x:消息无法发送到 {m}“)”不起作用打算的=(一点帮助将不胜感激,在此先感谢=)
    • 啊抱歉,忘了我可以在错误处理程序中处理该异常哈哈。编辑了该案例的代码^
    • 好吧,尝试了那个编辑,现在我在这一行“await ctx.send(f":x: Couldn't DM the following users: {', '.join([str(m) for m in members])}")" 然后它说“discord.ext.commands.errors.CommandInvokeError:命令引发异常:NameError: name 'members'没有定义“什么是几乎相同的......我现在正在用头撞墙xD
    • 对此真的很抱歉,我自己弄乱了它并让它工作。可能有点乱,但它可以完成工作!
    • 我可能不正确地使用了黑名单这个词。发生的情况是,如果代码出错,它会将成员添加到要忽略的列表中,这样它就不会再次出错。然后它再次运行命令await ctx.invoke(.... 并一直这样做,直到所有成员都被 DMed。我使用列表 errorssent 只是为了跟踪机器人试图向哪些成员发送 DM。您可以做的是在发送Done! 之后,您可以清空errorssent 列表。这样机器人就不会继续无视你了。
    猜你喜欢
    • 2022-01-16
    • 2020-02-11
    • 2021-12-29
    • 2020-07-13
    • 2020-11-19
    • 1970-01-01
    • 2019-11-01
    • 2020-06-29
    • 1970-01-01
    相关资源
    最近更新 更多