Json数据操作(Discord.py)

2024-05-15 14:23:51 发布

您现在位置:Python中文网/ 问答频道 /正文


@bot.command(name='setannounce')
async def setannounce(context, *, arg2):

    with open("data2.json", "w+") as f:
        json.dump(arg2, f, indent=2)
    setannounce = arg2

@bot.command(name='announce')
async def announce(context, *, arg1):

    embed = discord.Embed(title="**OpticPvP**", description="", color=0xc94747)
    embed.add_field(name="Announcement", value=arg1 , inline=False)
    embed.set_footer(text="Optic Development")
    
    try:
        inchan = bot.get_channel(announceChannel)
        await inchan.send(embed=embed)
    except NameError:
        await context.send('Announcement channel is not set, please use `.setannounce <channel id>')

所以基本上我想要它,所以在discord中我可以做。setannounce是一次设置,如果我做了,可能是一次更新。setannounce<;频道id2>;它将覆盖第一个频道id。提前感谢:)


Tags: namejsonasyncdefbotcontextchannelembed
1条回答
网友
1楼 · 发布于 2024-05-15 14:23:51
@bot.command()
async def setannounce(ctx, channel: discord.TextChannel):
    # Opening the file
    with open('data.json', 'r') as f:
        data = json.load(f)
    # Adding the channel id
    data[str(ctx.guild.id)] = channel.id
    # Dumping the data
    with open('data.json', 'w') as f:
        json.dump(data, f, indent=4)
  
    await ctx.send(f"Set announcement channel to {channel.mention}")


@bot.command()
async def announce(ctx, *, content):
    # Opening the file
    with open('data.json', 'r') as f:
        data = json.load(f)
    # If the channel is not set `KeyError` is going to be thrown
    try:
        # Getting the channel ID
        channel_id = data[str(ctx.guild.id)]
    except KeyError:
        await ctx.send("Announcement channel is not set, please use `.setannounce <channel>`")
    else:
        # Getting the channel object
        channel = bot.get_channel(channel_id)
        await channel.send(content) # <- or send whatever you want

相关问题 更多 >