使 /afk 命令接受 python 中的数字而不是字母
Make /afk command accept numbers not letters in python
我想让它当有人执行 /AFK 并写字母而不是数字时,它应该显示类似“输入数字而不是字母”的内容。这是我的代码:
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```
试试这个:
async def afk(ctx, mins : int):
try:
mins = int(mins)
except ValueError:
# ...
# <send the message here.>
# ...
return
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}")
asyncio.sleep(60 * mins)
await ctx.author.edit(nick=current_nick)
await ctx.send(f"{ctx.author.mention} is no longer AFK", delete_after=5)
这里,我们尝试将mins转换为int,如果失败,则发送消息。否则,照常继续。我想你也可以像我在这里做的那样删除 while 循环和 if 语句。
您需要删除类型提示,然后使用 try/except
async def afk(ctx, mins):
try:
mins = int(mins)
except ValueError:
return await ctx.send("input numbers not letters")
# your other code
大体上我同意,但是有一个比try/except更简单的方法:
async def afk(ctx, mins):
if not mins.isdigit():
return await ctx.send("input numbers not letters")
mins = int(mins)
我想让它当有人执行 /AFK 并写字母而不是数字时,它应该显示类似“输入数字而不是字母”的内容。这是我的代码:
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```
试试这个:
async def afk(ctx, mins : int):
try:
mins = int(mins)
except ValueError:
# ...
# <send the message here.>
# ...
return
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}")
asyncio.sleep(60 * mins)
await ctx.author.edit(nick=current_nick)
await ctx.send(f"{ctx.author.mention} is no longer AFK", delete_after=5)
这里,我们尝试将mins转换为int,如果失败,则发送消息。否则,照常继续。我想你也可以像我在这里做的那样删除 while 循环和 if 语句。
您需要删除类型提示,然后使用 try/except
async def afk(ctx, mins):
try:
mins = int(mins)
except ValueError:
return await ctx.send("input numbers not letters")
# your other code
大体上我同意
async def afk(ctx, mins):
if not mins.isdigit():
return await ctx.send("input numbers not letters")
mins = int(mins)