Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Created on Jan 14, 2017
- @author: thinger
- '''
- import asyncio
- import pickle
- import sys
- import traceback
- import re
- import random
- import discord
- from discord.ext import commands
- import markovify
- bot = commands.Bot(command_prefix='$', description="Markov bot is friend!", pm_help=True, self_bot=False)
- bot.training_data = []
- @bot.event
- async def on_ready():
- print('Logged in as')
- print(bot.user.name)
- #print(bot.user.id)
- print('------')
- if not 'predata' in sys.argv:
- bot.loop.create_task(load())
- else:
- with open('./markovdata.pkl', mode='rb') as f:
- bot.training_data = pickle.load(f)
- print("Data Loaded!")
- @bot.event
- async def on_message(message):
- bot.training_data.append(message)
- await bot.process_commands(message)
- @bot.command(pass_context=True)
- async def chanMarkov(ctx, channel:discord.Channel=None, num:int=1):
- text = ''
- if channel is None:
- channel = ctx.message.channel
- for m in bot.training_data:
- if m.channel.id == channel.id:
- text += m.content + '\n'
- markov = markovify.NewlineText(text,state_size=2)
- out = ''
- for i in range(num):
- try:
- out += markov.make_sentence(tries=1000) + '\n\n'
- except:
- pass
- out = fix_mentions(out)
- await bot.say(out) # @UndefinedVariable
- @bot.command(pass_context=True)
- async def servMarkov(ctx, num:int=1):
- loading = await bot.say("Generating, this might take a while...")
- text = ''
- for m in bot.training_data:
- if m.server is not None:
- if m.server.id == ctx.message.server.id:
- text += m.content + '\n'
- markov = markovify.NewlineText(text,state_size=2)
- out = ''
- for i in range(num):
- try:
- out += markov.make_sentence(tries=1000) + '\n\n'
- except:
- pass
- out = fix_mentions(out)
- await bot.edit_message(loading, out) # @UndefinedVariable
- @bot.command(pass_context=True)
- async def membMarkov(ctx, member:discord.Member, num:int=1):
- text = ''
- for m in bot.training_data:
- if m.server is not None:
- if m.author.id == member.id and m.server.id == ctx.message.server.id:
- text += m.content + '\n'
- markov = markovify.NewlineText(text,state_size=2)
- out = ''
- for i in range(num):
- try:
- out += markov.make_sentence(tries=1000) + '\n\n'
- except:
- pass
- out = fix_mentions(out)
- await bot.say(out) # @UndefinedVariable
- @bot.command(pass_context=True)
- async def userMarkov(ctx, member:str, num:int=1):
- text = ''
- for m in bot.training_data:
- if m.author.id == member:
- text += m.content + '\n'
- markov = markovify.NewlineText(text,state_size=2)
- out = ''
- for i in range(num):
- try:
- out += markov.make_sentence(tries=1000) + '\n\n'
- except:
- pass
- out = fix_mentions(out)
- await bot.say(out) # @UndefinedVariable
- @bot.command(pass_context=True)
- async def globMarkov(ctx, num:int=1):
- print("Starting global markov...")
- text = ''
- for m in bot.training_data:
- text += m.content + '\n'
- markov = markovify.NewlineText(text,state_size=2)
- out = ''
- for i in range(num):
- try:
- out += markov.make_sentence(tries=1000) + '\n\n'
- except:
- pass
- out = fix_mentions(out)
- await bot.say(out) # @UndefinedVariable
- @bot.command(pass_context=True)
- async def code(ctx, *, code : str):
- """Arbitrarily runs code."""
- if not ctx.message.author.id == '126215805053435904': return
- here = ctx.message.channel
- this = ctx.message
- def echo(out):
- msg(here, out)
- def rep(out):
- replace(this, out)
- def coro(coro):
- asyncio.ensure_future(coro)
- try:
- exec(code, globals(), locals())
- except:
- traceback.print_exc()
- out = discord_trim(traceback.format_exc())
- for o in out:
- await bot.send_message(ctx.message.channel, o)
- @bot.command(pass_context=True)
- async def getname(ctx, userid:str):
- out = str(discord.utils.get(bot.get_all_members(), id=userid))
- await bot.say(out) # @UndefinedVariable
- def msg(dest, out):
- coro = bot.send_message(dest, out)
- asyncio.ensure_future(coro)
- def replace(msg, out):
- coro = bot.edit_message(msg, out)
- asyncio.ensure_future(coro)
- def discord_trim(str):
- result = []
- trimLen = 0
- lastLen = 0
- while trimLen <= len(str):
- trimLen += 1999
- result.append(str[lastLen:trimLen])
- lastLen += 1999
- return result
- def fix_mentions(string):
- mentions = re.findall('<[@!]+[0-9]+>', string)
- for mention in mentions:
- string = string.replace(mention, "**@\u200b" + str(discord.utils.get(bot.get_all_members(), id=re.sub('[<>@!]', '', mention))) + "**")
- return string.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere')
- async def load():
- await bot.wait_until_ready()
- for s in bot.servers:
- print("Loading data for server " + str(s))
- for c in s.channels:
- print("Loading data for channel " + str(c))
- if c.type is discord.ChannelType.text:
- try:
- async for m in bot.logs_from(c, 1000):
- if m not in bot.training_data:
- bot.training_data.append(m)
- except: pass
- await asyncio.sleep(0.5) # @UndefinedVariable
- print("Loaded!")
- '''@bot.event
- async def on_command_error(error, ctx):
- if isinstance(error, commands.CommandNotFound):
- return
- print("Error caused by message: `{}`".format(ctx.message.content))
- traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
- tb = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
- if isinstance(error, commands.CheckFailure):
- await bot.send_message(ctx.message.channel, "Error: Either you do not have the permissions to run this command or the command is disabled.")
- return
- elif isinstance(error, (commands.MissingRequiredArgument, commands.BadArgument, commands.NoPrivateMessage)):
- await bot.send_message(ctx.message.channel, "Error: " + str(error) + "\nUse `!help " + ctx.command.qualified_name + "` for help.")
- elif bot.mask & coreCog.debug_mask:
- await bot.send_message(ctx.message.channel, "Error: " + str(error) + "\nThis incident has been reported to the developer.")
- try:
- 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))
- except AttributeError:
- 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))
- for o in discord_trim(tb):
- await bot.send_message(bot.owner, o)
- else:
- await bot.send_message(ctx.message.channel, "Error: " + str(error))'''
- try:
- bot.loop.run_until_complete(bot.start('BOT TOKEN KEY THINGER', bot=True))
- except KeyboardInterrupt:
- bot.loop.run_until_complete(bot.logout())
- with open('./markovdata.pkl', mode='wb') as f:
- pickle.dump(bot.training_data, f)
- finally:
- bot.loop.close()
Advertisement
Add Comment
Please, Sign In to add comment