Discord Python机器人开发:实现含指定关键词的消息响应并避免自回复
Discord Bot: Respond to "Hello" & Ignore Own Messages
Hey there, let's get your Discord bot sorted out with those requirements. Here's a clean, reliable way to implement what you need:
Key Fixes & Additions
- Ditch hardcoded bot usernames: Instead of checking for a specific bot tag like "Бот-Бобот#0869", use the built-in
message.author.botproperty. This works for any bot and is way more maintainable. - Add the "Hello" response: We'll add a new condition to trigger when a message starts with "Hello", and make sure the reply includes "Hello" as requested.
Full Updated Code
import random # Define your list of friendly suffixes (adjust this to your needs) list2 = ["buddy", "pal", "friend", "there"] async def on_message(message): # First, ignore any messages sent by bots (including our own!) if message.author.bot: return # Respond to Russian "Привет" (kept from your original code) if message.content.startswith('Привет'): print('[command]: Задан вопрос3 ') await message.channel.send(f'Привет {random.choice(list2)}!') # Respond to English "Hello" with a Hello-containing reply if message.content.startswith('Hello'): print('[command]: Received Hello command') # Customize this reply however you want—just keep "Hello" in it! await message.channel.send(f'Hello {message.author.display_name}, {random.choice(list2)}!')
Breakdown of Changes
- Bot Message Check: The
if message.author.bot: returnline goes first to immediately skip processing any bot messages. This ensures your bot never responds to itself, no matter what its username is. - Hello Response: The new
if message.content.startswith('Hello')block triggers when someone sends "Hello". The reply usesmessage.author.display_nameto address the user directly (a nice touch!) and includes "Hello" as required. We kept the randomlist2element to keep replies natural, just like your original code. - Cleaner String Formatting: Swapped the old string concatenation (
'Привет ' + random.choice(list2) + '!') for f-strings—they're easier to read and maintain.
内容的提问来源于stack exchange,提问作者369
相关产品推荐
相关产品推荐

