First implementation of event database for popular

This commit is contained in:
lomion 2022-12-20 19:45:57 +01:00 committed by Scott Wallace
parent 3523d1631b
commit 0f3cb6b3d3
Signed by: scott
GPG key ID: AA742FDC5AFE2A72
3 changed files with 70 additions and 7 deletions

View file

@ -14,7 +14,8 @@ 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/>. along with tmdb-bot. If not, see <https://www.gnu.org/licenses/>.
''' '''
from sqlalchemy import (Column, String, Integer, Table, MetaData, select) from time import time
from sqlalchemy import (Column, String, Integer, Table, MetaData, select, Float)
from sqlalchemy.engine.base import Engine from sqlalchemy.engine.base import Engine
@ -34,8 +35,26 @@ class Database:
Column("id", Integer, primary_key=True, autoincrement=True), Column("id", Integer, primary_key=True, autoincrement=True),
Column("user_id", String(255), nullable=False), Column("user_id", String(255), nullable=False),
Column("size", String(255), nullable=False),) Column("size", String(255), nullable=False),)
self.tmdb_messages = Table("tmdb_messages", meta,
Column("timestamp", Float, primary_key=True),
Column("event_id", String(64), nullable=False),
Column("result_json", String(255), nullable=False),)
meta.create_all(db) meta.create_all(db)
def set_message(self, event_id, result_json):
with self.db.begin() as tx:
timestamp = time()
tx.execute(self.tmdb_messages.insert().values(timestamp=timestamp, event_id=event_id, result_json=result_json))
def get_message(self, event_id):
rows = self.db.execute(select([self.tmdb_messages.c.result_json])
.where(self.tmdb_messages.c.event_id == event_id))
row = rows.fetchone()
if row:
return row['result_json']
else:
return None
def set_language(self, user_id, language): def set_language(self, user_id, language):
with self.db.begin() as tx: with self.db.begin() as tx:
tx.execute(self.language.delete().where(self.language.c.user_id == user_id)) tx.execute(self.language.delete().where(self.language.c.user_id == user_id))

View file

@ -15,11 +15,12 @@ along with tmdb-bot. If not, see <https://www.gnu.org/licenses/>.
''' '''
from html import escape from html import escape
import re import re
import json
from mautrix.types import TextMessageEventContent, MediaMessageEventContent, MessageType, Format, ImageInfo from mautrix.types import TextMessageEventContent, MediaMessageEventContent, MessageType, Format, ImageInfo, EventType
from maubot import Plugin, MessageEvent from maubot import Plugin, MessageEvent
from maubot.handlers import command from maubot.handlers import command, event
from tmdb.tmdb_api import TmdbApi, Movie, TvShow, MoviePopular from tmdb.tmdb_api import TmdbApi, Movie, TvShow, MoviePopular
from tmdb.database import Database from tmdb.database import Database
@ -59,18 +60,21 @@ class TmdbBot(Plugin):
self.db = Database(self.database) self.db = Database(self.database)
self.api = None self.api = None
async def send_html_message(self, evt: MessageEvent, text_message: str, html_message: str) -> None: async def send_html_message(self, evt: MessageEvent, text_message: str, html_message: str, data = None) -> None:
content = TextMessageEventContent( content = TextMessageEventContent(
msgtype=MessageType.TEXT, format=Format.HTML, msgtype=MessageType.TEXT, format=Format.HTML,
body=f"{text_message}", body=f"{text_message}",
formatted_body=f"{html_message}") formatted_body=f"{html_message}")
await evt.respond(content) event_id = await evt.respond(content)
if data:
self.db.set_message(event_id, json.dumps(data))
async def send_notice(self, evt: MessageEvent, message: str = "") -> None: async def send_notice(self, evt: MessageEvent, message: str = "") -> None:
content = TextMessageEventContent( content = TextMessageEventContent(
msgtype=MessageType.NOTICE, format=Format.HTML, msgtype=MessageType.NOTICE, format=Format.HTML,
body=message) body=message)
await evt.respond(content) event_id = await evt.respond(content)
self.db.set_message(event_id, '{ 1:"Notice"}')
async def send_help(self, evt: MessageEvent) -> None: async def send_help(self, evt: MessageEvent) -> None:
html = """<p>Use <b>!tmdb movie {title} [y:{release year}]</b> to get movie detail based on the given title.</p> html = """<p>Use <b>!tmdb movie {title} [y:{release year}]</b> to get movie detail based on the given title.</p>
@ -168,7 +172,8 @@ class TmdbBot(Plugin):
else: else:
text = popular.getListText(length) text = popular.getListText(length)
html = popular.getListHtml(length) html = popular.getListHtml(length)
await self.send_html_message(evt, text, html) results = popular.getDict(length)
await self.send_html_message(evt, text, html, results)
@command.new("movie-search", help="Movie lookup by Title") @command.new("movie-search", help="Movie lookup by Title")
@command.argument("message", pass_raw=True, required=True) @command.argument("message", pass_raw=True, required=True)
@ -269,3 +274,23 @@ class TmdbBot(Plugin):
await self.send_help(evt) await self.send_help(evt)
if self.api: if self.api:
await self.api.close_session() await self.api.close_session()
@event.on(EventType.ROOM_MESSAGE)
async def handle_reply(self, evt: MessageEvent) -> None:
reply_to = evt.content.get_reply_to()
if reply_to:
self.log.info(f"{evt.event_id} received. Reply to {evt.content.get_reply_to()}")
result_json = self.db.get_message(reply_to)
if result_json:
requ = int(evt.content.body)
if requ > 0:
populars = json.loads(result_json)
if str(requ) in populars:
await self.init_movie()
await self.api.search_id(populars[str(requ)])
await self.send_movie_info(evt, self.api)
#await self.movie_popular(evt, evt.content.body)
else:
self.log.info(f"Not in reply to a known message")
else:
self.log.info(f"No reply")

View file

@ -116,6 +116,18 @@ class MoviePopular(TmdbApi):
text += element['title'] text += element['title']
return text return text
def getDict(self, length: int = None) -> str:
result = {}
if length:
loop = length
else:
loop = self.length
id = 1
for element in self.list[:loop]:
result[id] = str(element['id'])
id += 1
return result
async def getMovieByNumber(self, number): async def getMovieByNumber(self, number):
movie = Movie() movie = Movie()
await movie.load_parameters() await movie.load_parameters()
@ -160,6 +172,13 @@ class Movie(TmdbApiSingle):
self.valid = False self.valid = False
return None return None
async def search_id(self, id):
await self.query_details(id)
await asyncio.gather(
self.query_cast(id),
self.query_image_binary())
return id
async def query_details(self, id): async def query_details(self, id):
data = await self.request('movie/' + str(id)) data = await self.request('movie/' + str(id))
self.title = data['title'] self.title = data['title']