首页 > 解决方案 > Discord.py 无法定义频道 [已修复]

问题描述

我正在制作一个不和谐的机器人,它将欢迎消息发送到 .jason 文件中的指定频道。因此它可以与多个服务器兼容。但它遇到了一个错误,我不知道如何修复它。

@client.command()
@commands.has_permissions(administrator=True)
async def welcomeMessage(ctx):
    with open("guild.json", "r") as f:
        guildInfo = json.load(f)

    guildInfo[ctx.message.guild.id] = ctx.message.channel.id #sets the channel it was sent to as the default welcome message channel

    with open("guild.json", "w") as f:
        json.dump(guildInfo, f)


@client.event
async def on_member_join(member):
    with open("guild.json", "r") as f:
        guildInfo = json.load(f)

    channel = guildInfo[ctx.message.guild.id] #this keeps causing the error
    
    embed = discord.Embed(colour=0x07faf6, description=f"***Welcome to the Server***")
    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 channel.send(embed=embed)

除了这个,我已经完成了所有工作:

channel = guildInfo[ctx.message.guild.id]

它一直给我这个错误:

    channel = guildInfo[ctx.message.guild.id]
AttributeError: module 'ctx' has no attribute 'message'

编辑:我重新编写了代码,现在它可以工作了。

这里是:

@client.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def welcomechannel(ctx):
    fileopen = str(ctx.message.guild.id) + ".json"
    file = open(fileopen, "w")
    data = {}
    data["channel"] = ctx.message.channel.id
    json.dump(data, file)
    print("The channel has been added to the list")

@client.event
async def on_member_join(member):
    colours = [0x3348FF, 0x000000, 0xFFFFFF]
    try:
        fileopen = str(member.guild.id) + ".json"
        file = open(fileopen, "r")
        data = json.load(file)

        channelid = data["channel"]
        channel = client.get_channel(id=channelid)

    
        embed = discord.Embed(colour=random.choice(colours), description="***Welcome***")
        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 channel.send(embed=embed)

    except:
        print("The server doesn't have a welcome channel")

标签: pythonjsondiscord.py

解决方案


on_member_join事件不提供上下文。幸运的是,传递给on_member_join事件的成员具有guild捕获成员所属公会(或在本例中为加入)的属性。替换你ctx.message.guild.idmember.guild.id,你应该很好


推荐阅读