【问题标题】:Share info Between Discord.py Commands在 Discord.py 命令之间共享信息
【发布时间】:2018-11-22 02:09:24
【问题描述】:

我正在制作一个 Discord Bot,它会踢出和禁止用户,然后自动将信息记录到 #mod-log 频道。这工作正常,因为我已经为我的测试服务器指定了#mod-log 通道 ID。但如果我的机器人在不同的服务器上,我希望该服务器的版主设置他们自己的#mod-log 频道。我写了以下命令:

@commands.command(pass_context=True)
@commands.has_permissions(kick_members=True)
async def setmodlog(self,ctx,mlog:discord.Channel):
    """Sets mod-log channel"""
    await self.bot.say("Mod Log channel set")

我希望那个“mlog”变量能够延续到我的 kick/ban 命令,这样它就会记录到主持人指定的频道。但是,这是行不通的。 “mlog”变量不会结转。有没有办法做到这一点?

【问题讨论】:

    标签: python bots discord discord.py


    【解决方案1】:

    您应该保留一个服务器 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)
    

    【讨论】:

    • @TheLarkShark 请注意,如果您的机器人停止运行,此映射将消失。您可能希望将其保存到一个文件中,您可以在 on_ready 事件中加载该文件。
    • 我该怎么做?机器人如何知道将哪些通道分配给哪些服务器?
    • @TheLarkShark 因为管理员调用了!setmodlog #somechannel。字典是服务器与其日志通道之间的映射。我将在此示例中添加加载/保存。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2011-06-10
    • 2011-11-25
    相关资源
    最近更新 更多