Discord.py 是一个用于与 Discord API 交互的 Python 库。它允许开发者创建和管理 Discord 机器人,处理消息、命令、通知等。在 Discord 中,用户可以通过在消息中提到(mention)一个机器人来与其交互。这通常是通过在消息中包含机器人的用户 ID 或用户名来实现的。
要检测用户是否提到了/ping机器人,你可以使用 Discord.py 提供的 Message
对象的 mentions
属性。这个属性包含了消息中提到的所有用户对象。
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
@bot.event
async def on_message(message):
if bot.user in message.mentions:
await message.channel.send(f'Hello, {message.author.name}!')
await bot.process_commands(message)
bot.run('YOUR_BOT_TOKEN')
discord
和 commands
模块。intents
以确保机器人可以接收消息内容和成员信息。commands.Bot
创建一个机器人实例,并设置命令前缀为 !
。on_ready
事件:on_message
事件:bot.user in message.mentions
)。bot.process_commands(message)
处理其他命令。通过这种方式,你可以轻松地检测用户是否提到了/ping你的机器人,并根据需要做出响应。
领取专属 10元无门槛券
手把手带您无忧上云