#!/usr/bin/env python3 """ This module exracts various information from imbd. It also contains functionality for the local movie database. """ import os import random import threading from sqlite3 import IntegrityError, OperationalError import bs4 import requests import config from module import commands, example, require_admin def setup(bot): bot.memory['movie_lock'] = threading.Lock() con = bot.db.connect() cur = con.cursor() try: cur.execute("SELECT * FROM movie").fetchone() except OperationalError: cur.execute("CREATE TABLE movie(" "title TEXT PRIMARY KEY," "added_by TEXT," "added_date INTEGER DEFAULT (STRFTIME('%s', 'now'))," "watched INTEGER DEFAULT 0" ")") con.commit() con.close() @commands("movie", "tmdb") @example(".movie ThisTitleDoesNotExist", "[MOVIE] Movie not found!") @example(".movie Citizen Kane", "[MOVIE] Title: Citizen Kane | Year: " + "1941 | Rating: 8.4 | Genre: Drama, Mystery | IMDB Link: " + "http://imdb.com/title/tt0033467") def movieInfo(bot, trigger): """ Returns some information about a movie, like Title, Year, Rating, Genre and IMDB Link. """ if len(trigger.args) < 2: return bot.reply("What movie?") word = '+'.join(trigger.args[1:]) api_key = config.tmdb_api_key uri = "https://api.themoviedb.org/3/search/movie?" + \ f"api_key={api_key}&query={word}" data = requests.get(uri, timeout=30, verify=True).json() try: data = data['results'][0] except IndexError: return bot.reply("No results found.") except KeyError: print(data) return bot.reply("An error. Please notify an adult.") uri = "https://api.themoviedb.org/3/genre/movie/list?" + \ f"api_key={api_key}&language=en-US" genres = requests.get(uri, timeout=30, verify=True).json() try: genres = genres['genres'] except KeyError: return bot.reply("An error. Please notify an adult.") movieGenres = [] for genre in genres: if genre['id'] in data['genre_ids']: movieGenres.append(genre['name']) msg = "[\x0304MOVIE\x03] \x0310Title\x03: \x0312" + data['title'] + \ "\x03 | \x0310Year\x03: \x0308" + data['release_date'][:4] + \ "\x03 | \x0310Rating\x03: \x0312" + str(data['vote_average']) + \ "\x03 | \x0310Genre\x03: \x0312" + ", ".join(movieGenres) + \ "\x03 | \x0310TMDb Link\x03: \x0307" + \ "https://www.themoviedb.org/movie/" + str(data['id']) msg += "\n\x0310Theater release date\x03: \x0308" + data['release_date'] + \ "\x03 | \x0310Physical release date\x03: \x0308" + \ phyiscalRelease(word, data['id'], api_key) msg += "\n\x0310Overview\x03: " + data['overview'] bot.msg(msg) def phyiscalRelease(word, tmdb_id=None, api_key=None): """ Attempts to find a physical US release from TMDb. Failing that, it will find a date on www.dvdreleasedates.com. """ if not tmdb_id: return "Feature not yet implemented." uri = f"https://api.themoviedb.org/3/movie/{tmdb_id}/release_dates?" + \ f"api_key={api_key}" res = requests.get(uri, timeout=30, verify=True) res.raise_for_status() try: releases = res.json()['results'] except KeyError: return "No results found." for release in releases: if release["iso_3166_1"] != "US": continue for date in release["release_dates"]: if date["type"] == 5: return date["release_date"][:10] #return "No physical US release found." return dvdReleaseDates(word) def dvdReleaseDates(word): """ Scrapes www.dvdsreleasedates.com for physical release dates. """ uri = f"http://www.dvdsreleasedates.com/search.php?searchStr={word}" res = requests.get(uri, timeout=30, verify=True) soup = bs4.BeautifulSoup(res.text, "html.parser") rDate = soup.title.text[soup.title.text.rfind("Date")+4:] if not rDate: rDate = "Not announced." elif rDate.startswith("rch results for"): rDate = "Not found." return rDate.strip() @commands('pickmovie', 'getmovie') @example('.pickmovie', 'Commandos') def pickMovie(bot, trigger): """ Picks a random movie title out of the database. """ bot.memory['movie_lock'].acquire() cur = bot.db.execute("SELECT title FROM movie WHERE " "watched = 0 ORDER BY RANDOM() LIMIT 1;") movie = cur.fetchone() bot.memory['movie_lock'].release() if not movie: return bot.reply("Movie database is empty!") else: bot.reply(movie[0]) if len(trigger.args) >= 2: trigger.args = f".movie {movie}".strip().split(' ') movieInfo(bot, trigger) #@require_admin @commands('addmovie') @example(".addmovie Dr. Strangelove or: How I Learned to Stop Worrying and " "Love the Bomb") def addMovie(bot, trigger): """ Adds the specified movie to the movie database. """ if len(trigger.args) < 2: return bot.reply("What movie?") movie = ' '.join(trigger.args[1:]) bot.memory['movie_lock'].acquire() try: bot.db.execute("INSERT INTO movie (title, added_by) VALUES(?,?)", (movie, trigger.nick)) confirm = f"Added movie: {movie}" except IntegrityError: confirm = f"Error: {movie} is already in the database." bot.memory['movie_lock'].release() bot.msg(confirm)