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

如何在一条消息中提及列表中的多个Discord用户?

问题:Discord Bot无法批量提及CSV匹配的用户

开发了一个Discord Bot,可读取包含username#0000格式用户名及对应关键词的CSV文件。当检测到消息中的特定关键词时,需发送消息提及所有匹配该关键词的用户,但目前仅实现了用户匹配逻辑,批量提及功能失效。

原错误代码

mentionMembers = []
key1 = "superstar"
with open('csvfile.csv',) as csvfile:
reader = csv.reader(csvfile)
for row in reader:
    if row[2].strip() == key1: #row 2 of the CSV is where the keyword is located
    mentionMembers.append(row[0].strip()) #row 0 of the CSV is where all the usernames are located
await message.channel.send(f"{" ".join([member.mention for member in mentionMembers])} You're now a superstar)

问题分析

  1. 语法错误:with代码块内的reader定义、for循环均未缩进,Python会直接报错;f-string内部使用双引号与外层冲突,且末尾缺少闭合引号。
  2. 核心逻辑错误:mentionMembers存储的是CSV读取的字符串格式用户名,而Discord的.mention属性仅能作用于Member/User对象,直接对字符串调用会触发属性错误。

解决方案

修复后的代码

import csv

# 假设代码位于Discord Bot的事件/命令处理函数内
mention_member_tags = []
target_keyword = "superstar"

# 正确读取CSV,处理缩进与格式校验
with open('csvfile.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    # 若CSV包含表头,取消下一行注释跳过表头
    # next(reader)
    for row in reader:
        # 避免因CSV行格式不全导致的索引错误
        if len(row) >= 3 and row[2].strip() == target_keyword:
            mention_member_tags.append(row[0].strip())

# 在当前服务器成员中匹配目标用户,获取可提及对象
mentioned_users = []
for member in message.guild.members:
    current_member_tag = f"{member.name}#{member.discriminator}"
    if current_member_tag in mention_member_tags:
        mentioned_users.append(member.mention)

# 发送批量提及消息
if mentioned_users:
    await message.channel.send(f"{' '.join(mentioned_users)} You're now a superstar.")
else:
    await message.channel.send("没有匹配到对应关键词的用户。")

关键注意事项

  • 启用成员意图:需在Discord开发者门户的Bot设置中开启Server Members Intent,否则无法获取服务器成员列表。
  • CSV格式校验:添加len(row)>=3判断,避免因CSV行数据缺失导致的索引越界错误。
  • 表头处理:若CSV第一行为表头,需添加next(reader)跳过表头行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 03:42:43