Compare commits
3 commits
610ed92322
...
4fa08e9e97
| Author | SHA1 | Date | |
|---|---|---|---|
| 4fa08e9e97 | |||
| 6a9c1038d2 | |||
| 6cfeed39e1 |
7 changed files with 99 additions and 34 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -3,6 +3,8 @@ config.toml
|
|||
|
||||
.vscode
|
||||
|
||||
database.db
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[codz]
|
||||
|
|
|
|||
36
bot.py
36
bot.py
|
|
@ -1,17 +1,23 @@
|
|||
import os
|
||||
import importlib
|
||||
import aiosqlite
|
||||
|
||||
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):
|
||||
def __init__(self, lastfm_api_key: str, lastfm_api_secret: str, db_file: str = "database.db", *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
# initialize last.fm client
|
||||
self.lastfm = pylast.LastFMNetwork(
|
||||
api_key = lastfm_api_key,
|
||||
api_secret = lastfm_api_secret
|
||||
)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
self.db = None
|
||||
self.db_file = db_file
|
||||
|
||||
def load_commands(self, commands_dir: str):
|
||||
for filename in os.listdir(commands_dir):
|
||||
|
|
@ -22,3 +28,29 @@ class Bot(nerimity.Client):
|
|||
module.setup(self)
|
||||
print(f"Loaded {module_name}")
|
||||
print("Registered commands:", self.commands)
|
||||
|
||||
async def init_db(self):
|
||||
print("Initializing database...")
|
||||
self.db = await aiosqlite.connect(self.db_file)
|
||||
await self.db.execute("""
|
||||
CREATE TABLE IF NOT EXISTS lastfm_users (
|
||||
user_id TEXT PRIMARY KEY,
|
||||
lastfm_username TEXT NOT NULL
|
||||
)
|
||||
""")
|
||||
await self.db.commit()
|
||||
|
||||
async def set_lastfm(self, user_id: str, username: str):
|
||||
await self.db.execute(
|
||||
"INSERT OR REPLACE INTO lastfm_users (user_id, lastfm_username) VALUES (?, ?)",
|
||||
(user_id, username)
|
||||
)
|
||||
await self.db.commit()
|
||||
|
||||
async def get_lastfm(self, user_id: str):
|
||||
async with self.db.execute(
|
||||
"SELECT lastfm_username FROM lastfm_users WHERE user_id = ?",
|
||||
(user_id,)
|
||||
) as cursor:
|
||||
row = await cursor.fetchone()
|
||||
return row[0] if row else None
|
||||
|
|
|
|||
18
commands/config.py
Normal file
18
commands/config.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import nerimity
|
||||
|
||||
import bot
|
||||
import utils as u
|
||||
|
||||
def setup(bot: bot.Bot):
|
||||
@bot.command(name="setfm", aliases=["setuser", "setlastfm"])
|
||||
@bot.slash_command(name="setfm", description="Sets your Last.fm username.")
|
||||
async def setfm(ctx: nerimity.Context, username: str = None):
|
||||
if not username:
|
||||
await ctx.send(u.error_msg("Please provide your Last.fm username."))
|
||||
else:
|
||||
try:
|
||||
await bot.set_lastfm(ctx.author.id, username)
|
||||
await ctx.send(u.good_msg(f"Your Last.fm user has been set to **{username}**!"))
|
||||
except Exception as e:
|
||||
print(e)
|
||||
await ctx.send(u.error_msg("Unknown database error."))
|
||||
|
|
@ -1,38 +1,49 @@
|
|||
import nerimity
|
||||
import pylast
|
||||
|
||||
import commands.utils as u
|
||||
import bot
|
||||
import utils as u
|
||||
|
||||
def setup(bot):
|
||||
def setup(bot: bot.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"
|
||||
async def fm(ctx: nerimity.Context, lookup: str = None):
|
||||
if lookup: username = lookup
|
||||
else:
|
||||
try: username = await bot.get_lastfm(ctx.author.id)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
await ctx.send(u.error_msg("Unknown database error."))
|
||||
|
||||
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
|
||||
if not username:
|
||||
await ctx.send(u.error_msg("Please provide a Last.fm username (or set yours with `/setfm`)"))
|
||||
else:
|
||||
try:
|
||||
user = bot.lastfm.get_user(username)
|
||||
track = user.get_now_playing()
|
||||
if track == None:
|
||||
now_playing = False
|
||||
played_track = user.get_recent_tracks(limit=1)
|
||||
track = played_track[0].track
|
||||
|
||||
else:
|
||||
now_playing = True
|
||||
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()
|
||||
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})")
|
||||
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."))
|
||||
except IndexError:
|
||||
await ctx.send(u.error_msg(f"User **{username}** has no recent tracks or they're set to private."))
|
||||
except pylast.WSError:
|
||||
await ctx.send(u.error_msg(f"User **{username}** not found."))
|
||||
|
||||
except Exception as e:
|
||||
print(e)
|
||||
await ctx.send(u.error_msg("Unknown error."))
|
||||
|
|
|
|||
|
|
@ -1,2 +0,0 @@
|
|||
def error_msg(message: str):
|
||||
return f"[#e5323b][Error] [#reset]{message}"
|
||||
5
main.py
5
main.py
|
|
@ -1,7 +1,5 @@
|
|||
import tomllib
|
||||
|
||||
import nerimity
|
||||
import pylast
|
||||
|
||||
import bot
|
||||
|
||||
|
|
@ -10,8 +8,8 @@ with open("config.toml", "rb") as f:
|
|||
|
||||
# nerimity client
|
||||
bot = bot.Bot(
|
||||
token = config['token'],
|
||||
prefix = '!',
|
||||
token = config['token'],
|
||||
lastfm_api_key = config['api_key'],
|
||||
lastfm_api_secret = config['api_secret']
|
||||
)
|
||||
|
|
@ -21,5 +19,6 @@ bot.load_commands("commands")
|
|||
@bot.listen("on_ready")
|
||||
async def on_ready(params):
|
||||
print(f"Logged in as {bot.account.username}")
|
||||
await bot.init_db()
|
||||
|
||||
bot.run()
|
||||
|
|
|
|||
5
utils.py
Normal file
5
utils.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
def error_msg(message: str):
|
||||
return f"[#e5323b][Error] [#reset]{message}"
|
||||
|
||||
def good_msg(message: str):
|
||||
return f"[#52ff54][Success] [#reset]{message}"
|
||||
Loading…
Add table
Reference in a new issue