Discord读书俱乐部Python Bot查询阅读进度始终返回0该如何修复
Discord读书俱乐部Bot问题排查与修复方案
现有代码核心问题
- 核心逻辑不完整:
on_message回调仅提取了用户名和消息内容,没有实现-update、-progress两个指令的处理分支,也没有进度更新、查询的对应逻辑,因此查询永远返回hg2g字典的初始值0 - 缺失多轮会话状态记录:用户发送
-update指令后,需要临时标记该用户处于「等待上报进度」的状态,才能识别用户后续发送的进度内容,现有代码没有相关状态存储 - 存储类型不匹配:
hg2g字典的默认值为数字类型,实际需要存储的是Book 2, Chapter 20这类字符串格式的进度内容
修复后代码
import discord import random import os from keep_online import keep_alive intents = discord.Intents.default() intents.members = True intents.message_content = True # 必须开启消息内容读取权限,否则无法获取用户消息内容 intents.emojis=True client=discord.Client(intents=intents) # 存储用户阅读进度,初始值设为空字符串 hg2g={ "User1":"", "User2":"", "User3":"", "User4":"" } # 临时存储处于待上报进度状态的用户 pending_update_users = set() @client.event async def on_message(message): # 跳过Bot自身发送的消息,避免循环触发 if message.author.bot: return username=str(message.author).split("#")[0] mess=message.content.strip() # 先判断用户是否处于待上报进度的状态 if username in pending_update_users: # 将用户发送的内容保存为进度 hg2g[username] = mess await message.channel.send("已记录") # 清除待上报状态 pending_update_users.remove(username) return # 处理-update指令 if mess.startswith("-update"): # 先校验用户是否在进度字典中,不在的话自动新增 if username not in hg2g: hg2g[username] = "" pending_update_users.add(username) await message.channel.send("请问你当前的阅读进度是多少?") return # 处理-progress指令 if mess.startswith("-progress"): # 提取指令后携带的用户名,没有的话默认查自己的进度 parts = mess.split(maxsplit=1) target_user = parts[1] if len(parts)>=2 else username if target_user not in hg2g: await message.channel.send(f"未找到用户{target_user}的进度记录") return progress = hg2g[target_user] if hg2g[target_user] else "暂无上报记录" await message.channel.send(f"{target_user}当前阅读进度为{progress}") return # 启动Bot keep_alive() client.run(os.getenv("DISCORD_BOT_TOKEN"))
额外注意事项
- 需要在Discord开发者后台的Bot设置中开启「Message Content Intent」权限,否则Bot无法读取用户发送的消息内容
- 代码中使用的
DISCORD_BOT_TOKEN需要提前配置在环境变量中,或者直接替换为你自己的Bot Token
内容的提问来源于stack exchange,提问作者R.Harsha vardhan Reddy
相关产品推荐
相关产品推荐

