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

如何在Discord宝可梦Bot的命令间共享变量且不使用全局变量?

解决方案:用Bot内存存储用户初始宝可梦

不用JSON文件,直接把用户的初始宝可梦列表存在Bot的内存里是更简便高效的方式,适合这种临时关联用户和数据的场景。以下是基于discord.py的实现示例:

核心思路

  • 给Bot实例添加一个字典属性,用用户ID作为键,存储该用户对应的3个初始宝可梦列表,实现用户数据的隔离
  • 生成初始宝可梦的命令负责随机选宝可梦并存入字典
  • 选择命令读取当前用户的缓存数据,判断选择是否有效

完整代码示例

import discord
from discord.ext import commands
import random

# 初始宝可梦集合,可根据需求替换
STARTER_POKEMON = ["妙蛙种子", "小火龙", "杰尼龟", "菊草叶", "火球鼠", "小锯鳄", "木守宫", "火稚鸡", "水跃鱼"]

bot = commands.Bot(command_prefix=".", intents=discord.Intents.all())
# 初始化缓存:键为用户ID(int),值为初始宝可梦列表
bot.starter_cache = {}

@bot.command(name="starters")
async def generate_starters(ctx):
    # 随机选3个不重复的初始宝可梦
    selected_starters = random.sample(STARTER_POKEMON, 3)
    # 存入当前用户的缓存
    bot.starter_cache[ctx.author.id] = selected_starters
    # 发送提示消息
    await ctx.channel.send(f'Your Starters are... {selected_starters[0]}, {selected_starters[1]} and {selected_starters[2]}. type .pick <pokemon name> to pick')

@bot.command(name="pick")
async def pick_starter(ctx, pokemon_name: str):
    # 检查用户是否已生成初始宝可梦
    if ctx.author.id not in bot.starter_cache:
        await ctx.send("你还没生成初始宝可梦,请先发送 .starters")
        return
    
    user_starters = bot.starter_cache[ctx.author.id]
    # 忽略大小写判断选择是否有效
    if pokemon_name.lower() in [p.lower() for p in user_starters]:
        await ctx.send(f"恭喜你选择了{pokemon_name}!")
        # 可选:选完后删除缓存,避免重复选择
        del bot.starter_cache[ctx.author.id]
    else:
        await ctx.send(f"无效选择!你的初始宝可梦是:{', '.join(user_starters)}")

bot.run("你的Bot Token")

说明

  1. 内存缓存优势:比JSON文件读写速度快,无需处理文件IO、序列化/反序列化逻辑,适合临时数据(用户选完后即可删除)
  2. 用户隔离:通过用户ID作为键,确保每个用户只能操作自己的初始宝可梦,不会互相干扰
  3. 可选优化:如果需要Bot重启后保留数据,可改用SQLite等轻量级数据库,但内存缓存是最简便的临时方案

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:48:38