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 #4

Merged
merged 6 commits into from
Feb 7, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,13 @@ dmypy.json

# Pyre type checker
.pyre/
# py-charm
/.idea/.gitignore
/.idea/discord.xml
/.idea/misc.xml
/.idea/modules.xml
/.idea/inspectionProfiles/profiles_settings.xml
/.idea/inspectionProfiles/Project_Default.xml
/.idea/pythonProject.iml
/.idea/vcs.xml
.vscode
16 changes: 16 additions & 0 deletions Bot/bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import aiosqlite
import discord
from discord.ext import commands

from utils.log import setup_logger


class DragonBot(commands.Bot):
def __init__(self, *args, **kwargs):
self.set_up = False
super().__init__(*args, **kwargs)


async def on_ready(self):
if not self.set_up:
self.log = setup_logger()
Empty file added CHANGELOG.md
Empty file.
56 changes: 56 additions & 0 deletions DragonBot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import datetime
import logging

import discord
from discord.ext import commands, tasks

import config
from utils import db, logger

log = logging.getLogger("DragonLog")


ascii_art = """
╭━━━╮╱╱╱╱╱╱╱╱╱╱╱╱╱╭━━╮╱╱╱╭╮
╰╮╭╮┃╱╱╱╱╱╱╱╱╱╱╱╱╱┃╭╮┃╱╱╭╯╰╮
╱┃┃┃┣━┳━━┳━━┳━━┳━╮┃╰╯╰┳━┻╮╭╯
╱┃┃┃┃╭┫╭╮┃╭╮┃╭╮┃╭╮┫╭━╮┃╭╮┃┃
╭╯╰╯┃┃┃╭╮┃╰╯┃╰╯┃┃┃┃╰━╯┃╰╯┃╰╮
╰━━━┻╯╰╯╰┻━╮┣━━┻╯╰┻━━━┻━━┻━╯
╱╱╱╱╱╱╱╱╱╭━╯┃
╱╱╱╱╱╱╱╱╱╰━━╯
"""


def pre_start_hook():
print(ascii_art)
client.load_extensions("extensions", recursive = True)


class DragonBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

async def on_ready(self) -> None:
try:
log.info(f"Bot started as {self.user.name}#{self.user.discriminator} | {self.user.id}")
except UnicodeEncodeError:
log.info("Bot started")
await db.set_up()
log.debug("Database setup successful")


client = DragonBot(
command_prefix = commands.when_mentioned,
case_insensitive = True,
strip_after_prefix = True,
intents = discord.Intents.all(),
debug_guilds = config.GUILDS,
activity = discord.Activity(type = discord.ActivityType.watching, name = "you"),
state = discord.Status.online,
)


if __name__ == "__main__":
pre_start_hook()
client.run(config.DISCORD_TOKEN)
Binary file added data/main.sqlite
Binary file not shown.
1 change: 1 addition & 0 deletions extensions/admin/.exist
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

37 changes: 37 additions & 0 deletions extensions/admin/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import discord
from discord.ext import commands

import config
from DragonBot import DragonBot
from utils import db


class SettingsCog(commands.Cog):
def __init__(self, client):
self.client: DragonBot = client

@commands.slash_command(name = "settings", description = "set some settings for your guild")
async def settings(self,
ctx: discord.ApplicationContext,
setting: discord.Option(
required = True,
choices = [
discord.OptionChoice("Team Role")
]
),
value: discord.Option(
required = True
)):
await db.insert_setting(
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only if permissions.admin

setting = setting,
value = value,
guild = ctx.guild_id
)
embed = discord.Embed(title = "Success",
description = f"Successfully set {setting} to {value}",
color = discord.Color.brand_green())
await ctx.response.send_message(embed = embed)


def setup(client: DragonBot):
client.add_cog(SettingsCog(client))
1 change: 1 addition & 0 deletions extensions/automation/.exist
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 1 addition & 0 deletions extensions/fun/.exist
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

24 changes: 24 additions & 0 deletions extensions/fun/qrcode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import logging

import discord
from discord.ext import commands
import pyqrcode

from DragonBot import DragonBot
from utils import db


class QRCog(commands.Cog):
def __init__(self, client):
self.client = client

@commands.command()
async def qrcodify(self, ctx: commands.Context):
qr_codes = []
for attachment in ctx.message.attachments:
qr_codes.append(pyqrcode.create(attachment))
await ctx.reply(qr_codes)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

doens't work


def setup(client: DragonBot):
client.add_cog(QRCog(client))
28 changes: 28 additions & 0 deletions extensions/moderation/warn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import logging

import discord
from discord.ext import commands

from DragonBot import DragonBot
from utils import db
from view import warn_v


class WarnCog(commands.Cog):
def __init__(self, client):
self.client = client

@commands.user_command(name = "warn")
async def warn(self, ctx: discord.ApplicationContext, member: discord.Member):
for role in ctx.author.roles:
if not role.id in await db.get_setting():
return await ctx.response.send_message("You are not allowed to warn a member!",
ephemeral = True,
delete_after = 5)

else:
await ctx.response.send_modal(warn_v.WarnModal())


def setup(client: DragonBot):
client.add_cog(WarnCog(client))
27 changes: 27 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
aiohttp==3.8.3
aiosignal==1.3.1
aiosqlite==0.18.0
async-timeout==4.0.2
attrs==22.2.0
autopep8==2.0.1
black==22.12.0
cffi==1.15.1
charset-normalizer==2.1.1
click==8.1.3
colorama==0.4.6
distlib==0.3.6
filelock==3.9.0
frozenlist==1.3.3
idna==3.4
multidict==6.0.4
mypy-extensions==0.4.3
pathspec==0.10.3
platformdirs==2.6.2
py-cord==2.3.2
pycodestyle==2.10.0
pycparser==2.21
PyNaCl==1.5.0
pypresence==4.2.1
virtualenv==20.17.1
wavelink==1.3.4
yarl==1.8.2
66 changes: 66 additions & 0 deletions utils/db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import aiosqlite
from config import DBPATH, DBFOLD
import os


async def set_up() -> None:
if not DBFOLD.exists():
os.mkdir(DBFOLD)
if not DBPATH.exists():
open(DBPATH, "w").close()
async with aiosqlite.connect(DBPATH) as conn:
async with conn.cursor() as cursor:
await cursor.execute("""
CREATE TABLE IF NOT EXISTS mod_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT,
member INTEGER,
time timestamp)
""")

await cursor.execute("""
CREATE TABLE IF NOT EXISTS settings (
setting TEXT,
value TEXT,
guild INTEGER)
""")

await conn.commit()


async def insert_setting(setting: str, value: str, guild: int):
setting = setting.lower()
value = value.lower()
async with aiosqlite.connect(DBPATH) as conn:
async with conn.cursor() as cursor:
await cursor.execute("""
SELECT value FROM settings where setting = ? AND guild = ?
""", (setting, guild))
response = await cursor.fetchone()
if response is None:
await cursor.execute("""
INSERT INTO settings (setting, value, guild) VALUES (?, ?, ?)
""", (setting, value, guild))
else:
await cursor.execute("""
UPDATE settings SET value = ? WHERE setting = ? AND guild = ?
""", (value, setting, guild))
await conn.commit()


async def get_setting(setting: str, guild: int) -> str | None:
setting = setting.lower()
async with aiosqlite.connect(DBPATH) as conn:
async with conn.cursor() as cursor:
await cursor.execute("""
SELECT value FROM settings where setting = ? AND guild = ?
""")
response = await cursor.fetchone()
if response is None:
return None
else:
return response[0]


async def add_warn():
pass
52 changes: 52 additions & 0 deletions utils/log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import datetime
import logging
from pathlib import Path
import os


class CustomFormatter(logging.Formatter):
def format(self, record):
log_fmt = FORMATS[record.levelno]
formatter = logging.Formatter(log_fmt, style="{", datefmt="%d-%m-%y %H:%M:%S")
return formatter.format(record)


FMT = "[{levelname:^9}] [{asctime}] [{name}] [{module}:{lineno}] : {message}"
FORMATS = {
logging.DEBUG: f"\33[37m{FMT}\33[0m",
logging.INFO: f"\33[36m{FMT}\33[0m",
logging.WARNING: f"\33[33m{FMT}\33[0m",
logging.ERROR: f"\33[31m{FMT}\33[0m",
logging.CRITICAL: f"\33[1m\33[31m{FMT}\33[0m",
}


def setup_logger() -> logging.Logger:
log = logging.getLogger("BotLog")
log.setLevel(logging.DEBUG)
if not Path("logs").exists():
os.mkdir("logs")
if len(os.listdir("logs")) > 7:
for file in os.listdir("logs"):
os.remove("logs/" + file)
break

log_path = f"logs/{log.name} {datetime.datetime.now().strftime('%Y-%m-%d')}.log"
file_format = logging.Formatter(
"[{levelname:^9}] [{asctime}] [{name}] [{module:^4}:{lineno:^4}] | {message}",
style="{",
datefmt="%d-%m-%y %H:%M:%S",
)


file_handler = logging.FileHandler(log_path, "w")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(file_format)

console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(CustomFormatter())

log.addHandler(file_handler)
log.addHandler(console_handler)
return log
50 changes: 50 additions & 0 deletions utils/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import datetime
import logging
import os
from pathlib import Path


class CustomFormatter(logging.Formatter):
def format(self, record):
log_fmt = FORMATS[record.levelno]
formatter = logging.Formatter(log_fmt, style="{", datefmt="%d-%m-%y %H:%M:%S")
return formatter.format(record)


FMT = "[{levelname:^9}] [{asctime}] [{name}] [{module}:{lineno}] : {message}"
FORMATS = {
logging.DEBUG: f"\33[37m{FMT}\33[0m",
logging.INFO: f"\33[36m{FMT}\33[0m",
logging.WARNING: f"\33[33m{FMT}\33[0m",
logging.ERROR: f"\33[31m{FMT}\33[0m",
logging.CRITICAL: f"\33[1m\33[31m{FMT}\33[0m",
}


log = logging.getLogger("DragonLog")
log.setLevel(logging.DEBUG)
if not Path("logs").exists():
os.mkdir("logs")
if len(os.listdir("logs")) > 10:
for file in os.listdir("logs"):
os.remove("logs/" + file)
break

log_path = f"logs/{log.name} {datetime.datetime.now().strftime('%Y-%m-%d')}.log"
file_format = logging.Formatter(
"[{levelname:^9}] [{asctime}] [{name}] [{module:^4}:{lineno:^4}] | {message}",
style="{",
datefmt="%d-%m-%y %H:%M:%S",
)


file_handler = logging.FileHandler(log_path, "w")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(file_format)

console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(CustomFormatter())

log.addHandler(file_handler)
log.addHandler(console_handler)
Loading