【问题标题】:Command, doesn't work without a space, how can I fix it命令,没有空格就无法工作,我该如何解决
【发布时间】:2021-04-27 03:32:49
【问题描述】:

好吧,我的代码让我很烦,对于我的不和谐机器人来说,如果没有前导空格,它似乎无法工作。

我希望它以两种方式工作,或者只是没有空间,我该怎么做。

这是我的代码:

如何更改我的代码,使其双向工作,或者只是没有空格。

    await ctx.send("Select an amount of time for the giveaway.")
    try:
        since = await client.wait_for('message', check = check, timeout=30.0)

    except asyncio.TimeoutError:
        await ctx.send("You took to long, please try again!")


    seconds = ("s", "sec", "secs", 'second', "seconds")
    minutes= ("m", "min", "mins", "minute", "minutes")
    hours= ("h", "hour", "hours")
    days = ("d", "day", "days")
    rawsince = since.content
    
    
    try:
        time = int(since.content.split(" ")[0])
    except ValueError:
        return await ctx.send("You did not specify a unit of time, please try again.")
        
    since = since.content.split(" ")[1]
    if since.lower() in seconds:
        timewait = time
    elif since.lower() in minutes:
        timewait = time*60
    elif since.lower() in hours:
        timewait = time*3600
    elif since.lower() in days:
        timewait = time*86400
    elif since.lower() in weeks:
        timewait = time*604800
    else:
        
        return await ctx.send("You did not specify a unit of time, please try again.")```

【问题讨论】:

    标签: python python-3.x discord bots discord.py


    【解决方案1】:

    您可以使用正则表达式来提取值:

    import re
    
    ...
    
    time, unit = re.findall('(\d+) *(.+)', since.content)[0]
    

    【讨论】:

    • try: time, unit = re.findall('(\d+) *(.+)', since.content)[0] time = int(since.content.split(" ")[0]) 我要这样做吗? @Yevhen Kuzmovych
    【解决方案2】:
    try:
        temp = re.compile("([0-9]+)([a-zA-Z]+)")
        res = temp.match(since.content).groups()
        time = int(res[0])
        since = res[1]
    
    This should work!
    

    【讨论】:

    • 不确定 try 是否是代码的一部分,或者您建议 OP 实际尝试该代码。 try 不能一个人来。它后面需要一个except 或至少一个finally...
    猜你喜欢
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    相关资源
    最近更新 更多