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

Discord新投票功能:如何用PyCharm实现机器人自动创建投票?

实现Discord机器人自动触发投票并复用选项变量

1. 先搞定依赖版本

Discord的新投票功能需要用支持该特性的discord.py版本,先升级到最新版:

pip install -U discord.py

2. 核心代码实现

下面是完整的可运行代码,包含消息触发、投票创建和选项变量复用的逻辑:

import discord
from discord.ext import commands

# 初始化机器人,开启消息内容意图(必须)
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

# 存储选中的游戏选项,后续可以直接调用
selected_game = None

@bot.event
async def on_ready():
    print(f"机器人已登录:{bot.user}")

@bot.event
async def on_message(message):
    # 跳过机器人自己发的消息
    if message.author == bot.user:
        return
    
    # 检测用户触发语
    if "嘿,我们玩个游戏吧" in message.content:
        # 把需要复用的选项设为变量
        custom_game_option = "狼人杀"
        # 构造投票选项列表
        poll_options = [
            discord.PollOption("真心话大冒险"),
            discord.PollOption(custom_game_option),
            discord.PollOption("谁是卧底")
        ]
        
        # 创建投票并发送
        game_poll = discord.Poll(
            question="选个游戏开始!",
            options=poll_options,
            duration=60  # 投票持续60秒,可按需调整
        )
        sent_poll = await message.channel.send(poll=game_poll)
        
        # 等待投票结束,获取结果
        await sent_poll.wait_for_poll_end()
        poll_results = sent_poll.poll.results
        
        # 找出得票最高的选项
        top_option = max(poll_results, key=lambda x: x.vote_count)
        global selected_game
        selected_game = top_option.label
        
        # 后续消息直接复用变量
        await message.channel.send(f"敲定了!玩{selected_game},准备开始~")
    
    # 处理其他命令,不能少这句
    await bot.process_commands(message)

# 替换成你的机器人Token,从Discord开发者后台获取
bot.run("YOUR_BOT_TOKEN")

3. 注意事项

  • 权限配置:要在Discord开发者后台的Bot页面开启Message Content Intent,否则机器人读不到用户消息。
  • 变量存储:示例用了全局变量,如果你需要更规范的写法,可以把变量改成Bot类的属性,或者用数据库存储,避免全局变量的问题。
  • 投票时长:duration参数单位是秒,可根据需求调整投票持续时间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:03:34