
本文详解如何在 discord.py 2.3+ 中正确创建并响应 Slash 命令以发送 Discord 原生投票(Poll),重点解决 AttributeError: 'InteractionResponse' object has no attribute 'send' 和 duration 类型错误两大常见问题。
本文详解如何在 discord.py 2.3+ 中正确创建并响应 slash 命令以发送 discord 原生投票(poll),重点解决 `attributeerror: 'interactionresponse' object has no attribute 'send'` 和 `duration` 类型错误两大常见问题。
Discord 的原生投票(Poll)功能自 2023 年底起正式支持通过 API 创建,但需严格遵循 discord.py 的交互响应规范。新手常因混淆旧版消息发送方法或忽略类型要求而报错——例如你遇到的 interaction.response.send(poll=p) 会触发 AttributeError,因为 InteractionResponse 对象没有 send() 方法;正确方法是调用 send_message(),且必须显式传入 poll= 关键字参数。
此外,discord.Poll 的 duration 参数不接受整数小时数(如 4),而必须是 datetime.timedelta 实例。直接写 duration=4 或 duration=4*3600 均会引发 TypeError。
✅ 正确实现方式如下:
import discord
from discord import app_commands
from discord import Poll
import datetime # 必须导入!用于构建 duration
@client.tree.command(
name="repo",
description="Create a poll to see who's free for REPO",
guild=GUILD_ID
)
async def repo(interaction: discord.Interaction):
# ✅ 正确创建 Poll:question + timedelta duration
poll = Poll(
question="Are you free for REPO?",
duration=datetime.timedelta(hours=4) # ⚠️ 不是 int,必须是 timedelta
)
poll.add_answer(text="Yes")
poll.add_answer(text="No")
# ✅ 正确响应:使用 send_message(),而非 send()
await interaction.response.send_message(poll=poll)
? 关键注意事项:
-
interaction.response.send_message()是唯一支持poll=参数的响应方法(followup.send()同样支持,但response.send()不存在); -
duration支持的最小值为 1 小时,最大值为 7 天(即timedelta(hours=1)至timedelta(days=7)); - 投票创建后不可编辑答案或持续时间,请确保
add_answer()调用顺序与预期一致(Discord 按添加顺序显示选项); - 若需延迟响应(例如执行耗时操作后再发投票),请先调用
await interaction.response.defer(),再用await interaction.followup.send(poll=...)发送。
? 小贴士:可通过 poll.is_expired 属性在后续逻辑中检查投票状态,或监听 on_poll_vote_add 事件(需启用 Intents.polls,当前 discord.py 版本中该 intent 尚未完全公开,建议关注 官方文档更新)。
掌握这两个核心要点——方法名用对、duration 类型写对——即可稳定发送 Slash 命令驱动的原生投票,大幅提升社区互动效率。











