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

如何使用discord.py实现:当加入未满两周的用户发送含指定关键词的消息时触发操作

嘿,我来帮你解决这个Discord机器人的功能问题!你的思路方向是对的,只是在时间差计算和几个代码细节上需要调整,我给你整理好正确的实现方式:

修正后的完整代码

import discord
from datetime import datetime, timedelta

newjoined_words = ["test", "test2"]

@bot.listen("on_message")
async def on_message(msg):
    # 忽略机器人自己的消息,避免循环触发
    if msg.author.bot:
        return
    
    # 确保消息来自服务器(不是私信),且作者是服务器成员
    if not isinstance(msg.author, discord.Member):
        return
    
    # 计算用户加入服务器的时间差(用UTC时间和Discord的时间保持一致)
    current_time = datetime.utcnow()
    join_time = msg.author.joined_at
    time_since_join = current_time - join_time
    
    # 判断是否加入未满两周,且消息包含指定关键词
    if time_since_join < timedelta(days=14):
        for word in newjoined_words:
            if word in msg.content.lower():
                await msg.channel.send("working")
                # 如果只需要触发一次,找到关键词后可以break跳出循环
                break

关键细节说明

  • 时间差计算:用datetime.utcnow()获取当前UTC时间(Discord的joined_at返回的是UTC时区的时间对象),两者相减得到timedelta对象,直接和timedelta(days=14)比较就能判断是否未满两周,非常直观。
  • 成员对象校验:私信消息的作者不是discord.Member类型,加个判断可以避免报错;同时忽略机器人自身的消息,防止不必要的触发。
  • 消息发送修正:原来的ctx.send在on_message事件里无法使用,要换成msg.channel.send来指定发送到当前消息所在的频道。
  • 属性名修正:你代码里的joindate是错误的,正确的属性名是joined_at,这是Discord.py中Member对象的标准属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:38:10