Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
51c3863
feat: ✨ Allow users to upload files directly to importclases command
nstringham Dec 29, 2022
e281ba0
ci: 👷 install pylint
nstringham Dec 29, 2022
9ce5e98
ci: 👷 install autopep8
nstringham Dec 29, 2022
5dd5dd1
ci: 👷 move settings to pyproject.toml
nstringham Dec 29, 2022
a712c20
ci: 👷 add extra args to pyproject.toml
nstringham Dec 29, 2022
d8018e3
ci: 👷 add ci with github actions
nstringham Dec 29, 2022
b308500
chore: 🧑‍💻 recomend VSCode extentions
nstringham Dec 29, 2022
c8d54bc
chore: 🔥 remove unneeded vscode setting
nstringham Dec 29, 2022
1f3cc08
fix: 💚 use diff mode for autopep8 CI
nstringham Dec 29, 2022
a5fafee
style: 🎨 format python code with autopep8
nstringham Dec 29, 2022
2b909f8
chore: 🧑‍💻 change editor cofig to reflect indentation in markdown
nstringham Dec 29, 2022
ad613b2
refactor: 🔥 remove unused imports
nstringham Dec 29, 2022
31e142f
refactor: ♻️ use singal declaration for gitignoring __pycache__
nstringham Dec 29, 2022
ec1bfbe
ci: 💚 disable pylint line length check
nstringham Dec 29, 2022
a4f7e01
fix: 🚨 reorder imports
nstringham Dec 29, 2022
567404e
refactor: 🚨 rename variable
nstringham Dec 29, 2022
003c338
fix: 🐛 use new name for scikit-learn
nstringham Dec 30, 2022
710ea39
build: 🔥 remove unused dependencies
nstringham Dec 30, 2022
366aa39
feat: ✨ add __init__ files change config to toml and move constants t…
nstringham Dec 30, 2022
2cefdc1
fix: 🐛 fix relitive import paths
nstringham Dec 30, 2022
a241e3e
fix: 🐛 ignore `_` files in cogs
nstringham Dec 30, 2022
3679616
feat: ✨ improve code regex
nstringham Dec 30, 2022
e518ba3
docs: 💡 add docstring
nstringham Dec 30, 2022
2ff06f2
refactor: 🚨 remove unused argument
nstringham Dec 30, 2022
b72767a
style: 🚨 remove extra no-op
nstringham Dec 30, 2022
a063755
refactor: 🚚 use snake case
nstringham Dec 30, 2022
ccae188
refactor: 🚨 remove unused argument
nstringham Dec 30, 2022
3464720
build: 🔧 add pebble host config
nstringham Dec 30, 2022
5d4ac29
docs: 💡 add module level doc strings
nstringham Dec 30, 2022
209e0da
refactor: 🚚 use snake_case
nstringham Dec 30, 2022
d8e42e5
chore: 🚨 ignore warning about catching all eceptions at the top level
nstringham Dec 30, 2022
8863ea6
refactor: 🚨 fix some pylint errors
nstringham Dec 30, 2022
1701f38
docs: 🚨 add docstring to cogs
nstringham Dec 30, 2022
36f1495
docs: 💡 add docstrings to cog setup
nstringham Dec 30, 2022
5224fa6
refactor: 🚨 import 3rd party code before relitive imports
nstringham Dec 30, 2022
09ad8cd
refactor: 🚨 snake_case
nstringham Dec 30, 2022
68397ac
refactor: 🚨 snake_case
nstringham Dec 30, 2022
d76676f
Merge branch 'main' of https://github.com/EMU-Compsci-Discord/Compsci…
nstringham Jan 5, 2023
b3b5575
refactor: ♻️ use `is` instead of `==` for None
nstringham Jan 5, 2023
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
6 changes: 6 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,9 @@ end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4

[*.yml]
indent_size = 2

[*.md]
indent_size = 2
37 changes: 37 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: CI

on:
push:
pull_request:
workflow_dispatch:

jobs:
pylint:
runs-on: ubuntu-latest
steps:
- name: Git checkout
uses: actions/checkout@v3

- name: Set up Python
uses: actions/setup-python@v3

- name: Install dependencies
run: pip install -r requirements.txt

- name: Run pylint
run: pylint .

autopep8:
runs-on: ubuntu-latest
steps:
- name: Git checkout
uses: actions/checkout@v3

- name: Set up Python
uses: actions/setup-python@v3

- name: Install dependencies
run: pip install -r requirements.txt

- name: Run autopep8
run: autopep8 --diff .
14 changes: 2 additions & 12 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*/__pycache__/
*.py[cod]
*$py.class

Expand All @@ -12,9 +12,7 @@ build/
develop-eggs/
dist/
downloads/
cogs/__pycache__
.vscode/
noncommands/__pycache__
eggs/
.eggs/
lib/
Expand All @@ -27,7 +25,7 @@ share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
config.yaml
config.toml
MANIFEST

# PyInstaller
Expand Down Expand Up @@ -144,14 +142,6 @@ cython_debug/
.idea/*
*.pyc
*.pyc
/cogs/__pycache__/fun.cpython-37.pyc
/cogs/__pycache__/general.cpython-37.pyc
/cogs/__pycache__/help.cpython-37.pyc
/cogs/__pycache__/moderation.cpython-37.pyc
/cogs/__pycache__/owner.cpython-37.pyc
/cogs/__pycache__/template.cpython-37.pyc
/noncommands/__pycache__/imchecker.cpython-37.pyc
/noncommands/__pycache__/reminderLoop.cpython-37.pyc
newperson.png
*.pyc
*/*.pyc
Expand Down
10 changes: 10 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"recommendations": [
"ms-python.python",
"EditorConfig.EditorConfig",
"bungcip.better-toml",
"esbenp.prettier-vscode",
"vivaxy.vscode-conventional-commits",
"eamodio.gitlens"
]
}
5 changes: 3 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"python.analysis.extraPaths": ["./cogs"],
"python.formatting.autopep8Args": ["--max-line-length", "120"]
"python.formatting.provider": "autopep8",
"python.linting.pylintEnabled": true,
"python.linting.enabled": true
}
25 changes: 9 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ You should see something similar to this result if you are using Windows Command

<img src="imgs/cmdCloneCommand.webp" alt="Command Line Output" width="100%"/>

You can set up a python virtual environment that uses python 3.9 by running this command on windows
You can set up a python virtual environment by running this command on windows

```pwsh
&"C:\Program Files\Python39\python.exe" -m venv .venv
python -m venv .venv
```

### 2. Getting a Discord Bot
Expand Down Expand Up @@ -86,25 +86,18 @@ Click the Administrator Box, so it looks as shown:

### 4. Config File

Now go to your IDE or Text Editor, and make a copy of `config template.yaml`. Save the copy as `config.yaml`. This will be the bots config file, and is important to running on discord.
Now go to your IDE or Text Editor, and make a copy of `config_template.toml`. Save the copy as `config.toml`. This will be the bots config file, and is important to running on discord.

DO NOT WRITE ON THE TEMPLATE

```yaml
token: "BOT_TOKEN"
application_id: "APPLICATION_ID"
owners:
- OWNER_ID
blacklist:
- 000000000000000000
main_color: 0xD75BF4
error: 0xE02B2B
success: 0x42F56C
warning: 0xF59E42
info: 0x4299F5
```toml
token = "BOT_TOKEN"
application_id = "APPLICATION_ID"
owners = ["OWNER_ID"]
blacklist = []
```

On the `config.yaml` file, you will be changing four lines:
On the `config.toml` file, you will be changing four lines:

- `token`
- `application_id`
Expand Down
214 changes: 115 additions & 99 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,99 +1,115 @@
import os
import platform
import random
import sys
import nextcord
import yaml
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from nextcord.ext import commands, tasks
from nextcord.ext.commands import Bot

from noncommands import auto_code_block,quotes


with open("config.yaml") as file:
config = yaml.load(file, Loader=yaml.FullLoader)

intents = nextcord.Intents.default().all()

bot = Bot(intents=intents, command_prefix="!")

scheduler = AsyncIOScheduler()
toSchedule = quotes.Quotes(bot)
autoCodeBlock = auto_code_block.AutoCodeBlock(bot)

# The code in this even is executed when the bot is ready
@bot.event
async def on_ready():
print(f"Logged in as {bot.user.name}")
print(f"nextcord.py API version: {nextcord.__version__}")
print(f"Python version: {platform.python_version()}")
print(f"Running on: {platform.system()} {platform.release()} ({os.name})")
print("-------------------")
await bot.change_presence(activity=nextcord.Game("/help"))

# Removes the default help command of nextcord.py to be able to create our custom help command.
bot.remove_command("help")

if __name__ == "__main__":
for file in os.listdir("./cogs"):
if file.endswith(".py"):
extension = file[:-3]
try:
bot.load_extension(f"cogs.{extension}")
print(f"Loaded extension '{extension}'")
except Exception as e:
exception = f"{type(e).__name__}: {e}"
print(f"Failed to load extension {extension}\n{exception}")

# The code in this event is executed every time someone sends a message, with or without the prefix
@bot.event
async def on_message(message):
# Ignores if a command is being executed by a bot or by the bot itself
if message.author == bot.user or message.author.bot:
return
# Ignores if a command is being executed by a blacklisted user

if message.author.id in config["blacklist"]:
return

await autoCodeBlock.check_message(message)

await bot.process_commands(message)

# The code in this event is executed every time a command has been *successfully* executed
@bot.event
async def on_command_completion(ctx):
fullCommandName = ctx.command.qualified_name
split = fullCommandName.split(" ")
executedCommand = str(split[0])
print(
f"Executed {executedCommand} command in {ctx.guild.name} (ID: {ctx.message.guild.id}) by {ctx.message.author} (ID: {ctx.message.author.id})")

# The code in this event is executed every time a valid commands catches an error
@bot.event
async def on_command_error(context, error):
if isinstance(error, commands.CommandOnCooldown):
minutes, seconds = divmod(error.retry_after, 60)
hours, minutes = divmod(minutes, 60)
hours = hours % 24
embed = nextcord.Embed(
title="Hey, please slow down!",
description=f"You can use this command again in {f'{round(hours)} hours' if round(hours) > 0 else ''} {f'{round(minutes)} minutes' if round(minutes) > 0 else ''} {f'{round(seconds)} seconds' if round(seconds) > 0 else ''}.",
color=config["error"]
)
await context.send(embed=embed)
elif isinstance(error, commands.MissingPermissions):
embed = nextcord.Embed(
title="Error!",
description="You are missing the permission `" + ", ".join(
error.missing_perms) + "` to execute this command!",
color=config["error"]
)
await context.send(embed=embed)
raise error

scheduler.add_job(toSchedule.dailyQuote, CronTrigger(hour="8",minute="0",second="0",day_of_week="0-4",timezone="EST"))
scheduler.start()
bot.run(config["token"])
"""
This is the main file that runs the bot.
"""


import os
import platform
import nextcord
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from nextcord.ext import commands
from nextcord.ext.commands import Bot

from noncommands import auto_code_block, quotes
from constants import ERROR_COLOR, config


intents = nextcord.Intents.default().all()

bot = Bot(intents=intents, command_prefix="!")

scheduler = AsyncIOScheduler()
toSchedule = quotes.Quotes(bot)
autoCodeBlock = auto_code_block.AutoCodeBlock(bot)


@bot.event
async def on_ready():
"""
The code in this even is executed when the bot is ready
"""

print(f"Logged in as {bot.user.name}")
print(f"nextcord.py API version: {nextcord.__version__}")
print(f"Python version: {platform.python_version()}")
print(f"Running on: {platform.system()} {platform.release()} ({os.name})")
print("-------------------")
await bot.change_presence(activity=nextcord.Game("/help"))

# Removes the default help command of nextcord.py to be able to create our custom help command.
bot.remove_command("help")

if __name__ == "__main__":
for file in os.listdir("./cogs"):
if file.endswith(".py") and not file.startswith("_"):
extension = file[:-3]
try:
bot.load_extension(f"cogs.{extension}")
print(f"Loaded extension '{extension}'")
except Exception as e:
exception = f"{type(e).__name__}: {e}"
print(f"Failed to load extension {extension}\n{exception}")


@bot.event
async def on_message(message):
"""
The code in this event is executed every time someone sends a message, with or without the prefix
"""

# Ignores if a command is being executed by a bot or by the bot itself
if message.author == bot.user or message.author.bot:
return
# Ignores if a command is being executed by a blacklisted user

if message.author.id in config["blacklist"]:
return

await autoCodeBlock.check_message(message)

await bot.process_commands(message)


@bot.event
async def on_command_completion(ctx):
"""
The code in this event is executed every time a command has been *successfully* executed
"""
full_command_name = ctx.command.qualified_name
split = full_command_name.split(" ")
executed_command = str(split[0])
print(
f"Executed {executed_command} command in {ctx.guild.name} (ID: {ctx.message.guild.id}) by {ctx.message.author} (ID: {ctx.message.author.id})")


@bot.event
async def on_command_error(context, error):
"""
The code in this event is executed every time a valid commands catches an error
"""

if isinstance(error, commands.CommandOnCooldown):
minutes, seconds = divmod(error.retry_after, 60)
hours, minutes = divmod(minutes, 60)
hours = hours % 24
embed = nextcord.Embed(
title="Hey, please slow down!",
description=f"You can use this command again in {f'{round(hours)} hours' if round(hours) > 0 else ''} {f'{round(minutes)} minutes' if round(minutes) > 0 else ''} {f'{round(seconds)} seconds' if round(seconds) > 0 else ''}.",
color=ERROR_COLOR
)
await context.send(embed=embed)
elif isinstance(error, commands.MissingPermissions):
embed = nextcord.Embed(
title="Error!",
description="You are missing the permission `" + ", ".join(
error.missing_perms) + "` to execute this command!",
color=ERROR_COLOR
)
await context.send(embed=embed)
raise error

scheduler.add_job(toSchedule.daily_quote,
CronTrigger(hour="8", minute="0", second="0", day_of_week="0-4", timezone="EST"))
scheduler.start()
bot.run(config["token"])
Empty file added cogs/__init__.py
Empty file.
Loading