【问题标题】:Json data manipulation (Discord.py)Json 数据操作 (Discord.py)
【发布时间】:2021-03-04 11:29:27
【问题描述】:

@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>')

所以基本上我想要它,所以在不和谐中我可以将 .setannounce 作为 1 次设置的东西,也许是更新的东西,所以如果我这样做 .setannounce 它会覆盖第一个频道 ID。在此先感谢:)

【问题讨论】:

  • 你是从哪里得到announceChannel变量的?

标签: python json discord discord.py


【解决方案1】:
@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多