You need to enable JavaScript to run this app. discord.py 使用if/elif/else实现定向用户响应时出现聊天回复刷频问题
优惠活动
大模型
产品
解决方案
定价
更多

discord.py 使用if/elif/else实现定向用户响应时出现聊天回复刷频问题

问题定位与代码修正

核心诱因

  • 分支缩进错位:和顶层if同级的elif、else语句开头多了额外缩进,Python解析器无法将其识别为同层级条件分支,会把所有发送消息的代码块识别为不受条件限制的平行执行逻辑,最终触发无判断全量发送所有预设内容的问题。
  • 变量名匹配错误:第一个分支的判断条件引用了未定义的teste变量,实际前置定义的Vitor对应ID变量名为vitor,变量名写错后条件判断完全失效。
  • 逻辑边界缺失:原else分支未增加消息内容校验,只要不匹配前两个分支的消息,不管发送什么内容都会触发回复,极易造成频道刷屏。

修正后可正常运行的代码

# 初始化所有用户ID映射,避免变量漏写、错写
vitor = 404119041318584330
rafael = 315642322463490060

# 所有同层级if/elif/else严格对齐,无额外缩进
if message.author.id == vitor and message.content.lower() == 'morning':
    des1 = 'good morniiiing, how are u baby???'
    des2 = 'Hey darling, I want to be with u all the day'
    des3 = 'I love u'
    des4 = 'Youre the best person in the world'
    url1 = 'https://cdn.discordapp.com/attachments/718543178109550652/783115078215925781/6fe7b4426b4a3c73e2c70c7cb25cd067.gif'
    url2 = 'https://cdn.discordapp.com/attachments/718543178109550652/783367148587974656/1518430510_tumblr_p2v8jr3yFT1qkz08qo1_540.gif'
    url3 = 'https://cdn.discordapp.com/attachments/718543178109550652/783367160704925756/1519434149_000000000000002.gif'
    url4 = 'https://cdn.discordapp.com/attachments/718543178109550652/783367221170405456/e29b67f7e735a9be2fb891a61488437e.gif'
    url5 = 'https://cdn.discordapp.com/attachments/718543178109550652/783368175114256434/9e21f42413dc4dc3f3d71ec64cbaf1ea.gif'
    url6 = 'https://cdn.discordapp.com/attachments/718543178109550652/783375880546287616/bd24c4048f80f562bd5ec135291bf5e578e4d43e_hq.gif'
    embed = discord.Embed(title='Bom diaaaa :heart::heart::heart:', description = random.choice([des1,des2,des3,des4]), color=0xe91e63)
    embed.set_image(url = random.choice([url1,url2,url3,url4,url5,url6]))
    embed.set_author(name ='Namorada do Vitor')
    embed.set_footer(text ='I love you <3')
    await message.channel.send(embed = embed)

elif message.author.id == rafael and message.content.lower() == 'morning':
    await message.channel.send('Sorry, youre too old for me')

# 仅当用户发送morning关键词、且不在目标专属用户列表时触发通用回复,避免无意义刷屏
elif message.content.lower() == 'morning':
    await message.channel.send('Youre not my boyfriend')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.15 02:36:04