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

Discord.py 2.3中interaction.response无send_message方法问题求助

问题

正在将旧版Discord机器人从1.7.3版本(斜杠命令推出前的版本)升级到2.3版本,使用interaction.response.send_message()回复斜杠命令时遇到以下问题:

  • PyCharm提示Cannot find reference 'send_message' in '() -> InteractionResponse'
  • Discord端显示“应用未响应”
  • 终端无相关报错

代码片段:

import cmath
import datetime
import json
import os
import pickle
import youtube_dl
import discord
import wolframalpha
from ruamel.yaml import YAML
from discord.ext import commands
from discord import app_commands
from discord.utils import get
import requests
import pickle
import asyncio
import chatbot
print(discord.__version__)
client = wolframalpha.Client(OTHER_TOKEN)
yaml = YAML()

with open("./config.yml", "r", encoding = "utf-8") as file:
    config = yaml.load(file)


bot = commands.Bot(command_prefix = config['Prefix'], intents=discord.Intents.all())

log_channel_id = config['Log Channel ID']

bot.embed_color = discord.Color.from_rgb(
    config['Embed Settings']['Colors']['r'],
    config['Embed Settings']['Colors']['g'],
    config['Embed Settings']['Colors']['b']
)
bot.footer = config['Embed Settings']['Footer']['Text']
bot.footer_image = config['Embed Settings']['Footer']['Icon URL']
bot.prefix = config['Prefix']
bot.playing_status = config['Playing Status'].format(prefix = bot.prefix)

bot.TOKEN = os.getenv(config['Bot Token Variable Name'])

bot.members = []
bot.owner = [500033041545166864]
extensions = sorted([
    'Cogs.general'
])

for extension in extensions:
    bot.load_extension(extension)

bot.remove_command('help')

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user} and connected to discord! (ID: {bot.user.id})")

    game = discord.Game(name = bot.playing_status)
    await bot.change_presence(activity = game)
    await bot.tree.sync()
    embed = discord.Embed(
        title = f"{bot.user.name} is online!",
        color = bot.embed_color,
        timestamp = datetime.datetime.now(datetime.timezone.utc)
    )
    embed.set_footer(
        text = bot.footer,
        icon_url = bot.footer_image
    )

    bot.log_channel = bot.get_channel(log_channel_id)
    await bot.log_channel.send(embed = embed)

async def main():
    async with bot:
        await bot.start(TOKEN, reconnect=True)

@bot.tree.command(name="whois", description="Shows information about a member or yourself if left blank")
async def userinfo(interaction: discord.Interaction, member: discord.Member = None):
    member = interaction.user if not member else member
    print(member.color)
    embed = discord.Embed(colour=member.color, timestamp=interaction.created_at)

    embed.set_author(name=f"User Info - {member}")
    print(member.avatar.url)
    embed.set_thumbnail(url=member.avatar.url)
    print(member.display_name)
    embed.add_field(name="Name", value=str(member.display_name), inline = True)
    print(member.top_role.mention)
    embed.add_field(name="Top role", value=member.top_role.mention, inline = True)
    print(member.bot)
    embed.add_field(name="Bot?", value=member.bot, inline = True)
    print("HI")
    embed.set_author(
        name=interaction.user.name,
        icon_url=interaction.user.avatar.url
    )
    embed.set_footer(
        text="Requested by " + interaction.user.name,
        icon_url= bot.footer_image
    )
    await interaction.response.send_message(embed=embed)
    await interaction.message.add_reaction('✅')

asyncio.run(main())

运行输出(无关警告已省略):

C:\Cloud\Programming\Python\CodingProjects\Bot Code\main.py:48: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  bot.load_extension(extension)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2.3.2
Logged in as Wolf Extension#0723 and connected to discord! (ID: 741545843986923580)
解决方案

你的代码存在三个关键问题,直接导致了报错和无响应:

  1. 异步扩展加载未使用await
    bot.load_extension()是异步函数,必须用await调用,否则会引发RuntimeWarning,甚至导致扩展加载失败。
    修复代码:
for extension in extensions:
    await bot.load_extension(extension)
  1. 响应后直接访问interaction.message引发异常
    调用interaction.response.send_message()后,interaction.message尚未生成,直接操作会导致异常,使机器人无法完成响应流程,Discord端因此显示“应用未响应”。需要先获取发送后的消息对象再添加反应。
    修复代码:
# 发送消息并获取返回的消息对象
message = await interaction.response.send_message(embed=embed, wait=True)
await message.add_reaction('✅')

注:wait=True参数会让函数返回已发送的消息对象,才能后续对其进行操作。

  1. PyCharm类型提示问题
    这是PyCharm的类型缓存或注解识别问题,可通过以下方式解决:
  • 重启PyCharm并清除缓存(File → Invalidate Caches...)
  • 确保discord.Interaction的导入正确,无类名混淆

另外还有一个小问题:main()函数中bot.start(TOKEN)的TOKEN未定义,应改为bot.TOKEN:

async def main():
    async with bot:
        await bot.start(bot.TOKEN, reconnect=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:45:11