N
N
Nikolai Fedorov2022-03-02 17:45:11
Node.js
Nikolai Fedorov, 2022-03-02 17:45:11

How to enter a command to issue a role with the removal of previous roles in the bot's discord?

I would like the bot to take away all the roles he has when using the "!pun @mention_action_time" command from the mentioned user, and give the role "Punished", at the same time, so that you can specify the amount of time with which the user will have this role, and after this time, the bot must return all the roles that it took from the user with the removal of the "Punished" role.

Example:
A user with the nickname A_Herberd is sitting on the server, he has the roles: "Fool", "Moder", "Gambler".
I use the command "!pun @A_Herberd 7d" The
bot takes the roles of "Fool", "Moder", "Gambler" from A_Herberd and gives the role "Punished"
Is it really possible to do this at all?
Thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2022-03-02
@Vindicar

Store in the database information about punished users + timestamp of the end of the sentence, and in a separate table - about the roles that were taken away from them.

Z
Zagir Majidov, 2022-03-03
@Zagir-vip

Especially for you and for experience, I wrote this code:

import discord
import json
import asyncio

from discord.ext import commands

@client.event
async def on_ready():
  with open("test.json", 'r') as f:
    data = json.load(f)
    for i in range(len(data)):
      member = await (await client.fetch_guild(data[i]["guild_id"])).fetch_member(data[i]["id"])
      client.loop.create_task(pun_start(member))
  print("ready")

def check_user_db(user_id:int):
  with open('test.json', 'r') as f:
    data = json.load(f)
    for i in range(len(data)):
      if data[i]["id"] == user_id: return True
  return False

def add_user_db(user_id:int, guild_id:int, author:str, timeout:int, reason:str, roles:list, role_pun:int):
  if check_user_db(user_id) is True: return False
  else:
    with open('test.json', 'r') as f:
      data = json.load(f)

    new_user = {
    "id": user_id,
    "guild_id": guild_id,
    "author": f"{author.name}#{author.discriminator}",
    "timeout": timeout,
    "reason": reason,
    "roles": roles,
    "role_pun": role_pun
    }
    data.append(new_user)

    with open('test.json', 'w') as f:
      json.dump(data, f, indent=3)

    return True

def remove_user_db(user_id:int):
  if check_user_db(user_id) is False: return False
  else:
    with open('test.json', 'r') as f:
      data = json.load(f)
      for i in range(len(data)):
        if data[i]["id"] == user_id:
          del data[i]
          with open('test.json', 'w') as f:
            json.dump(data, f)
          return True
    return False

async def pun_start(user):
  with open('test.json', 'r') as f:
    data = json.load(f)
    user_data = {}
    for i in range(len(data)):
      if data[i]["id"] == user.id: user_data = data[i]; break
    role_pun = discord.utils.get(user.guild.roles, id=id_роли) # роль для наказания
    old_roles = user_data["roles"] # старые роли участника
    await asyncio.sleep(user_data["timeout"])
    await user.remove_roles(role_pun)
    for role in old_roles:
      role_user = discord.utils.get(user.guild.roles, id=role)
      await user.add_roles(role_user)
    remove_user_db(user.id)



@client.command()
async def pun(ctx, member:discord.Member=None, timeout:int=None, reason:str="Не указано"):
  if member is None or timeout is None:
    await ctx.reply("Укажите участника и время.\nПример: !pun @участник 100 - наказываем участника на 100сек.\n**Важно:** Время указывается в секундах!")
  elif check_user_db(member.id) is True:
    await ctx.reply("Участника уже наказан!")
  else:
    role_pun = discord.utils.get(ctx.guild.roles, id=id_роли) # роль для наказания
    old_roles = [] # старые роли участника
    for role in member.roles:
      if role.name != "@everyone":
        old_roles.append(role.id)
        await member.remove_roles(role)
    await member.add_roles(role_pun)
    add_user_db(member.id, ctx.guild.id, ctx.author, timeout, reason, list(old_roles), role_pun.id) # добавляем участника в файл
    await ctx.send(f"{member.mention}, наказан!\nПричина: {reason}")
    await asyncio.sleep(timeout)
    await member.remove_roles(role_pun)
    for role in old_roles:
      role_user = discord.utils.get(ctx.guild.roles, id=role)
      await member.add_roles(role_user)
    remove_user_db(member.id)
    await ctx.send(f"Наказания с {member.mention} снято!\nПричина: Автоматическое снятие")

If there are errors write Xpeawey#5262

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question