首页 > 解决方案 > 如何从 .json 文件 discord.py 中获取信息

问题描述

我想制作一个具有可自定义欢迎消息的机器人,您可以在其中使用命令并键入#(频道)和之后的消息。问题是,在 on_member_join 事件中,我不知道如何制作 ,或者 guild = (the guild that the command was ran in) 所有 信息都在一个名为 welcomemsgs.json 的 json 文件中。我只需要以某种方式从 .json 文件中获取信息。这是 json 文件的示例channel = (the channel the user put in)message = (the message the user gave){"channel": 896476418421178397, "message": "Welcome!", "guild": 896476417968205894 }

标签: jsondiscorddiscord.py

解决方案


实际上很简单,如果你是初学者,你可以使用 json

首先你创建命令

@bot.command()
async def welcomechannel(ctx, channel):
    ch = int(channel.strip) # This removes the <#> and leaves the channel id
    with open('yourfilename.json', 'r') as f: # 'r' stands for read mode
        welcomes = json.load(f)

    welcomes[str(ctx.guild.id)] = ch # Sets the key to the channel

    with open('yourfilename.json', 'w') as f: # 'w' stands for write mode
        json.dump(welcomes, f) # Dumps the new data in the file

然后你做

@bot.event
async def on_member_join(member):
    with open('yourfilename.json', 'r') as f:
        welcomes = json.load(f)
    channel = bot.get_channel(welcomes[str(member.guild.id)]
    await channel.send("Welcome " + member.mention)

推荐阅读