matthileo

Untitled

Jan 15th, 2017
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.55 KB | None | 0 0
  1. '''
  2. Created on Jan 14, 2017
  3.  
  4. @author: thinger
  5. '''
  6. import asyncio
  7. import pickle
  8. import sys
  9. import traceback
  10. import re
  11. import random
  12.  
  13. import discord
  14. from discord.ext import commands
  15. import markovify
  16.  
  17.  
  18. bot = commands.Bot(command_prefix='$', description="Markov bot is friend!", pm_help=True, self_bot=False)
  19. bot.training_data = []
  20.  
  21.  
  22. @bot.event
  23. async def on_ready():
  24.     print('Logged in as')
  25.     print(bot.user.name)
  26.     #print(bot.user.id)
  27.     print('------')
  28.     if not 'predata' in sys.argv:
  29.         bot.loop.create_task(load())
  30.     else:
  31.         with open('./markovdata.pkl', mode='rb') as f:
  32.             bot.training_data = pickle.load(f)
  33.         print("Data Loaded!")
  34.        
  35. @bot.event
  36. async def on_message(message):
  37.     bot.training_data.append(message)
  38.     await bot.process_commands(message)
  39.    
  40. @bot.command(pass_context=True)
  41. async def chanMarkov(ctx, channel:discord.Channel=None, num:int=1):
  42.     text = ''
  43.     if channel is None:
  44.         channel = ctx.message.channel
  45.     for m in bot.training_data:
  46.         if m.channel.id == channel.id:
  47.             text += m.content + '\n'
  48.     markov = markovify.NewlineText(text,state_size=2)
  49.     out = ''
  50.     for i in range(num):
  51.         try:
  52.             out += markov.make_sentence(tries=1000) + '\n\n'
  53.         except:
  54.             pass
  55.     out = fix_mentions(out)
  56.     await bot.say(out)  # @UndefinedVariable
  57.  
  58. @bot.command(pass_context=True)
  59. async def servMarkov(ctx, num:int=1):
  60.     loading = await bot.say("Generating, this might take a while...")
  61.     text = ''
  62.     for m in bot.training_data:
  63.         if m.server is not None:
  64.             if m.server.id == ctx.message.server.id:
  65.                 text += m.content + '\n'
  66.     markov = markovify.NewlineText(text,state_size=2)
  67.     out = ''
  68.     for i in range(num):
  69.         try:
  70.             out += markov.make_sentence(tries=1000) + '\n\n'
  71.         except:
  72.             pass
  73.     out = fix_mentions(out)
  74.     await bot.edit_message(loading, out)  # @UndefinedVariable
  75.    
  76. @bot.command(pass_context=True)
  77. async def membMarkov(ctx, member:discord.Member, num:int=1):
  78.     text = ''
  79.     for m in bot.training_data:
  80.         if m.server is not None:
  81.             if m.author.id == member.id and m.server.id == ctx.message.server.id:
  82.                 text += m.content + '\n'
  83.     markov = markovify.NewlineText(text,state_size=2)
  84.     out = ''
  85.     for i in range(num):
  86.         try:
  87.             out += markov.make_sentence(tries=1000) + '\n\n'
  88.         except:
  89.             pass
  90.     out = fix_mentions(out)
  91.     await bot.say(out)  # @UndefinedVariable
  92.    
  93. @bot.command(pass_context=True)
  94. async def userMarkov(ctx, member:str, num:int=1):
  95.     text = ''
  96.     for m in bot.training_data:
  97.         if m.author.id == member:
  98.             text += m.content + '\n'
  99.     markov = markovify.NewlineText(text,state_size=2)
  100.     out = ''
  101.     for i in range(num):
  102.         try:
  103.             out += markov.make_sentence(tries=1000) + '\n\n'
  104.         except:
  105.             pass
  106.     out = fix_mentions(out)
  107.     await bot.say(out)  # @UndefinedVariable
  108.    
  109. @bot.command(pass_context=True)
  110. async def globMarkov(ctx, num:int=1):
  111.     print("Starting global markov...")
  112.     text = ''
  113.     for m in bot.training_data:
  114.         text += m.content + '\n'
  115.     markov = markovify.NewlineText(text,state_size=2)
  116.     out = ''
  117.     for i in range(num):
  118.         try:
  119.             out += markov.make_sentence(tries=1000) + '\n\n'
  120.         except:
  121.             pass
  122.     out = fix_mentions(out)
  123.     await bot.say(out)  # @UndefinedVariable
  124.    
  125. @bot.command(pass_context=True)
  126. async def code(ctx, *, code : str):
  127.     """Arbitrarily runs code."""
  128.     if not ctx.message.author.id == '126215805053435904': return
  129.     here = ctx.message.channel
  130.     this = ctx.message
  131.     def echo(out):
  132.         msg(here, out)
  133.     def rep(out):
  134.         replace(this, out)
  135.     def coro(coro):
  136.         asyncio.ensure_future(coro)
  137.     try:
  138.         exec(code, globals(), locals())
  139.     except:
  140.         traceback.print_exc()
  141.         out = discord_trim(traceback.format_exc())
  142.         for o in out:
  143.             await bot.send_message(ctx.message.channel, o)
  144.  
  145. @bot.command(pass_context=True)
  146. async def getname(ctx, userid:str):
  147.     out = str(discord.utils.get(bot.get_all_members(), id=userid))
  148.     await bot.say(out)  # @UndefinedVariable
  149.            
  150. def msg(dest, out):
  151.     coro = bot.send_message(dest, out)
  152.     asyncio.ensure_future(coro)
  153.    
  154. def replace(msg, out):
  155.     coro = bot.edit_message(msg, out)
  156.     asyncio.ensure_future(coro)
  157.    
  158. def discord_trim(str):
  159.     result = []
  160.     trimLen = 0
  161.     lastLen = 0
  162.     while trimLen <= len(str):
  163.         trimLen += 1999
  164.         result.append(str[lastLen:trimLen])
  165.         lastLen += 1999
  166.     return result
  167.  
  168. def fix_mentions(string):
  169.     mentions = re.findall('<[@!]+[0-9]+>', string)
  170.     for mention in mentions:
  171.         string = string.replace(mention, "**@\u200b" + str(discord.utils.get(bot.get_all_members(), id=re.sub('[<>@!]', '', mention))) + "**")
  172.     return string.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere')
  173.  
  174. async def load():
  175.     await bot.wait_until_ready()
  176.     for s in bot.servers:
  177.         print("Loading data for server " + str(s))
  178.         for c in s.channels:
  179.             print("Loading data for channel " + str(c))
  180.             if c.type is discord.ChannelType.text:
  181.                 try:
  182.                     async for m in bot.logs_from(c, 1000):
  183.                         if m not in bot.training_data:
  184.                             bot.training_data.append(m)
  185.                 except: pass
  186.             await asyncio.sleep(0.5)  # @UndefinedVariable
  187.     print("Loaded!")
  188.  
  189. '''@bot.event
  190. async def on_command_error(error, ctx):
  191.    if isinstance(error, commands.CommandNotFound):
  192.        return
  193.    print("Error caused by message: `{}`".format(ctx.message.content))
  194.    traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
  195.    tb = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
  196.    if isinstance(error, commands.CheckFailure):
  197.        await bot.send_message(ctx.message.channel, "Error: Either you do not have the permissions to run this command or the command is disabled.")
  198.        return
  199.    elif isinstance(error, (commands.MissingRequiredArgument, commands.BadArgument, commands.NoPrivateMessage)):
  200.        await bot.send_message(ctx.message.channel, "Error: " + str(error) + "\nUse `!help " + ctx.command.qualified_name + "` for help.")
  201.    elif bot.mask & coreCog.debug_mask:
  202.        await bot.send_message(ctx.message.channel, "Error: " + str(error) + "\nThis incident has been reported to the developer.")
  203.        try:
  204.            await bot.send_message(bot.owner, "Error in channel {} ({}), server {} ({}): {}\nCaused by message: `{}`".format(ctx.message.channel, ctx.message.channel.id, ctx.message.server, ctx.message.server.id, repr(error), ctx.message.content))
  205.        except AttributeError:
  206.            await bot.send_message(bot.owner, "Error in PM with {} ({}): {}\nCaused by message: `{}`".format(ctx.message.author.mention, str(ctx.message.author), repr(error), ctx.message.content))
  207.        for o in discord_trim(tb):
  208.            await bot.send_message(bot.owner, o)
  209.    else:
  210.        await bot.send_message(ctx.message.channel, "Error: " + str(error))'''
  211.  
  212. try:
  213.     bot.loop.run_until_complete(bot.start('BOT TOKEN KEY THINGER', bot=True))
  214. except KeyboardInterrupt:
  215.     bot.loop.run_until_complete(bot.logout())
  216.     with open('./markovdata.pkl', mode='wb') as f:
  217.         pickle.dump(bot.training_data, f)
  218. finally:
  219.     bot.loop.close()
Advertisement
Add Comment
Please, Sign In to add comment