matthileo

Untitled

Feb 12th, 2017
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.02 KB | None | 0 0
  1. import asyncio
  2. import datetime
  3. from os.path import isfile
  4. import pickle
  5. import re
  6. import sys
  7. import traceback
  8.  
  9. import discord
  10. from discord.ext import commands
  11. import markovify
  12. import os
  13. import uuid
  14. from random import randint
  15.  
  16. import botutils
  17. from botutils import Utils
  18. import botchecks
  19.  
  20. import music
  21. from music import Music
  22.  
  23. owner_id = '126215805053435904'
  24. bot_token='SEKRUT' ## THIS MUST BE REMOVED IF CODE IS SHARED
  25. bot = commands.Bot(command_prefix='$', description="Yes, I am called Locutus!", pm_help=True, self_bot=False)
  26. bot.training_data = []
  27. bot.STATE_SIZE = 2
  28.  
  29. utilsCog = botutils.Utils(bot)
  30. musicCog = music.Music(bot)
  31. bot.add_cog([utilsCog,musicCog])
  32.  
  33. @bot.event
  34. async def on_ready():
  35.     print('Logged in as')
  36.     print(bot.user.name)
  37.     #print(bot.user.id)
  38.     print('------')
  39.     await weather_bot()
  40.    
  41.        
  42. @bot.event
  43. async def on_message(message):
  44.     bot.training_data.append(message)
  45.     await bot.process_commands(message)
  46.  
  47. @bot.command(pass_context=True)
  48. async def load_markov(ctx):
  49.     if isfile('./markovdata.pkl'):
  50.         with open('./markovdata.pkl', mode='rb') as f:
  51.             bot.training_data = pickle.load(f)
  52.     if not 'predata' in sys.argv:
  53.         bot.loop.create_task(load())
  54.     else:
  55.         print("Loaded!")
  56.         await bot.say("Loaded Markov data!")
  57.    
  58. @bot.command(pass_context=True)
  59. async def chanMarkov(ctx, channel:discord.Channel=None, num:int=1):
  60.     text = ''
  61.     if channel is None:
  62.         channel = ctx.message.channel
  63.     for m in bot.training_data:
  64.         if m.channel.id == channel.id:
  65.             text += m.content + '\n'
  66.     markov = markovify.NewlineText(text, state_size=bot.STATE_SIZE)
  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.say(out)  # @UndefinedVariable
  75.  
  76. @bot.command(pass_context=True)
  77. async def servMarkov(ctx, num:int=1):
  78.     loading = await bot.say("Generating, this might take a while...")
  79.     text = ''
  80.     for m in bot.training_data:
  81.         if m.server is not None:
  82.             if m.server.id == ctx.message.server.id:
  83.                 text += m.content + '\n'
  84.     markov = markovify.NewlineText(text, state_size=bot.STATE_SIZE)
  85.     out = ''
  86.     for i in range(num):
  87.         try:
  88.             out += markov.make_sentence(tries=1000) + '\n\n'
  89.         except:
  90.             pass
  91.     out = fix_mentions(out)
  92.     await bot.edit_message(loading, out)  # @UndefinedVariable
  93.    
  94. @bot.command(pass_context=True)
  95. async def membMarkov(ctx, member:discord.Member, num:int=1):
  96.     text = ''
  97.     for m in bot.training_data:
  98.         if m.server is not None:
  99.             if m.author.id == member.id and m.server.id == ctx.message.server.id:
  100.                 text += m.content + '\n'
  101.     markov = markovify.NewlineText(text, state_size=bot.STATE_SIZE)
  102.     out = ''
  103.     for i in range(num):
  104.         try:
  105.             out += markov.make_sentence(tries=1000) + '\n\n'
  106.         except:
  107.             pass
  108.     out = fix_mentions(out)
  109.     await bot.say(out)  # @UndefinedVariable
  110.    
  111. @bot.command(pass_context=True)
  112. async def userMarkov(ctx, member:str, num:int=1, scrub="don't scrub"):
  113.     text = ''
  114.     for m in bot.training_data:
  115.         if m.author.id == member:
  116.             text += m.content + '\n'
  117.     markov = markovify.NewlineText(text, state_size=bot.STATE_SIZE)
  118.     out = ''
  119.     for i in range(num):
  120.         try:
  121.             out += markov.make_sentence(tries=1000) + '\n\n'
  122.         except:
  123.             pass
  124.     out = fix_mentions(out)
  125.     if scrub == "scrub": out = scrub_names(out)
  126.     await bot.say(out)  # @UndefinedVariable
  127.    
  128. @bot.command(pass_context=True)
  129. async def globMarkov(ctx, num:int=1):
  130.     print("Starting global markov...")
  131.     text = ''
  132.     for m in bot.training_data:
  133.         text += m.content + '\n'
  134.     markov = markovify.NewlineText(text, state_size=bot.STATE_SIZE)
  135.     out = ''
  136.     for i in range(num):
  137.         try:
  138.             out += markov.make_sentence(tries=1000) + '\n\n'
  139.         except:
  140.             pass
  141.     out = fix_mentions(out)
  142.     await bot.say(out)  # @UndefinedVariable
  143.    
  144. def fix_mentions(string):
  145.     mentions = re.findall('<[@!]+[0-9]+>', string)
  146.     for mention in mentions:
  147.         string = string.replace(mention, "**@" + str(discord.utils.get(bot.get_all_members(), id=re.sub('[<>@!]', '', mention)))+"**")
  148.     return string.replace('@', '@\u200b')
  149.    
  150. @bot.command(pass_context=True)
  151. async def code(ctx, *, code : str):
  152.     """Arbitrarily runs code."""
  153.     if not ctx.message.author.id == '126215805053435904': return
  154.     here = ctx.message.channel
  155.     this = ctx.message
  156.     def echo(out):
  157.         msg(here, out)
  158.     def rep(out):
  159.         replace(this, out)
  160.     def coro(coro):
  161.         asyncio.ensure_future(coro)
  162.     try:
  163.         exec(code, globals(), locals())
  164.     except:
  165.         traceback.print_exc()
  166.         out = discord_trim(traceback.format_exc())
  167.         for o in out:
  168.             await bot.send_message(ctx.message.channel, o)
  169.            
  170. def msg(dest, out):
  171.     coro = bot.send_message(dest, out)
  172.     asyncio.ensure_future(coro)
  173.    
  174. def replace(msg, out):
  175.     coro = bot.edit_message(msg, out)
  176.     asyncio.ensure_future(coro)
  177.    
  178. def discord_trim(str):
  179.     result = []
  180.     trimLen = 0
  181.     lastLen = 0
  182.     while trimLen <= len(str):
  183.         trimLen += 1999
  184.         result.append(str[lastLen:trimLen])
  185.         lastLen += 1999
  186.     return result
  187.  
  188. @bot.command()
  189. async def state_size(size:int=2):
  190.     bot.STATE_SIZE = size
  191.     await bot.say("State size set to " + str(size))
  192.  
  193. @bot.command(pass_context=True)
  194. async def load_all(ctx, chan:discord.Channel):
  195.     if not ctx.message.author.id == '126215805053435904': return
  196.     existing_data = [m.id for m in bot.training_data]
  197.     await bot.say("Loading ALL data for channel " + str(chan))
  198.     print("Loading ALL data for channel " + str(chan))
  199.     if chan.type is discord.ChannelType.text:
  200.         try:
  201.             oldest_timestamp = chan.created_at
  202.             all_loaded=0
  203.             while True:
  204.                 loaded = 0
  205.                 loglen = 0
  206.                 async for m in bot.logs_from(chan, 10000, after=oldest_timestamp):
  207.                     loglen += 1
  208.                     if m.timestamp > oldest_timestamp:
  209.                         oldest_timestamp = m.timestamp
  210.                     if m.id not in existing_data:
  211.                         bot.training_data.append(m)
  212.                         loaded += 1
  213.                         all_loaded += 1
  214.                 await asyncio.sleep(0.5)  # @UndefinedVariable
  215.                 print("... loaded {} messages.".format(str(loaded)))
  216.                 if loglen == 0: break
  217.         except: pass
  218.     print("Done! Loaded {} messages total.".format(str(all_loaded)))
  219.     await bot.say("Done! Loaded {} messages total.".format(str(all_loaded)))
  220.    
  221. @bot.command(pass_context=True)
  222. async def load_server(ctx):
  223.     if not ctx.message.author.id == '126215805053435904': return
  224.     existing_data = [m.id for m in bot.training_data]
  225.     print("Loading ALL data for server " + str(ctx.message.server))
  226.     all_loaded=0
  227.     for chan in ctx.message.server.channels:
  228.         print("Loading ALL data for channel " + str(chan))
  229.         if chan.type is discord.ChannelType.text:
  230.             try:
  231.                 oldest_timestamp = chan.created_at
  232.                 chan_loaded = 0
  233.                 while True:
  234.                     loaded = 0
  235.                     loglen = 0
  236.                     async for m in bot.logs_from(chan, 10000, after=oldest_timestamp):
  237.                         loglen += 1
  238.                         if m.timestamp > oldest_timestamp:
  239.                             oldest_timestamp = m.timestamp
  240.                         if m.id not in existing_data:
  241.                             bot.training_data.append(m)
  242.                             loaded += 1
  243.                             all_loaded += 1
  244.                             chan_loaded += 1
  245.                     await asyncio.sleep(0.5)  # @UndefinedVariable
  246.                     print("... loaded {} messages.".format(str(loaded)))
  247.                     if loglen == 0: break
  248.             except: pass
  249.         print("Done for channel {}! Loaded {} messages total.".format(str(chan), str(chan_loaded)))
  250.         await bot.say("Done for channel {}! Loaded {} messages total.".format(str(chan), str(chan_loaded)))
  251.     print("Done! Loaded {} messages total.".format(str(all_loaded)))
  252.     await bot.say("Done! Loaded {} messages total.".format(str(all_loaded)))
  253.    
  254. async def load():
  255.     await bot.wait_until_ready()
  256.     existing_data = [m.id for m in bot.training_data]
  257.     for s in bot.servers:
  258.         print("Loading data for server " + str(s))
  259.         for c in s.channels:
  260.             print("Loading data for channel " + str(c))
  261.             if c.type is discord.ChannelType.text:
  262.                 try:
  263.                     loaded = 0
  264.                     async for m in bot.logs_from(c, 1000):
  265.                         if m.id not in existing_data:
  266.                             bot.training_data.append(m)
  267.                             loaded += 1
  268.                 except: pass
  269.                 print("... loaded {} messages.".format(str(loaded)))
  270.             await asyncio.sleep(0.5)  # @UndefinedVariable
  271.     print("Loaded!")
  272.  
  273. async def weather_bot():
  274.     while True:
  275.         try:
  276.             await bot.change_presence(game=discord.Game(name=Utils.get_weather("short")))
  277.         except Exception as e:
  278.             print("Error: %s" % repr(e))  
  279.         await asyncio.sleep(1800)
  280.    
  281. try:
  282.     bot.loop.run_until_complete(bot.start(bot_token, bot=True))
  283. except KeyboardInterrupt:
  284.     bot.loop.run_until_complete(bot.logout())
  285. #     with open('./markovdata.pkl', mode='wb') as f:
  286. #         pickle.dump(bot.training_data, f)
  287.     temp = '%s-%s.tmp' % (uuid.uuid4(), 'markovdata.pkl')
  288.     with open(temp, mode='wb') as tmp:
  289.         pickle.dump(bot.training_data, tmp)
  290.  
  291.     # atomically move the file
  292.     os.replace(temp, 'markovdata.pkl')
  293. finally:
  294.     bot.loop.close()
Advertisement
Add Comment
Please, Sign In to add comment