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

Discord Python Bot报错:AttributeError: 'Select'对象无'user'属性

问题定位与解决方案

1. 核心错误原因:回调函数参数顺序错误

你遇到的AttributeError: 'Select' object has no attribute 'user'是因为select_callback的参数顺序写反了。在discord.py的UI组件回调中,第二个参数必须是interaction(交互对象),第三个才是组件本身。你当前把select放在了interaction前面,导致代码里的interaction变量实际是Select对象,自然没有user属性。

2. 次要问题:动态添加的按钮未绑定回调

当你在选择商品后动态添加"Confirm Buy"按钮时,直接创建的Button对象没有关联到confirm_callback方法,所以点击按钮后Bot不会响应。需要在创建按钮时显式指定callback参数。

3. 额外优化:余额计算逻辑冗余

在confirm_callback中,调用addchocobits扣除余额后,再用fetch_user_chocobits获取的已经是更新后的余额,无需再减去price,否则会导致显示的余额比实际少。


修改后的完整代码

from discord import ButtonStyle, SelectOption, Embed
from discord.ui import Button, View
import discord

from akashasql import getchocobits, addchocobits

class StoreView(View):
    def __init__(self):
        super().__init__()
        self.selected_item = None

    async def fetch_user_chocobits(self, user_id):
        return getchocobits(user_id)
    
    @discord.ui.select(
        placeholder="Choose an item to buy...",
        options=[
            SelectOption(label="Test1", description="Costs 100 chocobits", value="100"),
            SelectOption(label="Test2", description="Costs 200 chocobits", value="200"),
        ],
    )
    # 修复参数顺序:self -> interaction -> select
    async def select_callback(self, interaction, select):
        user_id = interaction.user.id
        user_chocobits = await self.fetch_user_chocobits(user_id)
        self.selected_item = select.values[0]
        price = int(self.selected_item)
        
        if user_chocobits < price:
            await interaction.response.send_message("You do not have enough chocobits.", ephemeral=True)
            self.stop()
        else:
            self.clear_items()
            # 动态添加按钮时绑定回调
            self.add_item(Button(label="Confirm Buy", style=ButtonStyle.green, callback=self.confirm_callback))
            await interaction.response.edit_message(content=f"Selected item costs {price} chocobits. Confirm purchase?", view=self)
    
    @discord.ui.button(label="Confirm Buy", style=ButtonStyle.green)
    async def confirm_callback(self, interaction, button):
        user_id = interaction.user.id
        price = int(self.selected_item)
        addchocobits(user_id, -price)
        # 直接获取更新后的余额,无需重复减价
        user_chocobits = await self.fetch_user_chocobits(user_id)
        await interaction.response.send_message(f"Purchase confirmed! You now have {user_chocobits} chocobits left.", ephemeral=True)
        self.stop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 08:34:59