如何用discord.py的@bot.command()实现交互式事件日志机器人?
Discord.py 事件日志机器人实现方案
前置要求
- 安装依赖:执行
pip install discord.py - 机器人权限:需开启「发送消息」「读取消息」「上传文件」「私信成员」权限
- 提前创建日志发布频道,记录该频道的ID(用于后续代码中指定发布位置)
核心实现代码
import discord import asyncio from discord.ext import commands # 初始化机器人,设置命令前缀为> bot = commands.Bot(command_prefix='>', intents=discord.Intents.all()) # 日志发布频道ID,替换成你自己的频道ID LOG_CHANNEL_ID = 123456789012345678 @bot.command(name='log') async def event_log(ctx): # 限制仅在服务器内触发命令 if not ctx.guild: await ctx.send("请在服务器内使用该命令!") return # 尝试发送私信启动流程 try: await ctx.author.send("开始填写事件日志信息,请按提示依次回复:") except discord.Forbidden: await ctx.send("无法给你发送私信,请检查隐私设置!") return # 定义需收集的字段、提示文本及验证规则 info_fields = [ ("请输入主持人用户名:", lambda x: len(x.strip()) > 0), ("请输入联合主持人用户名(无则填N/A):", lambda x: len(x.strip()) > 0), ("请输入参会人数(数字):", lambda x: x.strip().isdigit()), ("请输入通过人员用户名:", lambda x: len(x.strip()) > 0), ("请输入未通过人数(数字):", lambda x: x.strip().isdigit()), ("请上传证明图片:", lambda x: len(x.attachments) > 0) ] collected_info = [] for prompt, validator in info_fields: while True: await ctx.author.send(prompt) try: # 等待用户私信回复,超时120秒 response = await bot.wait_for( 'message', check=lambda m: m.author == ctx.author and m.channel.type == discord.ChannelType.private, timeout=120 ) except asyncio.TimeoutError: await ctx.author.send("等待超时,日志提交已取消!") return # 验证输入合法性 if validator(response): if prompt == "请上传证明图片:": collected_info.append(response.attachments[0].url) else: collected_info.append(response.content.strip()) break else: error_msg = "输入不能为空,请重新回复!" if prompt in ["请输入参会人数(数字):", "请输入未通过人数(数字):"]: error_msg = "输入无效,请输入数字!" await ctx.author.send(error_msg) # 整理成指定格式的日志内容 log_content = ( f"Host: {collected_info[0]}\n" f"Co-Host: {collected_info[1]}\n" f"Attendees: {collected_info[2]}\n" f"Passed: {collected_info[3]}\n" f"Failed: {collected_info[4]}\n" f"Proof: {collected_info[5]}" ) # 发布日志到指定频道 log_channel = bot.get_channel(LOG_CHANNEL_ID) if log_channel: await log_channel.send(log_content) await ctx.author.send("日志已成功发布!") else: await ctx.author.send("无法找到指定的日志频道,请检查频道ID是否正确!") # 机器人启动提示 @bot.event async def on_ready(): print(f"已登录为 {bot.user.name}(ID:{bot.user.id})") print("------------------------") # 替换成你的机器人TOKEN bot.run("YOUR_BOT_TOKEN_HERE")
关键部分说明
- 命令触发:通过
@bot.command(name='log')定义>log命令,限制仅服务器内触发避免误操作 - 私信交互:用
bot.wait_for监听用户私信回复,确保只收集触发命令用户的输入 - 输入验证:针对不同字段设置验证规则,比如人数强制数字、图片要求上传附件
- 日志发布:将收集到的信息整理成指定格式,发送到预设的日志频道
注意事项
- 替换代码中的
LOG_CHANNEL_ID和YOUR_BOT_TOKEN_HERE为实际值 - 若需支持多用户通过/未通过,可修改对应提示和输入处理逻辑(比如允许逗号分隔)
- 可根据需求调整超时时间(当前为120秒)
- 确保机器人已加入目标服务器,并拥有对应频道的发送权限
内容的提问来源于stack exchange,提问作者TheProChriss
相关产品推荐
相关产品推荐

