Python Discord Bot 发送Cool Meter消息时字符串拼接报错问题
问题排查与修复方案
错误原因
- 类型不兼容:
random.choice(Numbers)返回整数类型,Python禁止直接对整数和字符串执行+拼接操作 - 语法错误:
str"% Cool."写法不符合Python规范,str是内置转换函数,传入参数必须包裹在括号内,正确写法是str(待转换内容) - 附加逻辑问题:当前
RandomNumber为全局变量,仅会在脚本启动时生成一次,所有用户调用:coolmeter都会返回同一个固定值,不符合功能设计预期
修复代码
删除全局位置的RandomNumber定义,修改on_message中对应的触发分支即可:
@client.event async def on_message(message): if message.author == client.user: return if message.content.startswith(":quote"): quote = get_quote() await message.channel.send(quote) elif message.content.startswith(":coolmeter"): # 每次触发命令时生成新的随机数 random_num = random.choice(Numbers) # 用f-string完成字符串拼接,无需手动做类型转换 await message.channel.send(f"{random_num}% Cool.")
额外优化建议
你当前on_ready事件中使用了同步的time.sleep(1),会阻塞Discord Bot的整个异步事件循环,建议替换为异步休眠:
- 头部导入asyncio模块:
import asyncio - 将
time.sleep(1)修改为await asyncio.sleep(1)
内容的提问来源于stack exchange,提问作者Viridian
相关产品推荐
相关产品推荐

