Advertisement
Guest User

Untitled

a guest
Oct 2nd, 2017
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.35 KB | None | 0 0
  1. import discord
  2. from discord.ext import commands
  3. from asyncio import sleep
  4. from random import randint, choice
  5. from re import match
  6. from base64 import b64encode as b64en, b64decode as b64de
  7. import difflib
  8.  
  9. def timedelta_milliseconds(td):
  10.     return td.days*86400000 + td.seconds*1000 + td.microseconds/1000
  11.  
  12. class Fun:
  13.     def __init__(self, bot):
  14.         self.bot = bot
  15.  
  16.     @commands.cooldown(rate=1, per=5, type=commands.BucketType.user)
  17.     @commands.command(pass_context=True, aliases="pang peng pong pung \U0001F3D3".split())
  18.     async def ping(self, ctx):
  19.         """Tests the bot's latency."""
  20.         if ctx.message.author.bot: return
  21.         ver = ctx.invoked_with.title()
  22.         conversions = {
  23.                 "Pang": "\U0001F52B Peng! You've been hit after ",
  24.                 "Peng": "\U0001F52B Pang! You've been hit after ",
  25.                 "Ping": "\U0001F3D3 Pong! Took ",
  26.                 "Pong": "\U0001F3D3 Ping! Took ",
  27.                 "\U0001F3D3": "\U0001F3D3 Took "
  28.         }
  29.         if ver == "Pung":
  30.             raise commands.BadArgument("Sorry, no pung yet...")
  31.         pong = conversions[ver]
  32.         pongmsg = await self.bot.send_message(ctx.message.channel, "Please wait...")
  33.         await self.bot.edit_message(pongmsg, new_content="{}{}ms!".format(pong, str(int(timedelta_milliseconds(pongmsg.timestamp-ctx.message.timestamp)))))
  34.  
  35.     @commands.command(pass_context=True)
  36.     async def say(self, ctx, *, args):
  37.         """Says what you give it to say."""
  38.         if ctx.message.author.bot: return
  39.         channel = args.split()[0]
  40.         if match("^<#"+"\d"*18+">$", channel):
  41.             args = args.replace(channel, "").lstrip()
  42.             channel = channel.replace("<#", "").replace(">", "")
  43.             await self.bot.send_message(self.bot.get_channel(channel), args.replace("@everyone", "@ everyone").replace("@here","@ here"))
  44.         else:
  45.             await self.bot.say(args.replace("@everyone", "@ everyone").replace("@here","@ here"))
  46.         await self.bot.delete_message(ctx.message)
  47.  
  48.     @commands.command()
  49.     async def reverse(self, *args):
  50.         """Reverses what you give it.
  51.        Line breaks get removed."""
  52.         await self.bot.say(" ".join(args)[::-1].replace("@everyone", "@ everyone").replace("@here","@ here"))
  53.  
  54.     @commands.command()
  55.     async def dice(self):
  56.         """Outputs a number between 1 and 6."""
  57.         await self.bot.say(randint(1, 6))
  58.  
  59.     @commands.command()
  60.     async def coin(self):
  61.         """Flip a coin."""
  62.         await self.bot.say(choice(("Heads", "Tails")))
  63.  
  64.     @commands.command()
  65.     async def rps(self, *, inp):
  66.         """Play rock paper scissors with me.
  67.        Accepted inputs:
  68.        anything"""
  69.         inp = inp.lower()
  70.         if inp in ("r","p","s","rock","paper","scissors"):
  71.             if inp in ("r", "p", "s"):
  72.                 inp = {"r":"rock", "p":"paper", "s":"scissors"}[inp]
  73.             cpu = choice(("rock", "paper", "scissors"))
  74.             if inp == "rock":
  75.                 if cpu == "rock":
  76.                     res = 0
  77.                 elif cpu == "paper":
  78.                     res = -1
  79.                 elif cpu == "scissors":
  80.                     res = 1
  81.             elif inp == "paper":
  82.                 if cpu == "rock":
  83.                     res = 1
  84.                 elif cpu == "paper":
  85.                     res = 0
  86.                 elif cpu == "scissors":
  87.                     res = -1
  88.             elif inp == "scissors":
  89.                 if cpu == "rock":
  90.                     res = -1
  91.                 elif cpu == "paper":
  92.                     res = 1
  93.                 elif cpu == "scissors":
  94.                     res = 0
  95.             await self.bot.say("You: {}\nComputer: {}\n{}".format(inp, cpu, ("It's a draw.", "You won!", "You lost...")[res]))
  96.         else:
  97.             cpu = choice(("rock", "paper", "scissors"))
  98.             await self.bot.say("You: {0}\nComputer: {1}\n{1} wins!".format(inp, cpu))
  99.  
  100.     @commands.command()
  101.     async def choose(self, *things):
  102.         """Randomly choose an element of the input.
  103.        
  104.        Syntax: s!choose [elem1]|[elem2]|...\[suffix]"""
  105.         things = " ".join(things)
  106.         try:
  107.  
  108.             suffix = things.split("\\")[1]
  109.             suffix = things.split("\\")[-1]
  110.         except IndexError:
  111.             suffix = ""
  112.         things = things.split("\\")[0].split("|")
  113.         await self.bot.say(choice(things).replace("@everyone", "@ everyone").replace("@here", "@ here")+suffix.replace("@everyone", "@ everyone").replace("@here","@ here"))
  114.  
  115.     @commands.command(pass_context=True)
  116.     async def hi(self, ctx):
  117.         """Says hello to you."""
  118.         await self.bot.say("Hello, {}!".format(ctx.message.author.mention))
  119.  
  120.     @commands.command(pass_context=True)
  121.     @commands.cooldown(rate=1, per=20, type=commands.BucketType.channel)
  122.     async def repeat(self, ctx, num, *text):
  123.         """Repeat a message multiple times.
  124.        Add %count% to the message to get a counter, add %countBackwards% to have it count backwards.
  125.        Add a suffix that gets said after the repeated messages by adding it to the message after a \\
  126.        
  127.        Syntax: s!repeat <number of repeats> <message>"""
  128.         if not "spam" in ctx.message.channel.name:
  129.             await self.bot.reply("the repeat command is only available in channels with `spam` in the name.")
  130.             return
  131.         text = " ".join(text).replace("@", "@\u200b").split("\\")
  132.         try:
  133.             suffix = text[1]
  134.             suffix = text[-1]
  135.         except IndexError:
  136.             suffix = None
  137.  
  138.         # print(suffix)
  139.  
  140.         text = text[0]
  141.  
  142.         # print(text)
  143.  
  144.         try:
  145.             num = int(num)
  146.             num = 50 if num > 50 else num
  147.         except ValueError:
  148.             await self.bot.say("Invalid number.")
  149.             return False
  150.         text = text.replace("%count%", "{0}").replace("%countBackwards%", "{1}").replace("%enumerate%", "{2}")
  151.         for i in range(num):
  152.             if str(i+1)[-1:] == "1" and i+1 != 11:
  153.                 enumend = "st"
  154.             elif str(i+1)[-1:] == "2" and i+1 != 12:
  155.                 enumend = "nd"
  156.             elif str(i+1)[-1:] == "3" and i+1 != 13:
  157.                 enumend = "rd"
  158.             else:
  159.                 enumend = "th"
  160.             await self.bot.say(text.format(i+1, num-i, str(i+1)+enumend))
  161.             await sleep(2)
  162.         if suffix is not None:
  163.             await self.bot.say(suffix)
  164.  
  165.     @commands.command(pass_context=True)
  166.     async def typing(self, ctx):
  167.         """Pretends that the bot was typing."""
  168.         await self.bot.send_typing(ctx.message.channel)
  169.         await self.bot.delete_message(ctx.message)
  170.  
  171.     @commands.command(pass_context=True)
  172.     async def embed(self, ctx, color:discord.Colour, *, text):
  173.         """Creates an embed for you."""
  174.         em = discord.Embed(description=text, colour=color)
  175.         await self.bot.send_message(ctx.message.channel, embed=em)
  176.         await self.bot.delete_message(ctx.message)
  177.  
  178.     @commands.command(pass_context=True)
  179.     async def emojify(self, ctx, *, text):
  180.         """Turns your text into emojis."""
  181.         o = ""
  182.         for i in text:
  183.             i = i.lower()
  184.             if i in "abcdefghijklmnopqrstuvwxyz":
  185.                 o += ":regional_indicator_{}:".format(i)
  186.             elif i == " " and ctx.message.server.me.permissions_in(ctx.message.channel).external_emojis:
  187.                 o += "<:regional_indicator_space:321333486256521216>"
  188.             elif i == " ":
  189.                 o += i
  190.             elif i in "1234567890":
  191.                 if i == "1":
  192.                     i = "one"
  193.                 elif i == "2":
  194.                     i = "two"
  195.                 elif i == "3":
  196.                     i = "three"
  197.                 elif i == "4":
  198.                     i = "four"
  199.                 elif i == "5":
  200.                     i = "five"
  201.                 elif i == "6":
  202.                     i = "six"
  203.                 elif i == "7":
  204.                     i = "seven"
  205.                 elif i == "8":
  206.                     i = "eight"
  207.                 elif i == "9":
  208.                     i = "nine"
  209.                 elif i == "0":
  210.                     i = "zero"
  211.                 o += ":{}:".format(i)
  212.             elif i == "#":
  213.                 o += ":hash:"
  214.             elif i == "*":
  215.                 o += ":asterisk:"
  216.         await self.bot.say(o)
  217.  
  218.     @commands.command(pass_context=True)
  219.     async def emoji(self, ctx, ename):
  220.         """Search an emoji in all servers I know."""
  221.         em = None
  222.         em = discord.utils.find(lambda e: e.name.lower() == ename.lower(), self.bot.get_all_emojis())
  223.         if em is None:
  224.             await self.bot.say("Emoji not found.")
  225.         else:
  226.             await self.bot.say(em)
  227.             await self.bot.delete_message(ctx.message)
  228.            
  229.     @commands.command(pass_context=True)
  230.     async def memory(self, ctx, time:float=3.0, digits:int=7):
  231.         """Play a memory game.
  232.  
  233.        I will show a number for a specified time in seconds, and you have to remember and send it."""
  234.         try:
  235.             if time > 5:
  236.                 await self.bot.say("Nope, over 5 seconds is too easy")
  237.                 return
  238.             if not 0 < digits < 100:
  239.                 await self.bot.say("Are you kidding me?")
  240.                 return
  241.             num = randint(10**(digits-1), (10**digits)-1)
  242.             await self.bot.say(f"{ctx.message.author.mention}, remember this number:\n{num}", delete_after=time)
  243.             msg = await self.bot.wait_for_message(check=lambda m: m.channel==ctx.message.channel and m.author==ctx.message.author)
  244.             if msg.content == str(num):
  245.                 await self.bot.say(f"GG! {num} is right!")
  246.             else:
  247.                 await self.bot.say(f"Nope. It was {num}")
  248.         except Exception as e:
  249.             print(type(e).__name__, e)
  250.  
  251.     @commands.command()
  252.     async def randomchars(self, num:int=10, max:int=0x110000-1):
  253.         """Generate random unicode characters.
  254.        Max is the maximum unicode value a character should have."""
  255.         if not 0 < num < 2001:
  256.             await self.bot.reply('invalid number of characters.')
  257.             return
  258.         if not 0 < num < 0x110000:
  259.             await self.bot.reply('invalid unicode range.')
  260.             return
  261.         await self.bot.say(''.join([chr(randint(0, max)) for i in range(num)]))
  262.  
  263.     @commands.command()
  264.     async def vaporwave(self, *, text):
  265.         """Turns your text into vaporwave text."""
  266.         o = ""
  267.         for c in text:
  268.             if c == " ":
  269.                 c = "\u3000"
  270.             elif ord(c) in range(0x21, 0x7F):
  271.                 c = chr(ord(c) + 0xFEE0)
  272.             o += c
  273.         await self.bot.say(o)
  274.  
  275.     @commands.command()
  276.     async def ship(self, first:discord.User, second:discord.User):
  277.         """Ship people.
  278.        Unlike with those other shipping bots, the results of this command are NOT random, and stable, so they wont change if you run the command again. On the other hand, its extremely rare to find a 100% ship."""
  279.         fmt = """```
  280. Shipping {0} and {1}...
  281. Score: {2:.2%}```"""
  282.         res = difflib.SequenceMatcher(None, format(hash(first.id), "x"), format(hash(second.id), "x"))
  283.         await self.bot.say(fmt.format(first.name, second.name, await self.bot.loop.run_in_executor(None, res.ratio), ".2%"))
  284.  
  285. def setup(bot):
  286.     bot.add_cog(Fun(bot))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement