如何在Discord.py中获取消息内容并在机器人回复中返回
解决Discord.py中获取消息内容并返回的问题
问题分析
你的代码报错是因为copycat命令函数里未定义message变量。在Discord.py的命令上下文(ctx)中,触发命令的消息对象需要通过ctx.message来访问。
修复方案
方案1:返回完整消息内容(含命令前缀和命令名)
如果需要原样返回用户发送的整条消息,修改代码如下:
import discord from discord.ext import commands # 替换为你的机器人令牌 TOKEN = "your_bot_token_here" bot = commands.Bot(command_prefix="=", intents=discord.Intents.all()) @bot.event async def on_ready(): print("机器人已启动运行。") @bot.command() async def copycat(ctx): # 通过ctx.message获取触发命令的完整消息文本 full_content = ctx.message.content embed = discord.Embed(title="Copy Cat", description=full_content, color=0x3cc13c) await ctx.send(embed=embed) bot.run(TOKEN)
方案2:返回命令后的内容(排除=copycat部分)
如果只需要返回命令名称之后的文本内容,可以通过命令参数捕获:
import discord from discord.ext import commands TOKEN = "your_bot_token_here" bot = commands.Bot(command_prefix="=", intents=discord.Intents.all()) @bot.event async def on_ready(): print("机器人已启动运行。") @bot.command() async def copycat(ctx, *, content): # *符号用于捕获命令后所有文本(含空格)作为单个参数 embed = discord.Embed(title="Copy Cat", description=content, color=0x3cc13c) await ctx.send(embed=embed) bot.run(TOKEN)
关键说明
ctx.message.content:获取触发命令的整条消息文本,包括命令前缀和命令名。*, content:命令参数中的*会将命令名之后的所有内容(无论是否包含空格)合并为一个字符串参数传递给content。
内容的提问来源于stack exchange,提问作者Zyzzyx 914
相关产品推荐
相关产品推荐

