discord.py技术问题:如何获取用户名首字母用于工单系统频道命名?
Hey there! Let's get your ticket system to include the user's initials in the channel name. Here's a straightforward breakdown of what you need to adjust in your code:
Step 1: Fetch the User Who Triggered the Reaction
The on_raw_reaction_add event gives you a RawReactionActionEvent object (your reaction variable). From this, you can grab the user_id to fetch the actual user object:
user = await client.fetch_user(reaction.user_id)
Pro tip: Add a quick check to skip bot users so you don't create tickets for automated reactions:
if user.bot: return
Step 2: Extract the User's Initials
You can pull initials from either the user's base username (user.name) or their server-specific display name (user.display_name — this is better if users have custom nicknames in your server).
- For a single initial (first character of their display name):
initials = user.display_name[0].upper() # Uppercase for consistent formatting
- For multiple initials (e.g., "John Doe" → "JD"):
# Split the display name into words, take the first character of each, uppercase, then join initials = ''.join([word[0].upper() for word in user.display_name.split()])
Step 3: Update the Channel Name to Include Initials
Modify your create_text_channel call to insert the initials into the channel name. For example:
ticket = await guildbtv.create_text_channel( name=f'ticket-{initials}', # Creates names like "ticket-J" or "ticket-JD" overwrites=overwrites, category=supportcat, topic='Hier kannst du dein Anliegen äussern!', reason='Ticket' )
Full Updated Code Example
Putting it all together, your event handler should look like this:
@client.event async def on_raw_reaction_add(reaction): # Fetch the user who reacted user = await client.fetch_user(reaction.user_id) # Skip bot users to avoid unnecessary tickets if user.bot: return # Extract initials (swap this line if you want multi-word initials instead) initials = user.display_name[0].upper() # Create the ticket channel with initials in the name ticket = await guildbtv.create_text_channel( name=f'ticket-{initials}', overwrites=overwrites, category=supportcat, topic='Hier kannst du dein Anliegen äussern!', reason='Ticket' )
A quick note: Double-check that guildbtv is properly defined in your code (I assume you have this sorted already, but it never hurts to verify!). If a user's display name is ever empty (a rare edge case), you can add a fallback to use their username instead.
内容的提问来源于stack exchange,提问作者codeofandrin

