Discord.py:获取具有ID的用户对象 [英] Discord.py: Get user object with id
问题描述
我有一个仅保存用户ID的漫游器(最好这样工作).现在,我想从该ID获取用户对象.
I have a bot which only saves the id of a user (it's better working like that). Now I want to get the user-object from that id.
我尝试了以下对我不起作用的方法,也许是我做错了..
I tried following which doesn't work for me, maybe I have made something wrong..
client = discord.Client
client.get_user(id)
和 client.get_user_info(id)
这是代码:
import discord
class MyClient(discord.Client):
ntd = name_table.get_all_records() #google sheets api: returns a list of dicts
async def on_message(self, message):
print(message.content[1])
if message.author == client.user:
return
if isinstance(message.channel, discord.channel.DMChannel):
await self.handle_DM(message)
if message.content[0] == "/":
if message.content.split(" ")[0].lower() == "/rank":
await self.rank_command(message)
async def rank_command(self, message):
if len(message.content.split(" ")) < 2:
await message.channel.send(
message.author.mention + "/rank takes 2 or 3 arguments. Do '/rank ?' for help.")
try:
if message.content.split(" ")[1] == "?":
await self.help("rank", message)
return
except:
pass
try:
if message.content.split(" ")[1] == "top":
await self.top_rank_command(message)
return
except:
pass
async def top_rank_command(message):
print("Top rank entered")
_user = await client.fetch_user(372746847393021953) #my id: Cluebo#2312
print(_user)
print("Top rank end")
执行此操作,它将仅打印输入的最高排名"
,而不打印 user
或最高排名结束"
但是,我没有收到错误消息.该方法仅在此处停止(该机器人在Heroku上运行).预先感谢!
Executing this, it will only print "Top rank entered"
but not the user
or "Top rank end"
However, I did not get an error message. The method just stops there (The bot is running on Heroku).
Thanks in advance!
推荐答案
有两种方法可以从id中获取用户:
There are two methods to get a user from an id:
以下是一些示例(同时使用 Client
和 Bot
):
Here are some examples (using both Client
and Bot
):
#Get a discord.User object
@client.event
async def on_message(message):
content = message.content[6:]
if message.content.startswith('!find'):
user = await client.fetch_user(int(content))
print(user)
else:
pass
@bot.command()
async def find(ctx, id: int):
user = await bot.fetch_user(id)
print(user)
#Get a discord.Member object
@client.event
async def on_message(message):
content = message.content[6:]
if message.content.startswith('!find'):
member = await message.guild.fetch_member(int(content))
print(member)
else:
pass
@bot.command()
async def find(ctx, id: int):
member = await ctx.guild.fetch_member(id)
print(member)
在这些示例中,您只需要以不和谐的方式编写!find [id]
,它将打印从终端中获取的对象
With those examples, you'd just have to write !find [id]
in discord and it would print the object it fetched in your terminal
这篇关于Discord.py:获取具有ID的用户对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!