繁体   English   中英

如何从 id discord.py 获取用户对象

[英]How to get User object from id discord.py

我有一个机器人将 dm ping 发送给一个用户,该用户的 ID 作为命令中的参数给出。
这是命令: .spam ID #_OF_PINGS
我遇到以下错误:

Ignoring exception in command spam:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "bot.py", line 16, in spam
     await ctx.send(f'Started pinging {user.name} {num} times.')
AttributeError: 'NoneType' object has no attribute 'name'

The above exception was the direct cause of the following exception:
Traceback (most recent call last):
   File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 903, in invoke
     await ctx.command.invoke(ctx)
   File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 859, in invoke
     await injected(*ctx.args, **ctx.kwargs)
    File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 94, in wrapped
     raise CommandInvokeError(exc) from exc
     discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'name'

这是我的代码:

from discord.ext import commands
token = 'MyBotTokenHere'
prefix = '.'
client = commands.Bot(command_prefix=prefix)
client.remove_command("help")


@client.event
async def on_ready():
    print('Ready')


@client.command()
async def spam(ctx, id1: int, num: int):
    user = client.get_user(id1)
    await ctx.send(f'Started pinging {user.name} {num} times.')
    for i in range(num):
        await user.send(f'<@{str(id1)}>')
    await ctx.send(f'Finished {num} pings for {user.name}')


client.run(token)

昨天还好好的,今天就因为某种原因坏了。 我如何解决它?
PS我在Heroku上托管它

您可以为此使用转换器:

@client.command()
async def spam(ctx, user: discord.User, num: int):
    await ctx.send(f'Started pinging {user.name} {num} times.')
    for i in range(num):
        await user.send(f'<@{str(id1)}>')
    await ctx.send(f'Finished {num} pings for {user.name}')

这样,Discord 将自动尝试获取与您作为参数传递的id相对应的discord.User实例,如果您愿意,您也可以@mention某人,它仍然可以工作。

此外,从 Discord 1.5.0 开始,您现在需要在初始化机器人时传入intents ,而您显然还没有这样做。 更新您的 Discord,并使用以下内容初始化您的机器人:

intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=prefix, intents=intents)

相关API 文档中有关intents的方式和原因的更多信息。 您还需要在机器人的特权意图页面上启用members ,链接的 API 文档中也对此进行了解释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM