为了账号安全,请及时绑定邮箱和手机立即绑定

有没有办法将字符串转换为 discord.py 中的 discord.Member 类型?

有没有办法将字符串转换为 discord.py 中的 discord.Member 类型?

森栏 2023-03-22 10:17:41
我一直在尝试向我的 discord 机器人添加一个井字游戏迷你游戏。我最初在 @client.command() 中编写代码,因为我认为您可以在其中使用 client.wait_for() 但不幸的是,您不能。无论如何,我不得不将我的代码转换为在 on_message() 函数上工作,现在我遇到了从初始命令中获取 discord.Member 变量类型的问题,比如 ~tictactoe @user#1234。因此,例如,我尝试在 on_message() 函数中编写此代码但没有成功。if message.content.startswith("~tictactoe") or message.content.startwith("~ttt"):    member = str(message).split(" ")    member = discord.Member(member[1])    channel = message.channel这是我的完整代码:if message.content.startswith("~tictactoe") or message.content.startwith("~ttt"):    member = str(message).split(" ")    member = discord.Member(member[1])    channel = message.channel    if member.bot: channel.send("You can't play against a bot!")    else:        while True:            x = 0            player = [message.author if (x % 2 == 0) else member]            x += 1            symbol = [':x:' if player == message.author else ':o:']            def check(m):                possibilities = ['a1','a2','a3','b1','b2','b3','c1','c2','c3']                return (m.content.lower() in possibilities or m.content.lower() == 'end') and m.author == player and m.channel == channel            if x != 1:                channel.send("TicTacToe\n{message.author.name} vs. {member.name}")                for i in range(3):                    channel.send(f"{board[i][0]}{board[i][1]}{board[i][2]}\n")            channel.send(f"{player.mention}, where do you want to place your marker?\na1\ta2\ta3\nb1\tb2\tb3\nc1\tc2\tc3\n or `end` to end game")            try:                cell = await client.wait_for('message', timeout=20.0, check=check)            except:                channel.send("Input invalid or you took too long to respond.")任何帮助appreciated :)
查看完整描述

1 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

使用message.mentions


message.mentionsdiscord.Member返回提到的列表(或者discord.User如果消息是在私人消息中发送的)。

# Safe method

if message.mentions:

    member = message.mentions[0]

else:

    return  # There was no mentions


# Riskier but simpler method

# Having no mentions or more than one would raise an error

member, = message.mentions

快速说明:回复被视为提及,message.mentions将包含您的消息中提到的成员和您回复的成员。


解析消息

提及等同于<@!id>,因此您可以解析您的消息以获取成员的 id:


command, member = message.split()

member_id = int(member.strip('<@!>'))

然后,要从discord.Member中取出对象:


# Regardless of cache, but sends an API call

member = await bot.fetch_member(member_id)


# Depends on the bot's cache

# Doesn't make any API calls and isn't asynchronous

member = message.guild.get_member(member_id)


查看完整回答
反对 回复 2023-03-22
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信