【发布时间】: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