如何让Python编写的Discord机器人不对任何图片消息产生响应
问题描述
Python新手开发Discord关键词回复机器人时存在误触发问题:频道内发送任意图片都会触发机器人响应,需要新增逻辑让机器人检测到图片消息时直接终止流程,不执行后续回复逻辑。
原有代码如下:
@client.event async def on_message(message): # 避免机器人响应自身消息造成循环 if message.author == client.user: return msg = message.content if msg.lower().startswith('!hello'): await message.channel.send(f'Hello {message.author}!') if any(word in msg.lower() for word in suspicious): await message.channel.send(random.choice(sus_responses)) if msg.lower().startswith('!8ball'): await message.channel.send(random.choice(eight_ball)) if msg.lower().startswith('!ping'): await message.channel.send('Pong') if msg == 'MARCO': await message.channel.send('POLO...') client.run(token)
实现方案
Discord上传的图片会存储在消息对象的attachments列表中,每个附件自带content_type字段标识文件类型,在原有自身消息判断逻辑后新增图片检测即可:
- 精准拦截带图片的消息(不影响普通文件上传),添加如下代码:
# 检测到图片附件直接返回 if message.attachments: for attach in message.attachments: if attach.content_type and attach.content_type.startswith("image/"): return
- 如果需要拦截所有带附件的消息(含普通文件、图片),可以简化判断:
if message.attachments: return
修改后的完整可运行代码:
@client.event async def on_message(message): # 避免机器人响应自身消息造成循环 if message.author == client.user: return # 新增:检测到图片消息直接终止后续逻辑 if message.attachments: for attach in message.attachments: if attach.content_type and attach.content_type.startswith("image/"): return msg = message.content if msg.lower().startswith('!hello'): await message.channel.send(f'Hello {message.author}!') if any(word in msg.lower() for word in suspicious): await message.channel.send(random.choice(sus_responses)) if msg.lower().startswith('!8ball'): await message.channel.send(random.choice(eight_ball)) if msg.lower().startswith('!ping'): await message.channel.send('Pong') if msg == 'MARCO': await message.channel.send('POLO...') client.run(token)
补充:如果需要允许「文字+图片」的混合消息触发指令,不要把检测逻辑放在函数开头全局拦截,移到不需要响应图片的具体分支中即可。
内容的提问来源于stack exchange,提问作者Leone Varando
相关产品推荐
相关产品推荐

