1

比如说我有这个:

import discord, asyncio, time

client = discord.Client()

@client.event
async def on_message(message):
    if message.content.lower().startswith("!test"):
        await client.send_message(message.channel,'test')

client.run('clienttokenhere')

我想做两件事:

1) 使当且仅当用户准确 输入且没有其他内容时,它才会在频道中!test打印出来test

2)如果用户!test首先输入一个空格和至少一个其他字符串字符,它将打印出来test- 例如:a)!test不会打印出任何东西,b)!test !test后跟一个空格) 不会打印出任何东西,c)!test1不会打印出任何东西,d)!testabc不会打印出任何东西,但是 e)!test 1会打印出test,f)!test 123abc会打印出test,g)!test a会打印出test,h)!test ?!abc123会打印出test等等.

我只知道startswithand endswith,据我的研究表明,没有exactand 我不知道如何制作它,因此它在 a 之后需要最少数量的字符startswith

4

2 回答 2

0

使用==运算符。

!test1) 仅在接收到的字符串中打印测试

if message.content.lower() == '!test':
    await client.send_message(message.channel,'test')

2)当它后面跟着一个字符串时打印test后面跟着字符串

# If it starts with !test and a space, and the length of a list
# separated by a space containing only non-empty strings is larger than 1,
# print the string without the first word (which is !test)

if message.content.lower().startswith("!test ") 
   and len([x for x in message.content.lower().split(' ') if x]) > 1:
    await client.send_message(message.channel, 'test ' + ' '.join(message.content.split(' ')[1:]))
于 2017-05-28T13:32:39.490 回答
0

看起来你需要一个正则表达式而不是startswith(). 而且您似乎有两个相互矛盾的要求:

1) 使当且仅当用户准确输入且没有其他内容时,它才会在频道中!test打印出来test

2a)!test不会打印出任何东西

包括1和不包括2a:

import re
test_re = re.compile(r"!test( \S+)?$")
# This says: look for
# !test (optionally followed by one space followed by one or more nonspace chars) followed by EOL
# 

@client.event
async def on_message(message):
    if test_re.match(message.content.lower()):
        await client.send_message(message.channel,'test')

包括2a,不包括1,替换这一行(后面的空格和东西!test不再可选):

test_re = re.compile(r"!test \S+$")
于 2017-05-28T13:37:34.953 回答