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

如何通过dblpy检查用户12小时内是否为Discord机器人投票?

使用dblpy检查用户投票状态并限制命令使用

别担心,我来一步步帮你搞定这个问题!从API连接到投票检查,再到命令限制,咱们一步步来:

1. 安装dblpy并获取API令牌

  • 先安装dblpy包:pip install dblpy(确保你的Python环境已经装了discord.py)
  • 登录top.gg进入你的机器人页面,找到API Tokens板块,复制专属的API令牌——这是连接top.gg API的关键,别随便泄露哦。

2. 初始化dblpy客户端

把dblpy客户端和你的discord机器人关联起来,示例代码如下:

import discord
from discord.ext import commands
import dbl

# 初始化discord机器人
intents = discord.Intents.default()
intents.message_content = True  # 根据你的功能需求开启对应intents
bot = commands.Bot(command_prefix="!", intents=intents)

# 初始化dbl客户端,传入机器人实例和top.gg API令牌
TOPGG_TOKEN = "你的top.gg API令牌"
dbl_client = dbl.DblClient(bot, TOPGG_TOKEN)

3. 检查用户12小时内是否投票

dblpy提供了is_voted()异步方法,专门用来验证指定用户在过去12小时内是否投过票,用法很直观:

@bot.command()
async def check_vote(ctx):
    user_id = ctx.author.id
    try:
        has_voted = await dbl_client.is_voted(user_id)
        if has_voted:
            await ctx.send("你过去12小时内已经给我投票啦!感谢支持🥳")
        else:
            await ctx.send("你还没在过去12小时内投票哦,投完票才能解锁专属功能~")
    except Exception as e:
        await ctx.send("抱歉,暂时无法检查投票状态,请稍后再试")
        print(f"检查投票时出错: {e}")

4. 用投票状态限制命令使用

如果想让某些命令只对投过票的用户开放,有两种简单的实现方式:

方法一:直接在命令内检查

适合单个命令快速实现:

@bot.command()
async def premium(ctx):
    user_id = ctx.author.id
    try:
        has_voted = await dbl_client.is_voted(user_id)
        if not has_voted:
            await ctx.send("这个命令需要你过去12小时内给机器人投票才能使用哦!快去top.gg投票吧~")
            return
        # 这里写命令的核心功能逻辑
        await ctx.send("专属功能已解锁!这是只有投票用户才能用的内容~")
    except Exception as e:
        await ctx.send("抱歉,暂时无法验证投票状态,请稍后再试")
        print(f"验证投票时出错: {e}")

方法二:自定义装饰器(优雅复用)

如果多个命令都需要投票验证,写个装饰器能省不少重复代码:

def require_vote():
    def predicate(ctx):
        # 把异步检查包装成同步返回(discord.py的check要求同步)
        async def check():
            try:
                return await dbl_client.is_voted(ctx.author.id)
            except:
                return False
        return bot.loop.run_until_complete(check())
    return commands.check(predicate)

# 给需要限制的命令加上装饰器
@bot.command()
@require_vote()
async def exclusive(ctx):
    await ctx.send("欢迎使用投票专属命令!")

# 处理未通过检查的报错
@exclusive.error
async def exclusive_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send("这个命令需要你过去12小时内给机器人投票才能使用哦!快去top.gg投票吧~")

一些小提醒

  • 确保你的机器人开启了必要的intents,不然可能无法正常获取用户信息
  • 记得给API请求加上异常处理,避免偶尔的网络问题导致机器人崩溃
  • 定期更新dblpy到最新版本:pip install --upgrade dblpy,能避开不少已知的小bug

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:23:11