Python 在Discord.py命令之间共享信息

Python 在Discord.py命令之间共享信息,python,bots,discord,discord.py,Python,Bots,Discord,Discord.py,我正在制作一个Discord机器人,它将踢和禁止用户,然后自动将信息记录到一个#mod log频道。这工作正常,因为我已经为测试服务器指定了#mod log channel ID。但是,如果我的机器人位于不同的服务器中,我希望该服务器的管理员设置自己的#mod log频道。我编写了以下命令: 我希望将“mlog”变量带到我的kick/ban命令中,以便它将记录到主持人指定的频道。然而,这是行不通的。“mlog”变量不结转。有办法做到这一点吗?您应该为通道ID保留一个服务器ID字典。调用setm

我正在制作一个Discord机器人,它将踢和禁止用户,然后自动将信息记录到一个#mod log频道。这工作正常,因为我已经为测试服务器指定了#mod log channel ID。但是,如果我的机器人位于不同的服务器中,我希望该服务器的管理员设置自己的#mod log频道。我编写了以下命令:


我希望将“mlog”变量带到我的kick/ban命令中,以便它将记录到主持人指定的频道。然而,这是行不通的。“mlog”变量不结转。有办法做到这一点吗?

您应该为通道ID保留一个服务器ID字典。调用
setmodlog
时更新该字典,并检查它是否有其他命令

modlog = {}

async def on_ready(self):
    global modlog
    try:
        with open('modlog.json') as f:
            modlog = json.load(f)
    except:
        modlog = {}

@commands.command(pass_context=True)
@commands.has_permissions(kick_members=True)
async def setmodlog(self,ctx,mlog:discord.Channel):
    """Sets mod-log channel"""
    modlog[ctx.message.server.id] = mlog.id
    await self.bot.say("Mod Log channel set")
    with open('modlog.json', 'w+') as f:
        json.dump(modlog, f)

@commands.command(pass_context=True)
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member):
    server = ctx.message.server
    author = ctx.message.author
    message = "{} kicked {}".format(author.name, member.name)
    await bot.kick(member)
    channel = modlog[server.id]
    await bot.send_message(server.get_channel(channel), message)

@Markshark注意到,如果您的机器人停止运行,此映射将消失。您可能希望将其保存到一个文件中,您可以在\u ready事件时将其加载到您的
中。我该怎么做?机器人如何知道将哪些频道分配给哪些服务器?@TheLarkShark,因为管理员调用了
!setmodlog#somechannel
。字典是服务器与其日志通道之间的映射。我将在此示例中添加加载/保存。
modlog = {}

async def on_ready(self):
    global modlog
    try:
        with open('modlog.json') as f:
            modlog = json.load(f)
    except:
        modlog = {}

@commands.command(pass_context=True)
@commands.has_permissions(kick_members=True)
async def setmodlog(self,ctx,mlog:discord.Channel):
    """Sets mod-log channel"""
    modlog[ctx.message.server.id] = mlog.id
    await self.bot.say("Mod Log channel set")
    with open('modlog.json', 'w+') as f:
        json.dump(modlog, f)

@commands.command(pass_context=True)
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member):
    server = ctx.message.server
    author = ctx.message.author
    message = "{} kicked {}".format(author.name, member.name)
    await bot.kick(member)
    channel = modlog[server.id]
    await bot.send_message(server.get_channel(channel), message)