Skip to content

Commit

Permalink
Merge pull request #2 from Zalk0/py3.11
Browse files Browse the repository at this point in the history
Merge to main
  • Loading branch information
Zalk0 authored Oct 20, 2023
2 parents 62d8122 + 84e3a4e commit 6856f36
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 49 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Token of the Discord bot
BOT_TOKEN=
# Log level (see logging library, defaults to INFO if not defined)
LOG_LEVEL=DEBUG
# See doc to see status and activity type allowed
BOT_STATUS=online
BOT_ACTIVITY_TYPE=listening
Expand Down
20 changes: 12 additions & 8 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ def __init__(self):
# Associate the config to the bot
self.config = dotenv_values()

# Define the bot debug log level
self.bot_logger = logging.getLogger('bot')
self.bot_logger.setLevel(logging.getLevelNamesMapping().get(self.config['LOG_LEVEL']) or logging.INFO)

# Set intents for the bot
intents = discord.Intents.all()

Expand Down Expand Up @@ -54,10 +58,10 @@ async def on_ready(self):
self.first = False

# Check the number of servers the bot is a part of
logging.info(f"Number of servers I'm in : {len(self.guilds)}")
self.bot_logger.info(f"Number of servers I'm in : {len(self.guilds)}")

# Log in the console that the bot is ready
logging.info(f"{self.user} is now online and ready!")
self.bot_logger.info(f"{self.user} is now online and ready!")

# To react to messages sent in channels bot has access to
async def on_message(self, message):
Expand All @@ -71,13 +75,13 @@ async def on_message(self, message):
channel = message.channel

# Do a log on the Python console
# if message.guild is not None:
# logging.info(f'{username} said: "{user_msg}" #{channel} in {message.guild.name}')
# else:
# logging.info(f'{username} said: "{user_msg}" in Direct Message')
if message.guild is not None:
self.bot_logger.debug(f'{username} said: "{user_msg}" #{channel} in {message.guild.name}')
else:
self.bot_logger.debug(f'{username} said: "{user_msg}" in Direct Message')

# Call responses with message of the user and responds if necessary
response = await responses(self, user_msg, channel)
response = await responses(self, channel, user_msg, username)
if not response == '':
await channel.send(response)
logging.info(f'{self.user} responded : "{response}"')
self.bot_logger.info(f'{self.user} responded to {username}: "{response}"')
6 changes: 3 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ def main():

# Setup the logging
os.makedirs('logs', exist_ok=True)
handler = handlers.RotatingFileHandler(filename=os.path.join('logs', 'bot.log'), encoding='utf-8',
backupCount=3, delay=True)
handler = handlers.RotatingFileHandler(filename=os.path.join('logs', 'bot.log'), backupCount=3,
encoding='utf-8', delay=True)
handler.doRollover()

# Run the client with the token
client.run(client.config['BOT_TOKEN'], reconnect=True, root_logger=True, log_handler=handler)
client.run(client.config['BOT_TOKEN'], reconnect=True, log_handler=handler, root_logger=True)


if __name__ == '__main__':
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
aiohttp~=3.8.6
discord.py~=2.3.2
requests~=2.31.0
python-dotenv~=1.0.0
6 changes: 2 additions & 4 deletions responses.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import logging

from src.latex_render import latex_process


async def responses(self, message: str, channel) -> str:
async def responses(self, channel, message: str, username: str) -> str:
# Checks if a message ends with quoi
if ''.join(filter(str.isalpha, message)).lower().endswith("quoi"):
return "**FEUR**"
Expand All @@ -12,7 +10,7 @@ async def responses(self, message: str, channel) -> str:
if message.count("$") > 1:
if (message.count("$") % 2) == 0:
await channel.send(file=await latex_process(message))
logging.info(f'{self.user} responded : "equation.png"')
self.bot_logger.info(f'{self.user} responded to {username}: "equation.png"')
return ''
return "Nombre de $ impair, " \
"veuillez en mettre un nombre pair pour que je puisse afficher les équations LaTeX !"
Expand Down
73 changes: 40 additions & 33 deletions src/skyblock_guild.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,46 @@
import requests
import aiohttp
from dotenv import dotenv_values

api_hypixel = "https://api.hypixel.net/"
token_hypixel = dotenv_values()['HYPIXEL_KEY']


def return_discord_hypixel(uuid):
req = requests.get(f"{api_hypixel}player?key={token_hypixel}&uuid={uuid}").json()
async def fetch(session, url, params=None):
async with session.get(url, params=params) as response:
return await response.json()


async def return_discord_hypixel(session, uuid):
response = await fetch(session, f"{api_hypixel}player", {"key": token_hypixel, "uuid": uuid})
try:
return req["player"]["socialMedia"]["links"]["DISCORD"]
return response["player"]["socialMedia"]["links"]["DISCORD"]
except Exception:
if req["success"] == "true":
if response["success"] == "true":
return 0
return


def return_uuid(pseudo):
req = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{pseudo}").json()
async def return_uuid(session, pseudo):
response = await fetch(session, f"https://api.mojang.com/users/profiles/minecraft/{pseudo}")
try:
return req["id"]
return response["id"]
except Exception:
# This Minecraft pseudo doesn't exist
if req["errorMessage"] == f"Couldn't find any profile with name {pseudo}":
if response["errorMessage"] == f"Couldn't find any profile with name {pseudo}":
return 0
return


def return_guild(name):
req = requests.get(f"{api_hypixel}guild?key={token_hypixel}&name={name}").json()
async def return_guild(session, name):
response = await fetch(session, f"{api_hypixel}guild", {"key": token_hypixel, "name": name})
try:
return req["guild"]
return response["guild"]
except Exception:
return


def is_in_guild(uuid, g_name):
guild = return_guild(g_name)
async def is_in_guild(session, uuid, g_name):
guild = await return_guild(session, g_name)
if guild is None:
return
for member in guild["members"]:
Expand All @@ -44,23 +49,25 @@ def is_in_guild(uuid, g_name):
return False


def check(pseudo, guild, discord):
async def check(pseudo, guild, discord):
async with aiohttp.ClientSession() as session:
uuid = await return_uuid(session, pseudo)
if uuid == 0:
return f"Il n'y a pas de compte Minecraft avec ce pseudo : {pseudo}"
elif uuid is None:
return "Something wrong happened"

uuid = return_uuid(pseudo)
if uuid == 0:
return f"Il n'y a pas de compte Minecraft avec ce pseudo : {pseudo}"
elif uuid is None:
return "Something wrong happened"
discord_mc = return_discord_hypixel(uuid)
if discord_mc == 0:
return "Vous n'avez pas entré de pseudo Discord sur le serveur Hypixel"
elif not discord_mc == discord:
return "Votre pseudo Discord ne correspond pas à celui entré sur le serveur Hypixel"
elif discord_mc is None:
return "Something wrong happened"
test = is_in_guild(uuid, guild)
if test:
return True
elif test is None:
return f"Il n'y a pas de guilde avec ce nom : {guild}"
return "Something very wrong happened"
discord_mc = await return_discord_hypixel(session, uuid)
if discord_mc == 0:
return "Vous n'avez pas entré de pseudo Discord sur le serveur Hypixel"
elif not discord_mc == discord:
return "Votre pseudo Discord ne correspond pas à celui entré sur le serveur Hypixel"
elif discord_mc is None:
return "Something wrong happened"

test = await is_in_guild(session, uuid, guild)
if test:
return True
elif test is None:
return f"Il n'y a pas de guilde avec ce nom : {guild}"
return "Something very wrong happened"

0 comments on commit 6856f36

Please sign in to comment.