python - 如何让我的机器人响应用户提及?/如何制作 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...")
这是我的第二次尝试。
解决方案
您将需要使用 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 模块
推荐阅读
- python - 两个名称非常相似的列表的模糊匹配
- python - 如何找到元素之间的差异,忽略 NA 值
- python - Have gradient colours in sns.pairplot for one column of dataframe so that I can see which datapoints are connected to each other
- unity3d - 如何在具有特定 android 版本的 android 模拟器上测试 Unity 游戏?
- qt - 如何使用 yocto 构建简单的 qt 应用程序?
- linux - Xbindkeys 绑定鼠标按键来模拟 Super Key
- python - django ORM函数如何与db交互并解析sql代码?
- ios - MS Teams iOS 应用程序:从已发送的英雄卡中删除元素
- powerbi - 创建一个基于与长表不同的计数结果取平均值的度量?
- javascript - javascript 可重用函数