11 Commits
v1.0 ... v1.4

Author SHA1 Message Date
dce28dadb3 Update 1.4 2022-02-14 19:07:31 +02:00
Profitroll
3578c7b36e Update 1.4 2022-02-14 19:07:16 +02:00
4362d5cac4 Update 1.3 2022-02-10 21:26:16 +02:00
Profitroll
f52f9c2281 Update 1.2 2022-02-08 23:41:40 +02:00
9e19c28b82 Update 1.2 2022-02-08 23:37:24 +02:00
604e614401 Merge branch 'main' of https://github.com/profitrollgame/YusarinBot 2022-02-07 03:18:17 +02:00
dbe9236925 Update 1.1 2022-02-07 03:18:03 +02:00
Profitroll
80a34eb3eb Update 1.1 2022-02-07 03:17:38 +02:00
199d612098 Update 1.1 2022-02-07 03:11:51 +02:00
9acefbe757 Update 1.1 2022-02-07 03:10:47 +02:00
f165a1eeb5 Update 1.1 2022-02-07 03:06:01 +02:00
9 changed files with 594 additions and 223 deletions

View File

@@ -26,12 +26,23 @@ Installation instructions are listed below. Please, make sure you have installed
12. Bot is ready! Run it using `python yusarin.py`
## Config explanation
Default configuration file is [available here](https://github.com/profitrollgame/YusarinBot/blob/main/config.json)
- "debug" - Option that enables more detailed log messages [Boolean]
- "owner" - Discord ID of user who will be able to execute admin commands (`$shutdown` for example) [Integer]
- "bot_name" - Name of your bot. Is not used anywhere yet [String]
- "bot_token" - Token of your Discord bot [String]
- "bot_prefix" - Default prefix for all bot commands [String]
- "bot_locale" - Default language file of bot. Name of file in `locale` folder without extension is used [String]
- "bot_activity" - The name (string) of the song bot will be listening to [String]
- "color_default" - HTML color used in help messages embed [String]
- "color_ok" - HTML color used on command success embed [String]
- "color_warn" - HTML color used in all warning embeds [String]
- "color_error" - HTML color used on command error embed [String]
- "bot_site" - http or https link that will be used in help message header [String]
- "bot_icon" - http or https link that will be used in help message header's icon [String]
- "check_for_updates" - Option that defines whether bot should check for a new version available [Boolean]
- "auto_clear_trash" - Option that defines whether bot should clean all buggy inactive channels every "auto_clear_timer" seconds [Boolean]
- "auto_clear_timer" - Option that defines how often "auto_clear_trash" will do its job [Integer]
## Extra
1. Bot doesn't have any self updaters **yet**

View File

@@ -1,8 +1,18 @@
{
"owner": SET-OWNER-ID,
"debug": false,
"owner": "SET-OWNER-ID",
"bot_name": "Yusa Nishimori",
"bot_token": "SET-BOT-TOKEN",
"bot_prefix": "$",
"bot_locale": "en",
"bot_activity": "How-Low-Hello - Keep on Burnin'"
"bot_activity": "How-Low-Hello - Keep on Burnin'",
"color_default": "#F2C48D",
"color_ok": "#226699",
"color_warn": "#FFCC4D",
"color_error": "#DD2E44",
"bot_site": "https://www.end-play.xyz/yusarin",
"bot_icon": "https://www.end-play.xyz/yusarin/logo",
"check_for_updates": true,
"auto_clear_trash": false,
"auto_clear_timer": 120
}

View File

@@ -1,4 +1,9 @@
import json, os, sys, shutil, discord
import os
import sys
import json
import shutil
import discord
from datetime import datetime
from pathlib import Path
@@ -6,6 +11,19 @@ path = Path(__file__).resolve().parent
log_size = 512
# This is the default option for "debug" key in
# file config.json, so if cebug is not set in it
# bot will use this value instead.
debug = False
try:
with open("config.json", 'r', encoding="utf-8") as json_file:
output = json.load(json_file)
json_file.close()
debug = output["debug"]
except:
debug = debug
# Check latest log size
def checkSize():
global path
@@ -29,12 +47,20 @@ def checkSize():
pass
# Append string to log
def appendLog(message, guild="none"):
def appendLog(message, guild=None, announce=True):
global debug
global path
message_formatted = f'[{datetime.now().strftime("%d.%m.%Y")}] [{datetime.now().strftime("%H:%M:%S")}] [{str(guild)}] {message}'
if guild == None:
message_formatted = f'[{datetime.now().strftime("%d.%m.%Y")}] [{datetime.now().strftime("%H:%M:%S")}] {message}'
else:
if debug:
message_formatted = f'[{datetime.now().strftime("%d.%m.%Y")}] [{datetime.now().strftime("%H:%M:%S")}] [{guild} | {str(guild.id)}] {message}'
else:
message_formatted = f'[{datetime.now().strftime("%d.%m.%Y")}] [{datetime.now().strftime("%H:%M:%S")}] [{guild}] {message}'
print(message_formatted)
if announce:
print(message_formatted)
checkSize()
@@ -48,54 +74,126 @@ def saveJson(value, filename):
f.close()
def loadJson(filename):
global debug
try:
with open(filename, 'r', encoding="utf-8") as json_file:
output = json.load(json_file)
json_file.close()
except Exception as exp:
appendLog(f"Could not get contents of json file {filename} due to exception {exp}")
if debug:
appendLog(f"Could not load json file {filename} due to exception {exp}")
output = {}
return output
def getMsg(string):
global path
config = loadJson("config.json")
try:
locale = loadJson(f'{path}/locale/{config["bot_locale"]}.json')
return locale["messages"][string]
except Exception as exp:
appendLog(f"Could not get locale string named {string} due to exception {exp}")
return f"Could not get locale string {string}"
def colorToStr():
pass
def strToColor(string):
return int(hex(int(string.replace("#", ""), 16)), 0)
def gotCommand(message):
global debug
if debug:
appendLog(f"Command '{message.content}' from {message.author} ({str(message.author.id)})", message.guild)
else:
appendLog(f"Command '{message.content}' from {message.author}", message.guild)
def guildConfGet(guild, variable):
global path
config = loadJson(f"{path}/guilds/{str(guild)}/config.json")
global debug
try:
config = loadJson(f"{path}/guilds/{str(guild.id)}/config.json")
return config[variable]
except:
except Exception as exp:
if debug:
appendLog(f"Could not get guild config key '{variable}' due to {exp}", guild)
return None
def guildConfSet(guild, variable, value):
global path
config = loadJson(f"{path}/guilds/{str(guild)}/config.json")
config = loadJson(f"{path}/guilds/{str(guild.id)}/config.json")
config[variable] = value
try:
saveJson(config, f"{path}/guilds/{str(guild)}/config.json")
saveJson(config, f"{path}/guilds/{str(guild.id)}/config.json")
except:
os.mkdir(f"{path}/guilds/{str(guild)}")
os.mkdir(f"{path}/guilds/{str(guild)}/channels")
saveJson(config, f"{path}/guilds/{str(guild)}/config.json")
os.mkdir(f"{path}/guilds/{str(guild.id)}")
os.mkdir(f"{path}/guilds/{str(guild.id)}/channels")
saveJson(config, f"{path}/guilds/{str(guild.id)}/config.json")
appendLog(f"Guild config key '{variable}' is now set to '{value}'", guild)
def guildConfReset(guild, variable):
global path
config = loadJson(f"{path}/guilds/{str(guild)}/config.json")
del config[variable]
try:
saveJson(config, f"{path}/guilds/{str(guild)}/config.json")
config = loadJson(f"{path}/guilds/{str(guild.id)}/config.json")
del config[variable]
try:
saveJson(config, f"{path}/guilds/{str(guild.id)}/config.json")
except:
os.mkdir(f"{path}/guilds/{str(guild.id)}")
os.mkdir(f"{path}/guilds/{str(guild.id)}/channels")
saveJson(config, f"{path}/guilds/{str(guild.id)}/config.json")
appendLog(f"Guild config key '{variable}' has been reset", guild)
except Exception as exp:
appendLog(f"Could not reset guild config key '{variable}' due to {exp}", guild)
def guildLocaleGet(guild):
global path
config = loadJson(f"{path}/config.json")
try:
locale = guildConfGet(guild, "locale")
except:
os.mkdir(f"{path}/guilds/{str(guild)}")
os.mkdir(f"{path}/guilds/{str(guild)}/channels")
saveJson(config, f"{path}/guilds/{str(guild)}/config.json")
return config["bot_locale"]
if locale is None:
return config["bot_locale"]
else:
return locale
def getMsg(string, guild=None):
global path
config = loadJson("config.json")
try:
locale = loadJson(f'{path}/locale/{guildLocaleGet(guild)}.json')
return locale["messages"][string]
except Exception as exp:
appendLog(f"Could not get locale string named {string} due to exception {exp}", guild)
return string
def makeEmbed(title="", description="", footer="", color=0xffffff):
embed=discord.Embed(title=title, description=description, color=color)
if footer is not None:
embed.set_footer(text=footer)
return embed
def channelExists(number, guild, type="Any"):
global debug
if number == None:
return False
try:
if type == "Voice":
selected_channel = discord.utils.get(guild.channels, id=number)
if isinstance(selected_channel, discord.VoiceChannel):
return True
elif type == "Text":
selected_channel = discord.utils.get(guild.channels, id=number)
if isinstance(selected_channel, discord.TextChannel):
return True
elif type == "Any":
selected_channel = discord.utils.get(guild.channels, id=number)
return True
except Exception as exp:
if debug:
appendLog(f"Channel ID {str(number)} is not a channel due to {exp}")
return False
def channelGetName(number, guild):
global debug
try:
selected_channel = discord.utils.get(guild.channels, id=number)
return selected_channel.name
except Exception as exp:
if debug:
appendLog(f"Channel ID {str(number)} is not a channel due to {exp}")
return "Channel doesn't exist"
def isUserVoice(vc):
global path
@@ -110,6 +208,7 @@ def isUserVoice(vc):
async def removeUserVoice(vc):
global path
global debug
channels_list = os.listdir(f"{path}/guilds/{str(vc.guild.id)}/channels/")
if f"{vc.id}.json" in channels_list:
vc_file = f"{path}/guilds/{str(vc.guild.id)}/channels/{str(vc.id)}.json"
@@ -121,14 +220,21 @@ async def removeUserVoice(vc):
os.remove(vc_file)
await needed_channel.delete()
appendLog(f"Removed voice channel {str(needed_channel.id)} of user {str(vc_conf['ownerid'])}", guild=vc.guild.id)
if debug:
appendLog(f"Removed voice channel '{needed_channel}' ({str(needed_channel.id)}) of user with id {str(vc_conf['ownerid'])}", guild=vc.guild)
else:
appendLog(f"Removed voice channel '{needed_channel}' of user with id {str(vc_conf['ownerid'])}", guild=vc.guild)
await nomic_channel.delete()
appendLog(f"Removed nomic channel {str(nomic_channel.id)} of channel {str(needed_channel.id)}", guild=vc.guild.id)
if debug:
appendLog(f"Removed nomic channel {nomic_channel} ({str(nomic_channel.id)}) of channel with id {str(needed_channel.id)}", guild=vc.guild)
else:
appendLog(f"Removed nomic channel '{nomic_channel}' of channel with id {str(needed_channel.id)}", guild=vc.guild)
else:
return
async def createUserVoice(vc, category, member):
global path
global debug
chan = {}
overwrites_channel = {
vc.guild.default_role: discord.PermissionOverwrite(view_channel=True),
@@ -140,15 +246,21 @@ async def createUserVoice(vc, category, member):
vc.guild.me: discord.PermissionOverwrite(read_messages=True, view_channel=True, manage_channels=True),
member: discord.PermissionOverwrite(read_messages=True, view_channel=True, manage_channels=True)
}
created_channel = await vc.guild.create_voice_channel(getMsg("name_voice").format(member.name), category=category, overwrites=overwrites_channel)
appendLog(f"Created voice channel {str(created_channel.id)} for user {str(member.id)}", guild=vc.guild.id)
created_channel = await vc.guild.create_voice_channel(getMsg("name_voice", vc.guild).format(member.name), category=category, overwrites=overwrites_channel)
if debug:
appendLog(f"Created voice channel '{created_channel}' ({str(created_channel.id)}) for user {member} ({str(member.id)})", guild=vc.guild)
else:
appendLog(f"Created voice channel '{created_channel}' for user {member}", guild=vc.guild)
if not os.path.isdir(f"{path}/guilds/{str(created_channel.guild.id)}/channels"):
os.mkdir(f"{path}/guilds/{str(created_channel.guild.id)}/channels")
vc_file = f"{path}/guilds/{str(created_channel.guild.id)}/channels/{str(created_channel.id)}.json"
chan["ownerid"] = member.id
saveJson(chan, vc_file)
nomic_channel = await vc.guild.create_text_channel(getMsg("name_nomic").format(created_channel.id), category=category, overwrites=overwrites_nomic, topic=getMsg("description_nomic").format(str(created_channel.id)))
appendLog(f"Created nomic channel {str(nomic_channel.id)} for channel {str(created_channel.id)}", guild=vc.guild.id)
nomic_channel = await vc.guild.create_text_channel(getMsg("name_nomic", vc.guild).format(created_channel.id), category=category, overwrites=overwrites_nomic, topic=getMsg("description_nomic", vc.guild).format(str(created_channel.id)))
if debug:
appendLog(f"Created nomic channel '{nomic_channel}' ({str(nomic_channel.id)}) for channel '{created_channel}' ({str(created_channel.id)})", guild=vc.guild)
else:
appendLog(f"Created nomic channel '{nomic_channel}' for channel '{created_channel}'", guild=vc.guild)
chan["nomic"] = nomic_channel.id
saveJson(chan, vc_file)
return created_channel
@@ -171,32 +283,101 @@ async def changeNomicPerms(mode, vc, member):
await nomic_channel.set_permissions(member, view_channel=False)
else:
await nomic_channel.set_permissions(member, view_channel=True)
async def clearTrash(client):
global path
if not os.path.isdir(f"{path}/guilds/"):
os.mkdir(f"{path}/guilds")
guilds_list = os.listdir(f"{path}/guilds/")
for guild in guilds_list:
guild_object = client.get_guild(int(guild))
if os.path.isdir(f"{path}/guilds/{guild}/channels"):
channels_list = os.listdir(f"{path}/guilds/{guild}/channels/")
for channel in channels_list:
channel_id = channel[:-5]
try:
selected_channel = discord.utils.get(guild_object.voice_channels, id=int(channel_id))
channel_owner = loadJson(f"{path}/guilds/{guild}/channels/{channel}")["ownerid"]
remove_channel = True
for member in selected_channel.members:
if member.id == channel_owner:
remove_channel = False
if remove_channel:
await removeUserVoice(selected_channel)
except:
os.remove(f"{path}/guilds/{guild}/channels/{channel_id}.json")
#async def autoClearTrash(client):
# execute clearTrash every 120 seconds
def getHelpMessage(message, version, prefix=loadJson("config.json")["bot_prefix"]):
#channelExists(number, guild, type="Voice")
config = loadJson("config.json")
if message.guild is not None:
if channelExists(guildConfGet(message.guild, 'channel'), message.guild, type="Voice"):
desc_channel = getMsg("help_channel_set", guild=message.guild).format(channelGetName(guildConfGet(message.guild, 'channel'), message.guild))
else:
desc_channel = getMsg("help_channel_none", guild=message.guild)
if channelExists(guildConfGet(message.guild, 'category'), message.guild, type="Any"):
desc_category = getMsg("help_category_set", guild=message.guild).format(channelGetName(guildConfGet(message.guild, 'category'), message.guild))
else:
desc_category = getMsg("help_category_none", guild=message.guild)
desc_prefix = getMsg("help_prefix", guild=message.guild).format(prefix)
desc_locale = getMsg("help_locale", guild=message.guild).format(getMsg("locale_name", message.guild))
description = "\n".join([desc_prefix, desc_locale, desc_channel, desc_category])
embed=discord.Embed(title=getMsg("help_title", message.guild), description=description, color=strToColor(config["color_default"]))
else:
embed=discord.Embed(title=getMsg("help_title_dm", message.guild), color=strToColor(config["color_default"]))
embed.set_author(name=f'{config["bot_name"]} v{str(version)}', url=config["bot_site"], icon_url=config["bot_icon"])
if message.author.id == config["owner"]:
embed.add_field(name=f"{prefix}shutdown", value=getMsg("help_cmd_shutdown", message.guild), inline=False)
embed.add_field(name=f"{prefix}channel ID", value=getMsg("help_cmd_channel", message.guild), inline=False)
embed.add_field(name=f"{prefix}category ID", value=getMsg("help_cmd_category", message.guild), inline=False)
embed.add_field(name=f"{prefix}prefix SYMBOL", value=getMsg("help_cmd_prefix", message.guild), inline=False)
embed.add_field(name=f"{prefix}locale LOCALE", value=getMsg("help_cmd_locale", message.guild), inline=False)
if message.guild is None:
embed.set_footer(text=getMsg("help_server", message.guild))
else:
embed.set_footer(text=getMsg("help_notice_id", message.guild))
return embed
async def guildConfigured(guild):
output = {}
config = loadJson("config.json")
for kind in ["channel", "category", "prefix"]:
if guildConfGet(guild.id, kind) is not None:
if guildConfGet(guild, kind) is not None:
try:
if kind == "channel":
guild_object = discord.utils.get(guild.channels, id=guildConfGet(guild.id, kind))
output[kind] = getMsg("configured_"+kind).format(guild_object.name)
guild_object = discord.utils.get(guild.channels, id=guildConfGet(guild, kind))
output[kind] = getMsg("configured_"+kind, guild).format(guild_object.name)
elif kind == "category":
guild_object = discord.utils.get(guild.categories, id=guildConfGet(guild.id, kind))
output[kind] = getMsg("configured_"+kind).format(guild_object.name)
guild_object = discord.utils.get(guild.categories, id=guildConfGet(guild, kind))
output[kind] = getMsg("configured_"+kind, guild).format(guild_object.name)
elif kind == "prefix":
output[kind] = getMsg("configured_"+kind).format(guildConfGet(guild.id, kind))
output[kind] = getMsg("info_prefix", guild).format(guildConfGet(guild, kind))
except Exception as exp:
if kind == "prefix":
output[kind] = getMsg("unconfigured_"+kind).format(config["bot_prefix"])
output[kind] = getMsg("info_prefix", guild).format(config["bot_prefix"])
else:
output[kind] = getMsg("unconfigured_"+kind)
output[kind] = getMsg("unconfigured_"+kind, guild)
else:
if kind == "prefix":
output[kind] = getMsg("unconfigured_"+kind).format(config["bot_prefix"])
output[kind] = getMsg("info_prefix", guild).format(config["bot_prefix"])
else:
output[kind] = getMsg("unconfigured_"+kind)
output[kind] = getMsg("unconfigured_"+kind, guild)
return getMsg("server_config").format(output["prefix"], output["channel"], output["category"])
return getMsg("server_config", guild).format(output["prefix"], getMsg("info_locale", guild).format(getMsg("locale_name", guild)), output["channel"], output["category"])

View File

@@ -1,34 +1,63 @@
{
"messages": {
"shutdown": "Shutting down...",
"locale_set": "Bot's locale has been changed to **English**",
"help": "**List of command:**\n{0}• Set parent channel: `{1}channel CHANNEL-ID`\n• Set parent category: `{2}category CATEGORY-ID`\n• Set commands prefix: `{3}prefix SYMBOL`\n\nTo reset channel/category/prefix use `reset` as argument\n\nPlease note that channel/category name ≠ ID of channel/category",
"help_owner": "• Turn off the bot: `{0}shutdown`\n",
"command_in_dm": "Commands can only be executed on the server",
"command_forbidden": "To set up private channels, you need to have **Administrator** permission on the server",
"usage_channel": "Correct usage: `{0}channel CHANNEL-ID`\nPlease note that name of channel ≠ ID of channel.\nFind out more about this here: https://support.discord.com/hc/articles/206346498-Where-can-I-find-my-User-Server-Message-ID",
"usage_category": "Correct usage: `{0}category CATEGORY-ID`\nPlease note that name of category ≠ ID of category.\nFind out more about it here: https://support.discord.com/hc/articles/206346498-Where-can-I-find-my-User-Server-Message-ID",
"usage_prefix": "Correct usage: `{0}prefix SYMBOL`",
"result_channel": "Voice channel **{0}** is now set as parent",
"result_category": "Category **{0}** is now set as parent",
"result_prefix": "Command prefix **{0}** is now set as primary for this server",
"warn_channel": "⚠ Parent channel is not set!\nFor the bot to work, you need to set parent channel: `{0}channel CHANNEL-ID`",
"warn_category": "⚠ Parent category is not set!\nFor the bot to work, you need to set parent category: `{0}category CATEGORY-ID`",
"reset_channel": "Parent voice channel has been reset",
"reset_category": "Parent category has been reset",
"reset_prefix": "Commands prefix has been reset and now is `{0}`",
"none_channel": "Parent voice channel is not set",
"none_category": "Parent category is not set",
"none_prefix": "Commands prefix is not set, using default prefix `{0}`",
"server_config": "**Server status:**\n{0}\n{1}\n{2}\n\n",
"unconfigured_prefix": " Commands prefix: `{0}`",
"unconfigured_channel": "⚠ Parent channel",
"unconfigured_category": "⚠ Parent category",
"configured_prefix": " Commands prefix: `{0}`",
"configured_channel": "☑ Parent channel: **{0}**",
"configured_category": "☑ Parent category: **{0}**",
"shutdown": "**{0}** Shutting down...",
"locale_name": "English",
"name_voice": "{0}'s channel",
"name_nomic": "no-mic-{0}",
"description_nomic": "Text channel for no mic communication\nVoice room ID: {0}"
"description_nomic": "Text channel for communication without a microphone\nVoice room ID: {0}",
"set_channel_title": "☑ Parent channel set",
"set_channel_description": "Voice channel `{0}` has been set as a parent.",
"set_category_title": "☑ Parent category set",
"set_category_description": "Category `{0}` has been set as the parent category.",
"set_prefix_title": "☑ Command prefix set",
"set_prefix_description": "On this server, all commands are now prefixed with `{0}`",
"set_locale_title": "☑ Bot language set",
"set_locale_description": "This server is now using `{0}`",
"reset_channel_title": "☑ Parent channel reset",
"reset_channel_description": "Use `{0}channel CHANNELID` to select a new channel",
"reset_category_title": "☑ Parent category reset",
"reset_category_description": "Use `{0}category ID-CATEGORY` to select a new category",
"reset_prefix_title": "☑ Command Prefix Reset",
"reset_prefix_description": "The default prefix `{0}` is now used.\nUse `{1}prefix CHAR` to select a new one",
"reset_locale_title": "☑ Bot language reset",
"reset_locale_description": "The default locale `{0}` is now used.\nUse `{1}locale LANGUAGE` to select a different one",
"error_channel_title": "🚫 Error installing channel",
"error_channel_description": "Correct Usage: `{0}channel CHANNELID`",
"error_category_title": "🚫 Error setting category",
"error_category_description": "Correct Usage: `{0}category CATEGORY-ID`",
"error_prefix_title": "🚫 Error setting prefix",
"error_prefix_description": "Correct Usage: `{0}prefix SYMBOL`",
"error_locale_title": "🚫 Error installing language",
"error_locale_description": "Correct Usage: `{0}locale LANGUAGE`\nAvailable languages: {1}",
"hint_none_channel_title": "⚠ No parent channel set",
"hint_none_channel_description": "For the bot to work properly, you need to set the parent channel, by entering which the user can create his own private voice channel. Set the parent channel with the command `{0}channel CHANNEL-ID`",
"hint_none_category_title": "⚠ No parent category set",
"hint_none_category_description": "For the bot to work properly, you need to set a parent category, within which a private channel will be created for the user. Set the parent category with the command `{0}category ID-CATEGORY`",
"hint_none_prefix_title": "⚠ No prefix set",
"hint_none_prefix_description": "This server uses the default `{0}`.\nTo change it use `{1}prefix CHAR`",
"hint_none_locale_title": "⚠ Bot language not set",
"hint_none_locale_description": "This server uses default `{0}`.\nTo change it use `{1}locale LANGUAGE`",
"error_text_channel_title": "🚫 Error installing channel",
"error_text_channel_description": "The selected channel must be a voice channel.",
"help_title": "Server Information",
"help_title_dm": "Bot Commands",
"help_server": "Commands must be run on the server",
"help_prefix": " Command prefix: `{0}`",
"help_locale": " Server bot language: `{0}`",
"help_channel_set": "☑ Parent channel: `{0}`",
"help_channel_none": "⚠ Parent channel not installed",
"help_category_set": "☑ Parent category: `{0}`",
"help_category_none": "⚠ No parent category set",
"help_cmd_shutdown": "Shut the bot down",
"help_cmd_channel": "Set parent channel\nMust be a voice channel",
"help_cmd_category": "Set parent category",
"help_cmd_prefix": "Set command prefix",
"help_cmd_locale": "Change bot language on server",
"help_notice_id": "Note that channel name ≠ channel ID",
"help_notice_id_category": "Note that category name ≠ category ID",
"forbidden_title": "🚫 Access Denied",
"forbidden_description": "You must have **Administrator** right to set up private channels",
"dm_title": "🚫 Execution error",
"dm_description": "Commands can only be executed while on the server"
}
}

View File

@@ -1,34 +1,63 @@
{
"messages": {
"shutdown": "Выключаюсь...",
"locale_set": "Язык бота был изменён на **Русский**",
"help": "**Список команд:**\n{0}• Установить родительский канал: `{1}channel ID-КАНАЛА`\n• Установить родительскую категорию: `{2}category ID-КАТЕГОРИИ`\n• Установить префикс команд: `{3}prefix СИМВОЛ`\n\nДля сброса канала/категории/префикса используйте `reset` как аргумент\n\nОбратите внимание, что имя канала/категории ≠ ID канала/категории",
"help_owner": "• Выключиться: `{0}shutdown`\n",
"command_in_dm": "Команды можно исполнять только находясь на сервере",
"command_forbidden": "Для настройки приватных каналов нужно иметь право **Администратор** на сервере",
"usage_channel": "Правильное использование: `{0}channel ID-КАНАЛА`\nОбратите внимание, что имя канала ≠ ID канала.\nУзнайте больше об этом тут: https://support.discord.com/hc/articles/206346498-Where-can-I-find-my-User-Server-Message-ID",
"usage_category": "Правильное использование: `{0}category ID-КАТЕГОРИИ`\nОбратите внимание, что имя категории ≠ ID категории.\nУзнайте больше об этом тут: https://support.discord.com/hc/articles/206346498-Where-can-I-find-my-User-Server-Message-ID",
"usage_prefix": "Правильное использование: `{0}prefix СИМВОЛ`",
"result_channel": "Голосовой канал **{0}** был установлен как родительский",
"result_category": "Категория **{0}** была установлена как родительская",
"result_prefix": "Префикс **{0}** был установлен как основной для этого сервера",
"warn_channel": "⚠ Родительский канал не установлен!\nДля работы бота нужно установить канал: `{0}channel ID-КАНАЛА`",
"warn_category": "⚠ Родительская категория не установлена!\nДля работы бота нужно установить категорию: `{0}category ID-КАТЕГОРИИ`",
"reset_channel": "Родительский голосовой канал был сброшен",
"reset_category": "Родительская категория была сброшена",
"reset_prefix": "Прификс команд был сброшен, теперь это `{0}`",
"none_channel": "Родительский голосовой канал не был задан",
"none_category": "Родительская категория не была задана",
"none_prefix": "Префикс команд не был задан, используется стандартный `{0}`",
"server_config": "**Статус сервера:**\n{0}\n{1}\n{2}\n\n",
"unconfigured_prefix": " Префикс команд: `{0}`",
"unconfigured_channel": "⚠ Родительский канал",
"unconfigured_category": "⚠ Родительская категория",
"configured_prefix": " Префикс команд: `{0}`",
"configured_channel": "☑ Родительский канал: **{0}**",
"configured_category": "☑ Родительская категория: **{0}**",
"shutdown": "**{0}** Выключаюсь...",
"locale_name": "Русский",
"name_voice": "Канал {0}",
"name_nomic": "без-микро-{0}",
"description_nomic": "Текстовый канал для коммуникации без микрофона\nID голосовой комнаты: {0}"
"description_nomic": "Текстовый канал для коммуникации без микрофона\nID голосовой комнаты: {0}",
"set_channel_title": "☑ Родительский канал установлен",
"set_channel_description": "Голосовой канал `{0}` был установлен как родительский.",
"set_category_title": "☑ Родительская категория установлена",
"set_category_description": "Категория `{0}` была установлена как родительская.",
"set_prefix_title": "☑ Префикс команд установлен",
"set_prefix_description": "На этом сервере префикс всех команд теперь `{0}`",
"set_locale_title": "☑ Язык бота установлен",
"set_locale_description": "На этом сервере теперь используется `{0}`",
"reset_channel_title": "☑ Родительский канал сброшен",
"reset_channel_description": "Для выбора нового канала используйте `{0}channel ID-КАНАЛА`",
"reset_category_title": "☑ Родительская категория сброшена",
"reset_category_description": "Для выбора новой категории используйте `{0}category ID-КАТЕГОРИИ`",
"reset_prefix_title": "☑ Префикс команд сброшен",
"reset_prefix_description": "Теперь используется стандартный префикс `{0}`.\nДля выбора нового используйте `{1}prefix СИМВОЛ`",
"reset_locale_title": "☑ Язык бота сброшен",
"reset_locale_description": "Теперь используется стандартный язык `{0}`.\nДля выбора другого используйте `{1}locale ЯЗЫК`",
"error_channel_title": "🚫 Ошибка установки канала",
"error_channel_description": "Правильное использование: `{0}channel ID-КАНАЛА`",
"error_category_title": "🚫 Ошибка установки категории",
"error_category_description": "Правильное использование: `{0}category ID-КАТЕГОРИИ`",
"error_prefix_title": "🚫 Ошибка установки префикса",
"error_prefix_description": "Правильное использование: `{0}prefix СИМВОЛ`",
"error_locale_title": "🚫 Ошибка установки языка",
"error_locale_description": "Правильное использование: `{0}locale ЯЗЫК`\nДоступные языки: {1}",
"hint_none_channel_title": "⚠ Родительский канал не задан",
"hint_none_channel_description": "Для правильной работы бота необходимо задать родительский канал, входя в который пользователь сможет создать свой приватный голосовой канал. Установите родительский канал командой `{0}channel ID-КАНАЛА`",
"hint_none_category_title": "⚠ Родительская категория не задана",
"hint_none_category_description": "Для правильной работы бота необходимо задать родительскую категорию, внутри которой для пользователя будет создан его приватный канал. Установите родительскую категорию командой `{0}category ID-КАТЕГОРИИ`",
"hint_none_prefix_title": "⚠ Префикс не задан",
"hint_none_prefix_description": "На этом сервере используется стандартный `{0}`.\nЧтобы сменить его используйте `{1}prefix СИМВОЛ`",
"hint_none_locale_title": "⚠ Язык бота не задан",
"hint_none_locale_description": "На этом сервере используется стандартный `{0}`.\nЧтобы сменить его используйте `{1}locale ЯЗЫК`",
"error_text_channel_title": "🚫 Ошибка установки канала",
"error_text_channel_description": "Выбранный канал должен быть голосовым.",
"help_title": "Информация о сервере",
"help_title_dm": "Команды бота",
"help_server": "Команды должны выполняться на сервере",
"help_prefix": " Префикс команд: `{0}`",
"help_locale": " Язык бота на сервере: `{0}`",
"help_channel_set": "☑ Родительский канал: `{0}`",
"help_channel_none": "⚠ Родительский канал не установлен",
"help_category_set": "☑ Родительская категория: `{0}`",
"help_category_none": "⚠ Родительская категория не установлена",
"help_cmd_shutdown": "Выключить бота",
"help_cmd_channel": "Установить родительский канал\nКанал должен быть голосовым",
"help_cmd_category": "Установить родительскую категорию",
"help_cmd_prefix": "Установить префикс команд",
"help_cmd_locale": "Сменить язык бота на сервере",
"help_notice_id": "Обратите внимание, что имя канала ≠ ID канала",
"help_notice_id_category": "Обратите внимание, что имя категории ≠ ID категории",
"forbidden_title": "🚫 Отказано в доступе",
"forbidden_description": "Для настройки приватных каналов нужно иметь право **Администратор**",
"dm_title": "🚫 Ошибка исполнения",
"dm_description": "Команды можно исполнять только находясь на сервере"
}
}
}

View File

@@ -1,34 +1,63 @@
{
"messages": {
"shutdown": "Вимикаюсь...",
"locale_set": "Мова бота була змінена на **Українську**",
"help": "**Перелік команд:**\n{0}• Встановити твірний канал: `{1}channel ID-КАНАЛА`\n• Встановити твірну категорію: `{2}category ID-КАТЕГОРІЇ`\n• Встановити префікс команд: `{3}prefix СИМВОЛ`\n\nДля скидання каналу/категорії/префіксу використовуйте `reset` як аргумент\n\nЗверніть увагу, що назва каналу/категорії ≠ ID каналу/категорії",
"help_owner": "• Вимкнутись: `{0}shutdown`\n",
"command_in_dm": "Команди можна виконувати тільки знаходячись на сервері",
"command_forbidden": "Для налаштування приватних каналів потрібно мати право **Адміністратор** на сервері",
"usage_channel": "Правильне використання: `{0}channel ID-КАНАЛА`\nЗверніть увагу, що назва канала ≠ ID канала.\nДізнайтеся більше про це тут: https://support.discord.com/hc/articles/206346498-Where-can-I-find-my-User-Server-Message-ID",
"usage_category": "Правильне використання: `{0}category ID-КАТЕГОРІЇ`\nЗверніть увагу, що назва категорії ≠ ID категорії.\nДізнайтеся більше про це тут: https://support.discord.com/hc/articles/206346498-Where-can-I-find-my-User-Server-Message-ID",
"usage_prefix": "Правильне використання: `{0}prefix СИМВОЛ`",
"result_channel": "Голосовий канал **{0}** було встановлено як твірний",
"result_category": "Категорія **{0}** була встановлена як твірна",
"result_prefix": "Префікс **{0}** було встановлено як основний для цього сервера",
"warn_channel": "⚠ Твірний канал не встановлено!\nДля роботи робота потрібно встановити канал: `{0}channel ID-КАНАЛА`",
"warn_category": "⚠ Твірна категорія не встановлена!\nДля роботи робота потрібно встановити категорію: `{0}category ID-КАТЕГОРІЇ`",
"reset_channel": "Твірний голосовий канал було скинуто",
"reset_category": "Твірну категорію було скинуто",
"reset_prefix": "Префікс команд було скинуто, тепер це `{0}`",
"none_channel": "Твірний голосовий канал не було задано",
"none_category": "Твірну категорію не було задано",
"none_prefix": "Префікс команд не було задано, використовується стандартний `{0}`",
"server_config": "**Статус сервера:**\n{0}\n{1}\n{2}\n\n",
"unconfigured_prefix": " Префікс команд: `{0}`",
"unconfigured_channel": "⚠ Твірний канал",
"unconfigured_category": "⚠ Твірна категорія",
"configured_prefix": " Префікс команд: `{0}`",
"configured_channel": "☑ Твірний канал: **{0}**",
"configured_category": "☑ Твірна категорія: **{0}**",
"shutdown": "**{0}** Вимикаюсь...",
"locale_name": "Українська",
"name_voice": "Канал {0}",
"name_nomic": "без-мікро-{0}",
"description_nomic": "Текстовий канал для комунікації без мікрофона\nID голосової кімнати: {0}"
"description_nomic": "Текстовий канал для комунікації без мікрофона\nID голосової кімнати: {0}",
"set_channel_title": "☑ Твірний канал встановлено",
"set_channel_description": "Голосовий канал `{0}` був встановлений як твірний.",
"set_category_title": "☑ Твірну категорію встановлено",
"set_category_description": "Категорія `{0}` була встановлена ​​як твірна.",
"set_prefix_title": "☑ Префікс команд встановлено",
"set_prefix_description": "На цьому сервері префікс усіх команд тепер `{0}`",
"set_locale_title": "☑ Мова бота встановлена",
"set_locale_description": "На цьому сервері тепер використовується `{0}`",
"reset_channel_title": "☑ Твірний канал скинутий",
"reset_channel_description": "Для вибору нового каналу використовуйте `{0}channel ID-КАНАЛу`",
"reset_category_title": "☑ Твірна категорія скинута",
"reset_category_description": "Для вибору нової категорії використовуйте `{0}category ID-КАТЕГОРІЇ`",
"reset_prefix_title": "☑ Префікс команд скинутий",
"reset_prefix_description": "Тепер використовується стандартний префікс `{0}`.\nДля вибору нового використовуйте `{1}prefix СИМВОЛ`",
"reset_locale_title": "☑ Мова бота скинута",
"reset_locale_description": "Тепер використовується стандартна мова `{0}`.\nДля вибору іншого використовуйте `{1}locale МОВА`",
"error_channel_title": "🚫 Помилка установки каналу",
"error_channel_description": "Правильне використання: `{0}channel ID-КАНАЛу`",
"error_category_title": "🚫 Помилка установки категорії",
"error_category_description": "Правильне використання: `{0}category ID-КАТЕГОРІЇ`",
"error_prefix_title": "🚫 Помилка встановлення префіксу",
"error_prefix_description": "Правильне використання: `{0}prefix СИМВОЛ`",
"error_locale_title": "🚫 Помилка встановлення мови",
"error_locale_description": "Правильне використання: `{0}locale МОВА`\nДоступні мови: {1}",
"hint_none_channel_title": "⚠ Твірний канал не заданий",
"hint_none_channel_description": "Для правильної роботи робота необхідно задати твірний канал, входячи в який користувач зможе створити свій приватний голосовий канал. Встановіть твірний канал командою `{0}channel ID-КАНАЛУ",
"hint_none_category_title": "⚠ Твірна категорія не задана",
"hint_none_category_description": "Для правильної роботи робота необхідно задати твірну категорію, всередині якої для користувача буде створено його приватний канал. Встановіть твірну категорію командою `{0}category ID-КАТЕГОРІЇ`",
"hint_none_prefix_title": "⚠ Префікс не заданий",
"hint_none_prefix_description": "На цьому сервері використовується стандартний `{0}`.\nЩоб змінити його використовуйте `{1}prefix СИМВОЛ`",
"hint_none_locale_title": "⚠ Мова бота не задана",
"hint_none_locale_description": "На цьому сервері використовується стандартний `{0}`.\nЩоб змінити його використовуйте `{1}locale МОВА`",
"error_text_channel_title": "🚫 Помилка установки каналу",
"error_text_channel_description": "Вибраний канал повинен бути голосовим.",
"help_title": "Інформація про сервер",
"help_title_dm": "Команда бота",
"help_server": "Команди повинні виконуватись на сервері",
"help_prefix": " Префікс команд: `{0}`",
"help_locale": " Мова бота на сервері: `{0}`",
"help_channel_set": "☑ Твірний канал: `{0}`",
"help_channel_none": "⚠ Твірний канал не встановлено",
"help_category_set": "☑ Твірна категорія: `{0}`",
"help_category_none": "⚠ Твірна категорія не встановлена",
"help_cmd_shutdown": "Вимкнути бота",
"help_cmd_channel": "Встановити твірний канал\nКанал повинен бути голосовим",
"help_cmd_category": "Встановити твірну категорію",
"help_cmd_prefix": "Встановити префікс команд",
"help_cmd_locale": "Змінити мову бота на сервері",
"help_notice_id": "Зверніть увагу, що ім'я каналу ≠ ID каналу",
"help_notice_id_category": "Зверніть увагу, що ім'я категорії ≠ ID категорії",
"forbidden_title": "🚫 Відмовлено у доступі",
"forbidden_description": "Для налаштування приватних каналів потрібно мати право **Адміністратор**",
"dm_title": "🚫 Помилка виконання",
"dm_description": "Команди можна виконувати лише перебуваючи на сервері"
}
}

3
start.bat Normal file
View File

@@ -0,0 +1,3 @@
title YusarinBot
cls
python3 yusarin.py

2
start.sh Normal file
View File

@@ -0,0 +1,2 @@
#!/bin/sh
python3 yusarin.py

View File

@@ -1,4 +1,9 @@
import json, os, sys
import os
import sys
import json
import shutil
import requests
import threading
try:
import discord
@@ -7,65 +12,64 @@ except Exception as exp:
sys.exit()
from functions import *
#from discord_slash import SlashCommand, SlashContext
pid = os.getpid()
version = 1.4
if loadJson("config.json")["owner"] == "SET-OWNER-ID" or loadJson("config.json")["bot_token"] == "SET-BOT-TOKEN":
print(f"Bot is not correctly configured.\nMake sure you've set up owner id and bot token in {path}/config.json\nLearn more here: https://github.com/profitrollgame/YusarinBot")
sys.exit()
if loadJson("config.json")["check_for_updates"]:
try:
serv_ver = requests.get("https://www.end-play.xyz/yusarin/version.txt").text.replace('\n', '')
if float(serv_ver) > version:
appendLog(f"YusarinBot version {serv_ver} is available. Download new version here: https://github.com/profitrollgame/YusarinBot/releases/latest")
appendLog(f"Currently using YusarinBot v{str(version)}")
except Exception as exp:
appendLog(f"Could not get YusarinBot cloud version due to {exp}. Currently using {str(version)}")
intents = discord.Intents().all()
client = discord.Client(intents=intents)
#slash = SlashCommand(client)
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
appendLog(f"Logged in as {client.user}")
config = loadJson("config.json")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=config["bot_activity"]))
await clearTrash(client)
@client.event
async def on_guild_join(guild):
global path
if not os.path.isdir(f"{path}/guilds/"):
os.mkdir(f"{path}/guilds")
os.mkdir(f"{path}/guilds/{str(guild.id)}")
os.mkdir(f"{path}/guilds/{str(guild.id)}/channels")
saveJson({}, f"{path}/guilds/{str(guild.id)}/config.json")
guilds_list = os.listdir(f"{path}/guilds/")
for guild in guilds_list:
guild_object = client.get_guild(int(guild))
if os.path.isdir(f"{path}/guilds/{guild}/channels"):
channels_list = os.listdir(f"{path}/guilds/{guild}/channels/")
for channel in channels_list:
channel_id = channel[:-5]
try:
selected_channel = discord.utils.get(guild_object.voice_channels, id=int(channel_id))
channel_owner = loadJson(f"{path}/guilds/{guild}/channels/{channel}")["ownerid"]
remove_channel = True
for member in selected_channel.members:
if member.id == channel_owner:
remove_channel = False
if remove_channel:
await removeUserVoice(selected_channel)
except:
os.remove(f"{path}/guilds/{guild}/channels/{channel_id}.json")
appendLog(f"Joined guild '{guild}' with id {str(guild.id)}")
@client.event
async def on_guild_remove(guild):
global path
try:
shutil.rmtree(f"{path}/guilds/{str(guild.id)}")
except:
pass
appendLog(f"Left guild '{guild}' with id {str(guild.id)}")
@client.event
async def on_voice_state_update(member, before, after):
global debug
config = loadJson("config.json")
vc_from = before.channel
@@ -89,15 +93,18 @@ async def on_voice_state_update(member, before, after):
await changeNomicPerms("deny", vc_from, member)
if isUserVoice(vc_to):
await changeNomicPerms("allow", vc_to, member)
if vc_to.id == guildConfGet(vc_to.guild.id, "channel"):
if guildConfGet(vc_to.guild.id, "category") is not None:
voice_chan = await createUserVoice(vc_to, discord.utils.get(vc_to.guild.categories, id=guildConfGet(vc_to.guild.id, "category")), member)
if vc_to.id == guildConfGet(vc_to.guild, "channel"):
if guildConfGet(vc_to.guild, "category") is not None:
voice_chan = await createUserVoice(vc_to, discord.utils.get(vc_to.guild.categories, id=guildConfGet(vc_to.guild, "category")), member)
try:
await member.move_to(voice_chan)
except:
await removeUserVoice(voice_chan)
else:
appendLog(f"Category for guild {str(vc_to.guild.id)} is not set", guild=vc_to.guild.id)
if debug:
appendLog(f"Category for guild {vc_to.guild} ({str(vc_to.guild.id)}) is not set", guild=vc_to.guild)
else:
appendLog(f"Category for guild {vc_to.guild} is not set", guild=vc_to.guild)
# ==========================================================================================
@@ -108,7 +115,7 @@ async def on_message(message):
if message.guild is not None:
try:
prefix = guildConfGet(message.guild.id, "prefix")
prefix = guildConfGet(message.guild, "prefix")
if prefix is None:
prefix = config["bot_prefix"]
except Exception as exp:
@@ -123,9 +130,11 @@ async def on_message(message):
if message.content in [f"{prefix}reboot", f"{prefix}restart", f"{prefix}shutdown", f"{prefix}die"]:
gotCommand(message)
if message.author.id == config["owner"]:
await message.channel.send(getMsg("shutdown"))
await message.reply(embed=makeEmbed(description=getMsg("shutdown", message.guild).format(message.author), color=strToColor(config["color_default"])), mention_author=False)
os.system(f"kill -9 {str(pid)}")
else:
@@ -134,6 +143,8 @@ async def on_message(message):
elif message.content.startswith(f"{prefix}channel"):
gotCommand(message)
fullcmd = message.content.split()
if message.guild is not None:
@@ -144,43 +155,52 @@ async def on_message(message):
if fullcmd[1] == "reset":
if guildConfGet(message.guild.id, "channel") is not None:
if guildConfGet(message.guild, "channel") is not None:
guildConfReset(message.guild.id, "channel")
guildConfReset(message.guild, "channel")
await message.channel.send(getMsg("reset_channel"))
await message.reply(embed=makeEmbed(title=getMsg("reset_channel_title", message.guild), description=getMsg("reset_channel_description", message.guild).format(prefix), color=strToColor(config["color_ok"])), mention_author=False)
else:
await message.channel.send(getMsg("none_channel"))
await message.reply(embed=makeEmbed(title=getMsg("hint_none_channel_title", message.guild), description=getMsg("hint_none_channel_description", message.guild).format(prefix), color=strToColor(config["color_warn"])), mention_author=False)
else:
selected_channel = discord.utils.get(message.guild.channels, id=int(fullcmd[1]))
if isinstance(selected_channel, discord.VoiceChannel):
guildConfSet(message.guild.id, "channel", int(fullcmd[1]))
await message.channel.send(getMsg("result_channel").format(selected_channel.name))
if guildConfGet(message.guild.id, "category") is None:
guildConfSet(message.guild, "channel", int(fullcmd[1]))
await message.channel.send(getMsg("warn_category").format(prefix))
await message.reply(embed=makeEmbed(title=getMsg("set_channel_title", message.guild), description=getMsg("set_channel_description", message.guild).format(selected_channel.name), color=strToColor(config["color_ok"])), mention_author=False)
if guildConfGet(message.guild, "category") is None:
await message.channel.send(embed=makeEmbed(title=getMsg("hint_none_category_title", message.guild), description=getMsg("hint_none_category_description", message.guild).format(prefix), color=strToColor(config["color_warn"])))
else:
await message.reply(embed=makeEmbed(title=getMsg("error_text_channel_title", message.guild), description=getMsg("error_text_channel_description", message.guild), color=strToColor(config["color_error"])), mention_author=False)
except Exception as exp:
#print(exp)
if debug:
print(exp)
await message.channel.send(getMsg("usage_channel").format(prefix))
await message.reply(embed=makeEmbed(title=getMsg("error_channel_title", message.guild), description=getMsg("error_channel_description", message.guild).format(prefix), footer=getMsg("help_notice_id", message.guild), color=strToColor(config["color_error"])), mention_author=False)
else:
await message.channel.send(getMsg("command_forbidden"))
await message.reply(embed=makeEmbed(title=getMsg("forbidden_title", message.guild), description=getMsg("forbidden_description", message.guild), color=strToColor(config["color_error"])), mention_author=False)
else:
await message.channel.send(getMsg("command_in_dm"))
await message.reply(embed=makeEmbed(title=getMsg("dm_title", message.guild), description=getMsg("dm_description", message.guild), color=strToColor(config["color_error"])), mention_author=False)
elif message.content.startswith(f"{prefix}category"):
gotCommand(message)
fullcmd = message.content.split()
if message.guild is not None:
@@ -191,43 +211,46 @@ async def on_message(message):
if fullcmd[1] == "reset":
if guildConfGet(message.guild.id, "category") is not None:
if guildConfGet(message.guild, "category") is not None:
guildConfReset(message.guild.id, "category")
guildConfReset(message.guild, "category")
await message.channel.send(getMsg("reset_category"))
await message.reply(embed=makeEmbed(title=getMsg("reset_category_title", message.guild), description=getMsg("reset_category_description", message.guild).format(prefix), color=strToColor(config["color_ok"])), mention_author=False)
else:
await message.channel.send(getMsg("none_category"))
await message.reply(embed=makeEmbed(title=getMsg("hint_none_category_title", message.guild), description=getMsg("hint_none_category_description", message.guild).format(prefix), color=strToColor(config["color_warn"])), mention_author=False)
else:
selected_category = discord.utils.get(message.guild.channels, id=int(fullcmd[1]))
guildConfSet(message.guild.id, "category", int(fullcmd[1]))
guildConfSet(message.guild, "category", int(fullcmd[1]))
await message.channel.send(getMsg("result_category").format(selected_category.name))
await message.reply(embed=makeEmbed(title=getMsg("set_category_title", message.guild), description=getMsg("set_category_description", message.guild).format(selected_category.name), color=strToColor(config["color_ok"])), mention_author=False)
if guildConfGet(message.guild.id, "channel") is None:
if guildConfGet(message.guild, "channel") is None:
await message.channel.send(getMsg("warn_channel").format(prefix))
await message.channel.send(embed=makeEmbed(title=getMsg("hint_none_channel_title", message.guild), description=getMsg("hint_none_channel_description", message.guild).format(prefix), color=strToColor(config["color_warn"])))
except Exception as exp:
#print(exp)
if debug:
print(exp)
await message.channel.send(getMsg("usage_category").format(prefix))
await message.reply(embed=makeEmbed(title=getMsg("error_category_title", message.guild), description=getMsg("error_category_description", message.guild).format(prefix), footer=getMsg("help_notice_id_category", message.guild), color=strToColor(config["color_error"])), mention_author=False)
else:
await message.channel.send(getMsg("command_forbidden"))
await message.reply(embed=makeEmbed(title=getMsg("forbidden_title", message.guild), description=getMsg("forbidden_description", message.guild), color=strToColor(config["color_error"])), mention_author=False)
else:
await message.channel.send(getMsg("command_in_dm"))
await message.reply(embed=makeEmbed(title=getMsg("dm_title", message.guild), description=getMsg("dm_description", message.guild), color=strToColor(config["color_error"])), mention_author=False)
elif message.content.startswith(f"{prefix}prefix"):
gotCommand(message)
fullcmd = message.content.split()
if message.guild is not None:
@@ -238,42 +261,96 @@ async def on_message(message):
if fullcmd[1] == "reset":
if guildConfGet(message.guild.id, "prefix") is not None:
if guildConfGet(message.guild, "prefix") is not None:
guildConfReset(message.guild.id, "prefix")
guildConfReset(message.guild, "prefix")
await message.channel.send(getMsg("reset_prefix").format(config["bot_prefix"]))
await message.reply(embed=makeEmbed(title=getMsg("reset_prefix_title", message.guild), description=getMsg("reset_prefix_description", message.guild).format(config["bot_prefix"], config["bot_prefix"]), color=strToColor(config["color_ok"])), mention_author=False)
else:
await message.channel.send(getMsg("none_prefix").format(prefix))
await message.reply(embed=makeEmbed(title=getMsg("hint_none_prefix_title", message.guild), description=getMsg("hint_none_prefix_description", message.guild).format(prefix, prefix), color=strToColor(config["color_warn"])), mention_author=False)
else:
guildConfSet(message.guild.id, "prefix", fullcmd[1])
guildConfSet(message.guild, "prefix", fullcmd[1])
await message.channel.send(getMsg("result_prefix").format(fullcmd[1]))
await message.reply(embed=makeEmbed(title=getMsg("set_prefix_title", message.guild), description=getMsg("set_prefix_description", message.guild).format(fullcmd[1]), color=strToColor(config["color_ok"])), mention_author=False)
except:
await message.channel.send(getMsg("usage_prefix").format(prefix))
await message.reply(embed=makeEmbed(title=getMsg("error_prefix_title", message.guild), description=getMsg("error_prefix_description", message.guild).format(prefix), color=strToColor(config["color_error"])), mention_author=False)
else:
await message.channel.send(getMsg("command_forbidden"))
await message.reply(embed=makeEmbed(title=getMsg("forbidden_title", message.guild), description=getMsg("forbidden_description", message.guild), color=strToColor(config["color_error"])), mention_author=False)
else:
await message.channel.send(getMsg("command_in_dm"))
await message.reply(embed=makeEmbed(title=getMsg("dm_title", message.guild), description=getMsg("dm_description", message.guild), color=strToColor(config["color_error"])), mention_author=False)
elif message.content.startswith(f"{prefix}locale"):
gotCommand(message)
fullcmd = message.content.split()
if message.guild is not None:
if message.author.guild_permissions.administrator:
try:
if fullcmd[1] == "reset":
if guildConfGet(message.guild, "locale") is not None:
guildConfReset(message.guild, "locale")
appendLog(f"Server's locale has been reset", message.guild)
await message.reply(embed=makeEmbed(title=getMsg("reset_locale_title", message.guild), description=getMsg("reset_locale_description", message.guild).format(getMsg("locale_name", message.guild), prefix), color=strToColor(config["color_ok"])), mention_author=False)
else:
await message.reply(embed=makeEmbed(title=getMsg("hint_none_locale_title", message.guild), description=getMsg("hint_none_locale_description", message.guild).format(getMsg("locale_name", message.guild), prefix), color=strToColor(config["color_warn"])), mention_author=False)
else:
for locale_file in os.listdir(f"{path}/locale/"):
if locale_file[:-5] == fullcmd[1]:
guildConfSet(message.guild, "locale", fullcmd[1])
appendLog(f"Server's locale is now set to {fullcmd[1]}", message.guild)
await message.reply(embed=makeEmbed(title=getMsg("set_locale_title", message.guild), description=getMsg("set_locale_description", message.guild).format(getMsg("locale_name", message.guild)), color=strToColor(config["color_ok"])), mention_author=False)
return
locales = []
for locale_file in os.listdir(f"{path}/locale/"):
locales.append(f"`{locale_file[:-5]}`")
await message.reply(embed=makeEmbed(title=getMsg("error_locale_title", message.guild), description=getMsg("error_locale_description", message.guild).format(prefix, ", ".join(locales)), color=strToColor(config["color_error"])), mention_author=False)
except:
locales = []
for locale_file in os.listdir(f"{path}/locale/"):
locales.append(f"`{locale_file[:-5]}`")
await message.reply(embed=makeEmbed(title=getMsg("error_locale_title", message.guild), description=getMsg("error_locale_description", message.guild).format(prefix, ", ".join(locales)), color=strToColor(config["color_error"])), mention_author=False)
else:
await message.reply(embed=makeEmbed(title=getMsg("forbidden_title", message.guild), description=getMsg("forbidden_description", message.guild), color=strToColor(config["color_error"])), mention_author=False)
else:
await message.reply(embed=makeEmbed(title=getMsg("dm_title", message.guild), description=getMsg("dm_description", message.guild), color=strToColor(config["color_error"])), mention_author=False)
elif message.content.startswith(f"{prefix}help"):
if message.author.id == config["owner"]:
if message.guild is not None:
await message.channel.send(await guildConfigured(message.guild) + getMsg("help").format(getMsg("help_owner").format(prefix), prefix, prefix, prefix, prefix))
else:
await message.channel.send(getMsg("help").format(getMsg("help_owner").format(prefix), prefix, prefix, prefix, prefix))
else:
if message.guild is not None:
await message.channel.send(await guildConfigured(message.guild) + getMsg("help").format("", prefix, prefix, prefix))
else:
await message.channel.send(getMsg("help").format("", prefix, prefix, prefix))
gotCommand(message)
await message.reply(embed=getHelpMessage(message, version, prefix=prefix), mention_author=False)
client.run(loadJson("config.json")["bot_token"])
#if loadJson("config.json")["auto_clear_trash"]:
# run func
appendLog(f"Trying to log in...")
client.run(loadJson("config.json")["bot_token"])