#python #discord.py
Вопрос:
def get_channel_id(client, message):
with open('./json/welcome.json', 'r') as f:
channel_id = json.load(f)
return channel_id[str(message.guild.id)]
@client.event
async def on_member_join(member):
embed = discord.Embed(colour=0x767429, description=f"Welcome to my server! You are the {len(list(member.guild.members))}th member ")
embed.set_thumbnail(url=f" {member.avatar_url} ")
embed.set_author(name=f" {member.name} ", icon_url=f" {member.avatar_url} ")
embed.set_footer(text=f"{ member.guild }", icon_url=f" {member.guild.icon_url} ")
embed.timestamp = datetime.datetime.utcnow()
channel = client.get_channel(id=get_channel_id)
await channel.send(embed=embed)
@client.command()
async def welcomechannel(ctx, channel_id):
with open('./json/welcome.json', 'r') as f:
id = json.load(f)
id[str(ctx.guild.id)] = channel_id
with open('./json/welcome.json', 'w') as f:
json.dump(id, f, indent=4)
await ctx.send(f'Welcome channel changed to {channel_id}')
Я бы хотел, чтобы get_channel_id
функция была идентификатором channel = client.get_channel(id=get_channel_id)
, но каждый раз, когда я ее запускаю, я получаю ошибку AttributeError: 'NoneType' object has no attribute 'send'
. Кто-нибудь, пожалуйста, может мне помочь
Комментарии:
1. Вам нужно открыть JSON после присоединения участника, а затем извлечь канал из JSON.
Ответ №1:
Вы можете немного упростить код. Как упоминалось в моем комментарии, вам также необходимо открывать JSON, когда новый пользователь заходит на сервер.
Ваша собственная функция выше полностью избыточна и не нужна.
Я также однажды немного изменил вашу welcomechannel
команду , потому что вы не продвинулись далеко channel_id
, вы можете использовать channel: discord.TextChannel
ее вместо этого, и она выходит такой же.
Вот команда на данный момент:
@client.command()
async def welcomechannel(ctx, channel: discord.TextChannel): # We use discord.TextChannel
with open('./json/welcome.json', 'r') as f:
id = json.load(f)
id[str(ctx.guild.id)] = channel.id # Saving JUST the ID, you also had <#ID> in it
with open('./json/welcome.json', 'w') as f:
json.dump(id, f, indent=4)
await ctx.send(f'Welcome channel changed to `{channel}`')
А теперь проверим канал. Для этого мы открываем JSON таким же образом, как и с помощью команды:
@client.event
async def on_member_join(member):
with open('./json/welcome.json', 'r') as f:
wchannel = json.load(f) # Define our channel
try:
if wchannel: # If a channel is set for the server
wchannelsend = member.guild.get_channel(wchannel[str(member.guild.id)]) # Get the channel from the JSON
embed = discord.Embed(color=0x767429,
description=f"Welcome to my server! You are the {len(list(member.guild.members))}th member ")
embed.set_thumbnail(url=f"{member.avatar_url} ")
embed.set_author(name=f"{member.name} ", icon_url=f"{member.avatar_url} ")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url} ")
embed.timestamp = datetime.datetime.utcnow()
await wchannelsend.send(embed=embed) # Send the embed to the channel
else:
return # If no channel was set, nothing will happen
except:
return