Skip to content

Commit

Permalink
Merge pull request #23 from drawbu/chunked_embeds
Browse files Browse the repository at this point in the history
⚡ Implement chunked embed message.
  • Loading branch information
Sigmanificient authored Sep 9, 2022
2 parents 0494ee5 + d9dd1a2 commit d23f83c
Show file tree
Hide file tree
Showing 8 changed files with 376 additions and 361 deletions.
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Set the default behavior, in case people don't have core.autocrlf set.
* text=lf
* eol=lf
58 changes: 34 additions & 24 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,24 +1,34 @@
VENV = venv
VBIN = $(VENV)/bin

all: start

clean:
rm -rf venv
rm -rf *.egg-info
rm -rf */__pycache__
rm vars/*.json

$(VBIN)/python:
python3 -m venv venv
chmod +x $(VBIN)/activate
./$(VBIN)/activate
${VBIN}/pip install -e .

vars/config.json:
cp vars/config.json.example vars/config.json

start: $(VBIN)/python vars/config.json
python3 drawbot

.PHONY: all clean start
VENV = venv
V_BIN = $(VENV)/bin

all: start


$(V_BIN)/python:
python3 -m venv venv
chmod +x $(V_BIN)/activate
./$(V_BIN)/activate

$(V_BIN)/pip install -e .


vars/config.json:
cp vars/config.json.example vars/config.json


start: $(V_BIN)/python vars/config.json
python3 drawbot


clean:
rm -rf venv
rm -rf *.egg-info
rm -rf */__pycache__


fclean: clean
rm -rf venv
rm vars/*.json


.PHONY: all clean fclean start
134 changes: 65 additions & 69 deletions drawbot/bot.py
Original file line number Diff line number Diff line change
@@ -1,69 +1,65 @@
import os
import sys
from typing import Optional

from discord import LoginFailure, Intents
from discord.ext import commands
from colorama import Fore, Style

from .utils import json_wr, JsonData


class Bot(commands.Bot):
def __init__(self):
"""Initialize the bot and load config for token and prefix."""
self.embed_color: int = 0x1E744F
self._token: Optional[str] = None

default_config: JsonData = {
"token": "",
"prefix": "!",
"channelID": "",
"username": "",
"password": "",
"url": "",
}

self.config: JsonData = json_wr("config")

for key in default_config.keys():
if self.config.get(key, "") == "":
print(
f'Veuillez indiquer remplir la valeur "{key}" '
"dans le fichier vars/config.json"
)
sys.exit()

super().__init__(command_prefix=";", intents=Intents.default())
self._token = self.config.get("token")
self.config.pop("token")

self.remove_command("help")

for filename in os.listdir("drawbot/cogs"):
if filename.endswith(".py") and filename != "__init__.py":
self.load_extension(f"drawbot.cogs.{filename[:-3]}")

def run(self):
try:
super().run(self._token)
except LoginFailure:
print(
"Echec de la connexion au client."
"Veuillez vérifier que votre token est correct."
)

async def on_ready(self):
await self.load_cogs()
print(f"Connecté en temps que {self.user.name} !")

async def load_cogs(self):
for command in self.tree.get_commands():
await self.unload_extension(command.name)

for filename in os.listdir("drawbot/cogs"):
if filename.endswith(".py"):
await self.load_extension(f"cogs.{filename[:-3]}")
print(f" -> Loaded extension "
f"{Fore.BLUE}{Style.BRIGHT}{filename}{Style.RESET_ALL}")
await self.tree.sync()
import os
import sys
from typing import Optional

from discord import LoginFailure, Intents
from discord.ext import commands
from colorama import Fore, Style

from .utils import json_wr, JsonData


class Bot(commands.Bot):
def __init__(self):
"""Initialize the bot and load config for token and prefix."""
self.embed_color: int = 0x1E744F
self._token: Optional[str] = None

default_config: JsonData = {
"token": "",
"prefix": "!",
"channelID": "",
"username": "",
"password": "",
"url": "",
}

self.config: JsonData = json_wr("config")

for key in default_config.keys():
if self.config.get(key, "") == "":
print(
f'Veuillez indiquer remplir la valeur "{key}" '
"dans le fichier vars/config.json"
)
sys.exit()

super().__init__(command_prefix=";", intents=Intents.default())
self._token = self.config.get("token")
self.config.pop("token")

self.remove_command("help")

def run(self, **kwargs):
try:
super().run(self._token, **kwargs)
except LoginFailure:
print(
"Echec de la connexion au client."
"Veuillez vérifier que votre token est correct."
)

async def on_ready(self):
await self.load_cogs()
print(f"Connecté en temps que {self.user.name} !")

async def load_cogs(self):
for command in self.tree.get_commands():
await self.unload_extension(command.name)

for filename in os.listdir("drawbot/cogs"):
if filename.endswith(".py"):
await self.load_extension(f"cogs.{filename[:-3]}")
print(f" -> Loaded extension "
f"{Fore.BLUE}{Style.BRIGHT}{filename}{Style.RESET_ALL}")
await self.tree.sync()
Empty file added drawbot/cogs/__init__.py
Empty file.
176 changes: 88 additions & 88 deletions drawbot/cogs/pronote_commands.py
Original file line number Diff line number Diff line change
@@ -1,88 +1,88 @@
import time

from utils import json_wr, JsonDict

import discord
from discord.ext import commands
from discord import app_commands, Interaction


@app_commands.guild_only()
class PronoteCommandsGroup(app_commands.Group, name="pronote"):
@app_commands.command(name="help")
async def help_command(self, interaction: Interaction):
await interaction.response.send_message(
embed=discord.Embed(
title="Help of the Pronote",
description=(
"Un bot qui traque vos devoir pronote "
"et vous les notifient sur discord."
),
color=interaction.client.embed_color,
).add_field(
name="/pronote help",
value="Affiche ce message",
).add_field(
name="/pronote here",
value=("Change le salon d'envoi des nouveaux messages "
"pour pronote (nouveaux devoirs et notes)"),
).add_field(
name="/pronote incoming",
value="Affiche les prochains devoirs",
)
)

@app_commands.command()
async def here(self, interaction: Interaction):
pronote_config: JsonDict = json_wr("pronote")
pronote_config["channelID"] = interaction.channel_id
json_wr("pronote", data=pronote_config)

await interaction.response.send_message(
embed=discord.Embed(
title="Changement de salon",
description=(
"Le salon pour envoyer les nouveaux devoirs "
"à bien été mis à jour"
),
color=interaction.client.embed_color,
)
)

@app_commands.command(description="Donne la liste des prochains devoirs")
async def incoming(self, interaction: Interaction):
homeworks: JsonDict = json_wr("devoirs")

embed = discord.Embed(
title="Prochains devoirs",
color=interaction.client.embed_color
)

today = time.time()
homeworks_dict = {}
for date, homeworks_list in homeworks.items():

date_timestamp = int(time.mktime(time.strptime(date, "%Y-%m-%d")))
if date_timestamp >= today:
homeworks_dict[date_timestamp] = homeworks_list

homeworks_dict = {
key: homeworks_dict[key]
for key in sorted(homeworks_dict)
}

for date, homeworks_list in homeworks_dict.items():
embed.add_field(
name=f"Pour le <t:{date}:D>",
value="\n".join(
f"**- {h['subject']} :** {h['description']}"
for h in homeworks_list
),
inline=False,
)

await interaction.response.send_message(embed=embed)


async def setup(client: commands.Bot) -> None:
client.tree.add_command(PronoteCommandsGroup())
import time

import discord
from discord import app_commands, Interaction
from discord.ext import commands

from ..utils import json_wr, JsonDict


@app_commands.guild_only()
class PronoteCommandsGroup(app_commands.Group, name="pronote"):
@app_commands.command(name="help")
async def help_command(self, interaction: Interaction):
await interaction.response.send_message(
embed=discord.Embed(
title="Help of the Pronote",
description=(
"Un bot qui traque vos devoir pronote "
"et vous les notifient sur discord."
),
color=interaction.client.embed_color,
).add_field(
name="/pronote help",
value="Affiche ce message",
).add_field(
name="/pronote here",
value=("Change le salon d'envoi des nouveaux messages "
"pour pronote (nouveaux devoirs et notes)"),
).add_field(
name="/pronote incoming",
value="Affiche les prochains devoirs",
)
)

@app_commands.command()
async def here(self, interaction: Interaction):
pronote_config: JsonDict = json_wr("pronote")
pronote_config["channelID"] = interaction.channel_id
json_wr("pronote", data=pronote_config)

await interaction.response.send_message(
embed=discord.Embed(
title="Changement de salon",
description=(
"Le salon pour envoyer les nouveaux devoirs "
"à bien été mis à jour"
),
color=interaction.client.embed_color,
)
)

@app_commands.command(description="Donne la liste des prochains devoirs")
async def incoming(self, interaction: Interaction):
homeworks: JsonDict = json_wr("devoirs")

embed = discord.Embed(
title="Prochains devoirs",
color=interaction.client.embed_color
)

today = time.time()
homeworks_dict = {}
for date, homeworks_list in homeworks.items():

date_timestamp = int(time.mktime(time.strptime(date, "%Y-%m-%d")))
if date_timestamp >= today:
homeworks_dict[date_timestamp] = homeworks_list

homeworks_dict = {
key: homeworks_dict[key]
for key in sorted(homeworks_dict)
}

for date, homeworks_list in homeworks_dict.items():
embed.add_field(
name=f"Pour le <t:{date}:D>",
value="\n".join(
f"**- {h['subject']} :** {h['description']}"
for h in homeworks_list
),
inline=False,
)

await interaction.response.send_message(embed=embed)


async def setup(client: commands.Bot) -> None:
client.tree.add_command(PronoteCommandsGroup())
Loading

0 comments on commit d23f83c

Please sign in to comment.