Skip to content

Commit

Permalink
Merge pull request #84 from Dragons-Dev/pw_generator
Browse files Browse the repository at this point in the history
Password Generator and Logging Adjustments
  • Loading branch information
DTheIcyDragon authored Jan 24, 2025
2 parents d134640 + d32ec3a commit bb5e622
Show file tree
Hide file tree
Showing 4 changed files with 124 additions and 8 deletions.
12 changes: 9 additions & 3 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,22 @@
# The token you get from discord for authorizing your bot. https://discord.com/developers/applications

GOOGLE_API_KEY = ""
# An api key from googe, this is required in order to scan for harmful urls
# An api key from Google, this is required in order to scan for harmful urls
# https://console.cloud.google.com/apis/api/safebrowsing.googleapis.com/metrics?project=mails-366518

DEBUG_GUILDS: list[int] = []
# A debug guild. this is an optional value, but I recommend to set it if you use the bot private. this increases the
# time in which the commands show up after updating
# A debug guild. this is an optional value. this increases the time in which the commands show up after updating, but it
# will lead to commands not showing up in dm's which disables some features

log_level = DEBUG
# the log level. this bot has built in logging. by modifying this value with one from the first import you change what's
# logged
discord_log_level = INFO
# the log level for discord. Lowering this may lead to huge logs.

IPC_SECRET = ""
# this secret will be used to encrypt the communication between the bot and webinterface

SPOTIFY_CLIENT_ID = ""
SPOTIFY_CLIENT_SECRET = ""
# get from https://developer.spotify.com/dashboard/
100 changes: 100 additions & 0 deletions extensions/tools/password_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import random
import string

import discord
from discord.ext import commands
from discord.utils import escape_markdown

from utils import Bot, CustomLogger


class PasswordSelector(discord.ui.Select):
def __init__(self, length: int):
self.length = length
options = [
discord.SelectOption(
label="Upper-case Letters",
description="Password will contain Upper-case letters.",
value="uppercase"
),
discord.SelectOption(
label="Lower-case Letters",
description="Password will contain lower-case letters.",
value="lowercase"
),
discord.SelectOption(
label="Numbers",
description="Password will contain numbers.",
value="numbers"
),
discord.SelectOption(
label="Punctuation",
description="Password will contain punctuation.",
value="punctuation"
),
]
super().__init__(
options=options,
min_values=1,
max_values=4,
placeholder="Select all elements you password should contain!"
)

async def callback(self, interaction: discord.Interaction):
choices = []
if "uppercase" in self.values:
choices.append(string.ascii_uppercase)
if "lowercase" in self.values:
choices.append(string.ascii_lowercase)
if "numbers" in self.values:
choices.append(string.digits)
if "punctuation" in self.values:
choices.append(string.punctuation)
choices = ''.join(choices) # type: ignore
pw = ''.join(random.choice(choices) for _ in range(self.length))
await interaction.response.send_message(escape_markdown(pw), ephemeral=True)
await interaction.delete_original_response()


class PasswordView(discord.ui.View):
def __init__(self, length):
self.length = length
super().__init__()
self.disable_on_timeout = True
self.timeout = 5
self.add_item(PasswordSelector(length=self.length))


class PasswordGenerator(commands.Cog):
def __init__(self, client):
self.client: Bot = client
self.logger = CustomLogger(self.qualified_name, self.client.boot_time)

@commands.slash_command(
name="generate_password",
description="Generate a random password.",
contexts={
discord.InteractionContextType.guild,
discord.InteractionContextType.bot_dm,
discord.InteractionContextType.private_channel
}
)
@discord.option(
name="password length",
default=16,
required=False,
input_type=int,
max_value=1024,
description="The length of the generated password.",
)
async def generate_password(self, ctx: discord.ApplicationContext, length: int):
view = PasswordView(length=length)
await ctx.response.send_message(
"Please select all elements you password should contain!",
ephemeral=True,
view = view
)


def setup(client):
client.add_cog(PasswordGenerator(client))
16 changes: 13 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import asyncio
import json
import logging
import os
import time
from datetime import datetime as dt
from sys import exit as exit_
from sys import stdout

import aiohttp
import discord
import psutil
from discord.ext import commands

import config
from config import DEBUG_GUILDS, DISCORD_API_KEY
from utils import Bot, ContentDB, ShortTermStorage, rem_log
from utils.logger import CustomFormatter

bot = Bot(
command_prefix=commands.when_mentioned,
Expand All @@ -28,8 +31,10 @@
async def on_boot():
bot.db = ContentDB(path="data/content.sqlite")
await bot.db.setup(bot.boot_time)
bot.logger.debug("Initialized content db")
bot.sts = ShortTermStorage(path="data/sts.sqlite")
await bot.sts.setup(bot.boot_time)
bot.logger.debug("Initialized sts db")
bot.api = aiohttp.ClientSession(
"https://discord.com",
headers={"Authorization": "Bot " + DISCORD_API_KEY, "User-Agent": f"Dragons BotV{bot.client_version}"},
Expand All @@ -54,6 +59,12 @@ async def on_boot():


if __name__ == "__main__":
dc_logger = logging.getLogger("discord")
dc_logger.setLevel(config.discord_log_level)
console_handle = logging.StreamHandler(stdout)
console_handle.setFormatter(CustomFormatter())
console_handle.setLevel(config.discord_log_level)
dc_logger.addHandler(console_handle)
extensions = bot.load_extensions("extensions", recursive=True, store=True) # load every extension
with open("./assets/disabled.json") as f:
extension_store = json.load(f)
Expand All @@ -79,8 +90,7 @@ async def on_boot():

pid = os.getpid()
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(bot.start(DISCORD_API_KEY))
bot.run(DISCORD_API_KEY)
except KeyboardInterrupt:
bot.logger.critical("Shutting down...")
finally:
Expand Down
4 changes: 2 additions & 2 deletions utils/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,14 +171,14 @@ async def modify_infraction(
await self.db.commit()

async def get_infraction(
self, case_id: int = None, user: discord.User | discord.Member = None
self, case_id: int | None = None, user: discord.User | discord.Member | None = None
) -> aiosqlite.Row | list[aiosqlite.Row]:
"""Gets an infraction by id or all infractions from a user"""
if case_id is not None:
resp = await self.db.execute("SELECT * FROM infractions WHERE case_id = ?", (case_id,))
resp = await resp.fetchone()
else:
resp = await self.db.execute("SELECT * FROM infractions WHERE user = ?", (user.id,))
resp = await self.db.execute("SELECT * FROM infractions WHERE user = ?", (user.id,)) # type: ignore
resp = await resp.fetchall()
return resp

Expand Down

0 comments on commit bb5e622

Please sign in to comment.