python - 有没有办法在discord.py中更改事件中的昵称

标签 python discord.py

我想在人们发送消息时将其姓名更改为其原始姓名 + 1。

我已经获得了消息检测的所有代码,但没有更改名称的代码。

@bot.event
async def on_message(message):
      if message.author == bot.user: return
      await client.change_nickname(message.author, "...a")

我希望名称更改为 . 。 .a 当他们发送消息但没有执行任何操作时。

如有任何帮助,我们将不胜感激,谢谢。

最佳答案

正如我在评论中已经提到的:

As far I see from the docs the change_nickname represents guild-specific permissions. In order to change nick of user you have to call edit on a member and pass the nick parameter.

类似这样的事情:

@bot.event
async def on_message(message):
      if message.author == bot.user: return
      await message.author.edit(nick="some new nick")

对于您对原名+1形式的昵称的特定需求,您可以使用如下内容:

import re 

# Extracts digits that are at the end of string user_name
#
# @param user_name a string to extract digits from
# @return extracted digits as integer or -1 if error
def extract_number_suffix(user_name):
    # Using regex to find all digits at the end of the user_name
    # source https://docs.python.org/2/library/re.html#re.search
    # regex entry: https://regex101.com/r/WQkzhw/1
    extracted= re.search(r"[0-9]+$", user_name)
    try:
        return int(extracted[0])
    except:
        return -1


@bot.event
async def on_message(message):
      if message.author == bot.user: return
      previous_name = message.author.name
      number = extract_number_suffix(previous_name)
      if number == -1:
          # If number is -1 that means that the function extract_number_suffix
          # failed to extract a number because user has no number at the end of
          # it's name. So we just set the name to name1
          await message.author.edit(nick="{}1".format(previous_name))
      else:
          # Remove the current digit suffix
          clean_name = previous_name.replace(str(number ), "")
          # Increment current number and change nick
          new_number = number + 1
          await message.author.edit(nick="{0}{1}".format(clean_name , new_number ))

您还可以使用 message.author.display_name 其中:

Returns the user’s display name.

For regular users this is just their username, but if they have a guild specific nickname then that is returned instead. source

关于python - 有没有办法在discord.py中更改事件中的昵称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55621490/

相关文章:

python - Docker-Compose 配置容器时区

python - (discord.py) 如何让我的机器人随机回复 DM?

python - 属性错误: module 'discord' has no attribute 'ui' when trying to create button in discord. py

python - 属性错误: 'list' object has no attribute 'channel' discord. py

python - 使用pylab生成热图

python - Keras 和 TensorFlow : Saving non-sequential model weights

python - 如何将 HoverTool 添加到数据表(Bokeh、Python)

python - 在 xlim 范围之外可访问的 matplotlib 数据

discord - 如何限制某个角色使用命令(discord.py)

python - 无法获得不一致以在聊天中显示错误