def root(stream_log): bot = Bot() logging.getLogger('discord').setLevel(logging.INFO) log_dir = Path(os.path.dirname(__file__)).parent / 'logs' log_dir.mkdir(exist_ok=True) logger = logging.getLogger() logger.setLevel(logging.INFO) file_handler = logging.FileHandler( filename= f'../logs/2b-py.{datetime.now().strftime("%d%m%y-%H%M%S")}.log', encoding='utf-8', mode='w') formatter = logging.Formatter( '[{levelname}] ({asctime}) - {name}:{lineno} - {message}', '%Y-%m-%d %H:%M:%S', style='{') file_handler.setFormatter(formatter) logger.addHandler(file_handler) if stream_log: stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) try: bot.run() except KeyboardInterrupt: bot.loop.create_task(bot.logout())
def start(): start_time = time.time() bot = Bot() module_manager = ModuleManager() logger.log( 2, "Starting %s bot with %s %s" % (colored("Fusion", "magenta"), colored("Discord API", "blue"), colored("v" + discord.__version__, "green"))) logger.info("Setting up django") django.setup() logger.info( "Loading modules from \"%s\" and \"core/modules\" directories" % modules_dir) load_modules_from_dir("core/modules", ignore={"TemplateModule"}) load_modules_from_dir(modules_dir) module_manager.initialize(bot) logger.info("Setting up django models") for app in INSTALLED_APPS: call_command("makemigrations", app.split(".")[-1:][0]) call_command("migrate") logger.info("Connecting to discord") @bot.event async def on_ready(): logger.info("Logged into Discord as \"%s\"." % bot.user.name) logger.info("Running modules..") await module_manager.run_modules(bot) logger.info("Deploying threads and starting protocol processing") core.protocol.deploy() print("") logger.log( 2, "INIT FINISHED! (took %ss)" % math.floor(time.time() - start_time)) logger.log(2, "Loaded Modules: %s" % module_manager.modules_count) logger.log(2, "Loaded Commands: %s" % module_manager.commands_count) logger.log( 2, "Listening %s:%s" % (listen_ip if listen_ip != "" else "0.0.0.0", listen_port)) print("") @bot.event async def on_message(message: discord.Message): for mod in sorted(module_manager.modules.values(), key=lambda x: x.on_message.priority): await mod.on_message(message, bot) if not message.content.startswith(cmd_prefix): return if message.author.bot: return args = message.content.split() cmd = args.pop(0)[len(cmd_prefix):].lower() if cmd not in module_manager.commands: # await bot.send_error_embed(message.channel, "Команда \"%s\" не найдена." % cmd, # "Команда не найдена") return command = module_manager.commands[cmd] if command.guild_lock and message.guild.id not in command.guild_lock: await bot.send_error_embed( message.channel, "Команда \"%s\" недоступна на данном сервере." % cmd, "Команда не найдена") return logger.info( "Выполнение команды %s от %s (%s)." % (repr(message.content), str(message.author), message.author.id)) try: args_1, keys = parse(args) if not module_manager.check_permissions(message.author.guild_permissions, command.permissions) \ or not module_manager.check_sp_permissions(message.author.id, command.future_permissions): embed: discord.Embed = bot.get_error_embed( "У вас недостаточно прав для выполнения данной команды", "Нет прав!") required_perms = "\n".join( perm.special_name for perm in sorted(command.permissions, key=lambda x: x.value) + sorted(command.future_permissions, key=lambda x: x.value)) embed.add_field(name="Необходимые права:", value=required_perms) await message.channel.send(embed=embed) await message.add_reaction(emoji_warn) return async with message.channel.typing(): result = await command.execute(message, args_1, keys) except ParseError as e: await message.add_reaction(emoji_warn) await bot.send_error_embed(message.channel, str(e), "Ошибка разбора аргументов") except discord.Forbidden: await message.add_reaction(emoji_error) await bot.send_error_embed(message.channel, "У бота нет прав!") except AccessDeniedException: await message.add_reaction(emoji_warn) await bot.send_error_embed( message.channel, "У вас недостаточно прав для выполнения данной команды", "Нет прав!") except CommandException as e: await message.add_reaction(emoji_warn) await bot.send_error_embed(message.channel, str(e), e.title) except OpenComputersError as e: await bot.send_error_embed(message.channel, "```\n%s\n```" % str(e), "⚠ Криворукий уебан, у тебя ошибка! ⚠") await message.add_reaction(emoji_error) except Exception: await bot.send_error_embed(message.channel, "```\n%s\n```" % traceback.format_exc(), "⚠ Криворукий уебан, у тебя ошибка! ⚠") await message.add_reaction(emoji_error) else: if result == CommandResult.success: await message.add_reaction(emoji_ok) elif result == CommandResult.arguments_insufficient: embed: discord.Embed = bot.get_error_embed( title="Недостаточно аргументов!") embed.add_field(name="%s%s %s" % (cmd_prefix, command.name, command.arguments), value=command.description) await message.channel.send(embed=embed) await message.add_reaction(emoji_warn) @bot.event async def on_message_delete(message: discord.Message): for _, mod in list(module_manager.modules.items()): await mod.on_message_delete(message, bot) @bot.event async def on_message_edit(before: discord.Message, after: discord.Message): for _, mod in list(module_manager.modules.items()): await mod.on_message_edit(before, after, bot) @bot.event async def on_member_remove(member: discord.Member): for _, mod in list(module_manager.modules.items()): await mod.on_member_remove(member, bot) @bot.event async def on_member_join(member: discord.Member): for _, mod in list(module_manager.modules.items()): await mod.on_member_join(member, bot) bot.run(discord_token)
def main(): logging.basicConfig(level=logging.WARN) bot = Bot(settings=settings) bot.run()
import sys import time import discord from keys import token from core.bot import Bot def check_versions(): dv = discord.__version__.split(".") pv = sys.version_info discord_version = (int(dv[0]), int(dv[1]), int(dv[2])) python_version = (pv.major, pv.minor, pv.micro) if not discord_version >= (1, 2, 0) and not python_version >= (3, 6, 0): return False return True if __name__ == '__main__': if not check_versions(): print( "Please check the versions of python and discord. You need Python 3.6+ and Discord rewrite version 1.2+" ) time.sleep(10) exit() bot = Bot() bot.run(token)
"""Main bot module.""" import logging from core.bot import Bot from settings import settings from settings.settings import DEBUG instance = Bot() logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG if DEBUG else logging.INFO) # Register on ready event. @instance.event async def on_ready() -> None: """Notify that bot is ready.""" logger.info('Bot is now running.') # Load bot extensions. instance.load_extension('extensions.owner') instance.load_extension('extensions.publicroles') instance.load_extension('extensions.mod') instance.load_extension('extensions.autorole') instance.load_extension('extensions.welcome') # Run the bot. instance.run(settings.DISCORD_TOKEN, bot=True, reconnect=True)