Skip to content

Commit

Permalink
fix: Command Filter
Browse files Browse the repository at this point in the history
  • Loading branch information
krypton-byte committed Jul 11, 2024
1 parent a0244c7 commit 408ee82
Show file tree
Hide file tree
Showing 4 changed files with 195 additions and 9 deletions.
27 changes: 22 additions & 5 deletions thundra/button/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Iterable, Literal, NewType, overload
from typing import Iterable, Literal, overload

from neonize.proto.waE2E.WAWebProtobufsE2E_pb2 import (
DeviceListMetadata,
Expand All @@ -8,9 +8,9 @@
MessageContextInfo,
)

from thundra.button.v1 import CopyButton, ListButton, QuickReply

from thundra.button.v2 import ListButtonV2, QuickReplyV2
from thundra.button.v1 import CopyButton, ListButton, QuickReply, Row, Section
from thundra.button.registry import button_registry
from thundra.button.v2 import ListButtonV2, QuickReplyV2, RowV2, SectionV2

Button = QuickReply | ListButton | CopyButton | QuickReplyV2 | ListButtonV2

Expand Down Expand Up @@ -66,7 +66,8 @@ def create_button_message(
if buttons:
interactive_message.nativeFlowMessage.MergeFrom(
InteractiveMessage.NativeFlowMessage(
buttons=[button.create() for button in buttons]
buttons=[button.create() for button in buttons],
messageVersion=2
)
)
if direct_send:
Expand All @@ -82,3 +83,19 @@ def create_button_message(
)
)
return interactive_message


__all__ = (
'button_registry',
'ListButton',
'QuickReply',
'CopyButton',
'Row',
'Section',
'ListButtonV2',
'RowV2',
'QuickReplyV2',
'SectionV2',
'create_button_message',
'create_carousel_message'
)
6 changes: 3 additions & 3 deletions thundra/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def command(

class Command(Filter):
def __init__(
self, command: str, prefix: Optional[str] = None, space_detection: bool = True
self, command: str, prefix: Optional[str] = None
) -> None:
"""
Initializes a Command instance.
Expand All @@ -256,7 +256,7 @@ def __init__(
:param space_detection: A flag indicating whether to append a space to the command, defaults to False.
:type space_detection: bool, optional
"""
self.command = command + (" " if space_detection else "")
self.command = command
self.alt_prefix = prefix
super().__init__()

Expand All @@ -278,7 +278,7 @@ def filter(self, client: NewClient, message: Message) -> bool:
)
if matched:
_, end = matched.span(0)
return text[end:].startswith(self.command)
return text[end:].split(' ', 1)[0]==self.command
return False

def __repr__(self):
Expand Down
5 changes: 4 additions & 1 deletion thundra/templates/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
from thundra.core.memory import memory
from thundra.utils import ChainMessage, get_tag, get_user_id, get_message_type
from thundra.middleware import middleware
import signal
from thundra.core import chat_model
from thundra.button import button_registry
from neonize.events import event
import signal

# evaluate all module
from thundra.evaluater import evaluate_module
Expand Down Expand Up @@ -74,6 +75,8 @@ def on_message(client: NewClient, message: MessageEv):
r = middleware.execute(client, message)
if r in [False, None]:
cmd = command.execute(client, message)
if not cmd:
button_registry.click(client, message)
if not cmd and chat_model.available:
save_to_storage(message)
chat = message.Info.MessageSource.Chat
Expand Down
166 changes: 166 additions & 0 deletions thundra/templates/app/commands/yt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
from pathlib import Path
from neonize.client import NewClient
from neonize.proto.Neonize_pb2 import Message
from neonize.types import InteractiveMessage
from pydantic import BaseModel, Field
from thundra.button import create_button_message, ListButtonV2, RowV2, create_carousel_message
from thundra.command import Command, command
from thundra.utils import ChainMessage
from thundra.button.v2 import ListButtonV2, QuickReplyV2, RowV2, SectionV2
from concurrent.futures import ThreadPoolExecutor
from pytube import Search, YouTube
import sys
sys.path.insert(0, Path(__file__).parent.parent.__str__())
from agents.yt import convert_size, parse_duration


class AudioYT(BaseModel):
mime_type: str = Field()
abr: int = Field()
url: str = Field()


class VideoYT(BaseModel):
fps: int = Field()
vcodec: str = Field()
res: str = Field()
mime_type: str = Field()
url: str = Field()


class AudioSection(SectionV2[AudioYT]):
event_id = "audio_section"

def on_click(self, client: NewClient, message: Message, param: AudioYT):
client.send_audio(message.Info.MessageSource.Chat, param.url)


class VideoSection(SectionV2[VideoYT]):
event_id = "video_section"

def on_click(self, client: NewClient, message: Message, param: VideoYT):
client.send_video(message.Info.MessageSource.Chat, param.url)

def send_video_download_list(client: NewClient, message: Message, url: str):
yt = YouTube(url)
stream = yt.streams
audio_button = [
RowV2[AudioYT](
title=i.subtype,
header=i.bitrate.__str__(),
description=convert_size(i.filesize_approx),
params=AudioYT(mime_type=i.mime_type, abr=i.bitrate, url=i.url),
)
for i in stream.filter(type="audio")
]
video_button = [
RowV2[VideoYT](
header=i.resolution.__str__(),
title=i.fps.__str__(),
description=convert_size(i.filesize_approx),
params=VideoYT(
fps=i.fps,
vcodec=i.video_codec,
mime_type=i.mime_type,
res=i.resolution,
url=i.url,
),
)
for i in stream.filter(type="video")
]
msg = client.build_image_message(yt.thumbnail_url)
client.send_message(
message.Info.MessageSource.Chat,
create_button_message(
InteractiveMessage(
body=InteractiveMessage.Body(
text=f"Duration: {parse_duration(yt.length)}\nViews: {yt.views}\n\n{yt.description or ''}"
),
header=InteractiveMessage.Header(
title=yt.title,
imageMessage=msg.imageMessage,
hasMediaAttachment=True,
),
footer=InteractiveMessage.Footer(text="@thundra-ai"),
),
buttons=[
ListButtonV2(
title="Download",
sections=[
VideoSection(
title="Video", highlight_label="Video", rows=video_button
),
AudioSection(
title="Audio", highlight_label="Audio", rows=audio_button
),
],
)
],
),
)
@command.register(Command("yt"))
def yt(client: NewClient, message: Message):
url = ChainMessage.extract_text(message.Message)[3:].strip()
send_video_download_list(client, message, url)


class VideoMetadata(BaseModel):
url: str = Field()

class GetItem(QuickReplyV2[VideoMetadata]):
event_id= "get_video"
def on_click(self, client: NewClient, message: Message, params: VideoMetadata) -> None:
send_video_download_list(
client, message, params.url
)



@command.register(Command("ytsearch"))
def yt_search(client: NewClient, message: Message):
query = ChainMessage.extract_text(message.Message)[9:].strip()
search = Search(query)
def create_card(yt: YouTube):
return create_button_message(
InteractiveMessage(
header=InteractiveMessage.Header(
imageMessage=client.build_image_message(yt.thumbnail_url).imageMessage,
title=yt.title,
subtitle='',
hasMediaAttachment=True
),
body=InteractiveMessage.Body(text=f"{yt.title}\nduration: {parse_duration(yt.length)}\ndescription: {yt.description}"),
footer=InteractiveMessage.Footer(text=yt.author)
),
[
GetItem(
display_text="Download",
params=VideoMetadata(
url=yt.watch_url
)
)
],
direct_send=False
)
cards = []
results = search.results
if results:
with ThreadPoolExecutor(max_workers=5) as th:
for item in th.map(create_card, results[:5]):
cards.append(
item
)
client.send_message(
message.Info.MessageSource.Chat,
create_carousel_message(
InteractiveMessage(
body=InteractiveMessage.Body(text="hasil pencarian youtube dengan query %r" % query)
),
cards=cards
)
)
else:
client.reply_message(
"Video tidak ditemukan",
message
)

0 comments on commit 408ee82

Please sign in to comment.