From 04f30070a9061074b699b8ec99983ed9999a5f10 Mon Sep 17 00:00:00 2001
From: Will Hunt <will@half-shot.uk>
Date: Fri, 31 May 2019 16:49:53 +0100
Subject: [PATCH] Bind metrics safely

---
 src/bot.ts           | 1 +
 src/clientfactory.ts | 9 ++++++++-
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/src/bot.ts b/src/bot.ts
index 7e583f7..102c0ae 100644
--- a/src/bot.ts
+++ b/src/bot.ts
@@ -291,6 +291,7 @@ export class DiscordBot {
             try {
                 MetricPeg.get.registerRequest(msg.id);
                 await this.waitUnlock(msg.channel);
+                this.clientFactory.bindMetricsToChannel(msg.channel as Discord.TextChannel);
                 this.discordMessageQueue[msg.channel.id] = (async () => {
                     await (this.discordMessageQueue[msg.channel.id] || Promise.resolve());
                     try {
diff --git a/src/clientfactory.ts b/src/clientfactory.ts
index 22ded34..1b2adcf 100644
--- a/src/clientfactory.ts
+++ b/src/clientfactory.ts
@@ -110,10 +110,17 @@ export class DiscordClientFactory {
     }
 
     public bindMetricsToChannel(channel: TextChannel) {
+        // tslint:disable-next-line:no-any
+        const flexChan = channel as any;
+        if (flexChan._xmet_send !== undefined) {
+            return;
+        }
+        // Prefix the real functions with _xmet_
+        flexChan._xmet_send = channel.send;
         // tslint:disable-next-line:only-arrow-functions
         channel.send = function() {
             MetricPeg.get.remoteCall("channel.send");
-            return channel.send.apply(channel, arguments);
+            return flexChan._xmet_send.apply(channel, arguments);
         };
     }
 }
-- 
GitLab