DON'T CALL IT A COMEBACK
authorjweigele <jweigele@local>
Tue, 18 Jul 2017 21:07:03 +0000 (14:07 -0700)
committerjweigele <jweigele@local>
Tue, 18 Jul 2017 21:07:03 +0000 (14:07 -0700)
wigglydiscord.py [new file with mode: 0755]

diff --git a/wigglydiscord.py b/wigglydiscord.py
new file mode 100755 (executable)
index 0000000..6d7413d
--- /dev/null
@@ -0,0 +1,131 @@
+#!/usr/bin/python3
+
+import sys
+import discord
+import discord.voice_client
+import asyncio
+import json
+import traceback
+import os
+
+
+class WigglyDiscordException(Exception):
+    pass
+
+class WigglyDiscordBot(discord.Client):
+    def __init__(self, config):
+        self.config = config
+        self.voice = None
+        self.player = None
+
+        super().__init__()
+        self.run(self.config['token'])
+
+    @asyncio.coroutine
+    async def on_ready(self):
+        print('Logged in as')
+        print(self.user.name)
+        print(self.user.id)
+        print([x for x in self.get_all_channels()])
+        print(list(self.servers))
+        print(self.is_voice_connected(list(self.servers)[0]))
+        print('------')
+
+    @property
+    def voice_channels(self):
+        return [x for x in self.get_all_channels() if x.type == discord.ChannelType.voice]
+
+
+    @property
+    def text_channels(self):
+        return [x for x in self.get_all_channels() if x.type == discord.ChannelType.text]
+
+
+    @asyncio.coroutine
+    async def msg_play_sound(self, name=None):
+        if self.voice:
+            if self.player:
+                if self.player.is_playing():
+                    self.player.stop()
+            if name:
+                filename = '{}/{}.mp3'.format(self.config['airhorn_directory'], name)
+                if not os.path.exists(filename):
+                    raise WigglyDiscordException("File '{}' not found in airhorn directory".format(name))
+            else:
+                filename = '{}/coool.mp3'.format(self.config['airhorn_directory'])
+            self.player = self.voice.create_ffmpeg_player(filename)
+            self.player.start()
+
+
+    async def msg_join_voice_channel(self, channel_name):
+        print('Called join voice channel')
+        for vc in self.voice_channels:
+            if vc.name == channel_name:
+                print('Found a voice channel to join {} {}'.format(vc, type(vc)))
+                if self.voice:
+                    if vc != self.voice.channel:
+                        self.voice = await self.voice.move_to(vc)
+                else:
+                    self.voice = await self.join_voice_channel(vc)
+                print('Joined voice channel {} (id: {})'.format(vc.name, vc.id))
+                print('Voice now {}'.format(self.voice))
+
+        print('Exit join voice')
+
+    def get_airhorn_filenames(self):
+        return sorted([x[:-4] for x in os.listdir(self.config['airhorn_directory']) if 'mp3' in x.lower()])
+
+        
+    def chunk_it_up(self, filename_list):
+        yieldval = []
+        char_limit = 1950 
+        cur_chars = 0
+        for index, filename in enumerate(filename_list):
+            yieldval.append(filename)
+            cur_chars += len(yieldval)
+            if index + 1 < len(filename_list):
+                if len(filename_list[index+1]) + cur_chars > char_limit:
+                    yield yieldval
+                    yieldval = []
+                    cur_chars = 0
+
+        if yieldval:
+            yield yieldval
+                    
+
+    @asyncio.coroutine
+    async def oh_no(self, channel, exc):
+        exc_string = 'Ruh Roh! {}: {}'.format(type(exc), str(exc))
+        traceback.print_exc()
+        await self.send_message(channel, exc_string)
+
+    def print_call(self, message):
+        print('#{} <{}>: {}'.format(message.channel, message.author, message.content))
+
+    @asyncio.coroutine
+    async def on_message(self, message):
+        try:
+            if message.content.startswith('!sleep'):
+                await asyncio.sleep(5)
+                await self.send_message(message.channel, 'Done sleeping')
+            elif message.content.startswith('!joinvoice'):
+                self.print_call(message)
+                print('Was instructed to join {}'.format(message.content.split(' ')[1]))
+                await self.msg_join_voice_channel(message.content.split(' ')[1])
+            elif message.content.startswith('!play'):
+                self.print_call(message)
+                print('Was instructed to play {}'.format(message.content.split(' ')[1]))
+                await self.msg_play_sound(name=' '.join(message.content.split(' ')[1:]))
+            elif message.content.startswith('!listairhorns'):
+                self.print_call(message)
+                for airhorn_files in self.chunk_it_up(self.get_airhorn_filenames()):
+                    await self.send_message(message.channel, '```{}```'.format('\n'.join(airhorn_files)))
+            elif message.content.startswith('!leavevoice'):
+                await self.voice.disconnect()
+                self.voice = None
+        except Exception as e:
+            await self.oh_no(message.channel, e)
+
+if __name__ == '__main__':
+    config = json.load(open(sys.argv[1], 'r'))
+    bot = WigglyDiscordBot(config)