You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用discord.py实现预设消息的!Message命令功能

Fixing Your !Message Command for Predefined Messages in discord.py

Hey there! Let's get your bot's !Message command working to send a predefined message to all members of a specified role. Your existing code has a solid start, but we need to update it for modern discord.py versions and adjust it to use a preset message instead of taking user input for the message content.

First, Let's Address Outdated Code Bits

A few things in your original snippet are deprecated in discord.py v1.0 and later:

  • pass_context=True is no longer needed (context is automatically passed to commands)
  • ctx.message.server should be replaced with ctx.guild
  • bot.send_message() is outdated—we'll use direct member messaging methods instead

Complete Working Code

Here's the revised code that implements your desired functionality:

from discord.ext import commands
import discord

# Define your predefined message here—easy to update anytime!
PREDEFINED_MESSAGE = "Hello! This is the preset message your bot will send to role members."

# Initialize the bot with your prefix and required intents
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@bot.command(name="Message")
async def send_predefined_message(ctx, role: discord.Role):
    # Track successful and failed message sends
    success_count = 0
    fail_count = 0

    # Loop through all members in the server
    for member in ctx.guild.members:
        # Check if the member has the specified role
        if role in member.roles:
            try:
                # Send the predefined message via direct message
                await member.send(PREDEFINED_MESSAGE)
                success_count += 1
            except discord.Forbidden:
                # Handle cases where the bot can't send DMs (user has DMs closed)
                fail_count += 1
                print(f"Couldn't message {member.name}—their DMs are closed.")

    # Send a summary back to the user who ran the command
    await ctx.send(f"✅ Sent preset message to {success_count} members.")
    if fail_count > 0:
        await ctx.send(f"❌ Failed to send to {fail_count} members (likely DMs disabled).")

# Run the bot with your unique token—replace this with your actual bot token!
bot.run("YOUR_BOT_TOKEN_HERE")

Key Improvements & Explanations

  • Predefined Message: We moved the message content to a top-level variable PREDEFINED_MESSAGE so you can edit it quickly without digging into command logic.
  • Error Handling: The try-except block prevents the bot from crashing if it can't send a DM (e.g., a user has disabled DMs from server members) and gives you clear feedback on failures.
  • Modern Syntax: Updated to use ctx.guild and member.send()—the current standard for discord.py.
  • Intents: Added intents=discord.Intents.all() to ensure the bot can access member data (you'll also need to enable the Server Members Intent in your Discord Developer Portal under "Privileged Gateway Intents").
  • Command Feedback: The bot sends a summary to the command runner, so they know exactly how many messages went through and how many didn't.

Important Notes

  • Make sure your bot has the Send Messages permission in the server.
  • If you want to restrict who can use this command, add a check like @commands.has_permissions(administrator=True) above the command function to limit it to server admins.

内容的提问来源于stack exchange,提问作者Logicsx

火山引擎 最新活动