Python Discord Bot用户输入获取问题:文字类RPG角色创建会话无法正常获取用户输入的解决方法
解决你的Text-Based RPG角色创建会话问题
我一眼就看出了代码里的几个关键问题,这也是很多刚接触Discord.py异步开发的开发者常犯的错误,我来帮你一步步修正:
核心问题拆解
- 异步方法未正确等待:
client.wait_for()是异步函数,必须用await关键字来触发执行并获取结果,不然你拿到的只是一个未运行的协程对象,根本取不到用户的消息内容。 - 用户属性调用错误:在Discord.py里,消息的发送者对象是
message.author,而非message.user,你的校验条件里写错了这个属性,导致无法正确匹配命令发起者。 - 缺少超时处理(可选但推荐):如果用户长时间不回复,机器人会一直处于等待状态卡住,给
wait_for加上超时参数并捕获异常能避免这种情况。
修正后的完整代码
import asyncio from discord.ext import commands # 假设你的bot实例是这样定义的,根据你的实际代码调整 bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) @bot.command() async def karakterolustur(ctx): # 获取角色名称 await ctx.send("Karakterinin Adı Ne ? ") try: # 等待用户回复,超时60秒,校验发送者是否为命令发起者 message_response = await bot.wait_for('message', check=lambda m: m.author == ctx.author, timeout=60) ad = message_response.content print(ad) except asyncio.TimeoutError: return await ctx.send("Zaman doldu! Karakter oluşturma iptal edildi.") # 获取角色种族 await ctx.send("Bir Irk Seç [Elf | Cüce | İnsan] : ") try: message_response = await bot.wait_for('message', check=lambda m: m.author == ctx.author, timeout=60) irk = message_response.content # 可选:校验种族输入是否合法 if irk not in ["Elf", "Cüce", "İnsan"]: return await ctx.send("Geçersiz irk seçimi! Karakter oluşturma iptal edildi.") except asyncio.TimeoutError: return await ctx.send("Zaman doldu! Karakter oluşturma iptal edildi.") # 获取角色职业 await ctx.send("Bir Sınıf Seç :") try: message_response = await bot.wait_for('message', check=lambda m: m.author == ctx.author, timeout=60) sinif = message_response.content except asyncio.TimeoutError: return await ctx.send("Zaman doldu! Karakter oluşturma iptal edildi.") cid = ctx.author.id # 这里可以添加角色信息保存逻辑,比如存入数据库或本地字典 await ctx.send(f"🎉 Karakter oluşturuldu!\nAd: {ad}\nIrk: {irk}\nSınıf: {sinif}")
额外提示
- 确保你已经导入了
asyncio模块,不然会触发TimeoutError找不到的报错。 - 如果你的
client和bot是同一个实例(大部分情况都是),用bot.wait_for()和client.wait_for()效果完全一致。 - 还可以给职业选择也加上输入校验,避免用户输入无效内容,让你的角色创建流程更严谨。
内容的提问来源于stack exchange,提问作者Resually
相关产品推荐
相关产品推荐

