Add "Most Popular" - Part2

This commit is contained in:
lomion 2021-03-16 21:45:27 +01:00
parent 53d14f153c
commit 483372284c
4 changed files with 77 additions and 17 deletions

2
.gitignore vendored
View file

@ -129,5 +129,5 @@ dmypy.json
# Pyre type checker
.pyre/
lomion.tmdb.mbp
*.mbp
test.db

View file

@ -1,16 +1,18 @@
#!/usr/bin/env python3
import unittest
import requests
from html import escape
from tmdb.tmdb_api import Movie, TvShow, MoviePopular
from tmdb.tmdb import TmdbBot, MessageConstructor
from tmdb.database import Database
from sqlalchemy import create_engine
def apiRequests(command):
api_key = '51d75c00dc1502dc894b7773ec3e7a15'
base_url = "https://api.themoviedb.org/3/"
url = base_url + command.lstrip('/')
params={'api_key': api_key}
params = {'api_key': api_key}
params.update({'language': 'en'})
return requests.get(url, params=params).json()
@ -125,5 +127,28 @@ class TestTmdbMethods(unittest.TestCase):
list = MoviePopular()
self.assertEqual(list.query(), results['total_results'])
def test_movie_popular_id(self):
results = apiRequests('/movie/popular')
list = MoviePopular()
list.query()
self.assertEqual(list.list[2]['id'], results['results'][2]['id'])
def test_movie_popular_html(self):
results = apiRequests('/movie/popular')
list = MoviePopular()
list.query()
test_result = escape(results['results'][-1]['title'])
tested = list.getListHtml()[(len(results['results'][-1]['title']) + 8) * -1:]
self.assertEqual(tested, f"""{test_result}</a></p>""")
def test_movie_popular_text(self):
results = apiRequests('/movie/popular')
list = MoviePopular()
list.query()
test_result = results['results'][-1]['title']
tested = list.getListText()[(len(results['results'][-1]['title'])) * -1:]
self.assertEqual(tested, test_result)
if __name__ == '__main__':
unittest.main()

View file

@ -21,7 +21,7 @@ from mautrix.types import TextMessageEventContent, MediaMessageEventContent, Mes
from maubot import Plugin, MessageEvent
from maubot.handlers import command
from tmdb.tmdb_api import TmdbApi, Movie, TvShow
from tmdb.tmdb_api import TmdbApi, Movie, TvShow, MoviePopular
from tmdb.database import Database
@ -74,7 +74,7 @@ class TmdbBot(Plugin):
# <p>{cast}</p>
# <p>taken from www.themoviedb.org</p>"""
async def send_html_message(self, evt: MessageEvent, text_message, html_message) -> None:
async def send_html_message(self, evt: MessageEvent, text_message: str, html_message: str) -> None:
content = TextMessageEventContent(
msgtype=MessageType.TEXT, format=Format.HTML,
body=f"{text_message}",
@ -90,6 +90,7 @@ class TmdbBot(Plugin):
async def send_help(self, evt: MessageEvent) -> None:
html = """<p>Use <b>!tmdb id movie {tmdb id}</b> to get movie detail for tmdb-id.</p>
<p>Use <b>!tmdb movie {title} [y:{release year}]</b> to get movie detail based on the given title.</p>
<p>Use <b>!tmdb popular</b> to get most popular movies.</p>
<p>Use <b>!tmdb language {language}</b> to set your prefered language.</p>
<p>Use <b>!tmdb poster_size [{size}]</b> to set your prefered poster size. With empty {size} all available sizes are listed.</p>
<p>Use <b>!tmdb tvshow {title}</b> to get detail about a tv show based on the given title.</p>"""
@ -147,21 +148,13 @@ class TmdbBot(Plugin):
async def command_movie_id(self, evt: MessageEvent, message: str = "") -> None:
await self.movie_id(evt, message)
async def movie_search(self, evt: MessageEvent, message: str = "") -> None:
movie = Movie()
self.poster_size(evt, movie)
async def movie_popular(self, evt: MessageEvent, message: str = "") -> None:
popular = MoviePopular()
language = self.db.get_language(evt.sender)
if language:
movie.set_language(language)
title, year = self.split_title_year(message)
movie.search_title(title, year)
if movie.valid:
await self.send_movie_info(evt, movie)
else:
content = TextMessageEventContent(
msgtype=MessageType.NOTICE, format=Format.HTML,
body="No movie found!")
await evt.respond(content)
popular.set_language(language)
length = 5
await self.send_html_message(evt, popular.getListText(length), popular.getListHtml(length))
@command.new("movie-search", help="Movie lookup by Title")
@command.argument("message", pass_raw=True, required=True)
@ -220,6 +213,22 @@ class TmdbBot(Plugin):
async def command_tvshow_search(self, evt: MessageEvent, message: str = "") -> None:
await self.tvshow_search(evt, message)
async def movie_search(self, evt: MessageEvent, message: str = "") -> None:
movie = Movie()
self.poster_size(evt, movie)
language = self.db.get_language(evt.sender)
if language:
movie.set_language(language)
title, year = self.split_title_year(message)
movie.search_title(title, year)
if movie.valid:
await self.send_movie_info(evt, movie)
else:
content = TextMessageEventContent(
msgtype=MessageType.NOTICE, format=Format.HTML,
body="No movie found!")
await evt.respond(content)
@command.new("tmdb", help="TMDB Bot")
@command.argument("message", pass_raw=True, required=True)
async def command_dispatcher(self, evt: MessageEvent, message: str = "") -> None:
@ -231,6 +240,8 @@ class TmdbBot(Plugin):
await self.send_help(evt)
elif command.lower() == 'movie':
await self.movie_search(evt, parameters)
elif command.lower() == 'popular':
await self.movie_popular(evt, parameters)
elif command.lower() == 'language':
await self.movie_language(evt, parameters)
elif command.lower() == 'poster_size':

View file

@ -14,6 +14,7 @@ You should have received a copy of the GNU Affero General Public License
along with tmdb-bot. If not, see <https://www.gnu.org/licenses/>.
'''
import requests
from html import escape
class TmdbApi():
@ -68,6 +69,7 @@ class TmdbApiSingle(TmdbApi):
return x
return None
class MoviePopular(TmdbApi):
def __init__(self):
super().__init__()
@ -80,6 +82,28 @@ class MoviePopular(TmdbApi):
self.list = result['results']
return self.length
def getListHtml(self, length: int = None) -> str:
self.query()
html = ""
if length:
loop = length
else:
loop = self.length
for element in self.list[:loop]:
html += f"""<p><a href="https://www.themoviedb.org/movie/{str(element['id'])}">{escape(element['title'])}</a></p>"""
return html
def getListText(self, length: int = None) -> str:
self.query()
text = ""
if length:
loop = length
else:
loop = self.length
for element in self.list[:loop]:
text += element['title']
return text
class Movie(TmdbApiSingle):
def __init__(self):