You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

184 lines
6.5 KiB

import os
import sys
import logging
import logging.handlers
import traceback
import aiohttp
import config
import discord
from discord.ext import commands
script_name = os.path.basename(__file__).split('.')[0]
log_file_name = f"{script_name}.log"
# Limit of discord (non-nitro) is 8MB (not MiB)
max_file_size = 1000 * 1000 * 8
backup_count = 3
file_handler = logging.handlers.RotatingFileHandler(
filename=log_file_name, maxBytes=max_file_size, backupCount=backup_count)
stdout_handler = logging.StreamHandler(sys.stdout)
log_format = logging.Formatter(
'[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s')
log = logging.getLogger('discord')
def get_prefix(bot, message):
prefixes = config.prefixes
return commands.when_mentioned_or(*prefixes)(bot, message)
wanted_jsons = ["data/restrictions.json",
initial_extensions = ['cogs.common',
bot = commands.Bot(command_prefix=get_prefix,
description=config.bot_description, pm_help=True)
bot.log = log
bot.config = config
bot.script_name = script_name
bot.wanted_jsons = wanted_jsons
if __name__ == '__main__':
for extension in initial_extensions:
except Exception as e:
log.error(f'Failed to load extension {extension}.', file=sys.stderr)
async def on_ready():
aioh = {"User-Agent": f"{script_name}/1.0'"}
bot.aiosession = aiohttp.ClientSession(headers=aioh)
bot.app_info = await bot.application_info()'\nLogged in as: {} - '
f'{}\ndpy version: {discord.__version__}\n')
game_name = f"{config.prefixes[0]}help"
# Send "Robocop has started! x has y members!"
log_channel = bot.get_channel(config.log_channel)
guild = log_channel.guild
msg = f"{} has started! "\
f"{} has {guild.member_count} members!"
config_files = [discord.File(fpath) for fpath in wanted_jsons]
await log_channel.send(msg, files=config_files)
await bot.change_presence(activity=discord.Game(name=game_name))
async def on_command(ctx):
log_text = f"{} ({}): "\
f"\"{ctx.message.content}\" "
if ctx.guild: # was too long for tertiary if
log_text += f"on \"{}\" ({}) "\
f"at \"{}\" ({})"
log_text += f"on DMs ({})"
async def on_error(event_method, *args, **kwargs):
log.error(f"Error on {event_method}: {sys.exc_info()}")
async def on_command_error(ctx, error):
error_text = str(error)
log.error(f"Error with \"{ctx.message.content}\" from "
f"\"{} ({}) "
f"of type {type(error)}: {error_text}")
if isinstance(error, commands.NoPrivateMessage):
return await ctx.send("This command doesn't work on DMs.")
elif isinstance(error, commands.MissingPermissions):
roles_needed = '\n- '.join(error.missing_perms)
return await ctx.send(f"{}: You don't have the right"
" permissions to run this command. You need: "
f"```- {roles_needed}```")
elif isinstance(error, commands.BotMissingPermissions):
roles_needed = '\n-'.join(error.missing_perms)
return await ctx.send(f"{}: Bot doesn't have "
"the right permissions to run this command. "
"Please add the following roles: "
f"```- {roles_needed}```")
elif isinstance(error, commands.CommandOnCooldown):
return await ctx.send(f"{}: You're being "
"ratelimited. Try in "
f"{error.retry_after:.1f} seconds.")
elif isinstance(error, commands.CheckFailure):
return await ctx.send(f"{}: Check failed. "
"You might not have the right permissions "
"to run this command.")
elif isinstance(error, commands.CommandInvokeError) and\
("Cannot send messages to this user" in error_text):
return await ctx.send(f"{}: I can't DM you.\n"
"You might have me blocked or have DMs "
f"blocked globally or for {}.\n"
"Please resolve that, then "
"run the command again.")
elif isinstance(error, commands.CommandNotFound):
# Nothing to do when command is not found.
help_text = f"Usage of this command is: ```{ctx.prefix}"\
f"{ctx.command.signature}```\nPlease see `{ctx.prefix}help "\
f"{}` for more info about this command."
if isinstance(error, commands.BadArgument):
return await ctx.send(f"{}: You gave incorrect "
f"arguments. {help_text}")
elif isinstance(error, commands.MissingRequiredArgument):
return await ctx.send(f"{}: You gave incomplete "
f"arguments. {help_text}")
async def on_message(message):
if (message.guild) and ( not in config.guild_whitelist):
ctx = await bot.get_context(message)
await bot.invoke(ctx)
if not os.path.exists("data"):
for wanted_json in wanted_jsons:
if not os.path.exists(wanted_json):
with open(wanted_json, "w") as f:
f.write("{}"), bot=True, reconnect=True)