fulvia/modules/movie.py

174 lines
4.9 KiB
Python
Raw Normal View History

2018-03-16 03:13:43 -04:00
#!/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
2019-10-08 12:39:13 -04:00
import config
2018-03-16 03:13:43 -04:00
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("
2021-02-06 00:37:18 -05:00
"title TEXT PRIMARY KEY,"
"added_by TEXT,"
2018-03-16 03:13:43 -04:00
"added_date INTEGER DEFAULT (STRFTIME('%s', 'now')),"
2021-02-06 00:37:18 -05:00
"watched INTEGER DEFAULT 0"
2018-03-16 03:13:43 -04:00
")")
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")
2018-03-16 03:13:43 -04:00
def movieInfo(bot, trigger):
"""
Returns some information about a movie, like Title, Year, Rating,
Genre and IMDB Link.
"""
2020-01-07 18:58:19 -05:00
if len(trigger.args) < 2:
2018-03-16 03:13:43 -04:00
return bot.reply("What movie?")
2020-01-07 18:58:19 -05:00
word = '+'.join(trigger.args[1:])
2018-03-16 03:13:43 -04:00
2019-10-08 12:39:13 -04:00
api_key = config.tmdb_api_key
2018-03-16 03:13:43 -04:00
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']
2018-05-25 15:21:18 -04:00
bot.msg(msg)
2018-03-16 03:13:43 -04:00
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()
2021-02-06 00:37:18 -05:00
cur = bot.db.execute("SELECT title FROM movie WHERE "
"watched = 0 ORDER BY RANDOM() LIMIT 1;")
2018-03-16 03:13:43 -04:00
movie = cur.fetchone()
bot.memory['movie_lock'].release()
if not movie:
return bot.reply("Movie database is empty!")
else:
bot.reply(movie[0])
2020-01-07 18:58:19 -05:00
if len(trigger.args) >= 2:
trigger.args = f".movie {movie}".strip().split(' ')
2018-03-16 03:13:43 -04:00
movieInfo(bot, trigger)
2018-05-17 23:06:45 -04:00
@require_admin
2018-03-16 03:13:43 -04:00
@commands('addmovie')
2020-01-10 06:51:50 -05:00
@example(".addmovie Dr. Strangelove or: How I Learned to Stop Worrying and "
"Love the Bomb")
2018-03-16 03:13:43 -04:00
def addMovie(bot, trigger):
"""
Adds the specified movie to the movie database.
"""
2020-01-07 18:58:19 -05:00
if len(trigger.args) < 2:
return bot.reply("What movie?")
movie = ' '.join(trigger.args[1:])
2018-03-16 03:13:43 -04:00
bot.memory['movie_lock'].acquire()
try:
2021-02-06 00:37:18 -05:00
bot.db.execute("INSERT INTO movie (title, added_by) VALUES(?,?)",
2018-03-16 03:13:43 -04:00
(movie, trigger.nick))
confirm = f"Added movie: {movie}"
except IntegrityError:
confirm = f"Error: {movie} is already in the database."
bot.memory['movie_lock'].release()
2018-05-25 15:21:18 -04:00
bot.msg(confirm)