Discord Bot客户端.转换为Discord时用户错误.Python中的Utils



python 3.7.3不和谐.py 1.3.4树莓皮4

在一切正常之后,我一开始就被卡住了。

我从头开始。当我使用for循环然后使用print(f'{client.user}时,我没有问题,并且bot用户名会打印到终端。当我放弃循环并使用guild = discord.utils.get(client.guilds, name=GUILD)代码时,我在终端中得到以下错误。

忽略on_redy中的异常追踪(最近一次通话(:文件"/home/pi/.local/lib/python3.7/site packages/discord/client.py";,第312行,在_run_event中等待coro(*args,**kwargs(文件"/home/pi/TackleBot/bot2.py";,第27行,准备就绪f‘{client.user}已连接到以下公会:\n‘AttributeError:"NoneType"对象没有属性"name">

如果我在guild = discord.utils.get命令之后直接添加print(client.user)命令,它会在那里打印用户名,但仍会在下面出错。我花了几个小时梳理文档,这就是我现在的处境。还是很困惑。如果我注释掉for循环,就会得到错误。如果我注释掉discord实用程序命令,它可以正常工作。切勿使用print(f'{client.user}块更改任何内容。

我边学习边学习,任何帮助或建议都将不胜感激。非常感谢。

import os

import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()
@client.event
async def on_ready():
guild = discord.utils.get(client.guilds, name=GUILD)
if guild is not None:
channel = discord.utils.get(guild.text_channels, name=GUILD)
# when the lines 18-20 are used, line 26 throws an object type error 'none'
# when lines 23-25 are used, there is no error
#    for guild in client.guilds:
#        if guild.name == GUILD:
#            break
print(
f'{client.user} is connected to the following guild:n'
f'{guild.name}(id: {guild.id})'
)

members = 'n - '.join([member.name for member in guild.members])
print(f'{guild.name}:n - {members}')

client.run(TOKEN)

如果我理解正确,您将尝试首先在on_aready函数中打印公会信息,对吗?

你可以这样做:

client = discord.Client()
@client.event
async def on_ready():
for guild in client.guilds:
print(
f'{client.user} is connected to the following guild:n'
f'{guild.name}(id: {guild.id})'
)
members = 'n - '.join([member.name for member in guild.members])
print(f'Guild Members:n - {members}')

最后:

client.run(TOKEN)

最新更新