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

Discord机器人开发遇AttributeError: str对象无author属性如何解决?

问题排查与解决方案

报错核心原因

AttributeError: 'str' object has no attribute 'author' 报错的根因是命令定义时参数顺序错误:

  • 仅写在Cog类内部的命令需要将self作为第一个参数,你使用@client.command()装饰的全局命令不需要加self参数。加了self后,本该传入上下文对象ctx的位置被占用,后续的ctx实际接收到的是用户输入的第一个投票选项(字符串类型),调用字符串的author属性自然触发报错。

同时你的代码还存在两处逻辑问题:

  1. 投票结果判断条件重复,len(onechoice)>len(secchoice)和len(secchoice)<len(onechoice)完全等价,第二个选项永远不可能被判定为获胜
  2. 统计反应用户时没有过滤机器人自身,机器人主动添加的两个反应会被计入票数,导致结果不准

修复后代码

# 需提前导入依赖
import discord
from discord.ext import commands
import datetime
import asyncio

# 此处替换为你自己的机器人初始化逻辑
client = commands.Bot(command_prefix="你设定的命令前缀", intents=discord.Intents.all())

@client.command()
# 删掉多余的self参数
async def hlasovani(ctx, volba1, volba2, *, tema):
    embed = discord.Embed(title = tema,description = f":one: {volba1}\n\n:two: {volba2}",color = ctx.author.color,timestamp = datetime.datetime.utcnow())
    embed.set_footer(text = f"Hlasování zahájil {ctx.author.name}")
    embed.set_thumbnail(url = ctx.author.avatar_url)
    message = await ctx.send(embed = embed)
    await message.add_reaction("1️⃣")
    await message.add_reaction("2️⃣")
    await asyncio.sleep(5)

    newmessage = await ctx.fetch_message(message.id)
    # 统计时过滤机器人自身的反应
    onechoice = [user for user in await newmessage.reactions[0].users().flatten() if not user.bot]
    secchoice = [user for user in await newmessage.reactions[1].users().flatten() if not user.bot]

    vysledek = "REMÍZA!"
    if len(onechoice) > len(secchoice):
        vysledek = volba1
    # 修正判断逻辑
    elif len(secchoice) > len(onechoice):
        vysledek = volba2

    embed = discord.Embed(title = tema, description = f"Výsledek: {vysledek}", color = ctx.author.color, timestamp = datetime.datetime.utcnow())
    embed.set_footer(text = f"{volba1} || {volba2}")

    await newmessage.edit(embed = embed)

额外注意事项

  • 确保你已经在Discord开发者后台开启了Message Content Intent权限,否则机器人无法读取消息内容触发命令
  • 投票等待时间可以根据需求自行修改asyncio.sleep(5)的参数,单位为秒

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:15:05