Added RNG plugin.
authorCMDR furrycat <elite@furrycat.net>
Wed, 26 Oct 2016 10:50:49 +0000 (11:50 +0100)
committerCMDR furrycat <elite@furrycat.net>
Wed, 26 Oct 2016 10:50:49 +0000 (11:50 +0100)
plugins/rng.py [new file with mode: 0644]

diff --git a/plugins/rng.py b/plugins/rng.py
new file mode 100644 (file)
index 0000000..9bf71fb
--- /dev/null
@@ -0,0 +1,59 @@
+import asyncio
+import random
+import re
+import shlex
+
+from plugins import PluginCommand
+import bot
+
+class Rng(object):
+  def __init__(self):
+    return None
+
+  def description(self):
+    return 'Generates random numbers.'
+
+  def valid_commands(self):
+    return ['random']
+
+  def handle_command(self, message, command, raw):
+    if command not in self.valid_commands():
+      return PluginCommand.ignored
+    yield from self.rng(message.channel, shlex.split(raw)[1:])
+    return PluginCommand.exclusive
+
+  @asyncio.coroutine
+  def handle_help(self, message, command, *args):
+    yield from self.show_help(message.channel)
+
+  def generate(self, n):
+    return int(round((random.random() * (n - 1))))
+
+  @asyncio.coroutine
+  def show_help(self, destination):
+    lines = [
+      'Generate random numbers or pick an entry from a list.',
+      '```random N```',
+      'Pick a number between 1 and `N`',
+      ''
+      '```random OPTION1 OPTION2 ... OPTIONN```',
+      'Pick one of the given `OPTION`s.',
+      '',
+      'Example: `random 42`',
+      'Example: `random one two three four five six`'
+    ]
+    yield from bot.say_many(destination, lines)
+
+  @asyncio.coroutine
+  def rng(self, destination, args):
+    if not len(args):
+      yield from bot.say(destination, 'how many?')
+    elif len(args) == 1:
+      if args[0] == 'help':
+        yield from self.show_help(destination)
+      elif args[0] != '1' and re.match(r'^\d+$', args[0]):
+        yield from bot.say(destination, str(1 + self.generate(int(args[0]))))
+      else:
+        yield from bot.say(destination, 'only one?')
+    else:
+      yield from bot.say(destination, args[self.generate(len(args))])