async def on_guild_join(bot, guild: Guild): blocked = Configuration.get_persistent_var("server_blocklist", []) if guild.id in blocked: GearbotLogging.info( f"Someone tried to add me to blocked guild {guild.name} ({guild.id})" ) try: await guild.owner.send( "Someone tried adding me to {guild.name} (``{guild.id}``) but the server has been blocked" ) except Exception: pass await guild.leave() elif guild.owner_id in Configuration.get_persistent_var( "user_blocklist", []): GearbotLogging.info( f"Someone tried to add me to {Utils.clean(guild.name)} ({guild.id}) but the owner ({guild.owner} ({guild.owner_id})) is blocked" ) try: await (await bot.fetch_user(guild.owner_id)).send( f"Someone tried adding me to {guild.name} (``{guild.id}``) but you have been blocked due to bot abuse, so i left" ) except Exception: pass await guild.leave() else: bot.missing_guilds.add(guild.id) await guild.chunk(cache=True) bot.missing_guilds.remove(guild.id) GearbotLogging.info(f"A new guild came up: {guild.name} ({guild.id}).") Configuration.load_config(guild.id) name = await Utils.clean(guild.name) await GearbotLogging.bot_log( f"{Emoji.get_chat_emoji('JOIN')} A new guild came up: {name} ({guild.id}).", embed=server_info.server_info_embed(guild))
async def on_guild_remove(guild): blocked = Configuration.get_persistent_var("server_blocklist", []) blocked_users = Configuration.get_persistent_var("user_blocklist", []) if guild.id not in blocked and guild.owner_id not in blocked_users: GearbotLogging.info( f"I was removed from a guild: {guild.name} ({guild.id}).") await GearbotLogging.bot_log( f"{Emoji.get_chat_emoji('LEAVE')} I was removed from a guild: {guild.name} ({guild.id}).", embed=server_info.server_info_embed(guild))
async def on_guild_join(bot, guild: Guild): blocked = Configuration.get_persistent_var("server_blocklist", []) if guild.id in blocked: await guild.leave() await GearbotLogging.bot_log(f"Someone tried to add me to blocked guild {await Utils.clean(guild.name)} ({guild.id})") elif guild.owner_id in Configuration.get_persistent_var("user_blocklist", []): await guild.leave() await GearbotLogging.bot_log(f"Someone tried to add me to {await Utils.clean(guild.name)} ({guild.id}) but the owner {guild.owner_id} is blocked") else: GearbotLogging.info(f"A new guild came up: {guild.name} ({guild.id}).") Configuration.load_config(guild.id) name = await Utils.clean(guild.name) await guild.chunk(cache=True) await GearbotLogging.bot_log(f"{Emoji.get_chat_emoji('JOIN')} A new guild came up: {name} ({guild.id}).", embed=ServerInfo.server_info_embed(guild))
async def on_message(bot, message: Message): if message.author.bot: if message.author.id == bot.user.id: bot.self_messages += 1 else: bot.bot_messages += 1 return ctx: commands.Context = await bot.get_context(message) bot.user_messages += 1 if ctx.valid and ctx.command is not None: bot.commandCount = bot.commandCount + 1 if isinstance(ctx.channel, TextChannel) and not ctx.channel.permissions_for( ctx.channel.guild.me).send_messages: try: await ctx.author.send( "Hey, you tried triggering a command in a channel I'm not allowed to send messages in. Please grant me permissions to reply and try again." ) except Forbidden: pass # closed DMs elif ctx.author.id in Configuration.get_persistent_var( "user_blocklist", []): try: await MessageUtils.send_to( ctx, "BAD_USER", "You have been globally blocked from using this bot due to abuse", translate=False) except Forbidden: pass # closed DMs else: await bot.invoke(ctx)
async def on_message(self, message: discord.Message): if message.author.bot or message.webhook_id is not None: return if message.author.id in Configuration.get_persistent_var( "user_blocklist", []): return if not hasattr(message.channel, "guild") or message.channel.guild is None: return me = message.guild.me if me is None: message.guild.fetch_member(self.bot.user.id) permissions = message.channel.permissions_for(me) if not (permissions.read_messages and permissions.send_messages and permissions.embed_links): return role_list = Configuration.get_var(message.guild.id, "CUSTOM_COMMANDS", "ROLES") role_required = Configuration.get_var(message.guild.id, "CUSTOM_COMMANDS", "ROLE_REQUIRED") channel_list = Configuration.get_var(message.guild.id, "CUSTOM_COMMANDS", "CHANNELS") channels_ignored = Configuration.get_var(message.guild.id, "CUSTOM_COMMANDS", "CHANNELS_IGNORED") mod_bypass = Configuration.get_var(message.guild.id, "CUSTOM_COMMANDS", "MOD_BYPASS") is_mod = message.author is not None and Permissioncheckers.is_mod( message.author) if (message.channel.id in channel_list) is channels_ignored and not ( is_mod and mod_bypass): return has_role = False if message.author is not None and hasattr(message.author, "roles"): for role in message.author.roles: if role.id in role_list: has_role = True break if has_role is not role_required and not (is_mod and mod_bypass): return prefix = Configuration.get_var(message.guild.id, "GENERAL", "PREFIX") if message.content.startswith(prefix, 0) and message.guild.id in self.commands: for trigger in self.commands[message.guild.id]: if message.content.lower() == prefix + trigger or ( message.content.lower().startswith( trigger, len(prefix)) and message.content.lower()[len(prefix + trigger)] == " "): command_content = self.commands[ message.guild.id][trigger].replace("@", "@\u200b") await message.channel.send(command_content) self.bot.custom_command_count += 1
async def block_server(self, ctx, guild: Guild): blocked = Configuration.get_persistent_var("server_blocklist", []) blocked.append(guild.id) Configuration.set_persistent_var("server_blocklist", blocked) await guild.leave() await MessageUtils.send_to(ctx, "YES", f"{Utils.escape_markdown(guild.name)} (``{guild.id}``) has been added to the blocked servers list", translate=False) await GearbotLogging.bot_log( f"{Utils.escape_markdown(guild.name)} (``{guild.id}``) has been added to the blocked server list by {Utils.clean_user(ctx.author)}")
async def block_user(self, ctx, user:DiscordUser): for guild in self.bot.guilds: if guild.owner is not None and guild.owner.id == user.id: await guild.leave() blocked = Configuration.get_persistent_var("user_blocklist", []) blocked.append(user.id) Configuration.set_persistent_var("user_blocklist", blocked) await MessageUtils.send_to(ctx, "YES", f"{Utils.clean_user(user)} (``{user.id}``) has been added to the blocked users list", translate=False) await GearbotLogging.bot_log(f"{Utils.clean_user(user)} (``{user.id}``) has been added to the blocked users list by {Utils.clean_user(ctx.author)}")
async def on_guild_update(before, after): if after.owner is not None and after.owner.id in Configuration.get_persistent_var("user_blacklist", []): GearbotLogging.info( f"Someone transferred {after.name} ({after.id}) to ({after.owner} ({after.owner.id})) but they are blacklisted") try: await after.owner.send(f"Someone transferred {after.name} (``{after.id}``) to you, but you have been blacklisted due to bot abuse, so i left") except Exception: pass await after.leave()
async def blacklist(self, ctx, guild: Guild): blocked = Configuration.get_persistent_var("blacklist", []) blocked.append(guild.id) Configuration.set_persistent_var("blacklist", blocked) await guild.leave() await MessageUtils.send_to( ctx, "YES", f"{Utils.escape_markdown(guild.name)} (``{guild.id}``) has been added to the blacklist", translate=False)
async def upload(): new = hashlib.md5(open(f"lang/en_US.json", 'rb').read()).hexdigest() old = Configuration.get_persistent_var('lang_hash', '') if old == new: return Configuration.set_persistent_var('lang_hash', new) message = await tranlator_log('REFRESH', 'Uploading translation file') t = threading.Thread(target=upload_file) t.start() while t.is_alive(): await asyncio.sleep(1) await message.edit(content=f"{Emoji.get_chat_emoji('YES')} Translations file has been uploaded") await update_all()
async def upload(): t_info = Configuration.get_master_var("TRANSLATIONS", dict(SOURCE="SITE", CHANNEL=0, KEY="", LOGIN="", WEBROOT="")) if t_info["SOURCE"] == "DISABLED": return new = hashlib.md5(open(f"lang/en_US.json", 'rb').read()).hexdigest() old = Configuration.get_persistent_var('lang_hash', '') if old == new: return Configuration.set_persistent_var('lang_hash', new) message = await tranlator_log('REFRESH', 'Uploading translation file') t = threading.Thread(target=upload_file) t.start() while t.is_alive(): await asyncio.sleep(1) await message.edit(content=f"{Emoji.get_chat_emoji('YES')} Translations file has been uploaded") await update_all()
async def on_message(bot, message:Message): if message.author.bot: if message.author.id == bot.user.id: bot.self_messages += 1 else: bot.bot_messages += 1 return ctx: commands.Context = await bot.get_context(message) bot.user_messages += 1 if ctx.valid and ctx.command is not None: bot.commandCount += 1 if isinstance(ctx.channel, TextChannel) and not ctx.channel.permissions_for(ctx.channel.guild.me).send_messages: try: await ctx.author.send("Hey, you tried triggering a command in a channel I'm not allowed to send messages in. Please grant me permissions to reply and try again.") except Forbidden: pass # closed DMs return if ctx.author.id in Configuration.get_persistent_var("user_blocklist", []): return await bot.invoke(ctx)
async def on_guild_join(guild): blocked = Configuration.get_persistent_var("blacklist", []) if guild.id in blocked: GearbotLogging.info( f"Someone tried to add me to blacklisted guild {guild.name} ({guild.id})" ) try: await guild.owner.send( "Someone tried adding me to {guild.name} (``{guild.id}``) but the server has been blacklisted" ) except Exception: pass await guild.leave() else: GearbotLogging.info(f"A new guild came up: {guild.name} ({guild.id}).") Configuration.load_config(guild.id) name = await Utils.clean(guild.name) await GearbotLogging.bot_log( f"{Emoji.get_chat_emoji('JOIN')} A new guild came up: {name} ({guild.id}).", embed=server_info.server_info(guild))
async def on_message(self, message: discord.Message): if message.guild is not None or len( message.content ) > 1800 or message.author.id == self.bot.user.id: return if message.author.id in Configuration.get_persistent_var( "user_blocklist", []): return ctx: commands.Context = await self.bot.get_context(message) if ctx.command is not None: return channel = self.bot.get_channel(Configuration.get_master_var( "inbox", 0)) if channel is None: return await channel.send( f"[`{message.created_at.strftime('%c')}`] {message.author} (`{message.author.id}`) said: {message.clean_content}" ) for attachement in message.attachments: await channel.send(attachement.url)
async def updater(cog: BCVersionChecker): GearbotLogging.info("Started BC version checking background task") session: aiohttp.ClientSession = cog.bot.aiosession lastUpdate = 0 while cog.running: try: # check for a newer bc version async with session.get( 'https://www.mod-buildcraft.com/build_info_full/last_change.txt' ) as reply: stamp = await reply.text() stamp = int(stamp[:-1]) if stamp > lastUpdate: GearbotLogging.info("New BC version somewhere!") lastUpdate = stamp cog.BC_VERSION_LIST = await getList(session, "BuildCraft") cog.BCC_VERSION_LIST = await getList( session, "BuildCraftCompat") highestMC = VersionInfo.getLatest( cog.BC_VERSION_LIST.keys()) latestBC = VersionInfo.getLatest( cog.BC_VERSION_LIST[highestMC]) generalID = 309218657798455298 channel: discord.TextChannel = cog.bot.get_channel( generalID) old_latest = Configuration.get_persistent_var( "latest_bc", "0.0.0") Configuration.set_persistent_var( "latest_bc", latestBC ) # save already so we don't get stuck and keep trying over and over if something goes wrong if channel is not None and latestBC != old_latest: GearbotLogging.info( f"New BuildCraft version found: {latestBC}") notify_channel = cog.bot.get_channel( 349517224320565258) await notify_channel.send( f"{Emoji.get_chat_emoji('WRENCH')} New BuildCraft version detected ({latestBC})" ) GearbotLogging.info( f"Fetching metadata for BuildCraft {latestBC}") message = await notify_channel.send( f"{Emoji.get_chat_emoji('REFRESH')} Fetching metadata..." ) info = await cog.getVersionDetails( "BuildCraft", latestBC) GearbotLogging.info(f"Metadata acquired: {info}") await message.edit( content= f"{Emoji.get_chat_emoji('YES')} Metadata acquired") if 'blog_entry' in info: message = await notify_channel.send( f"{Emoji.get_chat_emoji('REFRESH')} Updating general topic..." ) newTopic = f"General discussions about BuildCraft.\n" \ f"Latest version: {latestBC}\n" \ f"Full changelog and download: {info['blog_entry']}" await channel.edit(topic=newTopic) await message.edit( content= f"{Emoji.get_chat_emoji('YES')} Topic updated") else: notify_channel.send( f"{Emoji.get_chat_emoji('WARNING')} No blog post data found, notifying <@180057061353193472>" ) # message = await notify_channel.send(f"{Emoji.get_chat_emoji('REFRESH')} Uploading files to CurseForge...") # code, output, errors = await Utils.execute(f'cd BuildCraft/uploader && gradle curseforge -Pnew_version="{latestBC}"') # GearbotLogging.info(f"Upload to CF complete\n)------stdout------\n{output}\n------stderr------\n{errors}") # if code is 0: # content = f"{Emoji.get_chat_emoji('YES')} All archives successfully uploaded" # await message.edit(content=content) # else: # content = f"{Emoji.get_chat_emoji('NO')} Upload failed with code {code}, notifying <@106354106196570112>" # await notify_channel.send(content) # update FAQs if needed async with session.get( 'https://mod-buildcraft.com/website_src/faq.md') as reply: data = await reply.text() h = hashlib.md5(data.encode('utf-8')).hexdigest() old = Configuration.get_persistent_var("BCFAQ", "") channel = cog.bot.get_channel(361557801492938762) # FAQs if channel is not None and h != old: Configuration.set_persistent_var("BCFAQ", h) #clean the old stuff await channel.purge() #send banner with open("BuildCraft/FAQs.png", "rb") as file: await channel.send(file=File(file, filename="FAQs.png") ) #send content out = "" parts = [ d.strip("#").strip() for d in data.split("##")[1:] ] for part in parts: lines = part.splitlines() content = '\n'.join(lines[1:]) out += f"**```{lines[0].strip()}```**{content}\n" for page in Pages.paginate(out, max_chars=2048, max_lines=50): embed = Embed(description=page) await channel.send(embed=embed) pass except CancelledError: pass # bot shutdown except Exception as ex: cog.bot.errors = cog.bot.errors + 1 GearbotLogging.error( "Something went wrong in the BC version checker task") GearbotLogging.error(traceback.format_exc()) embed = discord.Embed(colour=discord.Colour(0xff0000), timestamp=datetime.datetime.utcfromtimestamp( time.time())) embed.set_author( name="Something went wrong in the BC version checker task:") embed.add_field(name="Exception", value=str(ex)) v = "" for line in traceback.format_exc().splitlines(): if len(v) + len(line) >= 1024: embed.add_field(name="Stacktrace", value=v) v = "" v = f"{v}\n{line}" if len(v) > 0: embed.add_field(name="Stacktrace", value=v) await GearbotLogging.bot_log(embed=embed) for i in range(1, 60): if cog.force or not cog.running: break await asyncio.sleep(10) GearbotLogging.info("BC version checking background task terminated")
async def on_guild_update(before, after): if after.owner is not None and after.owner_id in Configuration.get_persistent_var("user_blocklist", []): await after.leave() await GearbotLogging.bot_log(f"Someone transferred {await Utils.clean(after.name)} ({after.id}) to {after.owner_id} but they are blocked")