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

discord.py如何检测消息中是否存在作为repl数据库键的特定单词

Replit DB 匹配关键词 Discord 机器人修复方案

Replit 数据库是键值存储结构,不支持直接像数组一样遍历DB对象本身,这是你代码报错的核心原因。

推荐实现方案(性能更高,维护更简单)

把所有触发发笑的关键词统一存在同一个DB键下,存储为数组格式:

  • 初始化存储逻辑:
from replit import db

# 首次运行初始化关键词列表,后续可以自定义添加内容
if "funny_words" not in db:
  db["funny_words"] = ["草", "233", "笑死", "hhh"]
  • 消息匹配检测逻辑:
import discord

client = discord.Client(intents=discord.Intents.all())

@client.event
async def on_message(message):
  # 忽略机器人自己发的消息
  if message.author == client.user:
    return
  # 从数据库取出关键词列表
  funny_words = db["funny_words"]
  # 遍历匹配消息内容
  msg_content = message.content.lower()
  for word in funny_words:
    if word in msg_content:
      await message.channel.send("😂😂")
      # 匹配到一个关键词就终止遍历,避免重复触发
      break

兼容散存键的临时方案

如果你已经把每个关键词单独存为了DB的独立键,可通过db.keys()获取所有键后再遍历,该方案性能较低,仅适合小数据量场景:

@client.event
async def on_message(message):
  if message.author == client.user:
    return
  msg_content = message.content.lower()
  # 获取所有DB键后遍历匹配
  for key in db.keys():
    if key in msg_content:
      await message.channel.send("😂😂")
      break

你之前第69行的报错是因为直接对DB对象执行了遍历操作,Replit DB 本身不是可迭代对象,必须调用keys()、values()方法才能拿到可遍历的集合,或者按照推荐方案把关键词存在同一个数组键下直接读取遍历即可。

内容的提问来源于stack exchange,提问作者Yago Rodriguez Carmona

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:06:01