diff --git a/discord_bot/bot_d.py b/discord_bot/bot_d.py index b966bf4..b61a401 100644 --- a/discord_bot/bot_d.py +++ b/discord_bot/bot_d.py @@ -40,6 +40,7 @@ from .d_commands.poll import poll_cmd from .d_commands.reputation import rep_cmd from .d_events.new_level import message_to_xp +from .d_commands.embed import embed_cmd import discord_bot.d_commands.set as settings import discord_bot.d_commands.profile as profile import discord_bot.d_events.cooldown as cooldown @@ -48,6 +49,7 @@ import discord_bot.d_commands.blacklist as blacklist import discord_bot.d_events.new_member as autorole import discord_bot.d_commands.codec as codec +import discord_bot.d_commands.music as music import discord_bot.mem import praw @@ -166,7 +168,10 @@ async def on_guild_join(guild): 'Authorization': '{}'.format(boticord_token)}, json={'shards': 0, 'servers': len(bot.guilds), 'users': len(bot.users)}) game = discord.Game(str(len(bot.guilds)) + " guilds | " + botconfig['prefix'] + "help", type=discord.ActivityType.watching) await bot.change_presence(status=discord.Status.dnd, activity=game) - guild_s = [(guild.id, str(guild.region), 0, unix_time_millis(datetime.datetime.now()), "Enabled", 'Standart', '=', 'English', 0, '', 0, '', "Disabled")] + if str(guild.region) == 'russia': + guild_s = [(guild.id, str(guild.region), 0, unix_time_millis(datetime.datetime.now()), "Enabled", 'Standart', '=', 'Russian', 0, '', 0, '', "Disabled")] + else: + guild_s = [(guild.id, str(guild.region), 0, unix_time_millis(datetime.datetime.now()), "Enabled", 'Standart', '=', 'English', 0, '', 0, '', "Disabled")] cursor.executemany("INSERT OR REPLACE INTO guilds VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", guild_s) # print(guild) connection.commit() @@ -174,19 +179,31 @@ async def on_guild_join(guild): @bot.event async def on_guild_remove(guild): - requests.post("https://api.server-discord.com/v2/bots/785383439196487720/stats", params={'id': 785383439196487720}, headers={'Authorization': os.environ['BOTSDST']}, data={'shards': 0, 'servers': len(bot.guilds)}) + if guild is None or guild.name is None: + return + boticord_token = os.environ['BOTICORDTOKEN'] + bots_ds_token = os.environ['BOTSDST'] + requests.post("https://api.server-discord.com/v2/bots/785383439196487720/stats", params={'id': 785383439196487720}, headers={'Authorization': 'SDC {0}'.format(bots_ds_token)}, data={'shards': 0, 'servers': len(bot.guilds)}) game = discord.Game(str(len(bot.guilds)) + " guilds | " + botconfig['prefix'] + "help", type=discord.ActivityType.watching) await bot.change_presence(status=discord.Status.dnd, activity=game) await logging.leaving_logger(bot, discord, guild, connection, cursor, unix_time_millis, botconfig) @bot.event async def on_member_join(member): - await autorole.autorole(bot, discord, member, botconfig, cursor, connection) + if member is None: + return + await autorole.autorole(bot, discord, member, botconfig, cursor, connection, unix_time_millis) await autorole.new_member(bot, discord, member, botconfig, cursor, connection) @bot.event async def on_member_remove(member): - await autorole.member_left(bot, discord, member, botconfig, cursor, connection) + if member is None: + return + cursor.execute("SELECT * FROM guilds WHERE guildid='" + str(member.guild.id) + "';") + guild_result = (cursor.fetchone()) + if guild_result is None: + return + await autorole.member_left(bot, discord, member, botconfig, cursor, connection, guild_result) @bot.event async def on_message(message): @@ -198,7 +215,6 @@ async def on_message(message): cursor.execute("SELECT * FROM guilds WHERE guildid='" + str(message.guild.id) + "';") guild_result = (cursor.fetchone()) # print("SQLite Database | " + str(guild_result)) - cursor.execute("SELECT * FROM users WHERE userid='" + str(message.author.id) + "';") cursor.execute("SELECT * FROM bot_data WHERE number='" + str(0) + "';") bot_data_result = (cursor.fetchone()) try: @@ -220,10 +236,26 @@ async def on_message(message): if time_diff < 500: return await cooldown.cooldown(bot, message, one_result, guild_result, connection, cursor, unix_time_millis, ru_RU, en_US) await logging.messaging_logger(bot, discord, message, one_result, guild_result, connection, cursor, unix_time_millis, botconfig, bot_data_result) + if guild_result[1] == "Russian": + localization = ru_RU.get() + longdate = ru_RU.longdate() + longdate_without_year = ru_RU.longdate_without_year() + shortdate_without_year = ru_RU.shortdate_without_year() + elif guild_result[1] == "English": + localization = en_US.get() + longdate = en_US.longdate() + longdate_without_year = en_US.longdate_without_year() + shortdate_without_year = en_US.shortdate_without_year() if one_result[1] == "Russian": localization = ru_RU.get() + longdate = ru_RU.longdate() + longdate_without_year = ru_RU.longdate_without_year() + shortdate_without_year = ru_RU.shortdate_without_year() elif one_result[1] == "English": localization = en_US.get() + longdate = en_US.longdate() + longdate_without_year = en_US.longdate_without_year() + shortdate_without_year = en_US.shortdate_without_year() if one_result[5] == "Enabled": user = [(message.author.id, one_result[1], one_result[2] + 1, one_result[3], one_result[4], "Enabled", unix_time_millis(message.created_at), one_result[7], one_result[8], one_result[9])] userdata_recovery = { @@ -249,7 +281,7 @@ async def on_message(message): "reputation": one_result[7] } else: - user = [(message.author.id, one_result[1], one_result[2] + 1, one_result[3], one_result[4], one_result[5], unix_time_millis(message.created_at))] + user = [(message.author.id, one_result[1], one_result[2] + 1, one_result[3], one_result[4], one_result[5], unix_time_millis(message.created_at), one_result[7], one_result[8], one_result[9])] userdata_recovery = { "userid": message.author.id, "botlanguage": one_result[1], @@ -330,21 +362,39 @@ async def on_message(message): if guild_result[5] == "Rose": embed_color = 0xff0066 except Exception as e: + cursor.execute("SELECT * FROM users WHERE userid='" + str(message.author.id) + "';") + one_result = (cursor.fetchone()) + # print("SQLite Database | " + str(one_result)) + cursor.execute("SELECT * FROM guilds WHERE guildid='" + str(message.guild.id) + "';") + guild_result = (cursor.fetchone()) if one_result is None or guild_result is None or bot_data_result is None: - print("Registration...") - pass - if str(message.guild.region) == "russia": - user = [(message.author.id, "Russian", 0, 10800000, unix_time_millis(message.created_at), "Disabled", unix_time_millis(message.created_at), 0, 0, 0)] - guild = [(message.guild.id, str(message.guild.region), 0, unix_time_millis(message.created_at), "Disabled", "Standart", "=", "Russian", 0, "", 0, "", "Disabled")] - else: - user = [(message.author.id, "English", 0, 10800000, unix_time_millis(message.created_at), "Disabled", unix_time_millis(message.created_at), 0, 0, 0)] - guild = [(message.guild.id, str(message.guild.region), 0, unix_time_millis(message.created_at), "Disabled", "Standart", "=", "English", 0, "", 0, "", "Disabled")] - print(e) - bot_data = [(0, 0)] + if message.guild.member_count <= 50: + print("Registration...") + await logging.registration_logger(bot, discord, message, one_result, guild_result, connection, cursor, unix_time_millis, botconfig, bot_data_result, e) + if str(message.guild.region) == "russia": + if one_result is None: + user = [(message.author.id, "Russian", 0, 10800000, unix_time_millis(message.created_at), "Disabled", unix_time_millis(message.created_at), 0, 0, 0)] + else: + user = [(message.author.id, one_result[1], one_result[2], one_result[3], one_result[4], one_result[5], unix_time_millis(message.created_at), one_result[7], one_result[8], one_result[9])] + if guild_result is None: + guild = [(message.guild.id, str(message.guild.region), 0, unix_time_millis(message.created_at), "Disabled", "Standart", "=", "Russian", 0, "", 0, "", "Disabled")] + else: + guild = [(message.guild.id, guild_result[1], guild_result[2], guild_result[3], guild_result[4], guild_result[5], guild_result[6], guild_result[7], guild_result[8], guild_result[9], guild_result[10], guild_result[11], guild_result[12])] + else: + if one_result is None: + user = [(message.author.id, "English", 0, 10800000, unix_time_millis(message.created_at), "Disabled", unix_time_millis(message.created_at), 0, 0, 0)] + else: + user = [(message.author.id, one_result[1], one_result[2], one_result[3], one_result[4], one_result[5], unix_time_millis(message.created_at), one_result[7], one_result[8], one_result[9])] + if guild_result is None: + guild = [(message.guild.id, str(message.guild.region), 0, unix_time_millis(message.created_at), "Disabled", "Standart", "=", "English", 0, "", 0, "", "Disabled")] + else: + guild = [(message.guild.id, guild_result[1], guild_result[2], guild_result[3], guild_result[4], guild_result[5], guild_result[6], guild_result[7], guild_result[8], guild_result[9], guild_result[10], guild_result[11], guild_result[12])] + + print(e) + bot_data = [(0, 0)] cursor.executemany("INSERT OR REPLACE INTO users VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", user) # print(user) - connection.commit() cursor.executemany("INSERT OR REPLACE INTO guilds VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", guild) # print(guild) cursor.executemany("INSERT OR REPLACE INTO bot_data VALUES(?, ?)", bot_data) @@ -356,37 +406,37 @@ async def on_message(message): pass timingcount = 0 - if message.content.startswith(botconfig['prefix']) or message.content.startswith(guild_result[6]): + if message.content.startswith(botconfig['prefix']) or message.content.startswith(prefix): try: time_diff = (datetime.datetime.utcnow() - epoch).total_seconds() - 2 print(time_diff) if time_diff >= 120: pass - if message.content.startswith(botconfig['prefix'] + 'help') or message.content.startswith(guild_result[6] + 'help'): + if message.content.startswith(botconfig['prefix'] + 'help') or message.content.startswith(prefix + 'help'): try: await help_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, embed_color, guild_result) except: if str(message.guild.region) == "russia": - await help_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, ru_RU.get(), botconfig['accent1'], "=") + await help_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, ru_RU.get(), botconfig['accent1'], guild_result) else: - await help_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, en_US.get(), botconfig['accent1'], "=") - if message.content.startswith(botconfig['prefix'] + 'state') or message.content.startswith(guild_result[6] + 'state'): + await help_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, en_US.get(), botconfig['accent1'], guild_result) + if message.content.startswith(botconfig['prefix'] + 'state') or message.content.startswith(prefix + 'state'): await state_cmd(bot, discord, sqlite3, message, botconfig, os, platform, datetime, one_result, localization, embed_color, connection, cursor, cpuinfo, psutil) - if message.content.startswith(botconfig['prefix'] + 'eval' or message.content.startswith(guild_result[6] + 'eval')): + if message.content.startswith(botconfig['prefix'] + 'eval' or message.content.startswith(prefix + 'eval')): await eval_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, en_US, guild_result, intents, embed_color) - if message.content.startswith(botconfig['prefix'] + 'guilds' or message.content.startswith(guild_result[6] + 'guilds')): + if message.content.startswith(botconfig['prefix'] + 'guilds' or message.content.startswith(prefix + 'guilds')): await guilds_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, guild_result, intents, embed_color) - if message.content.startswith(botconfig['prefix'] + 'db' or message.content.startswith(guild_result[6] + 'db')): + if message.content.startswith(botconfig['prefix'] + 'db' or message.content.startswith(prefix + 'db')): await db_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, connection, cursor) if message.content.startswith(botconfig['prefix'] + 'clock'): await eval_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, en_US, guild_result, intents, embed_color) - if message.content.startswith(botconfig['prefix'] + 'settings') or message.content.startswith(guild_result[6] + 'settings'): + if message.content.startswith(botconfig['prefix'] + 'settings') or message.content.startswith(prefix + 'settings'): await settings_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, unix_time_millis, embed_color, guild_result, prefix) - if message.content.startswith(botconfig['prefix'] + 'set') or message.content.startswith(guild_result[6] + 'set'): + if message.content.startswith(botconfig['prefix'] + 'set') or message.content.startswith(prefix + 'set'): args = message.content.split(" "); try: if args[1] == "-l": - await settings.set_bot_language(bot, discord, message, botconfig, os, platform, datetime, one_result, args, connection, cursor, unix_time_millis) + await settings.set_bot_language(bot, discord, message, botconfig, os, platform, datetime, one_result, args, connection, cursor, unix_time_millis, en_US, ru_RU, guild_result, prefix, embed_color, localization) if args[1] == "-tz": await settings.set_timezone(bot, discord, message, botconfig, os, platform, datetime, one_result, args, connection, cursor, localization, unix_time_millis) if args[1] == "-mc": @@ -404,19 +454,19 @@ async def on_message(message): else: return except Exception as e: print(e) - if message.content.startswith(botconfig['prefix'] + 'profile') or message.content.startswith(guild_result[6] + 'profile'): + if message.content.startswith(botconfig['prefix'] + 'profile') or message.content.startswith(prefix + 'profile'): args = message.content.split(); try: if args[1] == "-u": - await profile.get_user(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, args, unix_time_millis, connection, cursor, intents, lastmsgtime, embed_color) + await profile.get_user(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, longdate, longdate_without_year, shortdate_without_year, args, unix_time_millis, connection, cursor, intents, lastmsgtime, embed_color) if args[1] == "-g": - await profile.get_guild(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, args, unix_time_millis, connection, cursor, guild_result, intents, embed_color) + await profile.get_guild(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, longdate, longdate_without_year, shortdate_without_year, args, unix_time_millis, connection, cursor, guild_result, intents, embed_color) else: pass except Exception as e: print(e) await profile.get_help(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, args, unix_time_millis, connection, cursor, embed_color, prefix) - if message.content.startswith(botconfig['prefix'] + 'tnews') or message.content.startswith(guild_result[6] + 'tnews'): + if message.content.startswith(botconfig['prefix'] + 'tnews') or message.content.startswith(prefix + 'tnews'): args = message.content.split(); await tnews.get_tnews(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, args, unix_time_millis, connection, cursor, embed_color) if message.content.startswith(botconfig['prefix'] + 'blacklist'): @@ -426,21 +476,39 @@ async def on_message(message): await blacklist.add_guild_to_blacklist(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, args, unix_time_millis, connection, cursor) except Exception as e: print(e) - if message.content.startswith(botconfig['prefix'] + 'photo') or message.content.startswith(guild_result[6] + 'photo'): + if message.content.startswith(botconfig['prefix'] + 'photo') or message.content.startswith(prefix + 'photo'): await photo_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, unix_time_millis, unsplash, time_diff, bot_data_result, cursor, connection, embed_color, reddit, prefix) - if message.content.startswith(botconfig['prefix'] + 'calc') or message.content.startswith(guild_result[6] + 'calc'): + if message.content.startswith(botconfig['prefix'] + 'calc') or message.content.startswith(prefix + 'calc'): await calc_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, numexpr, prefix, embed_color) - if message.content.startswith(botconfig['prefix'] + 'feedback') or message.content.startswith(guild_result[6] + 'feedback'): - await feedback_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, embed_color, prefix) - if message.content.startswith(botconfig['prefix'] + 'weather') or message.content.startswith(guild_result[6] + 'weather'): + if message.content.startswith(botconfig['prefix'] + 'feedback') or message.content.startswith(prefix + 'feedback'): + try: + await feedback_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, embed_color, prefix) + except: + if str(message.guild.region) == "russia": + feedback_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, ru_RU.get(), botconfig['accent1'], "=") + else: + feedback_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, en_US.get(), botconfig['accent1'], "=") + if message.content.startswith(botconfig['prefix'] + 'weather') or message.content.startswith(prefix + 'weather'): + try: await weather_cmd(bot, discord, sqlite3, message, botconfig, os, platform, datetime, one_result, localization, embed_color, requests) - if message.content.startswith(botconfig['prefix'] + '8ball') or message.content.startswith(botconfig['prefix'] + 'crystball') or message.content.startswith(guild_result[6] + '8ball') or message.content.startswith(guild_result[6] + 'crystball'): + except: + if str(message.guild.region) == "russia": + await weather_cmd(bot, discord, sqlite3, message, botconfig, os, platform, datetime, one_result, ru_RU.get(), botconfig['accent1'], requests) + else: + await weather_cmd(bot, discord, sqlite3, message, botconfig, os, platform, datetime, one_result, en_US.get(), botconfig['accent1'], requests) + if message.content.startswith(botconfig['prefix'] + '8ball') or message.content.startswith(botconfig['prefix'] + 'crystball') or message.content.startswith(prefix + '8ball') or message.content.startswith(prefix + 'crystball'): await crystball_cmd(bot, discord, sqlite3, message, botconfig, os, platform, datetime, one_result, localization, embed_color, requests) - if message.content.startswith(botconfig['prefix'] + 'post') or message.content.startswith(guild_result[6] + 'post'): + if message.content.startswith(botconfig['prefix'] + 'post') or message.content.startswith(prefix + 'post'): await post_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, unix_time_millis, embed_color, prefix) - if message.content.startswith(botconfig['prefix'] + 'info') or message.content.startswith(guild_result[6] + 'info'): - await info_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, embed_color) - if message.content.startswith(botconfig['prefix'] + 'codec') or message.content.startswith(guild_result[6] + 'codec'): + if message.content.startswith(botconfig['prefix'] + 'info') or message.content.startswith(prefix + 'info'): + try: + await info_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, embed_color) + except: + if str(message.guild.region) == "russia": + await info_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, ru_RU.get(), botconfig['accent1']) + else: + await info_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, en_US.get(), botconfig['accent1']) + if message.content.startswith(botconfig['prefix'] + 'codec') or message.content.startswith(prefix + 'codec'): args = message.content.split(); try: if args[1] == "-d": @@ -450,16 +518,25 @@ async def on_message(message): except Exception as e: await codec.get_help(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, embed_color, prefix) print(e) - if message.content.startswith(botconfig['prefix'] + 'poll') or message.content.startswith(guild_result[6] + 'poll'): - await poll_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, unix_time_millis, embed_color, connection, cursor, prefix) - if message.content.startswith(botconfig['prefix'] + 'rep') or message.content.startswith(guild_result[6] + 'rep'): + if message.content.startswith(botconfig['prefix'] + 'poll') or message.content.startswith(prefix + 'poll'): + await poll_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, longdate, longdate_without_year, shortdate_without_year, unix_time_millis, embed_color, connection, cursor, prefix) + if message.content.startswith(botconfig['prefix'] + 'rep') or message.content.startswith(prefix + 'rep'): await rep_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, embed_color, connection, cursor, prefix) + if message.content.startswith(botconfig['prefix'] + 'embed') or message.content.startswith(prefix + 'embed'): + await embed_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, unix_time_millis, embed_color, connection, cursor, prefix) + if message.content.startswith(botconfig['prefix'] + 'music') or message.content.startswith(prefix + 'music'): + await music.yt_search(bot, discord, sqlite3, message, botconfig, os, platform, datetime, one_result, localization, embed_color, prefix, requests) except Exception as e: - if message.content.startswith(botconfig['prefix']) or message.content.startswith(guild_result[6]): + + if message.content.startswith(botconfig['prefix']) or message.content.startswith(prefix): + if str(e).startswith("403 Forbidden (error code: 50013):"): + return await message.channel.send("Please reconfigure the bot's permissions and try again.\n\n_Bot uses embed messages._") + else: + pass exc_type, exc_value, exc_tb = sys.exc_info() ex = traceback.format_exception(exc_type, exc_value, exc_tb) await logging.traceback_logger(bot, discord, message, one_result, guild_result, connection, cursor, unix_time_millis, botconfig, bot_data_result, ex, e) - if str(e) == "local variable 'localization' referenced before assignment": + if str(e) == "local variable 'localization' referenced before assignment" or str(e) == "local variable 'custom_prefix' referenced before assignment": if str(message.guild.region) == "russia": dbregistred_content = discord.Embed(title="База данных пользователя", description="База данных пользователя зарегистрирована. Напишите команду еще раз.", color=botconfig['accent1']) else: @@ -470,7 +547,5 @@ async def on_message(message): errorcode = discord.Embed(title="Something went wrong...", description="This bug was reported to the bot developer.\n\n```" + ex[0] + "\n" + ex[1] + "\n" + ex[2] + "\nErrorcode: " + str(e) + "```", color=botconfig['accent1']) await message.channel.send(embed=errorcode) gc.collect() - else: - pass bot.run(botconfig['token']) diff --git a/discord_bot/d_commands/calc.py b/discord_bot/d_commands/calc.py index 97e8b7b..2c23693 100644 --- a/discord_bot/d_commands/calc.py +++ b/discord_bot/d_commands/calc.py @@ -1,5 +1,6 @@ async def calc_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, numexpr, prefix, embed_color): - args = message.content.split(); + args = message.content.split(); + err = "" no_args = discord.Embed(title=localization[1][9][0], description=str(localization[1][9][4]).format(prefix), color=botconfig['accent1']) no_args.add_field(name=localization[1][9][6], value=localization[1][9][7], inline=False) if " ".join(args[1:]) == "" or " ".join(args[1:]) == " " or " ".join(args[1:]) == None: @@ -8,7 +9,14 @@ async def calc_cmd(bot, discord, message, botconfig, os, platform, datetime, one calc_content.add_field(name=localization[1][9][1], value="```py\n" + " ".join(args[1:]) + "```", inline=False) try: result = str(numexpr.evaluate(" ".join(args[1:]))) - except Exception as e: + except Exception as e: + if str(e) == 'division by zero': + result = localization[1][9][8] + elif str(e) == "Python int too large to convert to C long": + result = localization[1][9][9] + elif str(e).startswith("'VariableNode' object has no attribute"): + result = localization[1][9][10] + else: result = localization[1][9][3] + str(e) finally: calc_content.add_field(name=localization[1][9][2], value="```" + result + "```", inline=False) diff --git a/discord_bot/d_commands/db.py b/discord_bot/d_commands/db.py index 964a2c0..df75d06 100644 --- a/discord_bot/d_commands/db.py +++ b/discord_bot/d_commands/db.py @@ -1,7 +1,7 @@ async def db_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, connection, cursor): args = message.content.split(); subargs = args[1:] - accessdenied_msg = discord.Embed(title="Доступ запрещен", description="Эта команда защищена владельцем бота, поэтому она недоступна.", color=botconfig['accent2']) + accessdenied_msg = discord.Embed(description=localization[1][19][0], color=botconfig['accent2']) eval_content = discord.Embed(title="Просмотр базы данных", color=botconfig['accent1']) if str(message.author.id) != botconfig['owner']: return await message.channel.send(embed=accessdenied_msg) diff --git a/discord_bot/d_commands/embed.py b/discord_bot/d_commands/embed.py new file mode 100644 index 0000000..28fef13 --- /dev/null +++ b/discord_bot/d_commands/embed.py @@ -0,0 +1,51 @@ +def remove_outer_symbols(s): + left = s.index("[") + right = s.rindex("]", left) + return s[:left] + s[left+1:right] + s[right+1:] + +async def embed_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, unix_time_millis, embed_color, connection, cursor, prefix): + args = message.content.split(" "); + args2 = message.content.split("-[]"); + parameter_option = "" + args_str = " ".join(args[1:]) + try: + question_rindex = args_str.rindex('-t', 0) + text = args_str[:question_rindex] + options_str = "" + options = [] + endtimeerr = "" + endtime = 0 + for args_index in args: + if args_index == "-t": + parameter_option += '-t' + for args_index in args2: + try: + if message.content.startswith(botconfig['prefix']): + index = args_str.index('[') + 7 + rindex = args_str.rindex(']') + 8 + elif message.content.startswith(prefix): + index = args_str.index('[') + 6 + len(prefix) + rindex = args_str.rindex(']') + 7 + len(prefix) + options_str += remove_outer_symbols(args_index[index:rindex]) + options = options_str.split("],[") + except: + pass + + embed_title = "" + embed_footer = "" + for opt in options: + if options.index(opt) == 0: + embed_title = opt + print('Yes! ' + embed_title+ "\n" + str(options)) + if options.index(opt) == 1: + embed_footer += opt + if args[1] == "" or args[1] == None or args[2] == "" or parameter_option != '-t' or options == [] or args[2] == None: + no_args = discord.Embed(title=localization[1][20][0], description=str(localization[1][20][1]).format(prefix), color=embed_color) + return await message.channel.send(embed=no_args) + embed = discord.Embed(title=embed_title, description=text, color=embed_color) + embed.set_footer(text=embed_footer) + msg = await message.channel.send(embed=embed) + except Exception as e: + print(e) + no_args = discord.Embed(title=localization[1][16][0], description=str(localization[1][16][4]).format(prefix), color=embed_color) + await message.channel.send(embed=no_args) diff --git a/discord_bot/d_commands/eval.py b/discord_bot/d_commands/eval.py index 71dc508..eef0b85 100644 --- a/discord_bot/d_commands/eval.py +++ b/discord_bot/d_commands/eval.py @@ -1,6 +1,6 @@ async def eval_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, en_US, guild_result, intents, embed_color): args = message.content.split(); - accessdenied_msg = discord.Embed(title="Доступ запрещен", description="Эта команда защищена владельцем бота, поэтому она недоступна.", color=botconfig['accent2']) + accessdenied_msg = discord.Embed(description=localization[1][19][0], color=botconfig['accent2']) eval_content = discord.Embed(title="Определение качества кода", color=botconfig['accent1']) eval_content.add_field(name="Листинг", value="```py\n" + " ".join(args[1:]) + "```", inline=False) if str(message.author.id) != botconfig['owner']: diff --git a/discord_bot/d_commands/guilds.py b/discord_bot/d_commands/guilds.py index 076713b..b343fcf 100644 --- a/discord_bot/d_commands/guilds.py +++ b/discord_bot/d_commands/guilds.py @@ -5,7 +5,11 @@ async def guilds_cmd(bot, discord, message, botconfig, os, platform, datetime, o try: guild_list = "" for bot_guild in bot.guilds: - guild_list += str(bot.guilds.index(bot_guild) + 1) + ". " + str(bot_guild.name) + " | Members: " + str(bot_guild.member_count) + "\n" + bots_count = 0 + for member in bot_guild.members: + if member.bot == True: + bots_count += 1 + guild_list += str(bot.guilds.index(bot_guild) + 1) + ". " + str(bot_guild.id) + "\nMembers: " + str(bot_guild.member_count) + " | Bots: " + str(bots_count) + "\n" except Exception as e: guild_list = "Обнаружено исключение!\n" + str(e) finally: diff --git a/discord_bot/d_commands/help.py b/discord_bot/d_commands/help.py index 9c4f295..4b8c653 100644 --- a/discord_bot/d_commands/help.py +++ b/discord_bot/d_commands/help.py @@ -4,13 +4,14 @@ async def help_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, embed_color, guild_result): if localization[0] == "Russian": tips = [ - 'Для просмотра авторской информационной программы "Новости Тинеликса" достаточно написать команду `tnews`?', + 'С помощью VisionOne можно проводить голосования?', 'Все наши ссылки находятся в `info`?', 'Узнать погоду можно в `weather`?', 'Просмотреть рандомные фото можно в `photo`? Вдруг пригодится поставить обои на свой рабочий стол?', - 'Начиная с версии VisionOne 01R8 (21 января 2021 г.), стало возможным менять префиксы, получать опыты за сообщения и т.д?', + 'Поступили две новости в `=tnews`?', 'Игра "Магический шар" генерирует случайные ответы трех типов (да/нет/хз) для заданного вопроса? Обратите внимание, что совпадения случайны, поэтому воспринимайте как игру, а не как реальность.', - 'Автор {0} (`{1}`) начал строить своего предшественника под названием Highflash в декабре 2018 г. на discord.js (JavaScript).'.format(botconfig['name'], bot.get_user(int(botconfig['owner'])).name + "#" + str(bot.get_user(int(botconfig['owner'])).discriminator)) + 'Автор {0} (`{1}`) начал строить своего предшественника под названием Highflash в декабре 2018 г. на discord.js (JavaScript).'.format(botconfig['name'], bot.get_user(int(botconfig['owner'])).name + "#" + str(bot.get_user(int(botconfig['owner'])).discriminator)), + 'Можно послушать музыку в `=music`? В этой команде присутствует поддержка плейлиста, но такая своеобразная.' ] else: tips = [ @@ -23,6 +24,8 @@ async def help_cmd(bot, discord, message, botconfig, platform, os, datetime, one custom_prefix = "" else: custom_prefix = " `" + guild_result[6] + "`" + if custom_prefix == None: + custom_prefix = "=" except Exception as e: print(e) lucky_num = random.randint(0, len(tips) - 1) diff --git a/discord_bot/d_commands/music.py b/discord_bot/d_commands/music.py new file mode 100644 index 0000000..dd84f25 --- /dev/null +++ b/discord_bot/d_commands/music.py @@ -0,0 +1,362 @@ +from requests import get +import pafy +from youtube_search import YoutubeSearch as ytsearch +import sqlite3 +import tempfile +import os +import asyncio + +def sort_asc(item): + return item[0] + +def create_connection(path): + connection = None + try: + connection = sqlite3.connect(path) + except Exception as e: + print(f"SQLite Database | The error '{e}' occurred") + + return connection + + +async def yt_search(bot, discord, sqlite3, message, botconfig, os, platform, datetime, one_result, localization, embed_color, prefix, requests): + dl_status = [0, 0, 0] + def check_download_status(total, recvd, ratio, rate, eta): + dl_status = [recvd, total, eta] + + args = message.content.split(); + if " ".join(args[1:]) == "" or " ".join(args[1:]) == " " or " ".join(args[1:]) == None: + no_args = discord.Embed(title=localization[1][21][0], description=localization[1][21][14].format(prefix), color=embed_color) + return await message.channel.send(embed=no_args) + + results_list = "" + emoji_number = { + '0': '0️⃣', + '1': '1️⃣', + '2': '2️⃣', + '3': '3️⃣', + '4': '4️⃣', + '5': '5️⃣', + '6': '6️⃣', + '7': '7️⃣', + '8': '8️⃣', + '9': '9️⃣', + '0️⃣': 0, + '1️⃣': 1, + '2️⃣': 2, + '3️⃣': 3, + '4️⃣': 4, + '5️⃣': 5, + '6️⃣': 6, + '7️⃣': 7, + '8️⃣': 8, + '9️⃣': 9 + } + try: + results = ytsearch(" ".join(args[1:]), max_results=9).to_dict() + except Exception as e: + if str(e) == "'sectionListRenderer'": + err_yt_content = discord.Embed(title=localization[1][21][0], description=localization[1][21][17], color=embed_color) + else: + err_yt_content = discord.Embed(title=localization[1][21][0], description=localization[1][21][2], color=embed_color) + return await message.channel.send(content=err_yt_content) + results_text = "" + video_url = [] + video_title = [] + yt_channel = [] + yt_duration = [] + file_url = {} + for video in results: + if str(video['duration']) != "0": + results_text += emoji_number[str(results.index(video) + 1)] + " **{0}** ({1})\n".format(video['title'], video['duration']) + else: + results_text += emoji_number[str(results.index(video) + 1)] + " **{0}** (Stream)\n".format(video['title']) + video_url.append("https://youtube.com{0}".format(video['url_suffix'])) + video_title.append(video['title']) + yt_channel.append(video['channel']) + yt_duration.append(video['duration']) + yt_search_results = discord.Embed(title=localization[1][21][0], color=embed_color) + yt_search_results.add_field(name=localization[1][21][3], value=results_text) + msg = await message.channel.send(embed=yt_search_results) + for video in results: + await msg.add_reaction(emoji=emoji_number[str(results.index(video) + 1)]) + #print(video_infos['entries']) + @bot.event + async def on_reaction_add(reaction, user): + channel = reaction.message.channel + connection = create_connection(os.path.join(os.path.dirname(__file__), '../guilds_data.sqlite')) + cursor = connection.cursor() + queue_index = 0 + try: + if reaction.emoji == str(emoji_number[str(emoji_number[reaction.emoji])]) and reaction.message.embeds != [] and reaction.message.embeds[0].fields != [] and reaction.message.embeds[0].fields[0].name == localization[1][21][3] and user.bot != True: + if user.voice == None: + no_args = discord.Embed(title=localization[1][21][0], description=localization[1][21][6].format(prefix), color=embed_color) + return await message.channel.send(embed=no_args) + if user.voice != None or user.voice.channel != None: + + cursor.execute("""CREATE TABLE IF NOT EXISTS music_queues_{0}( + position TEXT NOT NULL PRIMARY KEY, + userid INT NOT NULL, + url TEXT NOT NULL, + duration TEXT NOT NULL, + status TEXT NOT NULL); + """.format(str(message.guild.id))) + + cursor.execute("SELECT * FROM music_queues_{0}".format(message.guild.id) + " ORDER BY position;") + music_queues = (cursor.fetchall()) + #print(music_queues) + def state_change(): + connection = create_connection(os.path.join(os.path.dirname(__file__), '../guilds_data.sqlite')) + cursor = connection.cursor() + if (music_queues != None or music_queues != []) and len(music_queues) > 1: + queue_mask = [(str(len(music_queues)), user.id, "{0}".format(video_url[emoji_number[reaction.emoji] - 1]), yt_duration[emoji_number[reaction.emoji] - 1], "Completed")] + + else: + queue_mask = [(str(1), user.id, "{0}".format(video_url[emoji_number[reaction.emoji] - 1]), yt_duration[emoji_number[reaction.emoji] - 1], "Completed")] + + cursor.executemany("INSERT OR REPLACE INTO music_queues_{0} VALUES(?, ?, ?, ?, ?);".format(str(message.guild.id)), queue_mask) + connection.commit() + def after(error): + try: + fut = asyncio.run_coroutine_threadsafe(state_change(), bot.loop) + fut.result() + except Exception as e: + print(e) + try: + os.remove(tempfile.gettempdir() + '/audio_dl_{0}.tmp'.format(reaction.message.guild.id)) + except: + pass + try: + if reaction.message.guild.voice_client is not None and reaction.message.guild.voice_client.is_playing() == True: + reaction.message.guild.voice_client.stop() + except: + pass + video = pafy.new("{0}".format(video_url[emoji_number[reaction.emoji] - 1])) + #print(video.length) + if video.length == 0.0 or video.length == 0: + music_length_exceed = discord.Embed(title=localization[1][21][0], description=localization[1][21][16], color=botconfig['accent2']) + return await channel.send(embed=music_length_exceed) + best = video.getbestaudio() + if video.length != None and video.length > 1800: + music_length_exceed = discord.Embed(title=localization[1][21][0], description=localization[1][21][13], color=botconfig['accent2']) + return await channel.send(embed=music_length_exceed) + if (music_queues != None or music_queues != []) and len(music_queues) > 1: + queue_mask = [(str(len(music_queues)), user.id, "{0}".format(video_url[emoji_number[reaction.emoji] - 1]), yt_duration[emoji_number[reaction.emoji] - 1], "Playing")] + else: + queue_mask = [(str(1), user.id, "{0}".format(video_url[emoji_number[reaction.emoji] - 1]), yt_duration[emoji_number[reaction.emoji] - 1], "Playing")] + current_queue_mask = [("Current", user.id, "{0}".format(video_url[emoji_number[reaction.emoji] - 1]), yt_duration[emoji_number[reaction.emoji] - 1], "Playing")] + cursor.executemany("INSERT OR REPLACE INTO music_queues_{0} VALUES(?, ?, ?, ?, ?);".format(str(message.guild.id)), queue_mask) + cursor.executemany("INSERT OR REPLACE INTO music_queues_{0} VALUES(?, ?, ?, ?, ?);".format(str(message.guild.id)), current_queue_mask) + connection.commit() + cursor.execute("SELECT * FROM music_queues_{0}".format(message.guild.id) + ";") + music_queues_currently = (cursor.fetchall()) + + for queue in music_queues_currently: + if music_queues_currently[music_queues_currently.index(queue)] == "{0}".format(video_url[emoji_number[reaction.emoji] - 1]): + queue_index = music_queues_currently.index(queue) + playing_now_embed = discord.Embed(title=localization[1][21][0], description=localization[1][21][12].format(str(round(dl_status[0] / 1024 / 1024, 2)), str(round(best.get_filesize() / 1024 / 1024, 2))), color=embed_color) + msg = await channel.send(embed=playing_now_embed) + if len(music_queues_currently) > 2: + await msg.add_reaction(emoji="⏮") + if len(music_queues_currently) > 2: + await msg.add_reaction(emoji="⏭") + await msg.add_reaction(emoji="⏯") + await msg.add_reaction(emoji="⏹") + best.download(quiet=False, filepath=tempfile.gettempdir() + '/audio_dl_{0}.tmp'.format(reaction.message.guild.id), callback=check_download_status) + #with ytdl(ydl_opts) as ytdl_video: + #song_info = ytdl_video.extract_info(, download=False) + try: + await user.voice.channel.connect() + except Exception as e: + print("Connection error: " + str(e)) + current_track = [()] + current_track_index = 0 + for current_queue in music_queues_currently: + if current_queue[0].startswith("Current"): + current_track = current_queue + try: + if current_queue[2] == current_track[2] and current_queue[0] == "Current": + current_track_index = music_queues_currently.index(current_queue) + except: + pass + playing_now_embed = discord.Embed(title=localization[1][21][0], description=localization[1][21][4].format(video_title[emoji_number[reaction.emoji] - 1], "0:00", yt_duration[emoji_number[reaction.emoji] - 1], str(current_track_index), str(len(music_queues_currently) - 1)), color=embed_color) + source = discord.FFmpegOpusAudio(tempfile.gettempdir() + '/audio_dl_{0}.tmp'.format(reaction.message.guild.id)) + if reaction.message.guild.voice_client is not None and reaction.message.guild.voice_client.is_playing() == True: + reaction.message.guild.voice_client.stop() + reaction.message.guild.voice_client.play(source, after=after) + else: + reaction.message.guild.voice_client.play(source, after=after) + await msg.edit(embed=playing_now_embed) + #reaction.message.guild.voice_client.source = discord.PCMVolumeTransformer(reaction.message.guild.voice_client.source) + #reaction.message.guild.voice_client.source.volume = 1 + except Exception as e: + if str(e).startswith == " 1800: + music_length_exceed = discord.Embed(title=localization[1][21][0], description=localization[1][21][13], color=botconfig['accent2']) + return await channel.send(embed=music_length_exceed) + msg = reaction.message + playing_now_embed = discord.Embed(title=localization[1][21][0], description=localization[1][21][12].format(str(round(dl_status[0] / 1024 / 1024, 2)), str(round(best.get_filesize() / 1024 / 1024, 2))), color=embed_color) + await msg.edit(embed=playing_now_embed) + def state_change(): + return + + def after(error): + try: + fut = asyncio.run_coroutine_threadsafe(state_change(), bot.loop) + fut.result() + except Exception as e: + print("error" + str(e)) + best.download(quiet=False, filepath=tempfile.gettempdir() + '/audio_dl_{0}.tmp'.format(reaction.message.guild.id), callback=check_download_status) + source = discord.FFmpegOpusAudio(tempfile.gettempdir() + '/audio_dl_{0}.tmp'.format(reaction.message.guild.id)) + + playing_now_embed = discord.Embed(title=localization[1][21][0], description=localization[1][21][4].format(prev_video.title, "0:00", music_queues_2[current_track_index][3], str(current_track_index + 1), str(len(music_queues_2) - 1)), color=embed_color) + await msg.edit(embed=playing_now_embed) + if reaction.message.guild.voice_client.is_playing() == True: + reaction.message.guild.voice_client.play(source, after=after) + else: + reaction.message.guild.voice_client.play(source, after=after) + if reaction.emoji == "⏭" and reaction.message.embeds != [] and (reaction.message.embeds[0].description.startswith("".join(localization[1][21][4][:8])) or reaction.message.embeds[0].description.startswith("".join(localization[1][21][15][:4]))) and user.bot != True: + if reaction.message.guild.voice_client.is_playing() == True: + reaction.message.guild.voice_client.stop() + cursor.execute("SELECT * FROM music_queues_{0}".format(message.guild.id) + " ORDER BY position;") + music_queues = (cursor.fetchall()) + music_queues.sort(key=sort_asc) + current_track = [()] + current_track_index = 0 + for current_queue in music_queues: + if current_queue[0].startswith("Current"): + current_track = current_queue + try: + if current_queue[2] == current_track[2] and current_queue[0] != "Current": + current_track_index = music_queues.index(current_queue) + 1 + except: + pass + try: + os.remove(tempfile.gettempdir() + '/audio_dl_{0}.tmp'.format(reaction.message.guild.id)) + except: + pass + cursor.execute("SELECT * FROM music_queues_{0}".format(message.guild.id) + " ORDER BY position;") + music_queues_2 = (cursor.fetchall()) + music_queues_2.sort(key=sort_asc) + for current_queue in music_queues_2: + if current_queue[0] == "Current": + current_track = current_queue + try: + if current_queue[2] == current_track[2] and current_queue[0] != "Current": + current_track_index = music_queues.index(current_queue) + 1 + print(current_queue) + except: + pass + if(current_track_index) >= len(music_queues) - 1: + return + #print(music_queues) + current_queue_mask = [("Current", user.id, "{0}".format(music_queues_2[current_track_index][2]), music_queues_2[current_track_index][3], "Playing")] + cursor.executemany("INSERT OR REPLACE INTO music_queues_{0} VALUES(?, ?, ?, ?, ?);".format(str(message.guild.id)), current_queue_mask) + connection.commit() + prev_video = pafy.new("{0}".format("{0}".format(music_queues_2[current_track_index][2]))) + best = prev_video.getbestaudio() + if prev_video.length > 1800: + music_length_exceed = discord.Embed(title=localization[1][21][0], description=localization[1][21][13], color=botconfig['accent2']) + return await channel.send(embed=music_length_exceed) + msg = reaction.message + playing_now_embed = discord.Embed(title=localization[1][21][0], description=localization[1][21][12].format(str(round(dl_status[0] / 1024 / 1024, 2)), str(round(best.get_filesize() / 1024 / 1024, 2))), color=embed_color) + await msg.edit(embed=playing_now_embed) + def state_change(): + return + + def after(error): + try: + fut = asyncio.run_coroutine_threadsafe(state_change(), bot.loop) + fut.result() + except Exception as e: + print("error" + str(e)) + best.download(quiet=False, filepath=tempfile.gettempdir() + '/audio_dl_{0}.tmp'.format(reaction.message.guild.id), callback=check_download_status) + source = discord.FFmpegOpusAudio(tempfile.gettempdir() + '/audio_dl_{0}.tmp'.format(reaction.message.guild.id)) + + playing_now_embed = discord.Embed(title=localization[1][21][0], description=localization[1][21][4].format(prev_video.title, "0:00", music_queues_2[current_track_index][3], str(current_track_index + 1), str(len(music_queues_2) - 1)), color=embed_color) + await msg.edit(embed=playing_now_embed) + if reaction.message.guild.voice_client.is_playing() == True: + reaction.message.guild.voice_client.play(source, after=after) + else: + reaction.message.guild.voice_client.play(source, after=after) + if reaction.emoji == "⏯" and reaction.message.embeds != [] and (reaction.message.embeds[0].description.startswith("".join(localization[1][21][4][:8])) or reaction.message.embeds[0].description.startswith("".join(localization[1][21][15][:4]))) and user.bot != True: + cursor.execute("SELECT * FROM music_queues_{0} WHERE position='Current'".format(message.guild.id) + ";") + music_queues = (cursor.fetchall())[len(cursor.fetchall()) - 1] + #print(music_queues) + cursor.execute("SELECT * FROM music_queues_{0}".format(message.guild.id) + " ORDER BY position;") + music_queues_2 = (cursor.fetchall()) + music_queues_2.sort(key=sort_asc) + current_track = [()] + current_track_index = 0 + for current_queue in music_queues_2: + if current_queue[0] == "Current": + current_track = current_queue + try: + if current_queue[2] == current_track[2] and current_queue[0] == "Current": + current_track_index = music_queues.index(current_queue) + print(current_queue) + except: + pass + paused_video = pafy.new("{0}".format(music_queues[2])) + best = paused_video.getbestaudio() + msg = reaction.message + if reaction.message.guild.voice_client.is_playing() == True: + playing_now_embed = discord.Embed(title=localization[1][21][0], description=localization[1][21][15].format(paused_video.title, "0:00", music_queues_2[current_track_index][3], str(current_track_index + 1), str(len(music_queues_2) - 1)), color=embed_color) + reaction.message.guild.voice_client.pause() + else: + playing_now_embed = discord.Embed(title=localization[1][21][0], description=localization[1][21][4].format(paused_video.title, "0:00", music_queues_2[current_track_index][3], str(current_track_index + 1), str(len(music_queues_2) - 1)), color=embed_color) + reaction.message.guild.voice_client.resume() + await msg.edit(embed=playing_now_embed) + if reaction.emoji == "⏹" and reaction.message.embeds != [] and (reaction.message.embeds[0].description.startswith("".join(localization[1][21][4][:8])) or reaction.message.embeds[0].description.startswith("".join(localization[1][21][15][:4]))) and user.bot != True: + msg = reaction.message + try: + reaction.message.guild.voice_client.stop() + await msg.guild.voice_client.disconnect() + os.remove(tempfile.gettempdir() + '/audio_dl_{0}.tmp'.format(reaction.message.guild.id)) + except: + pass + cursor.execute("DELETE FROM music_queues_{0};".format(message.guild.id)) + connection.commit() + playing_now_embed = discord.Embed(title=localization[1][21][0], description=localization[1][21][7], color=embed_color) + await msg.edit(embed=playing_now_embed) \ No newline at end of file diff --git a/discord_bot/d_commands/music_rec.py b/discord_bot/d_commands/music_rec.py new file mode 100644 index 0000000..36da1a0 --- /dev/null +++ b/discord_bot/d_commands/music_rec.py @@ -0,0 +1,56 @@ +from requests import get +from youtube_search import YoutubeSearch as ytsearch +import sqlite3 + +def create_connection(path): + connection = None + try: + connection = sqlite3.connect(path) + except Error as e: + print(f"SQLite Database | The error '{e}' occurred") + + return connection + +YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist':'True'} + + +async def yt_search(bot, discord, sqlite3, message, botconfig, os, platform, datetime, one_result, localization, embed_color, requests): + args = message.content.split(); + results_list = "" + emoji_number = { + '0': '0️⃣', + '1': '1️⃣', + '2': '2️⃣', + '3': '3️⃣', + '4': '4️⃣', + '5': '5️⃣', + '6': '6️⃣', + '7': '7️⃣', + '8': '8️⃣', + '9': '9️⃣', + '0️⃣': 0, + '1️⃣': 1, + '2️⃣': 2, + '3️⃣': 3, + '4️⃣': 4, + '5️⃣': 5, + '6️⃣': 6, + '7️⃣': 7, + '8️⃣': 8, + '9️⃣': 9 + } + results = ytsearch(" ".join(args[1:]), max_results=9).to_dict() + print(results) + results_text = "" + for video in results: + results_text += emoji_number[str(results.index(video) + 1)] + " **{0}**\n".format(video['title']) + yt_search_results = discord.Embed(title=localization[1][21][0], color=embed_color) + yt_search_results.add_field(name=localization[1][21][3], value=results_text) + msg = await message.channel.send(embed=yt_search_results) + for video in results: + await msg.add_reaction(emoji=emoji_number[str(results.index(video) + 1)]) + #print(video_infos['entries']) + @bot.event + async def on_reaction_add(reaction, user): + channel = reaction.message.channel + if reaction.emoji == emoji_number[] and user.bot != True: diff --git a/discord_bot/d_commands/photo.py b/discord_bot/d_commands/photo.py index 5484af7..72c5ed8 100644 --- a/discord_bot/d_commands/photo.py +++ b/discord_bot/d_commands/photo.py @@ -53,7 +53,7 @@ async def on_reaction_add(reaction, user): photo_changed = discord.Embed(title=localization[1][8][3], description=localization[1][8][4], color=embed_color) await msg.edit(embed=photo_changed) elif args[1] == "-r": - subreddits = ['analog', 'wallpaper', 'photo'] + subreddits = ['wallpaper', 'photo'] random_sr = subreddits[random.randint(0,len(subreddits) - 1)] subreddit = reddit.subreddit(random_sr) print(subreddit) @@ -66,7 +66,7 @@ async def on_reaction_add(reaction, user): @bot.event async def on_reaction_add(reaction, user): if reaction.emoji == "🎲" and user.id != bot.user.id: - subreddits = ['analog', 'wallpaper', 'photo'] + subreddits = ['wallpaper', 'photo'] random_sr = subreddits[random.randint(0,len(subreddits) - 1)] subreddit = reddit.subreddit(random_sr) photo = subreddit.random() diff --git a/discord_bot/d_commands/poll.py b/discord_bot/d_commands/poll.py index fecf5d9..0d6c05e 100644 --- a/discord_bot/d_commands/poll.py +++ b/discord_bot/d_commands/poll.py @@ -3,7 +3,8 @@ def remove_outer_symbols(s): right = s.rindex("]", left) return s[:left] + s[left+1:right] + s[right+1:] -async def poll_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, unix_time_millis, embed_color, connection, cursor, prefix): +async def poll_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, longdate, longdate_without_year, + shortdate_without_year, unix_time_millis, embed_color, connection, cursor, prefix): args = message.content.split(" "); args2 = message.content.split("-[]"); parameter_option = "" @@ -54,7 +55,8 @@ async def poll_cmd(bot, discord, message, botconfig, platform, os, datetime, one option_str = "" for opt in options: - option_str += emoji_number[str(options.index(opt))] + " " + options[options.index(opt)] + "\n" + if options.index(opt) < 9: + option_str += emoji_number[str(options.index(opt) + 1)] + " " + options[options.index(opt)] + "\n" if args[1] == "" or args[1] == None or args[2] == "" or parameter_option != '-o' or options == [] or args[2] == None or endtimeerr == "Error": no_args = discord.Embed(title=localization[1][16][0], description=str(localization[1][16][4]).format(prefix), color=embed_color) return await message.channel.send(embed=no_args) @@ -66,10 +68,14 @@ async def poll_cmd(bot, discord, message, botconfig, platform, os, datetime, one connection.commit() cursor.execute("SELECT * FROM polls WHERE msgid='" + str(message.id) + "';") poll_result = cursor.fetchone() - poll_content = discord.Embed(title=question, description=localization[1][16][2].format(str(datetime.datetime.fromtimestamp((poll_result[2] + one_result[3]) / 1000))) + "\n\n" + option_str, color=embed_color) + endtime_dt = datetime.datetime.fromtimestamp((poll_result[2] + one_result[3]) / 1000) + endtime_list = endtime_dt.timetuple() + endtime_format = longdate[endtime_list[1]].format(endtime_list[2], endtime_list[0]) + poll_content = discord.Embed(title=question, description=localization[1][16][2].format(str(endtime_format) + str( + endtime_dt.strftime(" %H:%M")) + "\n\n" + option_str), color=embed_color) msg = await message.channel.send(embed=poll_content) for opt in options: - emoji = emoji_number[str(options.index(opt))] + emoji = emoji_number[str(options.index(opt) + 1)] await msg.add_reaction(emoji=emoji) except Exception as e: print(e) diff --git a/discord_bot/d_commands/profile.py b/discord_bot/d_commands/profile.py index d2d9d30..0bda550 100644 --- a/discord_bot/d_commands/profile.py +++ b/discord_bot/d_commands/profile.py @@ -1,5 +1,6 @@ async def get_user(bot, discord, message, botconfig, platform, os, datetime, - one_result, localization, args, unix_time_millis, + one_result, localization, longdate, longdate_without_year, + shortdate_without_year, args, unix_time_millis, connection, cursor, intents, lastmsgtime, embed_color): try: subargs = args[2] @@ -21,8 +22,9 @@ async def get_user(bot, discord, message, botconfig, platform, os, datetime, for member in message.guild.members: member_name_lower = member.name.lower() if member_name_lower.startswith(" ".join(args[2:]).lower()) or member.name.startswith(" ".join(args[2:])): - search_results = 1 - ids.append(member.id) + if args[2:] != []: + search_results = 1 + ids.append(member.id) a_user = await message.guild.fetch_member(ids[0]) except: a_user = message.author @@ -40,7 +42,7 @@ async def get_user(bot, discord, message, botconfig, platform, os, datetime, else: bot_detector = "" if a_user.nick == None: - nick = "_Отсутствует_" + nick = "_(uh, nope)_" else: nick = a_user.nick result = cursor.execute("SELECT * FROM users WHERE userid = " + str(a_user.id) + ";").fetchone(); @@ -63,9 +65,13 @@ async def get_user(bot, discord, message, botconfig, platform, os, datetime, joindate_ms = int(unix_time_millis(a_user.joined_at) + one_result[3]) joindate = datetime.datetime.fromtimestamp( (joindate_ms) / 1000) # 25200000 for UTC+7 + joindate_list = joindate.timetuple() + joindate_format = longdate[joindate_list[1]].format(joindate_list[2], joindate_list[0]) regdate_ms = int(unix_time_millis(a_user.created_at) + one_result[3]) regdate = datetime.datetime.fromtimestamp( (regdate_ms) / 1000) # 25200000 for UTC+7 + regdate_list = regdate.timetuple() + regdate_format = longdate[regdate_list[1]].format(regdate_list[2], regdate_list[0]) except: pass try: @@ -78,6 +84,8 @@ async def get_user(bot, discord, message, botconfig, platform, os, datetime, try: prepostdate = datetime.datetime.fromtimestamp( (prepostdate_ms) / 1000) # 25200000 for UTC+7 + prepostdate_list = regdate.timetuple() + prepostdate_format = longdate[prepostdate_list[1]].format(prepostdate_list[2], prepostdate_list[0]) except: pass try: @@ -95,7 +103,7 @@ async def get_user(bot, discord, message, botconfig, platform, os, datetime, else: member_roles_a += "" if member_roles_a == "" or member_roles_a == None: - member_roles_a = "_Нет_" + member_roles_a = "_(nope)_" try: rep = "\n**" + str(localization[1][3][14]) + ": **" + str(one_result[7]) except: @@ -117,7 +125,7 @@ async def get_user(bot, discord, message, botconfig, platform, os, datetime, pass userprofile_content.add_field( name=str(localization[1][3][2]), - value=joindate.strftime("%Y-%m-%d %H:%M:%S") + " (UTC" + your_timezone + value=joindate_format + joindate.strftime(" %H:%M:%S") + " (UTC" + your_timezone + ")", inline=False) userprofile_content.set_thumbnail( @@ -127,7 +135,7 @@ async def get_user(bot, discord, message, botconfig, platform, os, datetime, try: userprofile_content.add_field( name=str(localization[1][3][3]), - value=regdate.strftime("%Y-%m-%d %H:%M:%S") + " (UTC" + your_timezone + + value=regdate_format + regdate.strftime(" %H:%M:%S") + " (UTC" + your_timezone + ")", inline=False) except: @@ -146,7 +154,7 @@ async def get_user(bot, discord, message, botconfig, platform, os, datetime, try: userprofile_content.add_field( name=str(localization[1][3][13]), - value=prepostdate.strftime("%Y-%m-%d %H:%M:%S") + " (UTC" + + value=prepostdate_format + prepostdate.strftime(" %H:%M:%S") + " (UTC" + your_timezone + ")", inline=False) except: @@ -155,7 +163,7 @@ async def get_user(bot, discord, message, botconfig, platform, os, datetime, try: userprofile_content.add_field( name=str(localization[1][3][15]), - value="**{0}** ({1}/{2})".format(str(one_result[9]), str(one_result[8]), str(((one_result[9]) * (50 + ((one_result[9]) * 10)) * (one_result[9] + 1)))), + value="**{0}** ({1}/{2})".format(str(result[9]), str(result[8]), str(((result[9]) * (50 + ((result[9]) * 10)) * (result[9] + 1)))), inline=False) except: pass @@ -235,7 +243,7 @@ async def on_member_update(before, after): try: userprofile_changed.add_field( name=str(localization[1][3][15]), - value="**{0}** ({1}/{2})".format(str(one_result[9]), str(one_result[8]), str(((one_result[9]) * (50 + ((one_result[9]) * 10)) * (one_result[9] + 1)))), + value="**{0}** ({1}/{2})".format(str(result[9]), str(result[8]), str(((result[9]) * (50 + ((result[9]) * 10)) * (result[9] + 1)))), inline=False) except: pass @@ -248,9 +256,6 @@ async def on_reaction_add(reaction, user): await msg.edit(embed=userprofile_content) if reaction.emoji == "🖼️" and user.id != bot.user.id: await msg.edit(embed=avatar_content) - if reaction.emoji == "🗨️" and user.id != bot.user.id: - await msg.edit(embed=userprofile_content) - async def get_help(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, args, unix_time_millis, @@ -275,9 +280,10 @@ async def get_help(bot, discord, message, botconfig, platform, os, datetime, await message.channel.send(embed=profilehelp_content) -async def get_guild(bot, discord, message, botconfig, platform, os, datetime, - one_result, localization, args, unix_time_millis, - connection, cursor, guild_result, intents, embed_color): +async def get_guild(bot, discord, message, botconfig, platform, os, datetime, + one_result, localization, longdate, longdate_without_year, + shortdate_without_year, args, unix_time_millis, connection, + cursor, guild_result, intents, embed_color): if one_result[3] < 0: your_timezone = "-" + str(-round(one_result[3] / 60 / 60 / 1000, 1)) if one_result[3] > 0: @@ -300,6 +306,8 @@ async def get_guild(bot, discord, message, botconfig, platform, os, datetime, unix_time_millis(message.guild.created_at) + one_result[3]) birthdate = datetime.datetime.fromtimestamp( (birthdate_ms - 25200000) / 1000) # 25200000 for UTC+7 + birthdate_list = birthdate.timetuple() + birthdate_format = longdate[birthdate_list[1]].format(birthdate_list[2], birthdate_list[0]) guildprofile_content = discord.Embed( title=str(localization[1][4][0]) + str(message.guild.name) + str( localization[1][4][1]), @@ -328,20 +336,24 @@ async def get_guild(bot, discord, message, botconfig, platform, os, datetime, else: msgcounter = str(guild_result[2]) owner = await message.guild.fetch_member(message.guild.owner_id) - guildprofile_content.add_field( - name=str(localization[1][4][2]), value=str(description), inline=False) + if description != None or str(description) != "None": + guildprofile_content.add_field( + name=str(localization[1][4][2]), value=str(description), inline=False) guildprofile_content.add_field( name=str(localization[1][4][3]), value=str(owner.name + "#" + owner.discriminator), inline=True) guildprofile_content.add_field( name=str(localization[1][4][4]), - value=str( - birthdate.strftime("%Y-%m-%d %H:%M:%S") + " (UTC" + your_timezone + + value=birthdate_format + str( + birthdate.strftime(" %H:%M:%S") + " (UTC" + your_timezone + ")"), inline=True) - guildprofile_content.add_field( - name=str(localization[1][4][16]), value=str(msgcounter), inline=True) + try: + guildprofile_content.add_field( + name=str(localization[1][4][16]), value=str(msgcounter), inline=True) + except: + pass guildprofile_content.add_field( name=str(localization[1][4][5]), value=str(localization[1][4][15][0]) + str( diff --git a/discord_bot/d_commands/set.py b/discord_bot/d_commands/set.py index ac77db1..e10dfbd 100644 --- a/discord_bot/d_commands/set.py +++ b/discord_bot/d_commands/set.py @@ -1,29 +1,75 @@ from .settings import settings_cmd -async def set_bot_language(bot, discord, message, botconfig, os, platform, datetime, one_result, args, connection, cursor, unix_time_millis): +async def set_bot_language(bot, discord, message, botconfig, os, platform, datetime, one_result, args, connection, cursor, unix_time_millis, en_US, ru_RU, guild_result, prefix, embed_color, localization): subargs = args[2] if subargs == "en-US": - try: - user = [(message.author.id, 'English', one_result[2] + 1, one_result[3], one_result[4], one_result[5], unix_time_millis(message.created_at), one_result[7], one_result[8], one_result[9])] - except: - user = [(message.author.id, 'English', 1, 10800000, unix_time_millis(message.created_at), 'Enabled', unix_time_millis(message.created_at), 0, 0 ,0)] - cursor.executemany("INSERT OR REPLACE INTO users VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", user) - connection.commit() - current_language = "English" - botlanguage_content = discord.Embed(title="Bot language", description="Your language choosed to " + current_language, color=botconfig['accent1']) - await message.channel.send(embed=botlanguage_content) + localization = en_US.get() + botlanguage_choice = discord.Embed(title=str(localization[1][2][2][0]), description=str(localization[1][2][5][1]), color=botconfig['accent1']) + nopermerr_content = discord.Embed(title=str(localization[1][2][2][0]), description=str(localization[1][2][5][4]), color=botconfig['accent1']) + msg = await message.channel.send(embed=botlanguage_choice) + await msg.add_reaction(emoji="🏠") + await msg.add_reaction(emoji="👤") + @bot.event + async def on_reaction_add(reaction, user): + channel = reaction.message.channel + if reaction.emoji == "🏠" and user.id != bot.user.id: + if message.author.guild_permissions.manage_guild == True: + try: + guild = [(message.guild.id, guild_result[1], guild_result[2], guild_result[3], guild_result[4], guild_result[5], guild_result[6], 'English', guild_result[8], guild_result[9], guild_result[10], guild_result[11], guild_result[12])] + except: + guild = [(message.guild.id, str(message.guild.region), 1, unix_time_millis(message.created_at), 'Enabled', 'Standart', '=', 'English', 0, '', 0, '', "Enabled")] + cursor.executemany("INSERT OR REPLACE INTO guilds VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", guild) + connection.commit() + current_language = "English" + botlanguage_content = discord.Embed(title="Bot language", description="Your language choosed to " + current_language, color=botconfig['accent1']) + await msg.edit(embed=botlanguage_content) + else: + msg.edit(embed=nopermerr_content) + if reaction.emoji == "👤" and user.id != bot.user.id: + try: + user = [(message.author.id, 'English', one_result[2] + 1, one_result[3], one_result[4], one_result[5], unix_time_millis(message.created_at), one_result[7], one_result[8], one_result[9])] + except: + user = [(message.author.id, 'English', 1, 10800000, unix_time_millis(message.created_at), 'Enabled', unix_time_millis(message.created_at), 0, 0 ,0)] + cursor.executemany("INSERT OR REPLACE INTO users VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", user) + connection.commit() + current_language = "English" + botlanguage_content = discord.Embed(title="Bot language", description="Your language choosed to " + current_language, color=botconfig['accent1']) + await msg.edit(embed=botlanguage_content) if subargs == "ru-RU": - try: - user = [(message.author.id, 'Russian', one_result[2] + 1, one_result[3], one_result[4], "Enabled", unix_time_millis(message.created_at), one_result[7], one_result[8], one_result[9])] - except: - user = [(message.author.id, 'Russian', 1, 10800000, unix_time_millis(message.created_at), "Enabled", unix_time_millis(message.created_at), 0, 0, 0)] - cursor.executemany("INSERT OR REPLACE INTO users VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", user) - connection.commit() - current_language = "Russian" - botlanguage_content = discord.Embed(title="Язык бота", description="Ваш язык выбран на " + current_language, color=botconfig['accent1']) - await message.channel.send(embed=botlanguage_content) + localization = ru_RU.get() + botlanguage_choice = discord.Embed(title=str(localization[1][2][2][0]), description=str(localization[1][2][5][1]), color=botconfig['accent1']) + nopermerr_content = discord.Embed(title=str(localization[1][2][2][0]), description=str(localization[1][2][5][4]), color=botconfig['accent1']) + msg = await message.channel.send(embed=botlanguage_choice) + await msg.add_reaction(emoji="🏠") + await msg.add_reaction(emoji="👤") + @bot.event + async def on_reaction_add(reaction, user): + channel = reaction.message.channel + if reaction.emoji == "🏠" and user.id != bot.user.id: + if message.author.guild_permissions.manage_guild == True: + try: + guild = [(message.guild.id, guild_result[1], guild_result[2], guild_result[3], guild_result[4], guild_result[5], guild_result[6], 'Russian', guild_result[8], guild_result[9], guild_result[10], guild_result[11], guild_result[12])] + except: + guild = [(message.guild.id, str(message.guild.region), 1, unix_time_millis(message.created_at), 'Enabled', 'Standart', '=', 'Russian', 0, '', 0, '', "Enabled")] + cursor.executemany("INSERT OR REPLACE INTO guilds VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", guild) + connection.commit() + current_language = "Russian" + botlanguage_content = discord.Embed(title="Язык бота", description="Ваш язык изменен на " + current_language + "\n\nОбратите внимание, что настройки вступят в силу только после регистрации пользователя в нашу БД. В таком случае нужно поменять язык в личных настройках.", color=botconfig['accent1']) + await msg.edit(embed=botlanguage_content) + else: + msg.edit(embed=nopermerr_content) + if reaction.emoji == "👤" and user.id != bot.user.id: + try: + user = [(message.author.id, 'Russian', one_result[2] + 1, one_result[3], one_result[4], one_result[5], unix_time_millis(message.created_at), one_result[7], one_result[8], one_result[9])] + except: + user = [(message.author.id, 'Russian', 1, 10800000, unix_time_millis(message.created_at), 'Enabled', unix_time_millis(message.created_at), 0, 0 ,0)] + cursor.executemany("INSERT OR REPLACE INTO users VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", user) + connection.commit() + current_language = "Russian" + botlanguage_content = discord.Embed(title="Язык бота", description="Ваш язык изменен на " + current_language, color=botconfig['accent1']) + await msg.edit(embed=botlanguage_content) if subargs != "en-US" and subargs != "ru-RU": - await settings_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result) + await settings_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, unix_time_millis, embed_color, guild_result, prefix) async def set_timezone(bot, discord, message, botconfig, os, platform, datetime, one_result, args, connection, cursor, localization, unix_time_millis): if one_result[3] < 0: @@ -44,13 +90,13 @@ async def set_timezone(bot, discord, message, botconfig, os, platform, datetime, user = [(message.author.id, one_result[1], one_result[2] + 1, int((-int(subargs2) / 10) * 60 * 60 * 1000), one_result[4], one_result[5], unix_time_millis(message.created_at), one_result[7], one_result[8], one_result[9])] except: user = [(message.author.id, "Russian", 0, 10800000, unix_time_millis(message.created_at), "Enabled", unix_time_millis(message.created_at), 0, 0, 0)] - cursor.executemany("INSERT OR REPLACE INTO users VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", user) + cursor.executemany("INSERT OR REPLACE INTO users VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", user) connection.commit() timezone_content = discord.Embed(title=str(localization[1][2][3][0]), description=localization[1][2][4][2] + your_timezone, color=botconfig['accent1']) await message.channel.send(embed=timezone_content) else: return await message.channel.send(embed=stringnotisdigit_content) - if int(subargs) >= -120 and int(subargs) <= 140: + if int(subargs) >= 0: try: user = [(message.author.id, one_result[1], one_result[2] + 1, int((int(subargs) / 10) * 60 * 60 * 1000), one_result[4], one_result[5], unix_time_millis(message.created_at), one_result[7], one_result[8], one_result[9])] except: diff --git a/discord_bot/d_commands/weather.py b/discord_bot/d_commands/weather.py index 463aa88..e20bf8a 100644 --- a/discord_bot/d_commands/weather.py +++ b/discord_bot/d_commands/weather.py @@ -16,7 +16,7 @@ async def weather_cmd(bot, discord, sqlite3, message, botconfig, os, platform, d res = requests.get("http://api.openweathermap.org/data/2.5/weather", params={'id': city_id, 'units': 'metric', 'lang': localization[1][11][10], 'APPID': os.environ['OPENWMAPT']}) res2 = requests.get("http://api.openweathermap.org/data/2.5/forecast", - params={'id': city_id, 'units': 'metric', 'lang': 'ru', 'cnt': '5', 'APPID': os.environ['OPENWMAPT']}) + params={'id': city_id, 'units': 'metric', 'lang': localization[1][11][10], 'cnt': '5', 'APPID': os.environ['OPENWMAPT']}) data = res.json() forecast_five_days_json = res2.json() forecast_str = "" diff --git a/discord_bot/d_events/logging.py b/discord_bot/d_events/logging.py index 9ed1460..6157fd3 100644 --- a/discord_bot/d_events/logging.py +++ b/discord_bot/d_events/logging.py @@ -10,6 +10,12 @@ async def traceback_logger(bot, discord, message, one_result, guild_result, conn logging_content.add_field(name="Message", value="```" + str(message.author.name) + "#" + str(message.author.discriminator) + ": " + message.content + "```") await bot.get_channel(botconfig['logs_channel']).send(embed=logging_content) + +async def registration_logger(bot, discord, message, one_result, guild_result, connection, cursor, unix_time_millis, botconfig, bot_data_result, e): + logging_content = discord.Embed(title=botconfig['name'] + " Logger", description="`" + str(message.author.name) + "#" + str(message.author.discriminator) + "` passed registation in DB.", color=botconfig['accent1']) + logging_content.add_field(name="Database", value="```S: " + str(guild_result) + "\nU: "+ str(one_result) + "```") + await bot.get_channel(botconfig['logs_channel']).send(embed=logging_content) + async def joining_logger(bot, discord, guild, connection, cursor, unix_time_millis, botconfig): logging_content = discord.Embed(title=botconfig['name'] + " Logger", description="Bot joined the **" + str(guild.name) + "** server! We have " + str(len(bot.guilds)) + " guilds.", color=botconfig['accent1']) logging_content.add_field(name="IDs", value="```S: " + str(guild.id) + "\nO: " + str(guild.owner_id) + "```", inline=False) @@ -21,7 +27,6 @@ async def joining_logger(bot, discord, guild, connection, cursor, unix_time_mill async def leaving_logger(bot, discord, guild, connection, cursor, unix_time_millis, botconfig): logging_content = discord.Embed(title=botconfig['name'] + " Logger", description="Bot left the **" + str(guild.name) + "** server. We have " + str(len(bot.guilds)) + " guilds.", color=botconfig['accent1']) logging_content.add_field(name="IDs", value="```S: " + str(guild.id) + "\nO: " + str(guild.owner_id) + "```", inline=False) - logging_content.add_field(name="Statistics", value="```Owner: " + str(guild.owner.name) + "#" + str(guild.owner.discriminator) + "\nMembers: " + str(guild.member_count) + "\nBoosts: " + str(guild.premium_subscription_count) + "\nChannels: Text - " + str(len(guild.text_channels)) + " | Voice - " + str(len(guild.voice_channels)) + "\nRegion: " + str(guild.region) + "```", inline=False) logging_content.set_thumbnail(url=str(guild.icon_url_as(format=None, static_format="jpeg", size=4096))) await bot.get_channel(botconfig['logs_channel']).send(embed=logging_content) diff --git a/discord_bot/d_events/new_member.py b/discord_bot/d_events/new_member.py index a686c9f..6c523a8 100644 --- a/discord_bot/d_events/new_member.py +++ b/discord_bot/d_events/new_member.py @@ -1,5 +1,11 @@ -async def autorole(bot, discord, member, botconfig, cursor, connection): +import datetime + +async def autorole(bot, discord, member, botconfig, cursor, connection, unix_time_millis): if member.guild.id == 795532426331422730: + newbie_content = discord.Embed(title="Хитро!", description="К сожалению, Вы совсем недавно зарегистрировались в Discord, так как в целях безопасности вход для Вас упразднен. Советуем повторить верификацию через неделю.") + if (unix_time_millis(datetime.datetime.utcnow()) - unix_time_millis(member.created_at)) < 604800000: + await bot.get_channel(795621547946934292).send("<@" + str(member.id) + ">") + return await bot.get_channel(795621547946934292).send(embed=newbie_content) new_member_content = discord.Embed(title=member.name + "#" + str(member.discriminator) + " пришел!", description="Привет! Для сохранения безопасной и комфортной атмосферы советуем прочитать правила в <#795532426331422733> и в окне приветствия. Для согласия нажмите на кнопку \"Выполнено\", затем после 10 минут на реакцию ✅.", color=botconfig['accent1']) await bot.get_channel(795621547946934292).send("<@" + str(member.id) + ">") msg = await bot.get_channel(795621547946934292).send(embed=new_member_content) @@ -11,7 +17,7 @@ async def on_reaction_add(reaction, user): try: await member.add_roles(member.guild.roles[2]) except: - new_member_content = discord.Embed(title="Хорошо...", description="А Вы пока подождите админов, чтобы они руками давали роль участника.", color=botconfig['accent1']) + new_member_content = discord.Embed(title="Хорошо...", description="А Вы пока подождите админов, чтобы они руками давали роль участника.\n\nЕсли заподозрим что-то неладное, администраторы могут в любой момент кикнуть или забанить Вас.", color=botconfig['accent1']) await msg.edit(embed=new_member_content) async def new_member(bot, discord, member, botconfig, cursor, connection): @@ -35,7 +41,7 @@ async def new_member(bot, discord, member, botconfig, cursor, connection): except: pass -async def member_left(bot, discord, member, botconfig, cursor, connection): +async def member_left(bot, discord, member, botconfig, cursor, connection, guild_result): cursor.execute("SELECT * FROM guilds WHERE guildid='" + str(member.guild.id) + "';") guild_result = (cursor.fetchone()) search_results = 0 diff --git a/discord_bot/d_languages/en_US.py b/discord_bot/d_languages/en_US.py index 4824738..7a21306 100644 --- a/discord_bot/d_languages/en_US.py +++ b/discord_bot/d_languages/en_US.py @@ -16,7 +16,7 @@ def get(): ], [ # 1.0.2 'Fun', # 1.0.2.0 - '`photo`, `8ball` (`crystball`)' # 1.0.2.1 + '`photo`, `8ball` (`crystball`), `music`' # 1.0.2.1 ], [ # 1.0.3 'Management', # 1.0.3.0 @@ -24,7 +24,7 @@ def get(): ], [ # 1.0.4 'Miscellaneous', # 1.0.4.0 - '`calc`, `weather`, `codec`, `poll`' # 1.0.4.1 + '`calc`, `weather`, `codec`, `poll`, `rep`, `embed`' # 1.0.4.1 ], '**Prefix:** ' # 1.0.5 ], @@ -50,7 +50,7 @@ def get(): ], [ # 1.2 'Settings', # 1.2.0 - 'To access the desired setting, click on one of the appropriate reactions.\n\n**🗣️ Bot language**\n**🕓 Timezone**\n**🗨️ Messages count**\n**🌈 Custom embed color**\n🚩 **Custom prefix** (beta)\n🏆 **Level system** (beta)\n👋 **Welcome/goodbye messages** (beta)', # 1.2.1 + 'To access the desired setting, click on one of the appropriate reactions.\n\n**🗣️ Bot language**\n**🕓 Timezone**\n**🗨️ Messages count**\n**🌈 Custom embed color**\n🚩 **Custom prefix**\n🏆 **Level system**\n👋 **Welcome/goodbye messages**', # 1.2.1 [ # 1.2.2 'Bot language', # 1.2.2.0 'To change the value, enter the commands below.\n\n**🇷🇺 Russian**\n```{0}set -l ru-RU```\n\n**🇺🇸 English**\n```{0}set -l en-US```' # 1.2.2.1 @@ -225,8 +225,11 @@ def get(): 'Exception caught!\n', # 1.9.3 'You forgot to enter an expression.\n```{0}calc 4 * 58```', # 1.9.4 'In this version of the Calculator you can only perform simple arithmetic operations.', # 1.9.5 - 'Available characters', # 1.9.7 - '`+` - add\n`-` - subtract\n`*` - multiply\n`/` - divide' + 'Available characters', # 1.9.6 + '`+` - add\n`-` - subtract\n`*` - multiply\n`/` - divide', # 1.9.7 + 'Attempt to divide by zero', # 1.9.8 + 'The expression is too large', # 1.9.9 + 'Variables are not accepted', # 1.9.10 ], [ # 1.10 'Feedback', # 1.10.0 @@ -256,7 +259,7 @@ def get(): 'Crystal Ball', # 1.12.0 'Question', # 1.12.1 'He says', # 1.12.2 - 'All matches are random.', # 1.12.3 + 'All matches are random. Think of it as a game, not as a reality.', # 1.12.3 'Error', # 1.12.4 'First ask him a question.' # 1.12.5 ], @@ -283,8 +286,8 @@ def get(): '{0} is a simple and extensible bot from Tinelix. This bot is a replacement for the Highflash bot, which was crude enough to run for monitoring bots. But don\'t worry, the Vision bot has (albeit imperfect) integration with the SQlite3 database, when there was only primitive JSON in Highflash. The bot was written from scratch and took into account the mistakes made during the development of the Highflash bot. It develops not only thanks to you, but also to the author (Tinelix) with its productivity. He can ask you the weather, encrypt or decrypt texts, show random and rather interesting photos from Reddit and Unsplash, play Crystal Ball, etc.'.format(name), # 1.15.1 'Written in', # 1.15.2 'Author', # 1.15.3 - 'Bots Monitoring', # 1.15.4 - '[bots.server-discord.com](https://bots.server-discord.com/785383439196487720)\n[BotiCord](https://boticord.top/bot/785383439196487720)\n[Bots for Discord](https://botsfordiscord.com/bot/785383439196487720)', # 1.15.5 + 'Bots Monitorings', # 1.15.4 + '[bots.server-discord.com](https://bots.server-discord.com/785383439196487720)\n[BotiCord](https://boticord.top/bot/785383439196487720)\n[Bots for Discord](https://botsfordiscord.com/bot/785383439196487720)\n[top.gg](https://top.gg/bot/785383439196487720)\n[discord.bots.gg](https://discord.bots.gg/bots/785383439196487720)', # 1.15.5 'Links', # 1.15.6 '[Invite](https://discord.com/api/oauth2/authorize?client_id=785383439196487720&permissions=8&scope=bot)\n[GitHub](https://github.com/tinelix/visionbot)\n[Our support server](https://discord.gg/HAt6K2QuJU)', # 1.15.7 '[Invite](https://discord.com/oauth2/authorize?client_id=769515555765616690&permissions=8&scope=bot)\n[GitHub](https://github.com/tinelix/visionbot)\n[Our support server](https://discord.gg/HAt6K2QuJU)' @@ -294,13 +297,9 @@ def get(): '', # 1.16.1 'Time has gone! End time: {0}', # 1.16.2 'Polling is over', # 1.16.3 - 'You forgot to supply the required arguments to this or to the command enter arguments as arguments with `[` and `],`. Follow the example below. And yes, between the parentheses, a comma without any spaces is required.\n\n```{0}poll How did you meet 2021? Good or bad? -o [Awesome],[Good],[I don\'t care],[So bad] 2020-01-10=20:00```', # 1.16.4 + 'You forgot to supply the required arguments to this or to the command enter arguments as arguments with `[` and `],`. Follow the example below. And yes, between the parentheses, a comma without any spaces is required.\n\n```{0}poll What do you like the most? -o [90s],[2000s],[2010s],[2020s] 2021-02-12=18:00```', # 1.16.4 'The voting end date must not be earlier than today.' ], - [ # 1.16 - 'Search for a user by discriminator', # 1.16.0 - 'Total results: {0}', # 1.16.1 - ], [ # 1.17 'Reputation', # 1.17.0 'Do you want to promote or demote a person? The selection is made by clicking on the reaction.\n\n👍 **Promote**\n👎 **Demote**', # 1.17.1 @@ -316,6 +315,42 @@ def get(): [ # 1.18 'Congratulations!', # 1.18.0 '{0} has moved to a new level **{1}**! The main thing is to be active.' # 1.18.1 + ], + [ # 1.19 + 'Access denied.' # 1.19.0 + ], + [ # 1.20 + 'Embed messages constructor', # 1.20.0 + 'You forgot to supply the required arguments to this or to the command enter arguments as arguments with `[` and `],`. Follow the example below. And yes, between the parentheses, a comma without any spaces is required.\n\n```{0}embed Text -t [Title],[Footer]```' # 1.20.1 + ], + [ # 1.21 + 'Music player', # 1.21.0 + 'No results found. Try another query.', # 1.21.1 + 'API is temporarily unavailable.', # 1.21.2 + 'Search results', # 1.21.3 + '**Now playing:** {0} ({1}/{2})\n{3} of {4}', # 1.21.4 + 'Queues', # 1.21.5 + 'First join any voice channel, then try again.', # 1.21.6 + 'Listening stopped.', # 1.21.7 + 'Are you sure want to clear the playlist?\nTo confirm, you need to collect 3 reactions.', # 1.21.8 + 'Playlist cleared.', # 1.21.9 + 'Used by the YouTube Data API', # 1.21.10 + 'Something went wrong...', # 1.21.11 + 'Loading {0} of {1} MB...', # 1.21.12 + 'The track should not exceed 30 minutes in duration.', # 1.21.13 + 'To play music, just specify a search query on YouTube.\n\n```{0}music Tobu Cacao```', # 1.21.14 + '**Paused:** {0} ({1}/{2})\n{3} of {4}', # 1.21.15 + 'There is currently no streaming media playback available.', # 1.21.16 + 'There was an error displaying search results. Most likely, this is some kind of issue on the side of the `youtube_search` module. Try searching again.' # 1.21.17 ] ] - ] \ No newline at end of file + ] + +def longdate(): + return ['English', 'January {0}, {1}', 'February {0}, {1}', 'March {0}, {1}', 'April {0}, {1}', 'May {0}, {1}', 'June {0}, {1}', 'July {0}, {1}', 'August {0}, {1}', 'September {0}, {1}', 'October {0}, {1}', 'November {0}, {1}', 'December {0}, {1}'] + +def longdate_without_year(): + return ['English', 'January {0}', 'February {0}', 'March {0}', 'April {0}', 'May {0}', 'June {0}', 'July {0}', 'August {0}', 'September {0}', 'October {0}', 'November {0}', 'December {0}'] + +def shortdate_without_year(): + return ['English', 'Jan {0}', 'Feb {0}', 'Mar {0}', 'Apr {0}', 'May {0}', 'Jun {0}', 'Jul {0}', 'Aug {0}', 'Sep {0}', 'Oct {0}', 'Nov {0}', 'Dec {0}'] \ No newline at end of file diff --git a/discord_bot/d_languages/ru_RU.py b/discord_bot/d_languages/ru_RU.py index 8f2db88..19066ed 100644 --- a/discord_bot/d_languages/ru_RU.py +++ b/discord_bot/d_languages/ru_RU.py @@ -17,7 +17,7 @@ def get(): ], [ # 1.0.2 'Развлечения', # 1.0.2.0 - '`photo`, `8ball` (`crystball`)' + '`photo`, `8ball` (`crystball`), `music`' ], [ 'Служебное', # 1.0.3.0 @@ -51,7 +51,7 @@ def get(): ], [ 'Настройки', - 'Для доступа к нужной настройке нажмите на одну из соотвествующих реакций.\n\n**🗣️ Язык бота (Bot language)**\n**🕓 Часовой пояс**\n**🗨️ Счетчик сообщений**\n**🌈 Свой цвет вложенных сообщений**\n🚩 **Префикс бота** (бета)\n🏆 **Система уровней** (бета)\n👋 **Приветственные/прощальные сообщения** (бета)', + 'Для доступа к нужной настройке нажмите на одну из соотвествующих реакций.\n\n**🗣️ Язык бота (Bot language)**\n**🕓 Часовой пояс**\n**🗨️ Счетчик сообщений**\n**🌈 Свой цвет вложенных сообщений**\n🚩 **Префикс бота**\n🏆 **Система уровней**\n👋 **Приветственные/прощальные сообщения**', [ 'Язык бота (Bot language)', 'Для изменения значения введите команды, которые указаны внизу.\n\n**🇷🇺 Русский**\n```{0}set -l ru-RU```\n\n**🇺🇸 English**\n```{0}set -l en-US```' @@ -230,8 +230,11 @@ def get(): 'Обнаружено исключение!\n', # 1.9.3 'Вы забыли ввести выражение.\n```{0}calc 4 * 58```', # 1.9.4 'В этой версии Калькулятора можно совершать только простые арифметические выражения.', # 1.9.5 - 'Доступные знаки', # 1.9.7 - '`+` - прибавить\n`-` - убавить\n`*` - умножить\n`/` - разделить' # 1.9.8 + 'Доступные знаки', # 1.9.6 + '`+` - прибавить\n`-` - убавить\n`*` - умножить\n`/` - разделить', # 1.9.7 + 'Попытка деления на ноль', # 1.9.8 + 'Выражение слишком большое', # 1.9.9 + 'Переменные не принимаются', # 1.9.10 ], [ # 1.10 'Обратная связь', # 1.10.0 @@ -255,13 +258,13 @@ def get(): 'Ошибка', # 1.11.11 'Не удается найти город или населенный пункт по запросу.\n\nМожет, напишете по-другому?', # 1.11.12 'Код ошибки', # 1.11.13 - 'Вы забыли дописать имя города или населенного пункта.' # 1.11.14 + 'Вы забыли дописать имя города или населенного пункта.\n```{0}weather Москва```' # 1.11.14 ], [ # 1.12 'Магический шар', # 1.12.0 'Вопрос', # 1.12.1 'Он говорит', # 1.12.2 - 'Все совпадения случайны', # 1.12.3 + 'Все совпадения случайны. Воспринимайте как игру, а не как реальность.', # 1.12.3 'Ошибка', # 1.12.4 'Сначала задайте ему вопрос.' # 1.12.5 ], @@ -289,7 +292,7 @@ def get(): 'Написан на', # 1.15.2 'Автор', # 1.15.3 'Мониторинги ботов', # 1.15.4 - '[bots.server-discord.com](https://bots.server-discord.com/785383439196487720)\n[BotiCord](https://boticord.top/bot/785383439196487720)\n[Bots for Discord](https://botsfordiscord.com/bot/785383439196487720)', # 1.15.5 + '[bots.server-discord.com](https://bots.server-discord.com/785383439196487720)\n[BotiCord](https://boticord.top/bot/785383439196487720)\n[Bots for Discord](https://botsfordiscord.com/bot/785383439196487720)\n[top.gg](https://top.gg/bot/785383439196487720)\n[discord.bots.gg](https://discord.bots.gg/bots/785383439196487720)', # 1.15.5 'Ссылки', # 1.15.5 '[Пригласить бота](https://discord.com/api/oauth2/authorize?client_id=785383439196487720&permissions=8&scope=bot)\n[GitHub](https://github.com/tinelix/visionbot)\n[ВКонтакте](https://vk.com/tinelix)\n[YouTube](https://www.youtube.com/channel/UCSPjn_Y0pLdPy6Ncb9NAdww)\n[Наш саппорт-сервер](https://discord.gg/HAt6K2QuJU)', # 1.15.6 '[Пригласить бота](https://discord.com/oauth2/authorize?client_id=769515555765616690&permissions=8&scope=bot)\n[GitHub](https://github.com/tinelix/visionbot)\n[ВКонтакте](https://vk.com/tinelix)\n[YouTube](https://www.youtube.com/channel/UCSPjn_Y0pLdPy6Ncb9NAdww)\n[Наш саппорт-сервер](https://discord.gg/HAt6K2QuJU)' @@ -299,7 +302,7 @@ def get(): 'Вести это голосование могут только администраторы сервера.', # 1.16.1 'Время пошло! Время окончания: {0}', # 1.16.2 'Голосование закончено.', # 1.16.3 - 'Вы забыли указать требуемые аргументы к этой команде или разделить аргументы знаками `[` и `],`. Следуйте примером внизу. И да, между скобками запятая без каких-либо пробелов обязательна.\n\n```{0}poll Как встретили 2021 год? Хорошо или плохо? -o [Отлично],[Хорошо],[А мне все равно],[Ужасно] 2020-01-10=20:00```', # 1.16.4 + 'Вы забыли указать требуемые аргументы к этой команде или разделить аргументы знаками `[` и `],`. Следуйте примером внизу. И да, между скобками запятая без каких-либо пробелов обязательна.\n\n```{0}poll Что Вам нравится больше всего? -o [90-е],[2000-е],[2010-е],[2020-е] 2021-02-12=18:00```', # 1.16.4 'Дата окончания голосования не должна быть раньше, чем сегодняшняя.' ], [ # 1.17 @@ -317,6 +320,40 @@ def get(): [ # 1.18 'Поздравляем!', '{0} перешел на новый уровень **{1}**! Главное - проявлять активность.' + ], + [ 'Доступ запрещен.'], + [ + 'Конструктор вложенных сообщений', + 'Вы забыли указать требуемые аргументы к этой команде или разделить аргументы знаками `[` и `],` Следуйте пример внизу. И да, между скобками запятая без каких-либо пробелов обязательна.\n\n```{0}embed Текст -t [Заголовок],[Футер]```' + ], + [ # 1.21 + 'Музыкальный плеер', # 1.21.0 + 'Не найдено результатов по Вашему запросу. Попробуйте другой запрос.', # 1.21.1 + 'API временно недоступен.', # 1.21.2 + 'Результаты поиска', # 1.21.3 + '**Сейчас играет:** {0} ({1}/{2})\n {3} из {4}', # 1.21.4 + 'Очереди', # 1.21.5 + 'Сначала присоединяйтесь к любому голосовому каналу, а затем повторите попытку.', # 1.21.6 + 'Прослушивание остановлено.', # 1.21.7 + 'Вы действительно хотите очистить плейлист?\nДля подтверждения нужно собрать 3 реакции.', + 'Плейлист очищен.', + 'Используется YouTube Data API', + 'Что-то пошло не так...', + 'Загрузка {0} из {1} МБ...', + 'Трек не должен превышать 30 минут в длительности.', + 'Для воспроизведения музыки достаточно указать запрос поиска на YouTube.\n\n```{0}music Tobu Cacao```', + '**Пауза:** {0} ({1}/{2})\n{3} из {4}', + 'На данный момент воспроизведение потокового мультимедиа недоступно.', + 'Произошла ошибка с выводом результатов поиска. Скорее всего, это какая-то проблема на стороне модуля `youtube_search`. Попробуйте поискать еще раз.' ] ] ] + +def longdate(): + return ['Russian', '{0} января {1} г.', '{0} февраля {1} г.', '{0} марта {1} г.', '{0} апреля {1} г.', '{0} мая {1} г.', '{0} июня {1} г.', '{0} июля {1} г.', '{0} августа {1} г.', '{0} сентября {1} г.', '{0} октября {1} г.', '{0} ноября {1} г.', '{0} декабря {1} г.'] + +def longdate_without_year(): + return ['Russian', '{0} января', '{0} февраля', '{0} марта', '{0} апреля', '{0} мая', '{0} июня', '{0} июля', '{0} августа', '{0} сентября', '{0} октября', '{0} ноября', '{0} декабря'] + +def shortdate_without_year(): + return ['Russian', '{0} янв.', '{0} фев.', '{0} мар.', '{0} апр.', '{0} мая', '{0} июн.', '{0} июл.', '{0} авг.', '{0} сен.', '{0} окт.', '{0} ноя.', '{0} дек.'] \ No newline at end of file diff --git a/discord_bot/discord_botconfig.py b/discord_bot/discord_botconfig.py index 3fd3f29..6b3b817 100644 --- a/discord_bot/discord_botconfig.py +++ b/discord_bot/discord_botconfig.py @@ -12,10 +12,10 @@ 'accent1': 0xd7832a, 'accent2': 0xcb3532, 'accent3': 0x6eda5f, - 'version': '01R8-210123', + 'version': '01R9-210221', 'owner': '741883312108339231', 'logs_channel': 788723868255649832, 'unsplash_ak': os.environ['UNSAKEY'], 'unsplash_sk': os.environ['UNSSKEY'], - 'unsplash_ur': os.environ['UNSRDC'] + 'unsplash_ur': os.environ['UNSRDC'], }