def init(): global connection connection = MySQLDatabase( Configuration.getMasterConfigVar("DATABASE_NAME"), user=Configuration.getMasterConfigVar("DATABASE_USER"), password=Configuration.getMasterConfigVar("DATABASE_PASS"), host=Configuration.getMasterConfigVar("DATABASE_HOST"), port=Configuration.getMasterConfigVar("DATABASE_PORT"), use_unicode=True, charset="utf8mb4") connection.connect() connection.create_tables( [LoggedMessage, CustomCommand, LoggedAttachment, Infraction]) connection.close()
async def on_ready(): if not bot.STARTUP_COMPLETE: await Util.readyBot(bot) Emoji.on_ready(bot) Utils.on_ready(bot) Translator.on_ready(bot) bot.loop.create_task( keepDBalive()) # ping DB every hour so it doesn't run off #shutdown handler for clean exit on linux try: for signame in ('SIGINT', 'SIGTERM'): asyncio.get_event_loop().add_signal_handler( getattr(signal, signame), lambda: asyncio.ensure_future( Utils.cleanExit(bot, signame))) except Exception: pass #doesn't work on windows bot.aiosession = aiohttp.ClientSession() bot.start_time = datetime.datetime.utcnow() GearbotLogging.info("Loading cogs...") for extension in extensions: try: bot.load_extension("Cogs." + extension) except Exception as e: GearbotLogging.exception( f"Failed to load extention {extension}", e) GearbotLogging.info("Cogs loaded") if Configuration.getMasterConfigVar("CROWDIN_KEY") is not None: bot.loop.create_task(translation_task()) bot.STARTUP_COMPLETE = True await bot.change_presence( activity=discord.Activity(type=3, name='the gears turn'))
async def update(): await GearbotLogging.logToBotlog( f"{Emoji.get_chat_emoji('REFRESH')} Updating translations") project_key = Configuration.getMasterConfigVar("CROWDIN_KEY") session: aiohttp.ClientSession = bot.aiosession async with session.get( f"https://api.crowdin.com/api/project/Gearbot/export?key={project_key}&json", ) as reply: if reply.status is not 200: await GearbotLogging.logToBotlog( f"{Emoji.get_chat_emoji('WARNING')} Crowdin api error, got response code {reply.status}" ) else: response = await reply.json() if response["success"][ "status"] == "built": # only update translations if we actually got a new build, should be every time though unless this runs 2x within 30 mins for some reason async with session.get( f"https://api.crowdin.com/api/project/Gearbot/download/all.zip?key={project_key}" ) as reply: data = await reply.read() with open("zip.zip", "wb") as file: file.write(data) with zipfile.ZipFile("zip.zip", "r") as archive: tempdir = os.path.abspath("temp") if os.path.isdir(tempdir): shutil.rmtree(tempdir, ignore_errors=True) os.mkdir(tempdir) archive.extractall("temp") for entry in archive.filelist: if not entry.filename.endswith(".json"): continue filename = entry.filename[-10:] if os.path.isfile( os.path.abspath(f"lang/{filename}")): os.remove(os.path.abspath(f"lang/{filename}")) archive.extract(entry, tempdir) os.rename( os.path.abspath(f"temp/{entry.filename}"), os.path.abspath(f"lang/{filename}")) shutil.rmtree("temp", ignore_errors=True) load_translations() await GearbotLogging.logToBotlog( f"{Emoji.get_chat_emoji('YES')} Translations have been updated" ) else: await GearbotLogging.logToBotlog( f"{Emoji.get_chat_emoji('WARNING')} Crowdin build status was `{response['success']['status']}`, no translation update required" )
async def on_raw_message_edit(self, event: RawMessageUpdateEvent): if event.data["channel_id"] == Configuration.getMasterConfigVar( "BOT_LOG_CHANNEL"): return message = LoggedMessage.get_or_none(messageid=event.message_id) if message is not None and "content" in event.data: channel: discord.TextChannel = self.bot.get_channel( int(event.data["channel_id"])) user: discord.User = self.bot.get_user(message.author) hasUser = user is not None channelid = Configuration.getConfigVar(channel.guild.id, "MINOR_LOGS") if channelid is not 0: logChannel: discord.TextChannel = self.bot.get_channel( channelid) if logChannel is not None: if message.content == event.data["content"]: #prob just pinned return if message.content is None or message.content == "": message.content = f"<{Translator.translate('no_content', channel.guild.id)}>" embed = discord.Embed(timestamp=datetime.datetime. utcfromtimestamp(time.time())) embed.set_author( name=user.name if hasUser else message.author, icon_url=user.avatar_url if hasUser else EmptyEmbed) embed.set_footer( text=Translator.translate('sent_in', channel.guild.id, channel=f"#{channel.name}")) embed.add_field( name=Translator.translate('before', channel.guild.id), value=Utils.trim_message(message.content, 1024), inline=False) embed.add_field( name=Translator.translate('after', channel.guild.id), value=Utils.trim_message(event.data["content"], 1024), inline=False) if not (hasUser and user.id in Configuration.getConfigVar( channel.guild.id, "IGNORED_USERS")): await logChannel.send( f":pencil: {Translator.translate('edit_logging', channel.guild.id, user=Utils.clean_user(user), user_id=user.id, channel=channel.mention)}", embed=embed) message.content = event.data["content"] message.save()
async def sync_guides(bot): category = bot.get_channel(Configuration.getMasterConfigVar("GUIDES")) if category is not None: guide_hashes = Utils.fetchFromDisk("guide_hashes") for channel in category.channels: if isinstance(channel, discord.TextChannel): name = channel.name if os.path.isfile(f"docs/Guides/{name}.md") or os.path.isfile( f"../docs/Guides/{name}.md"): GearbotLogging.info( f"Found guide {name}, verifying file hash...") h = hashlib.md5( open(f"docs/Guides/{name}.md", 'rb').read()).hexdigest() if not name in guide_hashes or guide_hashes[name] != h: GearbotLogging.info( f"Guide {name} is outdated, updating...") guide_hashes[name] = h with open(f"docs/Guides/{name}.md", 'r') as file: buffer = "" await channel.purge() for line in file.readlines(): while line.startswith('#'): line = line[1:] match = image_pattern.search(line) if match is None: buffer += f"{line}" else: if buffer != "": await send_buffer(channel, buffer) await channel.send(file=discord.File( f"docs/{match.group(2)}")) buffer = match.group(3) await send_buffer(channel, buffer) else: GearbotLogging.info( f"Found guide channel {name} but file for it!") Utils.saveToDisk("guide_hashes", guide_hashes)
from peewee import * from Util import Configuration connection = MySQLDatabase( Configuration.getMasterConfigVar("DATABASE_NAME"), user=Configuration.getMasterConfigVar("DATABASE_USER"), password=Configuration.getMasterConfigVar("DATABASE_PASS"), host=Configuration.getMasterConfigVar("DATABASE_HOST"), port=Configuration.getMasterConfigVar("DATABASE_PORT"), use_unicode=True, charset="utf8mb4") class LoggedMessage(Model): messageid = BigIntegerField(primary_key=True) content = CharField(max_length=2048, collation="utf8mb4_general_ci", null=True) author = BigIntegerField() timestamp = FloatField() channel = BigIntegerField() server = BigIntegerField() class Meta: database = connection class LoggedAttachment(Model): id = BigIntegerField(primary_key=True) url = CharField()
def on_ready(bot): for name, eid in Configuration.getMasterConfigVar("EMOJI").items(): emojis[name] = utils.get(bot.emojis, id=eid)
action='store_true') parser.add_argument("--token", help="Specify your Discord token") logger = logging.getLogger('discord') logger.setLevel(logging.INFO) handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w+') handler.setFormatter( logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) GearbotLogging.init_logger() clargs = parser.parse_args() if 'gearbotlogin' in os.environ: token = os.environ['gearbotlogin'] elif clargs.token: token = clargs.token elif not Configuration.getMasterConfigVar("LOGIN_TOKEN", "0") is "0": token = Configuration.getMasterConfigVar("LOGIN_TOKEN") else: token = input("Please enter your Discord token: ") bot.remove_command("help") Util.prepDatabase(bot) GearbotLogging.info("Ready to go, spinning up the gears") bot.run(token) GearbotLogging.info("GearBot shutting down, cleaning up") bot.database_connection.close() GearbotLogging.info("Cleanup complete")
def upload_file(): data = {'files[master/lang/en_US.json]': open('lang/en_US.json', 'r')} project_key = Configuration.getMasterConfigVar("CROWDIN_KEY") requests.post( f"https://api.crowdin.com/api/project/gearbot/update-file?key={project_key}&json", files=data)