Compare commits

...

4 commits

Author SHA1 Message Date
610ed92322 add __init__.py 2025-10-07 01:51:13 -03:00
980c4153ac migrate np command to folder 2025-10-07 01:51:05 -03:00
1aebafc648 merge lastfm client into bot class 2025-10-07 01:50:51 -03:00
1ed84a6058 create Bot class and command modules 2025-10-07 01:38:27 -03:00
6 changed files with 79 additions and 58 deletions

24
bot.py Normal file
View file

@ -0,0 +1,24 @@
import os
import importlib
import nerimity
import pylast
class Bot(nerimity.Client):
"""Extended client class for extra functionality."""
def __init__(self, lastfm_api_key: str, lastfm_api_secret: str, *args, **kwargs):
self.lastfm = pylast.LastFMNetwork(
api_key = lastfm_api_key,
api_secret = lastfm_api_secret
)
super().__init__(*args, **kwargs)
def load_commands(self, commands_dir: str):
for filename in os.listdir(commands_dir):
if filename.endswith(".py") and not filename.startswith("_"):
module_name = f"{commands_dir}.{filename[:-3]}"
module = importlib.import_module(module_name)
if hasattr(module, "setup"):
module.setup(self)
print(f"Loaded {module_name}")
print("Registered commands:", self.commands)

0
commands/__init__.py Normal file
View file

38
commands/now_playing.py Normal file
View file

@ -0,0 +1,38 @@
import nerimity
import pylast
import commands.utils as u
def setup(bot):
@bot.command(name="fm", aliases=["np"])
@bot.slash_command(name="fm", description="Shows what you're currently playing")
async def fm(ctx: nerimity.Context, params: str = ""):
username = params if params else "kaaisudev"
try:
track = bot.lastfm.get_user(username).get_now_playing()
if track == None:
now_playing = False
played_track = bot.lastfm.get_user(username).get_recent_tracks(limit=1)
track = played_track[0].track
else:
now_playing = True
track_url = track.get_url()
track_name = track.get_name()
track_artist = track.get_artist().get_name()
track_artist_url = track.get_artist().get_url()
if now_playing == True:
await ctx.send(f"Now playing for **{username}**: [{track_name}]({track_url}) by [{track_artist}]({track_artist_url})")
else:
await ctx.send(f"Last played for **{username}**: [{track_name}]({track_url}) by [{track_artist}]({track_artist_url})")
except IndexError:
await ctx.send(u.error_msg("User has no recent tracks or they're set to private."))
except pylast.WSError:
await ctx.send(u.error_msg("User not found."))
except Exception as e:
print(e)
await ctx.send(u.error_msg("Unknown error."))

7
commands/ping.py Normal file
View file

@ -0,0 +1,7 @@
import nerimity
def setup(bot):
@bot.command(name="ping")
@bot.slash_command(name="ping", description="Ping...")
async def ping(ctx: nerimity.Context):
await ctx.send("Pong!")

68
main.py
View file

@ -3,71 +3,23 @@ import tomllib
import nerimity
import pylast
import utils
import bot
with open("config.toml", "rb") as f:
config = tomllib.load(f)
# last.fm client
network = pylast.LastFMNetwork(
api_key = config['api_key'],
api_secret = config['api_secret']
)
# nerimity client
client = nerimity.Client(
token=config['token'],
prefix='!'
bot = bot.Bot(
token = config['token'],
prefix = '!',
lastfm_api_key = config['api_key'],
lastfm_api_secret = config['api_secret']
)
# Prefix command -> !ping
@client.command(name="ping")
@client.slash_command(name="ping", description="Ping...")
async def ping(ctx: nerimity.Context):
await ctx.send("Pong!")
bot.load_commands("commands")
# fm command
@client.command(name="fm", aliases=["np"])
@client.slash_command(name="fm", description="Shows what you're currently playing")
async def fm(ctx: nerimity.Context, params: str = ""):
username = ""
if params == "":
username = "kaaisudev"
else:
username = params
try:
track = network.get_user(username).get_now_playing()
if track == None:
now_playing = False
played_track = network.get_user(username).get_recent_tracks(limit=1)
track = played_track[0].track
else:
now_playing = True
track_url = track.get_url()
track_name = track.get_name()
track_artist = track.get_artist().get_name()
track_artist_url = track.get_artist().get_url()
if now_playing == True:
await ctx.send(f"Now playing for **{username}**: [{track_name}]({track_url}) by [{track_artist}]({track_artist_url})")
else:
await ctx.send(f"Last played for **{username}**: [{track_name}]({track_url}) by [{track_artist}]({track_artist_url})")
except IndexError:
await ctx.send(utils.error_msg("User has no recent tracks or they're set to private."))
except pylast.WSError:
await ctx.send(utils.error_msg("User not found."))
except Exception as e:
print(e)
await ctx.send(utils.error_msg("Unknown error."))
@client.listen("on_ready")
@bot.listen("on_ready")
async def on_ready(params):
print(f"Logged in as {client.account.username}")
print(f"Logged in as {bot.account.username}")
client.run()
bot.run()