Skip to content

Commit a96c307

Browse files
committed
Start youtube notifications
1 parent c3e6a1c commit a96c307

File tree

4 files changed

+89
-10
lines changed

4 files changed

+89
-10
lines changed

lib/bot/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ async def on_disconnect(self):
6060
print(f"Bot Disconnected, Retrying to sign into user {self.user.display_name}#{self.user.discriminator}")
6161

6262
async def on_guild_join(self, guild: Guild):
63-
self.db.execute("""INSERT OR IGNORE INTO guilds VALUES (?,?)""", guild.id, None)
63+
self.db.execute("""INSERT OR IGNORE INTO guilds VALUES (?,?,?)""", guild.id, None, None)
6464

6565
async def on_guild_remove(self, guild: Guild):
6666
self.db.execute("""DELETE FROM guilds WHERE id=?""", guild.id)
@@ -90,7 +90,7 @@ async def on_interaction(self, interaction: discord.Interaction):
9090
if interaction.is_command():
9191
name_list, options = self.get_name(interaction.data, [])
9292
name = " ".join(name_list)
93-
self.db.execute(f"""INSERT INTO commands VALUES (?,?,?,?,?)""", name, interaction.guild_id, interaction.user.id, json.dumps(options), datetime.now().timestamp())
93+
# self.db.execute(f"""INSERT INTO commands VALUES (?,?,?,?,?)""", name, interaction.guild_id, interaction.user.id, json.dumps(options), datetime.now().timestamp())
9494
return await super().on_interaction(interaction=interaction)
9595

9696
async def on_application_command_error(self, ctx: CustomContext, exc) -> None:

lib/cogs/Youtube.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import re
2+
3+
from discord.ext.commands import Cog
4+
from discord.commands import slash_command, SlashCommandGroup, option
5+
from discord.embeds import Embed
6+
import aiohttp
7+
8+
from bs4 import BeautifulSoup
9+
10+
from lib.bot import Bot
11+
from lib.context import CustomContext
12+
13+
14+
class Youtube(Cog):
15+
def __init__(self, bot):
16+
self.bot: Bot = bot
17+
18+
youtube = SlashCommandGroup('youtube')
19+
20+
def check_channel(self, handle: str, message: str, guild_id: str):
21+
async with aiohttp.ClientSession() as session:
22+
res = await session.get(f"https://youtube.com/@{handle}/videos")
23+
html = await res.text()
24+
try:
25+
latest_video_url = "https://www.youtube.com/watch?v=" + re.search('(?<="videoId":").*?(?=")',
26+
html).group()
27+
except AttributeError:
28+
latest_video_url = ""
29+
30+
31+
@youtube.command(name='notify', description='Get a ping when this user uploads')
32+
@option('handle',
33+
str,
34+
description='Youtube handle',
35+
required=True)
36+
@option('message',
37+
str,
38+
description='Message to send when video is uploaded',
39+
required=False)
40+
@option('channel',
41+
str,
42+
description='Channel to send announcement',
43+
required=False)
44+
async def youtube_notify(self, ctx: CustomContext, handle: str, message: str | None):
45+
async with aiohttp.ClientSession() as session:
46+
res = await session.get(f"https://youtube.com/@{handle}/videos")
47+
if res.status == 404:
48+
return await ctx.respond(embed=Embed(title=':x: | Channel not found', colour=0xff0000))
49+
elif res.status not in range(200, 300):
50+
return await ctx.respond(embed=Embed(title=':x: | Something went wrong', colour=0xff0000))
51+
52+
user = self.bot.db.record("""SELECT * FROM youtube WHERE handle = ? AND guild_id = ?""", handle, ctx.guild_id)
53+
if user:
54+
return await ctx.respond(embed=Embed(title=':x: | Already watching for new videos', colour=0xff0000))
55+
56+
res = await session.get(f"https://youtube.com/@{handle}/videos")
57+
html = await res.text()
58+
59+
try:
60+
latest_video_url = "https://www.youtube.com/watch?v=" + re.search('(?<="videoId":").*?(?=")', html).group()
61+
except AttributeError:
62+
latest_video_url = ""
63+
self.bot.db.execute("""INSERT INTO youtube VALUES (?,?,?,?)""", handle, ctx.guild_id, message if message else f"@{handle} has uploaded a video", latest_video_url)
64+
await ctx.respond(embed=Embed(title=f'✅ | Waiting for @{handle} to post more videos'))
65+
self.bot.tasks.add_job(id=f"{handle}|{ctx.guild_id}", args=(handle, message, ctx.guild_id,), trigger='interval', minutes=1)
66+
67+
68+
69+
70+
71+
72+
73+
74+
75+
def setup(bot):
76+
bot.add_cog(Youtube(bot))

lib/db/__init__.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ class DB:
1717
},
1818
'guilds': {
1919
'id': 'TEXT PRIMARY KEY NOT NULL',
20-
'l_id': 'TEXT',
21-
'a_id': 'TEXT'
20+
'level_id': 'TEXT',
21+
'announce_id': 'TEXT'
2222
},
2323
'reports': {
2424
'guild_id': 'TEXT',
@@ -37,22 +37,24 @@ class DB:
3737
'guild_id': 'TEXT',
3838
'user_id': 'TEXT',
3939
'xp': 'INTEGER'
40+
},
41+
'youtube': {
42+
'handle': 'TEXT',
43+
'guild_id': 'TEXT',
44+
'message': 'TEXT',
45+
'latest_url': 'TEXT'
4046
}
4147
}
4248

4349
def __init__(self):
4450
self.cxn = connect(self.DB_PATH, check_same_thread=False)
4551
self.cur = self.cxn.cursor()
4652

47-
@staticmethod
48-
def diff(list1, list2):
49-
return list(set(list1).symmetric_difference(set(list2)))
50-
5153
def update_table(self, table: str, columns_str_list: list[str], columns_list: dict[str, str]):
5254
self.cur.execute(f"CREATE TABLE {table}_new ({' '.join(columns_str_list)});")
5355
self.cur.execute(f"INSERT INTO {table}_new SELECT * FROM {table};")
5456
self.cur.execute(f"DROP TABLE {table};")
55-
self.cur.execute(f"ALTER TABLE {table}_new RENAME TO {table}")
57+
self.cur.execute(f"ALTER TABLE {table}_new RENAME TO {table};")
5658

5759
def build(self) -> None:
5860
for table, columns in self.tables.items():

template.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from discord.ext.commands import Cog
2-
from discord.commands import slash_command
2+
from discord.commands import slash_command, SlashCommandGroup, option
3+
from discord.embeds import Embed
34

45
from lib.bot import Bot
56
from lib.context import CustomContext

0 commit comments

Comments
 (0)