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

Discord JDA按钮交互开发:实现Login按钮触发登录日志至指定频道

按钮交互事件逻辑实现

核心步骤说明

  • 监听按钮交互事件
  • 验证触发按钮的自定义ID
  • 收集用户信息与登录时间
  • 构建日志Embed并发送到指定频道
  • 向用户反馈操作结果

代码示例(以Discord.js v14为例)

// 监听按钮交互事件
client.on('interactionCreate', async (interaction) => {
  // 确认是按钮交互
  if (!interaction.isButton()) return;

  // 检查是否为"Login"按钮(需匹配你设置的自定义ID)
  if (interaction.customId !== 'login_button') return;

  try {
    // 1. 收集用户信息与登录时间
    const user = interaction.user;
    const loginTime = new Date().toLocaleString('zh-CN'); // 格式化成本地时间

    // 2. 构建日志Embed
    const logEmbed = new EmbedBuilder()
      .setColor('#00ff00')
      .setTitle('用户登录日志')
      .setDescription(`用户 **${user.tag}** 完成登录操作`)
      .addFields(
        { name: '用户ID', value: user.id, inline: true },
        { name: '登录时间', value: loginTime, inline: true }
      )
      .setThumbnail(user.displayAvatarURL())
      .setTimestamp();

    // 3. 获取目标日志频道(优先使用频道ID,避免名称变更问题)
    const logChannel = client.channels.cache.get('YOUR_LOG_CHANNEL_ID') || 
                       client.channels.cache.find(channel => channel.name === 'login-log');

    if (!logChannel) {
      console.error('未找到login-log频道');
      return interaction.reply({ content: '登录日志记录失败,请联系管理员', ephemeral: true });
    }

    // 4. 发送日志到频道
    await logChannel.send({ embeds: [logEmbed] });

    // 5. 向用户发送操作反馈(ephemeral=true仅用户可见)
    await interaction.reply({ content: '登录成功!', ephemeral: true });
  } catch (error) {
    console.error('处理登录按钮交互时出错:', error);
    await interaction.reply({ content: '登录过程中出现错误,请稍后重试', ephemeral: true });
  }
});

关键注意事项

  • 自定义ID匹配: 确保按钮的customId与代码中判断的字符串完全一致(比如你创建按钮时设置的是login_button,代码里就不能写错)
  • 频道权限: 机器人需要拥有sendMessages和embedLinks权限才能在login-log频道发送Embed
  • 错误处理: 加入try-catch块可以避免单个交互出错导致机器人崩溃
  • 时间格式化: 使用toLocaleString可以根据地区显示合适的时间格式,比如zh-CN对应中文时区

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:25:20