import datetime import random from base import config from models.level import Level from models.user import User from discord import TextChannel class Exp: def __init__(self, user: User, bot_channel: TextChannel): self.user = user self.channel = bot_channel async def calculate_exp(self): self.add_message(self.user) gained_exp = self.gain_exp(self.user) if gained_exp: if self.check_level_up(self.user): await self.level_up(self.user, self.channel) def add_message(self, user: User): messages = user.message_count user.message_count = messages + 1 user.save() def gain_exp(self, user: User): time_now = datetime.datetime.utcnow() minute_ago = time_now - datetime.timedelta(seconds=60) print(f"now: {time_now}, minute: {minute_ago}, user: {user.exp_gained_time}") if user.exp_gained_time is None or user.exp_gained_time < minute_ago: gained_exp = random.randrange(15, 25) total_exp = user.exp + gained_exp user.exp = total_exp user.exp_gained_time = time_now user.save() return True else: return False def check_level_up(self, user: User): next_level = Level.get(user.level + 1) if user.exp > next_level.exp_required: return True else: return False async def level_up(self, user: User, channel: TextChannel): user.level += 1 level = Level.get(level=user.level) user.currency += level.reward_currency await channel.send( f"Congrats {user.display_name}, you levelled up to {user.level}! You win {level.reward_currency} {config['currency']}!" ) user.save()