首页 > 解决方案 > 如何让我的机器人响应用户提及?/如何制作 afk 命令?

问题描述

基本上我想要做的是学习如何制作一个 afk 命令来响应提及并告诉用户他发送 afk 消息以来的时间,以及他们目前在做什么。就像 Dyno 的 bot 的 afk 命令 :)。

@client.command()                                                                          
async def afk(ctx, activity=None, minutes=None):                                           
    if ctx.author.mention and activity and minutes:                                        
        time = await asyncio.sleep(minutes)                                                
        await ctx.send(f"""{ctx.author} is afk. Reason: {activity}. Time Left: {time} """) 

这就是我所拥有的,因为现在,我不知道如何发送消息发送时间的时间戳 XD

更新

@client.command()
async def afk(ctx, activity=None):
    if ctx.author.mention:
        await ctx.send(f"""{ctx.author.mention} is currently afk. Reason: {activity}""")

    else:
        print("A user is afk...")

这是我的第二次尝试。

标签: pythonpython-3.xdiscorddiscord.pydiscord.py-rewrite

解决方案


您将需要使用 on_message 事件来检查消息是否有提及,以通知提及他们提到的用户是 afk 的人。

我为自己的机器人创建 afk 命令的方式是创建一个空的 afk 字典,并在用户运行 afk 命令时将用户作为键添加到字典中,并且值是当他们被提及时要发送的消息/其他详细信息:

afkdict = {}

@client.command()
async def afk(ctx, message):
    global afkdict

    #remove member from afk dict if they are already in it
    if ctx.message.author in afkdict:
        afkdict.pop(ctx.message.author)
        await ctx.send('you are no longer afk')


    else:
        afkdict[ctx.message.author] = message
        await ctx.send(f"You are now afk with message - {message}")

@client.event
async def on_message(message):
    global afkdict
        
    #check if mention is in afk dict
    for member in message.mentions: #loops through every mention in the message
        if member != message.author: #checks if mention isn't the person who sent the message
            if member in afkdict: #checks if person mentioned is afk
                afkmsg = afkdict[member] #gets the message the afk user set
                await message.channel.send(f" {member} is afk - {afkmsg}") #send message to the channel the message was sent to 

如果您想保存的不仅仅是一条消息,以供用户在 afk 时使用,您可以使用 2d 字典:

async def afk(ctx, arg1, arg2):
    afkdict[ctx.message.author] = {arg1:arg1, arg2:arg2}

并访问这些其他详细信息,你会做

afkdict[member][arg1]  #gets arg1 from 2d dictionary where key is member

就时间戳而言,明智的做法是使用datetime 模块


推荐阅读