如何让Discord Bot记录指定用户的消息发送与语音频道加入行为?
实现Discord用户活跃度自动记录Bot(新手友好版)
前置准备
- 去Discord开发者平台创建Bot账号:新建应用→进入Bot选项卡→添加Bot→复制生成的Token
- 安装Python(3.8及以上版本),打开命令行输入
pip install discord.py安装依赖库
核心代码(直接用,改参数就行)
import discord from discord.ext import commands from datetime import datetime # 替换成你的Bot Token TOKEN = "你的Bot专属Token" # 替换成要监控的用户ID列表,多个就用逗号分隔,比如[123456789, 987654321] TARGET_USER_IDS = [123456789] # 替换成用来存记录的频道ID LOG_CHANNEL_ID = 987654321 # 开启必要权限 intents = discord.Intents.default() intents.message_content = True intents.members = True bot = commands.Bot(command_prefix="!", intents=intents) @bot.event async def on_ready(): print(f"Bot已登录:{bot.user}") log_channel = bot.get_channel(LOG_CHANNEL_ID) if log_channel: await log_channel.send("活跃度记录Bot启动完成!") # 监听目标用户发消息 @bot.event async def on_message(message): if message.author.bot: return if message.author.id in TARGET_USER_IDS: log_channel = bot.get_channel(LOG_CHANNEL_ID) if log_channel: log_text = ( f"📝 用户 **{message.author.name}**(ID: {message.author.id})于 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} " f"在频道「{message.channel.name}」发送消息:\n> {message.content}" ) await log_channel.send(log_text) await bot.process_commands(message) # 监听目标用户加入语音频道 @bot.event async def on_voice_state_update(member, before, after): if member.bot: return # 只记录从无到有加入语音的行为 if member.id in TARGET_USER_IDS and before.channel is None and after.channel is not None: log_channel = bot.get_channel(LOG_CHANNEL_ID) if log_channel: log_text = ( f"🎤 用户 **{member.name}**(ID: {member.id})于 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} " f"加入语音频道「{after.channel.name}」" ) await log_channel.send(log_text) bot.run(TOKEN)
操作步骤
- 把代码里的
TOKEN、TARGET_USER_IDS、LOG_CHANNEL_ID换成你自己的信息 - 保存文件为
activity_bot.py,打开命令行运行python activity_bot.py - 在Discord服务器里给Bot分配「查看频道」「发送消息」「查看成员」的权限,确保它能正常工作
简单拓展提示
- 要记录退出语音频道的行为,就在
on_voice_state_update里加判断:if before.channel is not None and after.channel is None,然后写对应的记录逻辑 - 想把记录存到电子表格里,安装
pip install pandas,每次记录时追加数据到Excel文件即可(代码逻辑不难,新手可以慢慢试)
内容的提问来源于stack exchange,提问作者Angalie
相关产品推荐
相关产品推荐

