python - Json 数据操作 (Discord.py)
问题描述
@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 作为一次设置的事情,也许是一个更新的事情,所以如果我这样做 .setannounce <channel_id2> 它会覆盖第一个频道 ID。提前致谢 :)
解决方案
@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
推荐阅读
- html - 如何让我的搜索栏和周围的文本占导航栏下方空白的 25%?
- javascript - Excel 加载项:在 Office for Mac v16 中 deleteAllDataValuesAsync 后 addRowsAsync 不起作用
- java - 尝试将数据添加到数据库时出现未知列
- docker - 如何做来自 GitHub:linuxkit/linuxkit 的 hello_world 示例?
- java - 嗅探局域网:Jpcap java 程序似乎只捕获我的数据包
- regex - 正则表达式提取 tcl 中模式的所有匹配项的问题
- javascript - 在 URL 字符串中使用 load() 传递值
- c# - 如何使用 MSI 从 Azure 中的 VMSS 访问服务总线
- c# - 我应该何时将 CancellationToken 添加到异步接口方法?
- c# - 为什么我尝试退出时我的 c# 控制台应用程序挂起?