【问题标题】:How to ping members from a string discord.py如何从字符串 discord.py ping 成员
【发布时间】:2021-08-19 03:04:20
【问题描述】:

我正在从服务器获取游戏聊天字符串,我需要检查该字符串中是否提到了用户,如果是,我需要在服务器上找到他并提及他,因为我不能只按原样发送字符串,因为它没有提到他。

这是一个简单的例子:

socket_str = "Hey this is a ping test for @TheBeast"

我需要检查该字符串 (@) 上的标签,然后将名称分开,以便 TheBeast ,然后我需要检查服务器中的成员并找到一个 使用该名称的成员对象,并构建一个包含提及之前和提及的字符串的最终 fstring。

所以它看起来是一样的,但机器人实际上会提到这个用户。

这是最简单的例子,但是有很多边缘情况我无法处理,例如,如果这个人的名字中有空格怎么办,你怎么知道名字什么时候结束?这是我能做的最复杂的例子:

socket_str = "Hey I'm looking for @The New Beast is he online?, or @Newly Born Beast or @someone that doesnt exists is on?"

我正在为此寻找一种不同的方法,我可以分享我到目前为止写的很多内容,但老实说,它是如此复杂的代码,即使我不再理解它了

【问题讨论】:

  • stackoverflow.com/questions/58639644/… 我觉得这篇文章有答案?
  • 与我的问题并不真正相关,我的问题上的用户没有发送消息,我正在将它们从套接字放入字符串中。
  • 哦,尝试用 user_id 替换名称?

标签: python discord.py


【解决方案1】:

这实际上非常重要。你自己已经说过了

“如果这个人的名字中有空格,你怎么知道名字的结尾?”

我能想到的可靠检查用户名(包含空格)是否存在的唯一选择是迭代检查每个间隔单词的组合,只要满足特定的语义标准。
在 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?
# ...

附带说明,此方法适用于任何数量的提及!

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 2021-05-05
    • 2021-03-27
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    相关资源
    最近更新 更多