diff --git a/cogs/misc.py b/cogs/misc.py index 88fb3d8..3a96b32 100644 --- a/cogs/misc.py +++ b/cogs/misc.py @@ -1,6 +1,6 @@ # Discord Packages import discord -from discord.ext import commands +from discord.ext import commands, tasks # Bot Utilities from cogs.utils.Bot_version import bot_version @@ -12,6 +12,7 @@ from datetime import datetime, timezone from io import StringIO from os import listdir, name +from random import choice from re import IGNORECASE from re import compile as re_compile from re import search as re_search @@ -28,6 +29,18 @@ ) TIMEDELTA_PATTERN = re_compile(TIMEDELTA_REGEX, IGNORECASE) +presencePool = [ + { + "name": "Ser etter stjerner", + "emoji": "đŸ€–" + }, + { + "name": "Vokter {stars} stjerner", + "emoji": "⭐" + }, +] + + class Misc(commands.Cog): """ Klasse for diverse komandoer @@ -38,6 +51,12 @@ def __init__(self, bot): self.repo = "https://github.com/Norsk-Programmering/ProgBott" self.ico = "https://github.com/Norsk-Programmering/Profilering/raw/master/BotAvatar.gif" + async def cog_load(self): + self.presence.start() + + async def cog_unload(self): + self.presence.cancel() + def _get_uptime(self): now = time.time() diff = int(now - self.bot.uptime) @@ -91,7 +110,7 @@ async def syntax(self, ctx): """ embed = easy_embed(self, ctx) embed.title = "Hvordan fĂ„ vakre meldinger nĂ„r man poster kode" - embed.description = """ + embed.description = r""" Hei, du kan gjĂžre koden din mer leselig med Ă„ sende koden i kodeblokker.\n\n For vanlig kodeblokk skriv:\n\`\`\`\nconst dinKode = "Laget av meg"\nconsole.log(dinKode)\n\`\`\`\n Den kommer til Ă„ se ut som dette:\n```\nconst dinKode = "Laget av meg"\nconsole.log(dinKode)```\n @@ -131,7 +150,7 @@ async def info(self, ctx): dev = await self.bot.fetch_user(self.bot.appinfo.owner.id) desc = f"Discord-programvareagent for Norsk programmering" \ - f"\nForbedringforslag mottas pĂ„ [GitHub]({self.repo})" + f"\nForbedringforslag mottas pĂ„ [GitHub]({self.repo})" py_ver = platform.python_version() how = "Med Python sĂ„klart!" \ @@ -314,15 +333,15 @@ async def guild(self, ctx): embed.add_field(name="Opprettet", value=f"{discord.utils.format_dt(ctx.guild.created_at)}\n" + f"{discord.utils.format_dt(ctx.guild.created_at, style='R')}", inline=False) embed.add_field(name=f"Kanaler ({total_channels})", value=f"💬 Tekst: **{text_channels}**\n" + - f"🔊 Tale: **{voice_channels}**\n" + - f"đŸ—ƒïž Kategorier: **{categories}**") + f"🔊 Tale: **{voice_channels}**\n" + + f"đŸ—ƒïž Kategorier: **{categories}**") embed.add_field(name=f"Medlemmer ({total_members})", value=f"đŸ‘€ Mennesker: **{int(total_members) - int(bot_members)}**\n" + - f"đŸ€– BĂ„tter: **{bot_members}**\n" + - f"<:online:743471541169291335>{online_members} " + - f"<:idle:743471541127348255>{idle_members} " + - f"<:dnd:743471541093662840>{dnd_members} " + - f"<:offline:743471543543136266>{offline_members}") + f"đŸ€– BĂ„tter: **{bot_members}**\n" + + f"<:online:743471541169291335>{online_members} " + + f"<:idle:743471541127348255>{idle_members} " + + f"<:dnd:743471541093662840>{dnd_members} " + + f"<:offline:743471543543136266>{offline_members}") embed.add_field(name=f"Roller ({len(ctx.guild.roles) - 1})", value=roles, inline=False) if ctx.guild.premium_tier != 0: embed.add_field(name=f"Boosts ({ctx.guild.premium_subscription_count})", value=boosters, inline=False) @@ -443,7 +462,7 @@ async def bruker(self, ctx, *, bruker: discord.Member = None): if bruker.premium_since: premium_since = discord.utils.format_dt(bruker.premium_since, style="R") embed.add_field(name="Boost", value=f"{premium_since}\n" + - f"Booster #{premium_index} av serveren", inline=False) + f"Booster #{premium_index} av serveren", inline=False) embed.add_field(name=f"Roller ({len(bruker.roles) - 1})", value=roles, inline=False) embed.set_footer(text=f"#{join_index} Medlem av serveren | #{creation_index} Eldste brukeren pĂ„ serveren") @@ -595,7 +614,7 @@ async def smekk(self, ctx, member: discord.Member = None): @commands.cooldown(1, 5, type=commands.BucketType.guild) @commands.command(aliases=['owoify', 'uwu']) - async def owo(self, ctx, *, tekst: str = None): # https://github.com/LBlend/MornBot/blob/master/cogs/Misc.py#L149-L170 + async def owo(self, ctx, *, tekst: str = None): # https://github.com/LBlend/MornBot/blob/master/cogs/Misc.py#L149-L170 """Oversetter tekst til owo""" context = ctx.message @@ -636,7 +655,7 @@ async def brukere_siden(self, ctx, *, tid: str): stamp = None - if tid.endswith(("h","d", "w", "m", "y")): + if tid.endswith(("h", "d", "w", "m", "y")): try: delta = await self.parse_delta(tid) except ValueError: @@ -701,6 +720,26 @@ async def jada(self, ctx): async def lom(self, ctx): await ctx.send("https://imgur.com/RN3a1AX") + @tasks.loop(minutes=30) + async def presence(self): + """ + Endrer statusen til botten + """ + + if not self.bot.is_ready(): + return + + activity = choice(presencePool) + self.bot.logger.debug(f"Changing presence {activity.get("name")}") + + await self.bot.change_presence( + activity=discord.CustomActivity( + name=activity.get("name").format(stars=self.bot.cache_overview["stars"]), + emoji=activity.get("emoji", None) + ), + status=discord.Status.online + ) + async def setup(bot): # pylint: disable=missing-function-docstring diff --git a/cogs/poeng.py b/cogs/poeng.py index 6ce498a..89b65e5 100644 --- a/cogs/poeng.py +++ b/cogs/poeng.py @@ -85,8 +85,12 @@ async def add_star(self, message): """ Funksjon som gir stjerne """ - emoji = self.bot.get_emoji(743471543706976256) - emoji_str = f'<:forkast:{emoji.id}>' + try: + emoji = self.bot.get_emoji(743471543706976256) + emoji_str = f'<:forkast:{emoji.id}>' + except AttributeError: + emoji = '❌' + emoji_str = emoji dudes = {'id': [], 'mention': []} embed = easy_embed(self, message) for dude in message.mentions: @@ -107,40 +111,40 @@ async def add_star(self, message): embed.title = "Ny stjerne tildelt!" embed.description = f'{message.author.mention} ga {", ".join(dudes["mention"])} en stjerne!' reply = await message.reply(f"Registrerer stjerne\nreager med {emoji_str} for Ă„ avbryte") - async with message.channel.typing(): + await message.channel.typing() - def check(reaction, user): - if user is None or user.id != message.author.id: - return False + def check(reaction, user): + if user is None or user.id != message.author.id: + return False - if reaction.message.id != message.id: - return False + if reaction.message.id != message.id: + return False - if reaction.emoji == emoji: - return True + if reaction.emoji == emoji: + return True - return False + return False + try: + await self.bot.wait_for('reaction_add', timeout=10.0, check=check) + await message.remove_reaction(emoji, self.bot.user) try: - await self.bot.wait_for('reaction_add', timeout=10.0, check=check) - await message.remove_reaction(emoji, self.bot.user) - try: - await message.remove_reaction(emoji, message.author) - except discord.Forbidden: - self.bot.logger.warn('Missing permission to remove reaction (manage_messages)') - return await reply.delete() - - except asyncio.TimeoutError: - self.teller_data['meldinger'][str(message.id)] = msg_data - try: - await reply.edit(content=None, embed=embed) - except discord.HTTPException as err: - self.bot.logger.error(f'Edit failed. $${err}$$ @@{pformat(embed.to_dict())}@@') - await message.remove_reaction(emoji, self.bot.user) - try: - return await message.remove_reaction(emoji, message.author) - except discord.Forbidden: - return self.bot.logger.warn('Missing permission to remove reaction (manage_messages)') + await message.remove_reaction(emoji, message.author) + except discord.Forbidden: + self.bot.logger.warn('Missing permission to remove reaction (manage_messages)') + return await reply.delete() + + except asyncio.TimeoutError: + self.teller_data['meldinger'][str(message.id)] = msg_data + try: + await reply.edit(content=None, embed=embed) + except discord.HTTPException as err: + self.bot.logger.error(f'Edit failed. $${err}$$ @@{pformat(embed.to_dict())}@@') + await message.remove_reaction(emoji, self.bot.user) + try: + return await message.remove_reaction(emoji, message.author) + except discord.Forbidden: + return self.bot.logger.warn('Missing permission to remove reaction (manage_messages)') @commands.guild_only() @commands.group(name="stjerne") @@ -250,6 +254,7 @@ def load_json(self, mode): if mode == 'teller': with codecs.open(self.teller_file, 'r', encoding='utf8') as json_file: self.teller_data = json.load(json_file) + self.bot.cache_overview['stars'] = len(self.teller_data.get('meldinger')) elif mode == 'settings': with codecs.open(self.settings_file, 'r', encoding='utf8') as json_file: self.settings_data = json.load(json_file) @@ -271,9 +276,9 @@ def save_json(self, mode): except Exception as err: return self.bot.logger.warn(f'Failed to validate JSON before saving:\n{err}\n{self.settings_data}') - async def cog_unload(self): self.cacher.cancel() + self.save_json('teller') def check_folder(bot): @@ -282,6 +287,7 @@ def check_folder(bot): if not os.path.exists(_f): os.makedirs(_f) + def check_files(bot): # pylint: disable=missing-function-docstring files = [ diff --git a/cogs/utils/Bot_version.py b/cogs/utils/Bot_version.py index 9128285..83e7bc6 100644 --- a/cogs/utils/Bot_version.py +++ b/cogs/utils/Bot_version.py @@ -1 +1 @@ -bot_version = "0.1.15" +bot_version = "0.1.16" diff --git a/cogs/utils/defaults.py b/cogs/utils/defaults.py index 4bc3853..a6c22e6 100644 --- a/cogs/utils/defaults.py +++ b/cogs/utils/defaults.py @@ -43,21 +43,30 @@ "vip-us-west": "Vest-USA (VIP)", } +# https://discord.com/developers/docs/resources/guild#guild-object-guild-features features = { "ANIMATED_BANNER": "Annimert banner", "ANIMATED_ICON": "Animert ikon", + "APPLICATION_COMMAND_PERMISSIONS_V2": "Moderne kommandopermisjoner", + "AUTO_MODERATION": "Automatisk moderasjon", "BANNER": "Banner", "CHANNEL_BANNER": "Kannalbanner", "CHANNEL_ICON_EMOJIS_GENERATED": "Autogenererte kanal-emojis", "COMMERCE": "Butikkanaler", "COMMUNITY": "Sammfunsguild", + "CREATOR_MONETIZABLE_PROVISIONAL": "Innholdskaper monetisering", + "CREATOR_STORE_PAGE": "Innholdskaper butikk", + "DEVELOPER_SUPPORT_SERVER": "UtviklerstĂžtteguild", "DISCOVERABLE": "Fremhevet", "ENABLED_DISCOVERABLE_BEFORE": False, "FEATURABLE": "Kan fremheves", "GUILD_WEB_PAGE_VANITY_URL": "Egen URL til nettsted", "INVITE_SPLASH": "Invitasjonsbilde", + "INVITES_DISABLED": "Invitasjoner deaktivert", "MEMBER_PROFILES": "Medlemsprofiler", + "MEMBER_VERIFICATION_GATE_ENABLED": "Medlemsverifisering", "MORE_EMOJI": "Ekstra emoji", + "MORE_STICKERS": "Ekstra stickers", "NEW_THREAD_PERMISSIONS": "Nye trĂ„der", "NEWS": "Nyhetskanaler", "PARTNERED": "Discord Partner", @@ -65,11 +74,16 @@ "PRIVATE_THREADS": "Private trĂ„der", "PUBLIC_DISABLED": "Ikke offentlig", "PUBLIC": "Offentlig guild", - "ROLE_ICONS": "Rolle ikoner", + "RAID_ALERTS_DISABLED": "Raidvarsler deaktivert", + "ROLE_ICONS": "Rolleikoner", + "ROLE_SUBSCRIPTIONS_AVAILABLE_FOR_PURCHASE": "Rolleabonnement til salgs", + "ROLE_SUBSCRIPTIONS_ENABLED": "Rolleabonnement", "SEVEN_DAY_THREAD_ARCHIVE": "Ukeslang trĂ„darkiv", + "SOUNDBOARD": "Lydbrett", "TEXT_IN_VOICE_ENABLED": "Tekst i stemmekanaler", "THREADS_ENABLED": "TĂ„der", "THREE_DAY_THREAD_ARCHIVE": "Tredagers trĂ„darkiv", + "TICKETED_EVENTS_ENABLED": "Billettarrangementer", "VANITY_URL": "Egen URL", "VERIFIED": "Verifisert", "VIP_REGIONS": "VIP", @@ -105,8 +119,10 @@ "auto_moderation": "automatisk-moderasjon", "bans": "bans", "dm_messages": "dm-meldinger", + "dm_polls": "dm-avstemninger", "dm_reactions": "dm-reaksjoner", "dm_typing": "dm-skrivestatus", + "emojis_and_stickers": "emojis-og-stickers", "emojis": "emojis", "guild_messages": "guild-meldinger", "guild_reactions": "guild-reaksjoner", @@ -118,6 +134,8 @@ "members": "medlemmer", "message_content": "meldingsinnhold", "messages": "meldinger", + "moderation": "moderasjon", + "polls": "avstemninger", "presences": "tilstedevĂŠrelse", "reactions": "reaksjoner", "scheduled_events": "planlagte-hendelser", diff --git a/launcher.py b/launcher.py index 00843ee..cba1421 100644 --- a/launcher.py +++ b/launcher.py @@ -49,6 +49,7 @@ def __init__(self): self.logger = logger self.data_dir = data_dir self.settings = settings.extra + self.cache_overview = {"stars": 0} async def on_message(self, message): if message.author.bot: @@ -75,6 +76,10 @@ async def setup_hook(self): except Exception as _e: self.logger.exception("Loading of extension %s failed: %s", extension, _e) + async def close(self): + self.logger.info("Logging out") + await super().close() + if __name__ == "__main__": parser = ArgumentParser(prog="Roxedus' ProgBott", diff --git a/requirements.txt b/requirements.txt index dea793c..104ef4b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -discord.py==2.3.2 +discord.py==2.4.0 environs==11.0.0 flask==2.3.3 marshmallow==3.21.3