AFK function in Discord Bot

落爺英雄遲暮 提交于 2021-01-28 04:14:19

问题


I'm currently trying to make a bot in Discord using python (something almost brand new for me). I was trying to make an AFK function (similar to Dyno's). This is my code:

afkdict = {}
@client.command(name = "afk", brief = "Away From Keyboard",
                description = "I'll give you the afk status and if someone pings you before you come back, I'll tell "
                              "them that you are not available. You can add your own afk message!")
async def afk(ctx, message = "They didn't leave a message!"):
    global afkdict

    if ctx.message.author in afkdict:
        afkdict.pop(ctx.message.author)
        await ctx.send('Welcome back! You are no longer afk.')

    else:
        afkdict[ctx.message.author] = message
        await ctx.send("You are now afk. Beware of the real world!")


@client.event
async def on_message(message):
    global afkdict

    for member in message.mentions:  
        if member != message.author:  
            if member in afkdict:  
                afkmsg = afkdict[member]  
                await message.channel.send(f"Oh noes! {member} is afk. {afkmsg}")
    await client.process_commands(message)

My issue here is that the user that uses this function will be AFK until they write again >afk. My intention was to make the bot able to remove the AFK status whenever the user talked again in the server, regardless they used a bot function or not. I know it's possible because other bots do so, but I'm lost and can't think of a way to do so. Thanks in advance!


回答1:


async def on_message(message):
    global afkdict
    if message.author in afkdict:
       afkdict.pop(message.author)

    for member in message.mentions:  
        if member != message.author:  
            if member in afkdict:  
                afkmsg = afkdict[member]  
                await message.channel.send(f"Oh noes! {member} is afk. {afkmsg}")
    await client.process_commands(message)

I think that should do it, but you could as well pass the ctx again or save ctx as an parameter to access. But this version does not notify the user, that they are not afk anymore



来源:https://stackoverflow.com/questions/63683549/afk-function-in-discord-bot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!