Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

Make /afk command accept numbers not letters in python

I want to make it that when someone does /AFK and writes letters instead of numbers, it should show something like "input numbers not letters". Here is my code:

async def afk(ctx, mins : int):
    current_nick = ctx.author.nick
    await ctx.send(f"{ctx.author.mention} has gone afk for {mins} minutes.", delete_after=5)
    await ctx.author.edit(nick=f"[AFK]{ctx.author.name}")

    counter = 0
    while counter <= int(mins):
        counter += 1
        await asyncio.sleep(60)

        if counter == int(mins):
            await ctx.author.edit(nick=current_nick)
            await ctx.send(f"{ctx.author.mention} is no longer AFK", delete_after=5)
            break```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to remove the typehint and then use try/except

async def afk(ctx, mins):
    try:
        mins = int(mins)
    except ValueError:
        return await ctx.send("input numbers not letters")
    # your other code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...