Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #139

Merged
merged 8 commits into from
Jun 23, 2024
Merged

Dev #139

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 52 additions & 13 deletions cogs/misc.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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!" \
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
68 changes: 37 additions & 31 deletions cogs/poeng.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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")
Expand Down Expand Up @@ -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)
Expand All @@ -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):
Expand All @@ -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 = [
Expand Down
2 changes: 1 addition & 1 deletion cogs/utils/Bot_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
bot_version = "0.1.15"
bot_version = "0.1.16"
20 changes: 19 additions & 1 deletion cogs/utils/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,33 +43,47 @@
"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",
"PREVIEW_ENABLED": "Forhåndstesting",
"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",
Expand Down Expand Up @@ -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",
Expand All @@ -118,6 +134,8 @@
"members": "medlemmer",
"message_content": "meldingsinnhold",
"messages": "meldinger",
"moderation": "moderasjon",
"polls": "avstemninger",
"presences": "tilstedeværelse",
"reactions": "reaksjoner",
"scheduled_events": "planlagte-hendelser",
Expand Down
5 changes: 5 additions & 0 deletions launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -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
Expand Down