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

开发Discord机器人抽奖命令时遇'int' object has no attribute 'time'错误

解决Discord抽奖命令报错:'int' object has no attribute 'time'

问题原因

你的命令参数名time和Python标准库的time模块重名了。当执行time.time()时,代码会把你传入的整数参数time当成模块来调用方法,而整数类型根本没有time属性,因此触发报错。

修复步骤

  1. 把命令参数time改成不冲突的名称,比如duration
  2. 同步修改代码中所有用到该参数的位置

修改后的完整代码

import time
import asyncio
import random
import discord
from discord.ext import commands
from discord.utils import has_permissions

@client.command(description="Starts a giveaway.")
@has_permissions(manage_messages=True)
async def gstart(ctx, duration: int, winners: int, *, prize: str):
    try:
        em = discord.Embed(
            title=f"<a:fun:1052215771738165269> {prize} <a:fun:1052215771738165269>",
            color=discord.Colour.random()
        )
        # 使用time模块的time()方法,参数改为duration
        timestamp = time.time() + duration
        em.set_footer(text=f"Started by {ctx.author}")
        em.add_field(
            name=f"** **",
            value=f"**Ends at**: <t:{int(timestamp)}:f> or <t:{int(timestamp)}:R> \n **Prize**: {prize} \n **Hosted by**: {ctx.author.mention}",
            inline=False
        )
        my_msg = await ctx.send(embed=em)
        await my_msg.add_reaction("🎉")
        await asyncio.sleep(duration)
        new_msg = await ctx.channel.fetch_message(my_msg.id)
        
        # 获取参与用户,排除机器人自身
        reaction = new_msg.reactions[0]
        users = [user async for user in reaction.users()]
        users = [user for user in users if user != client.user]
        
        if not users:
            await ctx.send(f"没人参与本次抽奖,{prize}抽奖取消!")
            return
        
        # 抽取指定数量的获奖者
        for i in range(winners):
            if not users:
                break
            winner = random.choice(users)
            users.remove(winner)  # 避免重复中奖
            await ctx.send(f'恭喜 {winner.mention} 获得 **{prize}**!发起者:{ctx.author.mention}')
    except Exception as er:
        await ctx.send(f"出错了:{str(er)}")

额外优化说明

  • 移除了不必要的全局变量users和new_msg,改用局部变量更安全
  • 添加了无用户参与时的错误处理,避免抽奖崩溃
  • 获奖者抽取后从列表移除,防止同一用户重复中奖
  • 明确导入了所需的模块,避免隐式依赖

内容的提问来源于stack exchange,提问作者I am goku

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:50:34