You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.bot property. 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

  1. Bot Message Check: The if message.author.bot: return line goes first to immediately skip processing any bot messages. This ensures your bot never responds to itself, no matter what its username is.
  2. Hello Response: The new if message.content.startswith('Hello') block triggers when someone sends "Hello". The reply uses message.author.display_name to address the user directly (a nice touch!) and includes "Hello" as required. We kept the random list2 element to keep replies natural, just like your original code.
  3. Cleaner String Formatting: Swapped the old string concatenation ('Привет ' + random.choice(list2) + '!') for f-strings—they're easier to read and maintain.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 07:12:43