【发布时间】:2021-10-14 03:27:48
【问题描述】:
我正在尝试制作模组日志,但我并不擅长此操作,我自己编写了脚本并且有点工作,但没有成功。所以基本上我的计划是当有人键入 .modlogs #channel 时,机器人将获取频道 ID 并将其键入带有公会 ID 的 json 文件,我让它工作得很好我一直坚持从 json 文件中获取关键信息,我打印值并且它们是相同的。
@commands.command(aliases=['purge'])
@commands.guild_only()
@commands.has_permissions(manage_messages=True)
async def clear(self,ctx, arg: int = None):
if arg is None:
await ctx.send(':x: You need to state a value!')
else:
with open('./logs.json', 'r') as f:
logsf = json.load(f)
if ctx.guild.id in logsf:
embedv = discord.Embed(color = discord.Colour.random())
embedv.add_field(name='Event Type:', value="Clear")
embedv.add_field(name='Channel:', value= ctx.channel)
embedv.add_field(name='Moderator:', value=ctx.message.author)
embedv.footer(text='Epifiz Logging')
schannel = commands.get_channel(logsf[ctx.guild.id])
await ctx.channel.purge(limit=arg)
await discord.schannel.send(embed=embedv)
await ctx.send('Done')
elif ctx.guild.id not in logsf:
await ctx.channel.purge(limit=arg)
await ctx.send(':white_check_mark: Successfully cleared {} messages.'.format(arg))
也是我的 json 文件:
{
"838355243817369620": 853297044922564608
}
公会ID也在json文件中,没有错。
【问题讨论】:
-
你的 json 字典有一个字符串作为键,而 ctx.guild.id 是一个 int。要解决此问题,您有两个选择:要么在加载 json(使用 object_hook 函数)时将密钥恢复为整数,要么在每次需要时将 ctx.guild.id 转换为 str
-
我将如何使我的密钥 int?
-
在 json.load() 中使用 object_hook 关键字,例如:data = json.load(f, object_hook=convert_keys_to_int) 用于我使用的 convert_keys_to_int...原谅格式:def convert_keys_to_int(d) : new_dict = {} for k, v in d.items(): try: new_key = int(k) except ValueError: new_key = k if type(v) == dict: v = convert_keys_to_int(v) new_dict[new_key] = v 返回新字典
-
谢谢,我解决了。
-
没问题,请注意,如果可能,使用该函数将所有键转换为整数,因此,如果您有任何键是字符串但可以转换为整数,它将转换它们并可能破坏您的程序
标签: discord discord.py