簡體   English   中英

Discord.py:獲取帶有 id 的用戶對象

[英]Discord.py: Get user object with id

我有一個機器人,它只保存用戶的 id(這樣工作更好)。 現在我想從那個 id 中獲取用戶對象。

我試過以下這對我不起作用,也許我做錯了什么..

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")

執行此操作,它只會打印"Top rank entered"而不會打印user"Top rank end"但是,我沒有收到錯誤消息。 該方法就停在那里(機器人在 Heroku 上運行)。 提前致謝!

有兩種方法可以從 id 中獲取用戶:

以下是一些示例(同時使用ClientBot ):

#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)

有了這些例子,你只需要在 discord 中寫!find [id] ,它就會打印它在你的終端中獲取的對象

client.fetch_user(id(int)) 是一個協程。 這意味着我需要添加一個await ,所以它需要是_user = await client.fetch_user(id) 確保 id 正確,因為腳本可能會在沒有錯誤的情況下停止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM