【问题标题】:Add Muted Users in a database? When they rejoin they get the role again在数据库中添加静音用户?当他们重新加入时,他们再次获得角色
【发布时间】:2021-10-13 04:29:32
【问题描述】:
@commands.command()
    @commands.has_permissions(manage_roles=True)
    async def mute(self, ctx, member:discord.Member, *, time: TimeConverter = None):
        role = discord.utils.get(ctx.guild.roles, name="Muted by ez")
        if not role:
            role = await ctx.guild.create_role(name="Muted by ez")

            for channel in ctx.guild.channels:
                await channel.set_permissions(role, speak=False, send_messages=False, read_message_history=True,
                                              read_messages=False)
            await member.add_roles(role)
            await asyncio.sleep(time)
            await member.remove_roles(role)
            await ctx.send(f"Muted {member.mention} for {time}s")
        else:
            await member.add_roles(role)
            await ctx.send(f"Muted {member.mention} for {time}s")
            await asyncio.sleep(time)
            await member.remove_roles(role)
            await ctx.send(f'Unmuted {member.mention}')


    @commands.command()
    @commands.has_permissions(manage_roles=True)
    async def unmute(self, ctx, member: discord.Member):
        role = discord.utils.get(ctx.guild.roles, name="Muted by ez")
        await member.remove_roles(role)
        await ctx.send(f'Unmuted {member.mention}')

到目前为止,这是我的代码完美运行,但我已经很长时间了,并问自己如何在 json 数据库中添加用户,以便当他们重新加入时,他们仍然拥有角色。

更新更好的代码 我现在得到了所有你的chanches,但没有更多数据: 我想添加公会 id、静音时长和作者 id

所以我尝试存储所有内容,但我遇到了很多错误,所以我希望你能再次帮助我 到目前为止这是我的代码

import re

import asyncio
import discord
from discord.ext import commands
import cogs._json
time_regex = re.compile("(?:(\d{1,5})(h|s|m|d))+?")
time_dict = {"h": 3600, "s": 1, "m": 60, "d": 86400}



class TimeConverter(commands.Converter):
    async def convert(self, ctx, argument):
        args = argument.lower()
        matches = re.findall(time_regex, args)
        time = 0
        for key, value in matches:
            try:
                time += time_dict[value] * float(key)
            except KeyError:
                raise commands.BadArgument(
                    f"{value} is an invalid time key! h|m|s|d are valid arguments"
                )
            except ValueError:
                raise commands.BadArgument(f"{key} is not a number!")
        return round(time)


class Moderation(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(
        name='mute',
        description="Mutes a given user for x time!",
        ussage='<user> [time]'
    )
    @commands.has_permissions(manage_roles=True)
    async def mute(self, ctx, member: discord.Member, *, time: TimeConverter= None):
        role = discord.utils.get(ctx.guild.roles, name="Muted by ez")
        if not role:
            role = await ctx.guild.create_role(name="Muted by ez", colour=0x171717)

            for channel in ctx.guild.channels:
                await channel.set_permissions(role, speak=False, send_messages=False, read_message_history=True,
                                              read_messages=False, add_reactions=False)
            pass

        try:

                data = cogs._json.read_json("muted_users")
                if member.id in data['muted_users']:
                    remsg = await ctx.send("reloading the mute")
                    await member.remove_roles(role)
                    data = cogs._json.read_json("muted_users")
                    data["muted_users"].remove(member.id)
                    cogs._json.write_json(data, "muted_users")
                    await asyncio.sleep(2)
                    await remsg.edit(content=f"Unmuted `{member}`")
                    data = cogs._json.read_json("muted_users")
                    data["muted_users"].append(member.id)
                    cogs._json.write_json(data, "muted_users")
                    await member.add_roles(role)
                    if not time:
                        await asyncio.sleep(2)
                        await remsg.edit(content=f"Muted `{member}`")
                    else:
                        await asyncio.sleep(2)
                        await remsg.edit(content=f"Muted `{member}` for `{time}s`")

                        await asyncio.sleep(time)
                        await member.remove_roles(role)
                        data = cogs._json.read_json("muted_users")
                        data["muted_users"].remove(member.id)
                        cogs._json.write_json(data, "muted_users")
                        await ctx.send(content=f"Unmuted `{member}`")


                    return
        except KeyError:
            pass
        data = cogs._json.read_json("muted_users")
        data["muted_users"].append(member.id)
        cogs._json.write_json(data, "muted_users")
        await member.add_roles(role)

        if not time:
            await ctx.send(f"Muted `{member}`")
        else:
            await ctx.send(f"Muted `{member}`for `{time}s`")
            await asyncio.sleep(time)
            print(time)
            if role in member.roles:
                await member.remove_roles(role)
                data = cogs._json.read_json("muted_users")
                data["muted_users"].remove(member.id)
                cogs._json.write_json(data, "muted_users")
                await ctx.send(f"Unmuted `{member}`")
            else:
                data = cogs._json.read_json("muted_users")
                data["muted_users"].remove(member.id)
                cogs._json.write_json(data, "muted_users")

    @commands.command(
        name='unmute',
        description="Unmuted a member!",
        usage='<user>'
    )
    @commands.has_permissions(manage_roles=True)
    async def unmute(self, ctx, member: discord.Member):
        role = discord.utils.get(ctx.guild.roles, name="Muted by ez")
        if not role:
            role = await ctx.guild.create_role(name="Muted by ez", color=0x171717)

            for channel in ctx.guild.channels:
                await channel.set_permissions(role, speak=False, send_messages=False, read_message_history=True,
                                              read_messages=False, add_reactions=False)
            return

        if role not in member.roles:
            await ctx.send("This member is not muted.")
            data = cogs._json.read_json("muted_users")
            data["muted_users"].remove(member.id)
            cogs._json.write_json(data, "muted_users")





        await member.remove_roles(role)
        data = cogs._json.read_json("muted_users")
        data["muted_users"].remove(member.id)
        cogs._json.write_json(data, "muted_users")
        await ctx.send(f"Unmuted `{member}`")
def setup(bot):
    bot.add_cog(Moderation(bot))

这就是齿轮

import json
from pathlib import Path

def get_path():
    """
    A function to get the current path to bot.py

    Returns:
     - cwd (string) : Path to bot.py directory
    """
    cwd = Path(__file__).parents[1]
    cwd = str(cwd)
    return cwd

def read_json(filename):
    """
    A function to read a json file and return the data.

    Params:
     - filename (string) : The name of the file to open

    Returns:
     - data (dict) : A dict of the data in the file
    """
    cwd = get_path()
    with open(cwd+'/bot_config/'+filename+'.json', 'r') as file:
        data = json.load(file)
    return data

def write_json(data, filename):
    """
    A function used to write data to a json file

    Params:
     - data (dict) : The data to write to the file
     - filename (string) : The name of the file to write to
    """
    cwd = get_path()
    with open(cwd+'/bot_config/'+filename+'.json', 'w') as file:
        json.dump(data, file, indent=4)

我的“转换文件”

{
    "muted_users": []
}

我的 json 存储文件

@commands.Cog.listener()
    async def on_member_join(self, member):
        print(member)
        await member.send("hello")
        role = discord.utils.get(member.guild.roles, name="Muted by ez")
        data = cogs._json.read_json("muted_users")
        if member.id in data['muted_users']:
            await member.add_roles(role)

还有我的 on_member_join 模块。 这段代码可以正常工作,但我想让它变得更好,就像在成员加入模块中的 bcs 可能是一个成员,所以同一个孩子在一台服务器上被静音,而不是在另一台服务器上,但在两者上都静音。这就是为什么我需要公会ID。 当我再次取消静音成员时,如何删除所有数据? 我不明白,所以你能再帮我一次吗?

【问题讨论】:

    标签: discord discord.py


    【解决方案1】:

    工作流程步骤如下

    1. 使用命令时,收集用户数据
    2. 将其存储到 json 文件中,最好使用唯一的用户 ID 作为键。
    3. 新成员加入时,查看json数据下的用户id
    4. 如果json数据中存在id,则为其分配muted角色,否则通过。

    有用的资源


    数据存储示例

    import json
    ...
    
    class Moderation(commands.Cog):
        ...
    
        @commands.command()
        async def mute(self, ctx, member:discord.Member):
            ...
            # add the muted role
            await member.add_roles(role)
    
            # open the json file and add the data
            with open('users.json', 'w') as fp:
                data = json.load(fp)
                if member.id not in data['muted']:
                    data['muted'].append(member.id)
                    json.dump(data, fp)
            ... 
    

    使用以下数据创建一个名为 users.json 的 JSON 文件:

    {
        "muted": []
    }
    

    在这个简单的例子中,被静音的用户被存储在一个列表中。生成的 JSON 文件如下所示:

    {
        "muted": [123123123, 1231231231, 23423423423]
    }
    

    检查用户是否在列表中的示例

    import json
    ...
    
    @client.event
    async def on_member_join(member):
        ...
        with open('users.json', 'r') as fp:
            data = json.load(fp)
            if member.id in data['muted']:
                await member.add_roles(role)
    
    ...
    

    编辑:存储更多数据

    此编辑用于回答 cmets 中收到的部分问题

    为了收集更多数据,您可以使用字典而不是单个列表。您要使用的 JSON 数据结构的可能性如下

    {
        "guild_1_id": {
            "user_1_id": {
                "channel": "12345678",
                "moderator": "12345678"
            },
            "user_2_id": {
                "channel": "12345678",
                "moderator": "12345678"
            },
            ...
        },
        "guild_2_id": {
            "user_1_id": {
                "channel": "12345678",
                "moderator": "12345678"
            }
        }
        ...
    }
    

    首先,收集您需要的所有数据,将其存储在成员 ID 下的字典中

    newdata = {
        member.id: {
            "channel": ctx.channel.id,
            "moderator": ctx.author.id
        }
    }
    

    更新JSON数据时,检查公会ID是否存在,如果存在则更新服务器的数据以包含新成员的数据,否则创建一个具有公会ID的新密钥并将新成员的数据分配给它.

    修改后的版本如下

    # open the json file and add the data
    with open('users.json', 'w') as fp:
        data = json.load(fp)
        if ctx.guild.id not in data.keys():
            data[ctx.guild.id] = newdata
        else:
            data[ctx.guild.id].update(newdata)
        json.dump(data, fp)
    

    结合它们,你就有了这个

    import json
    ...
    
    class Moderation(commands.Cog):
        ...
    
        @commands.command()
        async def mute(self, ctx, member:discord.Member):
            ...
            await member.add_roles(role)
    
            newdata = {
                member.id: {
                    "channel": ctx.channel.id,
                    "moderator": ctx.author.id
                }
            }
    
            # open the json file and add the data
            with open('users.json', 'w') as fp:
                data = json.load(fp)
                if ctx.guild.id not in data.keys():
                    data[ctx.guild.id] = newdata
                else:
                    data[ctx.guild.id].update(newdata)
                json.dump(data, fp)
            ... 
    

    现在将on_member_join中的会员数据检查修改为

    @client.event
    async def on_member_join(member):
        ...
        with open('users.json', 'r') as fp:
            data = json.load(fp)
            if member.id in data[member.guild.id].keys():
                await member.add_roles(role)
    
                # further data can be accessed as following
                user_data = data[member.guild.id][member.id]
                
                channel = user_data['channel']
                moderator = user_data['moderator']
    ...
    

    还要检查

    【讨论】:

    • 首先,我已经存储了它,但是当我想存储更多数据(如频道 ID 公会 ID 或作者 ID)时,我必须如何做我有更多的数据选项吗?或者这是如何工作的?
    • @Socsz 我已经更新了我的答案以包含有关如何存储更多数据的更多详细信息,请再次检查:)
    • 兄弟非常感谢您的帮助,但我不明白,所以我在我的问题中添加了更多细节,希望您能提供帮助
    猜你喜欢
    • 2022-01-06
    • 2019-02-01
    • 2021-10-23
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多