这实际上非常重要。你自己已经说过了
“如果这个人的名字中有空格,你怎么知道名字的结尾?”
我能想到的可靠检查用户名(包含空格)是否存在的唯一选择是迭代检查每个间隔单词的组合,只要满足特定的语义标准。
在 Discord 中,用户名的唯一限制是最多 32 个字符。 AFAIK 你可以在你的名字中拥有每一个符号、表情符号......
为了说明,这些语句看起来像这样
string = "Hello @This is a username! Whats up?"
# is "This" a username?
# yes -> great! | no -> is "This is" a username?
# yes -> great! | no -> is "This is a" a username?
# yes -> great! | no -> is "This is a username!" a username?
# ...
不过,这也是另一种极端情况。 This is a username 是一个有效用户,但通过用空格分割,程序会查找无效的This is a username!。据我所知,如果用户名有效,最好的选择肯定是实际检查每个字符,直到 Discord 用户名的最大长度。
可以这样实现
string = "Hello @This is a username! Whats up?"
potentialUsernames = string.split("@") # Split string into potential usernames
del potentialUsernames [0] # Delete first element, as it is definitely not a username
for potentialUsername in potentialUsernames: # for every potential username, do
for run, letter in enumerate(potentialUsername): # for every letter in every potential username, do
checkUsername = potentialUsername[:(run+1)]
if run > 32:
break # break out of this loop as there cant be a username here anymore
potentialMember = guild.get_member_named(checkUsername) # check if potential username exists
if potentialMember != None: # BOOM, we found a member!
string = string.replace("@" + checkUsername, potentialMember.mention) # replace the username with real mention in string
break # break because the user was already found
print(string) 的输出将是
"Hello <@!1234567891011121314>! Whats up?"
是的.. 如果您不知道,这就是提及的文本形式。长数字将是用户 ID,但是 Member.mention 已经为您构造了这个!
在这段代码中,guild 必须是公会对象,您想从中获取成员。
现在,此代码的作用是检查每个被 @ 分割的潜在用户名,并检查每个可能的长度,直到下一个 @,或不和谐的 32 个字符限制。
即
# is "T" a username?
# yes -> great | no -> is "Th" a username?
# yes -> great | no -> is "Thi" a username?
# ...
附带说明,此方法适用于任何数量的提及!