From 6d88024f0f7bb8e0f4d0549ed312676f575629b0 Mon Sep 17 00:00:00 2001
From: Rapptz <rapptz@gmail.com>
Date: Sat, 17 Dec 2016 14:13:05 -0500
Subject: [PATCH] [commands] Add special extension function 'teardown' for
 clean-up.

This is to support people who want to clean up some external resource
that the extension is maintaining outside of a cog, where __unload
should be used instead.

The callable is the antipode of 'setup' and takes the same sole
parameter, the bot, after all commands, events, and cogs have been
unloaded.

Fixes #405.
---
 discord/ext/commands/bot.py | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/discord/ext/commands/bot.py b/discord/ext/commands/bot.py
index 9025493d9..1aa4133d1 100644
--- a/discord/ext/commands/bot.py
+++ b/discord/ext/commands/bot.py
@@ -764,10 +764,20 @@ class Bot(GroupMixin, discord.Client):
             for index in reversed(remove):
                 del event_list[index]
 
-        # finally remove the import..
-        del lib
-        del self.extensions[name]
-        del sys.modules[name]
+        try:
+            func = getattr(lib, 'teardown')
+        except AttributeError:
+            pass
+        else:
+            try:
+                func(bot)
+            except:
+                pass
+        finally:
+            # finally remove the import..
+            del lib
+            del self.extensions[name]
+            del sys.modules[name]
 
     # command processing