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

discord.py中if语句修改变量值无效问题排查

问题原因及解决方法

核心问题是:当你输入c!command credits时,theircommande.replace('c!command','')得到的theircommand值是带前导空格的' credits',而非纯字符串'credits',导致if theircommand == 'credits'的判断不成立,所以if语句没有触发,imag和info保持初始值'joe',最终引发URL格式错误。

几种可行的解决方式:

  • 方式一:替换时包含命令后的空格
    把替换语句改成:

    theircommand = theircommande.replace('c!command ','')
    

    直接将c!command (命令加空格)替换为空,得到干净的'credits'。

  • 方式二:用strip()清除前后空白字符
    在替换后调用strip(),无论前后有多少空格或换行都能清除:

    theircommand = theircommande.replace('c!command','').strip()
    
  • 方式三:用字符串分割更可靠
    采用分割方式提取命令参数,能适配各种输入空格情况:

    parts = message.content.split(maxsplit=1)
    theircommand = parts[1].strip() if len(parts) >= 2 else ''
    

修改后的完整代码示例(以方式二为例):

theircommande = message.content
theircommand = theircommande.replace('c!command','').strip()
await message.channel.send(theircommand)
info = 'joe'
imag = 'joe'
if theircommand == 'credits':
  imag = 'https://cdn.discordapp.com/attachments/1048897561253122120/1055079211297165413/image.png'
  info = 'List of people who have helped or currently helping the Chappers bot, and credits to helpful websites used for some specific commands.'
comme=discord.Embed(title=theircommand,description=info,color=0x00aaff)
comme.set_image(url=imag)
await message.channel.send(embed=comme)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:55:15