如何在用户加入新Guild时运行代码发送包含服务器ID、服务器名称、成员数的Embed?
实现Discord机器人加入新服务器时发送Embed通知的完整方案
Got it, let's break down exactly how to build this feature for your Discord bot. I'll cover the core workflow, share working code examples for two popular libraries (discord.js v14 and py-cord), and highlight critical details you don't want to miss.
核心实现思路
The key here is listening to the guildCreate (JS) / on_guild_join (Python) event—this triggers automatically when your bot is added to a new server. From there, you'll:
- Pull the server's ID, name, and member count from the event's Guild object
- Build a formatted Embed message with those details
- Send the Embed to a designated log channel (or optionally, the new server's system channel)
Step 1: Prep Work
First, make sure you have these bases covered:
- A working Discord bot setup with either discord.js (v14) or py-cord installed
- Your bot has the
SendMessagesandEmbedLinkspermissions in any channel you want to send the notification to - In the Discord Developer Portal, enable the Guilds Intent (required to receive the server join event)
Step 2: Code Implementation
Example 1: discord.js (v14)
const { Client, EmbedBuilder, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, // Mandatory for guildCreate events GatewayIntentBits.GuildMembers // Optional: For more accurate member counts if needed ] }); // Replace these with your actual values const BOT_TOKEN = 'your-bot-token-here'; const LOG_CHANNEL_ID = 'your-log-channel-id-here'; // Channel to send all join notifications to client.on('guildCreate', async (guild) => { // Build the Embed message const joinEmbed = new EmbedBuilder() .setColor('#2ecc71') // Green accent color—feel free to change .setTitle('🎉 Bot Joined a New Server!') .addFields( { name: 'Server ID', value: guild.id, inline: true }, { name: 'Server Name', value: guild.name, inline: true }, { name: 'Total Members', value: guild.memberCount.toString(), inline: true } ) .setTimestamp(); try { // Send to your designated log channel first const logChannel = await client.channels.fetch(LOG_CHANNEL_ID); if (logChannel && logChannel.isTextBased()) { await logChannel.send({ embeds: [joinEmbed] }); } // Optional: Try sending to the new server's system channel (if bot has permissions) const systemChannel = guild.systemChannel; if (systemChannel && systemChannel.permissionsFor(client.user).has(['SendMessages', 'EmbedLinks'])) { await systemChannel.send({ embeds: [joinEmbed] }); } } catch (error) { console.error('Failed to send join notification:', error); } }); client.login(BOT_TOKEN);
Example 2: py-cord
import discord from discord.ext import commands # Enable required intents intents = discord.Intents.default() intents.guilds = True # Required to trigger on_guild_join bot = commands.Bot(command_prefix='!', intents=intents) # Replace these with your actual values BOT_TOKEN = 'your-bot-token-here' LOG_CHANNEL_ID = 123456789012345678 # Numeric ID of your log channel @bot.event async def on_guild_join(guild): # Build the Embed message join_embed = discord.Embed( title='🎉 Bot Joined a New Server!', color=discord.Color.green() ) join_embed.add_field(name='Server ID', value=guild.id, inline=True) join_embed.add_field(name='Server Name', value=guild.name, inline=True) join_embed.add_field(name='Total Members', value=str(guild.member_count), inline=True) join_embed.timestamp = discord.utils.utcnow() try: # Send to your designated log channel log_channel = bot.get_channel(LOG_CHANNEL_ID) if log_channel: await log_channel.send(embed=join_embed) # Optional: Send to the new server's system channel (if permissions allow) system_channel = guild.system_channel if system_channel and system_channel.permissions_for(bot.user).send_messages and system_channel.permissions_for(bot.user).embed_links: await system_channel.send(embed=join_embed) except Exception as e: print(f'Failed to send join notification: {e}') bot.run(BOT_TOKEN)
Critical Notes to Avoid Headaches
- Permission Checks: Always verify the bot has the right permissions before sending messages—otherwise, you'll get silent failures or errors.
- Intent Configuration: Don't forget to enable the Guilds Intent in the Discord Developer Portal (under "Privileged Gateway Intents")—without it, your bot won't receive the join event at all.
- Member Count Accuracy: The
memberCountvalue can be cached. If you need real-time accurate counts, you'll need to enable the Guild Members Intent and callguild.members.fetch()(but be aware of Discord's rate limits). - Error Handling: The try/catch blocks are essential—they prevent your bot from crashing if a channel is deleted, permissions are missing, or other unexpected issues pop up.
内容的提问来源于stack exchange,提问作者IThundxr
相关产品推荐
相关产品推荐

