MarxBot/bot/marxbot.py

162 lines
6.4 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# System packages
import logging
from pathlib import Path
from typing import Dict, Any
# PyPi packages
import discord
import bot.dbmanager as dbmanager
class MarxBot(discord.Client):
def __init__(self, botconfig: Dict[str, Any], *args, **kwargs):
super().__init__(*args, **kwargs)
# Paths for various information.
self.path_root: Path = Path(botconfig["path_root"])
self.path_sqldb: Path = self.path_root / botconfig["path_sqldb"]
# Prefix of every command to call the bot.
self.command = botconfig["command"]
self.subcommand = {
"cite": {
"--marx": "Karl Marx",
"--kadoc": "Kadoc"
}
}
# Answer requests from these servers only (Tea-Tanches or Obi'lia)
self.authorized_servers = [93251981056970752, 363070323412697088]
# Initialize the DB.
dbmanager.initialize(self.path_sqldb)
async def on_ready(self):
logging.info(f"MarxBot is ready as {self.user}")
async def on_message(self, message):
# Avoid responding to ourselves
if message.author == self.user:
return
msg_txt = message.content
msg_channel = message.channel
msg_guild = message.guild
msg_author = message.author
# If called from an unauthorized server:
if msg_guild is None or msg_guild.id not in self.authorized_servers:
return
# We record the number of words from each member coming from the guild "Les Tea-Tanches".
if msg_guild is not None and msg_guild.id == 93251981056970752:
await dbmanager.add_numberword(self.path_sqldb, message)
# The bot is not called by someone.
if not msg_txt.startswith(self.command):
return
# The bot prints a random citation.
if msg_txt.startswith(f"{self.command} cite"):
await self.send_msg_citation(msg_channel, msg_txt)
# The bot prints help if needed.
elif msg_txt.startswith(f"{self.command} help") or msg_txt.startswith(f"{self.command} aide"):
await self.send_msg_help(msg_channel)
# The bot sends the best music in the world.
elif msg_txt.startswith(f"{self.command} music") or msg_txt.startswith(f"{self.command} musique"):
await self.send_msg_music(msg_channel)
# The bot prints the number of words written by the members of the guild "Les Tea-Tanches".
elif msg_txt.startswith(f"{self.command} words") or msg_txt.startswith(f"{self.command} mots"):
await self.send_msg_stats(msg_channel, msg_guild)
elif msg_txt.startswith(f"{self.command} birthday") or msg_txt.startswith(f"{self.command} anniversaire"):
if "--add" in msg_txt or "--ajouter" in msg_txt:
self.add_birthday(msg_author, msg_txt)
elif "--delete" in msg_txt or "--effacer" in msg_txt:
self.delete_birthday(msg_author)
else:
await self.send_msg_birthday(msg_channel, msg_guild)
# The bot shutdown if I tell it to do so.
elif msg_txt.startswith(f"{self.command} shutdown"):
await self.close()
# If the command has not been recognized by the bot.
else:
await msg_channel.send("Commande non reconnue :c")
async def shutdown(self, msg_author: discord.User):
if msg_author.id == 133318295003594752:
await self.close()
async def send_msg_help(self, channel: discord.TextChannel) -> None:
help_str = "```\n"
help_str += "Utilisation : \n"
help_str += "\t─ !marx cite [--marx|--kadoc] : Afficher une citation inspirante.\n"
help_str += "\t─ !marx aide : Afficher l'aide.\n"
help_str += "\t─ !marx mots : Afficher qui est le meilleur spammeur.\n"
help_str += "\t─ !marx musique : Donne un lien vers la meilleure musique du monde !\n"
help_str += "\t─ !marx anniversaire : Affiche toutes les dates d'anniversaire.\n"
help_str += "\t\t─ !marx anniversaire --ajouter date_anniversaire_texte : Rajouter sa date d'anniversaire.\n"
help_str += "\t\t─ !marx anniversaire --effacer : Effacer sa date d'anniversaire.\n"
help_str += "```"
await channel.send(help_str)
async def send_msg_stats(self, msg_channel: discord.TextChannel, msg_guild: discord.Guild):
# Server Tea-Tanches or Obi'lia
if msg_guild.id == 93251981056970752 or msg_guild.id == 363070323412697088:
await msg_channel.send(dbmanager.get_numberwords(self.path_sqldb, msg_guild))
async def send_msg_citation(self, msg_channel: discord.TextChannel, msg_txt: str):
options = msg_txt.split()
author = None
if "--marx" in options:
author = self.subcommand.get("cite").get("--marx")
elif "--kadoc" in options:
author = self.subcommand.get("cite").get("--kadoc")
await msg_channel.send(dbmanager.get_citation(self.path_sqldb, author))
async def send_msg_music(self, msg_channel: discord.TextChannel):
await msg_channel.send(":notes: https://www.youtube.com/watch?v=wKDD1H-Hlpc :musical_note:")
def add_birthday(self, msg_author: discord.Member, msg_txt: str):
if "--add" in msg_txt:
birthday_txt = msg_txt.split("--add ")[-1]
elif "--ajouter" in msg_txt:
birthday_txt = msg_txt.split("--ajouter ")[-1]
else:
logging.warning(f"No --add or --ajouter parameter found: {msg_txt}")
return
dbmanager.add_birthday(self.path_sqldb, str(msg_author.id), birthday_txt)
def delete_birthday(self, msg_author: discord.Member):
dbmanager.delete_birthday(self.path_sqldb, str(msg_author.id))
async def send_msg_birthday(self, msg_channel: discord.TextChannel, msg_guild: discord.Guild):
birthday = dbmanager.get_all_birthday(self.path_sqldb)
birthday_str = "```\nJours d'anniversaire :\n"
for birthday_id, birthday_txt in birthday.items():
member = msg_guild.get_member(int(birthday_id))
if member is not None:
birthday_str += f"\t· {member.display_name} -- {birthday_txt}.\n"
if len(birthday.keys()) == 0:
birthday_str += "\t Aucun anniversaire :c"
birthday_str += "```"
await msg_channel.send(birthday_str)