myanimebot.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. #!/usr/bin/env python3
  2. # Copyright Penta (c) 2018/2020 - Under BSD License - Based on feed2discord.py by Eric Eisenhart
  3. # Compatible for Python 3.7.X
  4. #
  5. # Dependencies (for CentOS 7):
  6. # curl -LsS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash
  7. # yum install gcc MariaDB-client MariaDB-common MariaDB-shared MariaDB-devel
  8. # python3.7 -m pip install --upgrade pip
  9. # pip3.7 install discord.py mariadb pytz feedparser python-dateutil asyncio html2text bs4 PyNaCL aiodns cchardet configparser
  10. # TODO Remove all of that
  11. # TODO MAL should not check AniList users
  12. import asyncio
  13. # Library import
  14. import logging
  15. import sys
  16. import urllib.request
  17. from configparser import ConfigParser
  18. from datetime import datetime
  19. from typing import List, Tuple
  20. import aiohttp
  21. import discord
  22. import feedparser
  23. from aiohttp.web_exceptions import HTTPError, HTTPNotModified
  24. from dateutil.parser import parse as parse_datetime
  25. from html2text import HTML2Text
  26. # Our modules
  27. import myanimebot.anilist as anilist
  28. import myanimebot.globals as globals
  29. import myanimebot.utils as utils
  30. import myanimebot.myanimelist as myanimelist
  31. from myanimebot.discord import send_embed_wrapper, build_embed
  32. if not sys.version_info[:2] >= (3, 7):
  33. print("ERROR: Requires python 3.7 or newer.")
  34. exit(1)
  35. # Main function that check the RSS feeds from MyAnimeList
  36. async def background_check_feed(asyncioloop):
  37. globals.logger.info("Starting up background_check_feed")
  38. # We configure the http header
  39. http_headers = { "User-Agent": "MyAnimeBot Discord Bot v" + globals.VERSION, }
  40. await globals.client.wait_until_ready()
  41. globals.logger.debug("Discord client connected, unlocking background_check_feed...")
  42. while not globals.client.is_closed():
  43. try:
  44. db_user = globals.conn.cursor(buffered=True, dictionary=True)
  45. db_user.execute("SELECT mal_user, servers FROM t_users")
  46. data_user = db_user.fetchone()
  47. except Exception as e:
  48. globals.logger.critical("Database unavailable! (" + str(e) + ")")
  49. quit()
  50. while data_user is not None:
  51. user = utils.User(id=None,
  52. service_id=None,
  53. name=data_user[globals.DB_USER_NAME],
  54. servers=data_user["servers"].split(','))
  55. stop_boucle = 0
  56. feed_type = 1
  57. try:
  58. while stop_boucle == 0 :
  59. try:
  60. async with aiohttp.ClientSession() as httpclient:
  61. if feed_type == 1 :
  62. http_response = await httpclient.request("GET", "https://myanimelist.net/rss.php?type=rm&u=" + user.name, headers=http_headers)
  63. media = "manga"
  64. else :
  65. http_response = await httpclient.request("GET", "https://myanimelist.net/rss.php?type=rw&u=" + user.name, headers=http_headers)
  66. media = "anime"
  67. except Exception as e:
  68. globals.logger.error("Error while loading RSS (" + str(feed_type) + ") of '" + user.name + "': " + str(e))
  69. break
  70. http_data = await http_response.read()
  71. feeds_data = feedparser.parse(http_data)
  72. for feed_data in feeds_data.entries:
  73. pubDateRaw = datetime.strptime(feed_data.published, '%a, %d %b %Y %H:%M:%S %z').astimezone(globals.timezone)
  74. DateTimezone = pubDateRaw.strftime("%z")[:3] + ':' + pubDateRaw.strftime("%z")[3:]
  75. pubDate = pubDateRaw.strftime("%Y-%m-%d %H:%M:%S")
  76. if feed_type == 1:
  77. media_type = utils.MediaType.MANGA
  78. else:
  79. media_type = utils.MediaType.ANIME
  80. feed = myanimelist.build_feed_from_data(feed_data, user, None, pubDateRaw.timestamp(), media_type)
  81. cursor = globals.conn.cursor(buffered=True)
  82. cursor.execute("SELECT published, title, url FROM t_feeds WHERE published=%s AND title=%s AND user=%s", [pubDate, feed.media.name, user.name])
  83. data = cursor.fetchone()
  84. if data is None:
  85. var = datetime.now(globals.timezone) - pubDateRaw
  86. globals.logger.debug(" - " + feed.media.name + ": " + str(var.total_seconds()))
  87. if var.total_seconds() < globals.secondMax:
  88. globals.logger.info(user.name + ": Item '" + feed.media.name + "' not seen, processing...")
  89. cursor.execute("SELECT thumbnail FROM t_animes WHERE guid=%s LIMIT 1", [feed.media.url]) # TODO Change that ?
  90. data_img = cursor.fetchone()
  91. if data_img is None:
  92. try:
  93. image = myanimelist.get_thumbnail(feed.media.url)
  94. globals.logger.info("First time seeing this " + media + ", adding thumbnail into database: " + image)
  95. except Exception as e:
  96. globals.logger.warning("Error while getting the thumbnail: " + str(e))
  97. image = ""
  98. cursor.execute("INSERT INTO t_animes (guid, title, thumbnail, found, discoverer, media) VALUES (%s, %s, %s, NOW(), %s, %s)", [feed.media.url, feed.media.name, image, user.name, media])
  99. globals.conn.commit()
  100. else: image = data_img[0]
  101. feed.media.image = image
  102. type = feed.description.partition(" - ")[0]
  103. cursor.execute("INSERT INTO t_feeds (published, title, url, user, found, type) VALUES (%s, %s, %s, %s, NOW(), %s)", (pubDate, feed.media.name, feed.media.url, user.name, type))
  104. globals.conn.commit()
  105. for server in user.servers:
  106. db_srv = globals.conn.cursor(buffered=True)
  107. db_srv.execute("SELECT channel FROM t_servers WHERE server = %s", [server])
  108. data_channel = db_srv.fetchone()
  109. while data_channel is not None:
  110. for channel in data_channel: await send_embed_wrapper(asyncioloop, channel, globals.client, build_embed(feed))
  111. data_channel = db_srv.fetchone()
  112. if feed_type == 1:
  113. feed_type = 0
  114. await asyncio.sleep(1)
  115. else:
  116. stop_boucle = 1
  117. except Exception as e:
  118. globals.logger.error("Error when parsing RSS for '" + user.name + "': " + str(e))
  119. await asyncio.sleep(1)
  120. data_user = db_user.fetchone()
  121. async def fetch_activities_anilist():
  122. await anilist.check_new_activities()
  123. @globals.client.event
  124. async def on_ready():
  125. globals.logger.info("Logged in as " + globals.client.user.name + " (" + str(globals.client.user.id) + ")")
  126. globals.logger.info("Starting all tasks...")
  127. globals.task_feed = globals.client.loop.create_task(background_check_feed(globals.client.loop))
  128. globals.task_feed_anilist = globals.client.loop.create_task(anilist.background_check_feed(globals.client.loop))
  129. globals.task_thumbnail = globals.client.loop.create_task(update_thumbnail_catalog(globals.client.loop))
  130. globals.task_gameplayed = globals.client.loop.create_task(change_gameplayed(globals.client.loop))
  131. @globals.client.event
  132. async def on_error(event, *args, **kwargs):
  133. globals.logger.exception("Crap! An unknown Discord error occured...")
  134. def build_info_cmd_message(users, server, channels, filters : List[utils.Service]) -> str:
  135. ''' Build the corresponding message for the info command '''
  136. registered_channel = globals.client.get_channel(int(channels[0]["channel"]))
  137. # Store users
  138. mal_users = []
  139. anilist_users = []
  140. for user in users:
  141. # If user is part of the server, add it to the message
  142. if str(server.id) in user['servers'].split(','):
  143. try:
  144. user_service = utils.Service.from_str(user["service"])
  145. if user_service == utils.Service.MAL:
  146. mal_users.append(user[globals.DB_USER_NAME])
  147. elif user_service == utils.Service.ANILIST:
  148. anilist_users.append(user[globals.DB_USER_NAME])
  149. except NotImplementedError:
  150. pass # Nothing to do here
  151. if not mal_users and not anilist_users:
  152. return "No users registered on this server. Try to add one."
  153. else:
  154. message = 'Registered user(s) on **{}**\n\n'.format(server)
  155. if mal_users: # If not empty
  156. # Don't print if there is filters and MAL is not in them
  157. if not filters or (filters and utils.Service.MAL in filters):
  158. message += '**MyAnimeList** users:\n'
  159. message += '```{}```\n'.format(', '.join(mal_users))
  160. if anilist_users: # If not empty
  161. # Don't print if there is filters and MAL is not in them
  162. if not filters or (filters and utils.Service.ANILIST in filters):
  163. message += '**AniList** users:\n'
  164. message += '```{}```\n'.format(', '.join(anilist_users))
  165. message += 'Assigned channel : **{}**'.format(registered_channel)
  166. return message
  167. def get_service_filters_list(filters : str) -> List[utils.Service]:
  168. ''' Creates and returns a service filter list from a comma-separated string '''
  169. filters_list = []
  170. for filter in filters.split(','):
  171. try:
  172. filters_list.append(utils.Service.from_str(filter))
  173. except NotImplementedError:
  174. pass # Ignore incorrect filter
  175. return filters_list
  176. async def info_cmd(message, words):
  177. ''' Processes the command "info" and sends a message '''
  178. # Get filters if available
  179. filters = []
  180. if (len(words) >= 3): # If filters are specified
  181. filters = get_service_filters_list(words[2])
  182. server = message.guild
  183. if utils.is_server_in_db(server.id) == False:
  184. await message.channel.send("The server **{}** is not in our database.".format(server))
  185. else:
  186. users = utils.get_users()
  187. channels = utils.get_channels(server.id)
  188. if channels is None:
  189. await message.channel.send("No channel assigned for this bot on this server.")
  190. else:
  191. await message.channel.send(build_info_cmd_message(users, server, channels, filters))
  192. def check_user_name_validity(user_name: str, service : utils.Service) -> Tuple[bool, str]:
  193. """ Check if user_name exists on a specific service.
  194. Returns:
  195. - bool: True if user_name exists
  196. - str: Error string if the user does not exist
  197. """
  198. if service == utils.Service.MAL:
  199. try:
  200. # Ping user profile to check validity
  201. urllib.request.urlopen('{}{}'.format(globals.MAL_PROFILE_URL, user_name))
  202. except urllib.error.HTTPError as e:
  203. if (e.code == 404): # URL profile not found
  204. return False, "User **{}** doesn't exist on MyAnimeList!".format(user_name)
  205. else:
  206. globals.logger.warning("HTTP Code {} while trying to add user '{}' and checking its validity.".format(e.code, user_name))
  207. return False, "An error occured when we checked this username on MyAnimeList, maybe the website is down?"
  208. elif service == utils.Service.ANILIST:
  209. is_user_valid = anilist.check_username_validity(user_name)
  210. if is_user_valid == False:
  211. globals.logger.warning("No results returned while trying to add user '{}' and checking its validity.".format(user_name))
  212. return False, "User **{}** doesn't exist on AniList!".format(user_name)
  213. return True, None
  214. async def add_user_cmd(words, message):
  215. ''' Processes the command "add" and add a user to fetch the data for '''
  216. # Check if command is valid
  217. if len(words) != 4:
  218. if (len(words) < 4):
  219. return await message.channel.send("Usage: {} add **{}**/**{}** **username**".format(globals.prefix, globals.SERVICE_MAL, globals.SERVICE_ANILIST))
  220. return await message.channel.send("Too many arguments! You have to specify only one username.")
  221. try:
  222. service = utils.Service.from_str(words[2])
  223. except NotImplementedError:
  224. return await message.channel.send('Incorrect service. Use **"{}"** or **"{}"** for example'.format(globals.SERVICE_MAL, globals.SERVICE_ANILIST))
  225. user = words[3]
  226. server_id = str(message.guild.id)
  227. if(len(user) > 14):
  228. return await message.channel.send("Username too long!")
  229. try:
  230. # Check user validity
  231. is_valid, error_string = check_user_name_validity(user, service)
  232. if is_valid == False:
  233. return await message.channel.send(error_string)
  234. # Get user's servers
  235. user_servers = utils.get_user_servers(user, service)
  236. # User not present in database
  237. if user_servers is None:
  238. utils.insert_user_into_db(user, service, server_id)
  239. return await message.channel.send("**{}** added to the database for the server **{}**.".format(user, str(message.guild)))
  240. else: # User present in database
  241. is_server_present = server_id in user_servers.split(',')
  242. if is_server_present == True: # The user already has registered this server
  243. return await message.channel.send("User **{}** is already registered in our database for this server!".format(user))
  244. else:
  245. new_servers = '{},{}'.format(user_servers, server_id)
  246. utils.update_user_servers_db(user, service, new_servers)
  247. return await message.channel.send("**{}** added to the database for the server **{}**.".format(user, str(message.guild)))
  248. except Exception as e:
  249. globals.logger.warning("Error while adding user '{}' on server '{}': {}".format(user, message.guild, str(e)))
  250. return await message.channel.send("An unknown error occured while addind this user, the error has been logged.")
  251. async def delete_user_cmd(words, message):
  252. ''' Processes the command "delete" and remove a registered user '''
  253. # Check if command is valid
  254. if len(words) != 4:
  255. if (len(words) < 4):
  256. return await message.channel.send("Usage: {} delete **{}**/**{}** **username**".format(globals.prefix, globals.SERVICE_MAL, globals.SERVICE_ANILIST))
  257. return await message.channel.send("Too many arguments! You have to specify only one username.")
  258. try:
  259. service = utils.Service.from_str(words[2])
  260. except NotImplementedError:
  261. return await message.channel.send('Incorrect service. Use **"{}"** or **"{}"** for example'.format(globals.SERVICE_MAL, globals.SERVICE_ANILIST))
  262. user = words[3]
  263. server_id = str(message.guild.id)
  264. user_servers = utils.get_user_servers(user, service)
  265. # If user is not present in the database
  266. if user_servers is None:
  267. return await message.channel.send("The user **" + user + "** is not in our database for this server!")
  268. # Else if present, update the servers for this user
  269. srv_string = utils.remove_server_from_servers(server_id, user_servers)
  270. if srv_string is None: # Server not present in the user's servers
  271. return await message.channel.send("The user **" + user + "** is not in our database for this server!")
  272. if srv_string == "":
  273. utils.delete_user_from_db(user, service)
  274. else:
  275. utils.update_user_servers_db(user, service, srv_string)
  276. return await message.channel.send("**" + user + "** deleted from the database for this server.")
  277. @globals.client.event
  278. async def on_message(message):
  279. if message.author == globals.client.user: return
  280. words = message.content.split(" ")
  281. author = str('{0.author.mention}'.format(message))
  282. # A user is trying to get help
  283. if words[0] == globals.prefix:
  284. if len(words) > 1:
  285. if words[1] == "ping":
  286. await message.channel.send("pong")
  287. elif words[1] == "here":
  288. if message.author.guild_permissions.administrator:
  289. cursor = globals.conn.cursor(buffered=True)
  290. cursor.execute("SELECT server, channel FROM t_servers WHERE server=%s", [str(message.guild.id)])
  291. data = cursor.fetchone()
  292. if data is None:
  293. cursor.execute("INSERT INTO t_servers (server, channel) VALUES (%s,%s)", [str(message.guild.id), str(message.channel.id)])
  294. globals.conn.commit()
  295. await message.channel.send("Channel **" + str(message.channel) + "** configured for **" + str(message.guild) + "**.")
  296. else:
  297. if(data[1] == str(message.channel.id)): await message.channel.send("Channel **" + str(message.channel) + "** already in use for this server.")
  298. else:
  299. cursor.execute("UPDATE t_servers SET channel = %s WHERE server = %s", [str(message.channel.id), str(message.guild.id)])
  300. globals.conn.commit()
  301. await message.channel.send("Channel updated to: **" + str(message.channel) + "**.")
  302. cursor.close()
  303. else: await message.channel.send("Only server's admins can use this command!")
  304. elif words[1] == "add":
  305. await add_user_cmd(words, message)
  306. elif words[1] == "delete":
  307. await delete_user_cmd(words, message)
  308. elif words[1] == "stop":
  309. if message.author.guild_permissions.administrator:
  310. if (len(words) == 2):
  311. cursor = globals.conn.cursor(buffered=True)
  312. cursor.execute("SELECT server FROM t_servers WHERE server=%s", [str(message.guild.id)])
  313. data = cursor.fetchone()
  314. if data is None: await globals.client.send_message(message.channel, "The server **" + str(message.guild) + "** is not in our database.")
  315. else:
  316. cursor.execute("DELETE FROM t_servers WHERE server = %s", [message.guild.id])
  317. globals.conn.commit()
  318. await message.channel.send("Server **" + str(message.guild) + "** deleted from our database.")
  319. cursor.close()
  320. else: await message.channel.send("Too many arguments! Only type *stop* if you want to stop this bot on **" + message.guild + "**")
  321. else: await message.channel.send("Only server's admins can use this command!")
  322. elif words[1] == "info":
  323. await info_cmd(message, words)
  324. elif words[1] == "about": await message.channel.send(embed=discord.Embed(colour=0x777777, title="MyAnimeBot version " + globals.VERSION + " by Penta", description="This bot check the MyAnimeList's RSS for each user specified, and send a message if there is something new.\nMore help with the **!malbot help** command.\n\nAdd me on steam: http://steamcommunity.com/id/Penta_Pingouin").set_thumbnail(url="https://cdn.discordapp.com/avatars/415474467033317376/2d847944aab2104923c18863a41647da.jpg?size=64"))
  325. elif words[1] == "help": await message.channel.send(globals.HELP)
  326. elif words[1] == "top":
  327. if len(words) == 2:
  328. try:
  329. cursor = globals.conn.cursor(buffered=True)
  330. cursor.execute("SELECT * FROM v_Top")
  331. data = cursor.fetchone()
  332. if data is None: await message.channel.send("It seems that there is no statistics... (what happened?!)")
  333. else:
  334. topText = "**__Here is the global statistics of this bot:__**\n\n"
  335. while data is not None:
  336. topText += " - " + str(data[0]) + ": " + str(data[1]) + "\n"
  337. data = cursor.fetchone()
  338. cursor = globals.conn.cursor(buffered=True)
  339. cursor.execute("SELECT * FROM v_TotalFeeds")
  340. data = cursor.fetchone()
  341. topText += "\n***Total user entry***: " + str(data[0])
  342. cursor = globals.conn.cursor(buffered=True)
  343. cursor.execute("SELECT * FROM v_TotalAnimes")
  344. data = cursor.fetchone()
  345. topText += "\n***Total unique manga/anime***: " + str(data[0])
  346. await message.channel.send(topText)
  347. cursor.close()
  348. except Exception as e:
  349. globals.logger.warning("An error occured while displaying the global top: " + str(e))
  350. await message.channel.send("Unable to reply to your request at the moment...")
  351. elif len(words) > 2:
  352. keyword = str(' '.join(words[2:]))
  353. globals.logger.info("Displaying the global top for the keyword: " + keyword)
  354. try:
  355. cursor = globals.conn.cursor(buffered=True)
  356. cursor.callproc('sp_UsersPerKeyword', [str(keyword), '20'])
  357. for result in cursor.stored_results():
  358. data = result.fetchone()
  359. if data is None: await message.channel.send("It seems that there is no statistics for the keyword **" + keyword + "**.")
  360. else:
  361. topKeyText = "**__Here is the statistics for the keyword " + keyword + ":__**\n\n"
  362. while data is not None:
  363. topKeyText += " - " + str(data[0]) + ": " + str(data[1]) + "\n"
  364. data = result.fetchone()
  365. await message.channel.send(topKeyText)
  366. cursor.close()
  367. except Exception as e:
  368. globals.logger.warning("An error occured while displaying the global top for keyword '" + keyword + "': " + str(e))
  369. await message.channel.send("Unable to reply to your request at the moment...")
  370. elif words[1] == "group":
  371. if len(words) > 2:
  372. if message.author.guild_permissions.administrator:
  373. group = words[2]
  374. await message.channel.send("admin OK")
  375. else: await message.channel.send("Only server's admins can use this command!")
  376. else:
  377. await message.channel.send("You have to specify a group!")
  378. elif words[1] == "fetch-debug":
  379. await fetch_activities_anilist()
  380. # If mentioned
  381. elif globals.client.user in message.mentions:
  382. await message.channel.send(":heart:")
  383. # Get a random anime name and change the bot's activity
  384. async def change_gameplayed(asyncioloop):
  385. globals.logger.info("Starting up change_gameplayed")
  386. await globals.client.wait_until_ready()
  387. await asyncio.sleep(1)
  388. while not globals.client.is_closed():
  389. # Get a random anime name from the users' list
  390. cursor = globals.conn.cursor(buffered=True)
  391. cursor.execute("SELECT title FROM t_animes ORDER BY RAND() LIMIT 1")
  392. data = cursor.fetchone()
  393. anime = utils.truncate_end_show(data[0])
  394. # Try to change the bot's activity
  395. try:
  396. if data is not None: await globals.client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=anime))
  397. except Exception as e:
  398. globals.logger.warning("An error occured while changing the displayed anime title: " + str(e))
  399. cursor.close()
  400. # Do it every minute
  401. await asyncio.sleep(60)
  402. async def update_thumbnail_catalog(asyncioloop):
  403. globals.logger.info("Starting up update_thumbnail_catalog")
  404. while not globals.client.is_closed():
  405. await asyncio.sleep(43200)
  406. globals.logger.info("Automatic check of the thumbnail database on going...")
  407. reload = 0
  408. cursor = globals.conn.cursor(buffered=True)
  409. cursor.execute("SELECT guid, title, thumbnail FROM t_animes")
  410. data = cursor.fetchone()
  411. while data is not None:
  412. try:
  413. if (data[2] != "") : urllib.request.urlopen(data[2])
  414. else: reload = 1
  415. except urllib.error.HTTPError as e:
  416. globals.logger.warning("HTTP Error while getting the current thumbnail of '" + str(data[1]) + "': " + str(e))
  417. reload = 1
  418. except Exception as e:
  419. globals.logger.debug("Error while getting the current thumbnail of '" + str(data[1]) + "': " + str(e))
  420. if (reload == 1) :
  421. try:
  422. image = myanimelist.get_thumbnail(data[0])
  423. cursor.execute("UPDATE t_animes SET thumbnail = %s WHERE guid = %s", [image, data[0]])
  424. globals.conn.commit()
  425. globals.logger.info("Updated thumbnail found for \"" + str(data[1]) + "\": %s", image)
  426. except Exception as e:
  427. globals.logger.warning("Error while downloading updated thumbnail for '" + str(data[1]) + "': " + str(e))
  428. await asyncio.sleep(3)
  429. data = cursor.fetchone()
  430. cursor.close()
  431. globals.logger.info("Thumbnail database checked.")
  432. # Starting main function
  433. if __name__ == "__main__":
  434. try:
  435. globals.client.run(globals.token)
  436. except:
  437. logging.info("Closing all tasks...")
  438. globals.task_feed.cancel()
  439. globals.task_feed_anilist.cancel()
  440. globals.task_thumbnail.cancel()
  441. globals.task_gameplayed.cancel()
  442. globals.logger.critical("Script halted.")
  443. # We close all the ressources
  444. globals.conn.close()
  445. globals.log_cursor.close()
  446. globals.log_conn.close()