Certainly! Below is a complete discord.py script that greets users when they join your Discord server. It creates a customized embed with a welcome image that includes the new member's profile picture (avatar), greeting text, and additional aesthetic elements. This script uses the Pillow library to manipulate images, so ensure you have it installed.
Prerequisites
-
Install Required Libraries
Make sure you have discord.py and Pillow installed. You can install them using pip:
pip install discord.py Pillow
-
Bot Setup
- Intents: To access member events like
on_member_join, you need to enable the Server Members Intent in your bot's settings on the Discord Developer Portal.
- Permissions: Ensure your bot has permission to send messages and embed links in the designated welcome channel.
Complete Script
import discord
from discord.ext import commands
from discord import Intents
from PIL import Image, ImageDraw, ImageFont
import io
import requests
# Replace these with your actual values
TOKEN = 'YOUR_BOT_TOKEN'
WELCOME_CHANNEL_ID = 123456789012345678 # Replace with your welcome channel ID
BACKGROUND_IMAGE_URL = 'https://i.imgur.com/your_background_image.png' # Replace with your background image URL
# Intents are required to receive certain events
intents = Intents.default()
intents.members = True # Subscribe to the privileged members intent
# Initialize bot
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
@bot.event
async def on_member_join(member: discord.Member):
# Fetch the welcome channel
channel = bot.get_channel(WELCOME_CHANNEL_ID)
if channel is None:
print(f"Welcome channel with ID {WELCOME_CHANNEL_ID} not found.")
return
# Download the background image
response = requests.get(BACKGROUND_IMAGE_URL)
if response.status_code != 200:
print("Failed to download background image.")
return
background = Image.open(io.BytesIO(response.content)).convert("RGBA")
# Download the member's avatar
avatar_url = member.avatar.url if member.avatar else member.default_avatar.url
avatar_response = requests.get(avatar_url)
if avatar_response.status_code != 200:
print("Failed to download member avatar.")
return
avatar = Image.open(io.BytesIO(avatar_response.content)).convert("RGBA")
avatar = avatar.resize((150, 150)) # Resize avatar as needed
# Create a mask to make the avatar circular
mask = Image.new('L', avatar.size, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + avatar.size, fill=255)
avatar.putalpha(mask)
# Paste the avatar onto the background
background_width, background_height = background.size
avatar_position = (background_width - 200, background_height - 200) # Adjust position as needed
background.paste(avatar, avatar_position, avatar)
# Draw text
draw = ImageDraw.Draw(background)
try:
# You can use a custom font by providing the path to a .ttf file
font = ImageFont.truetype("arial.ttf", 40)
except IOError:
font = ImageFont.load_default()
welcome_text = f"Welcome, {member.name}!"
text_width, text_height = draw.textsize(welcome_text, font=font)
text_position = ((background_width - text_width) / 2, 50) # Centered at the top
draw.text(text_position, welcome_text, font=font, fill=(255, 255, 255, 255)) # White text
# Convert the image to a file-like object
with io.BytesIO() as image_binary:
background.save(image_binary, 'PNG')
image_binary.seek(0)
# Create a Discord file
discord_file = discord.File(fp=image_binary, filename='welcome.png')
# Create an embed
embed = discord.Embed(
title="🎉 Welcome!",
description=f"Hello {member.mention}, we're glad to have you here!",
color=0x00ff00 # Green color
)
embed.set_image(url="attachment://welcome.png")
embed.set_thumbnail(url=member.avatar.url if member.avatar else member.default_avatar.url)
embed.set_footer(text=f"User ID: {member.id}")
# Send the embed with the image
await channel.send(embed=embed, file=discord_file)
# Run the bot
bot.run(TOKEN)
Explanation & Customization
-
Imports:
discord, commands, and Intents from discord.py handle Discord interactions.
Image, ImageDraw, ImageFont from Pillow handle image processing.
io and requests are used to handle image downloads and in-memory files.
-
Configuration:
- TOKEN: Replace
'YOUR_BOT_TOKEN' with your bot's actual token.
- WELCOME_CHANNEL_ID: Replace
123456789012345678 with the ID of the channel where you want welcome messages to appear.
- BACKGROUND_IMAGE_URL: Replace the URL with the link to your desired background image for the welcome picture. Ensure the image has appropriate dimensions (e.g., 800x600 pixels) for best results.
-
Bot Intents:
- Enable
intents.members to allow the bot to receive member-related events like on_member_join.
-
Event Handler (on_member_join):
- Channel Retrieval: Fetches the designated welcome channel using its ID.
- Background Image: Downloads and opens the background image from the provided URL.
- Member Avatar:
- Downloads the new member's avatar. If the member doesn't have a custom avatar, it uses the default one.
- Resizes and masks the avatar to make it circular.
- Image Composition:
- Pastes the avatar onto the background image at a specified position.
- Adds a welcome text at the top center. You can customize the font, size, color, and position as needed.
- Embed Creation:
- Converts the composed image into a Discord-compatible file.
- Creates an embed that includes:
- A title with an emoji.
- A description mentioning the new member.
- The composed welcome image.
- The member's avatar as a thumbnail.
- A footer with the member's user ID for reference.
- Sending the Message: Sends the embed along with the image file to the welcome channel.
Additional Aesthetic Enhancements
Feel free to enhance the welcome image further:
-
Custom Fonts: Use a more stylish font by providing the path to a .ttf file in the ImageFont.truetype method.
font = ImageFont.truetype("path_to_your_font.ttf", 40)
-
Decorative Elements: Add shapes, lines, or other images to the background to make the welcome message more attractive.
# Example: Add a border
border_color = (255, 215, 0, 255) # Gold color
border_width = 10
draw.rectangle([(0, 0), (background_width, background_height)], outline=border_color, width=border_width)
-
Dynamic Content: Include dynamic content such as server rules, member count, or assign a welcome role automatically.
# Example: Assign a role upon joining
welcome_role = discord.utils.get(member.guild.roles, name="New Member")
if welcome_role:
await member.add_roles(welcome_role)
Final Notes
- Error Handling: The script includes basic error handling for missing channels and failed image downloads. You can expand this to handle more edge cases as needed.
- Performance: For servers with high join rates, consider optimizing image processing or caching resources to improve performance.
- Security: Ensure that your bot has only the necessary permissions and that sensitive information like the bot token is securely stored (e.g., using environment variables or a secure config file).
Feel free to modify and expand upon this script to best suit your server's needs. Happy coding!