如何将Python猜数字函数改造为discord.py的-guesstall命令
Discord猜数字命令改造方案
原有代码问题梳理
- 直接读取触发命令的
message.content无法获取用户后续发送的猜测内容,需要用wait_for监听新消息 - 同步的
time.sleep()会阻塞机器人全部功能,需替换为异步的asyncio.sleep() send()方法不支持多参数直接传入,需要用f-string拼接输出内容- 未将用户输入的字符串转为整数,直接和数字对比永远不匹配
- 没有限制仅接收游戏发起者的回复,其他用户发消息会干扰游戏
- 没有处理用户输入非数字的异常场景
完整可运行代码
import discord import random import asyncio # 替换为你的机器人令牌 BOT_TOKEN = "你的机器人令牌" # 开启消息内容权限,必须在开发者后台也开启对应开关 intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) async def guesstall(start_message): target_num = random.randint(1, 50) left_chances = 5 # 校验规则:仅接收发起游戏的用户在当前频道发送的数字内容 def check(msg): return msg.author == start_message.author and msg.channel == start_message.channel and msg.content.isdigit() while left_chances > 0: await start_message.channel.send("请输入1-50之间的数字进行猜测") try: # 等待用户回复,30秒无响应自动结束游戏 reply_msg = await client.wait_for("message", timeout=30, check=check) except asyncio.TimeoutError: await start_message.channel.send("等待超时,游戏自动结束") return user_guess = int(reply_msg.content) await asyncio.sleep(1) if user_guess == target_num: await start_message.channel.send("恭喜你猜对了!") break elif user_guess < target_num: left_chances -= 1 await start_message.channel.send(f"答案更大,你还有{left_chances}次猜测机会") else: left_chances -= 1 await start_message.channel.send(f"答案更小,你还有{left_chances}次猜测机会") if left_chances == 0: await start_message.channel.send(f"游戏失败,正确答案是{target_num}") @client.event async def on_ready(): print(f"机器人登录成功,身份为:{client.user}") @client.event async def on_message(message): # 忽略机器人自身发送的消息,避免触发死循环 if message.author.bot: return if message.content.startswith("-guesstall"): await guesstall(message) client.run(BOT_TOKEN)
使用说明
- 先安装依赖:执行
pip install discord.py - 前往Discord开发者门户创建机器人,开启
Message Content Intent权限,复制令牌替换代码中的对应内容 - 邀请机器人进入服务器时,需要授予发送消息的权限
内容的提问来源于stack exchange,提问作者thomas0305
相关产品推荐
相关产品推荐

