<commit_before># I'M BUSY! Plugin by Curs3d #
##############################
# Concept by CookieManors :D #
# http://bit.ly/1GnNPW8      #
##############################
# This plugin permits users to
# send a command that renders
# them "busy", not letting them
# to get tpa requests or direct
# messages, except from console.
# On restart, all busy data will
# be cleared.

from helpers import *
from basecommands import simplecommand
import org.bukkit.command.Command as Command
from traceback import format_exc as trace

busy_players = []

def unclear(sender):
    msg(sender, "Umm, what? Sorry, directions unclear, got head stuck in washing machine")

@hook.command("busy",
    aliases = ["focus"],
    usage = "/<command> <on|off|status>",
    description = "Sets busy mode on, you cannot recieve tpas and MSGs"
    )
def on_busy_command(sender, cmd, label, args):

    if not is_player(sender):
       msg(sender, "Sorry, Console cannot be busy")
       return True

    plugin_header(recipient = sender, name = "I'M BUSY!")

    if not sender.hasPermission("utils.busy.allowed"):
        noperm(sender)
        return True

    if len(args) == 0:
        msg(sender, "This plugin allows being busy, and when turned on you will not receive any direct messages or tpa requests.")
        msg(sender, "\nCommands:")
        msg(sender, "/busy on: turns on busy mode")
        msg(sender, "/busy off: turns off busy mode")
        msg(sender, "/busy status [player]: shows your or [player]'s current busy status.")

    elif len(args) == 1:
        if args[0] == "on":
            if sender.getName() in busy_players:
                msg(sender, "You cannot be even more focused than this without being a jedi!")
            else:
                busy_players.append(sender.getName())
                broadcast(None, "&c[&2Busy&c] %s&r is now busy, don't even TRY bothering them!" % sender.getDisplayName())

        elif args[0] == "off":
            try:
                busy_players.remove(sender.getName())
                msg(sender, "Master has sent /busy command, %s&r is freeee of bothering!" % sender.getDisplayName())
            except ValueError:
                msg(sender, "You are not busy! You cannot be even less busy! Are you perhaps bored?")

        elif args[0] == "status":
            if sender.getName() in busy_players:
                msg(sender, "You are super-duper busy and concentrated right now. Think, think, think!")
            else:
                msg(sender, "You are completely unable to focus right now.")

        else:
            unclear(sender)
            return False

    elif len(args) == 2 and args[0] == "status":
        target = server.getPlayer(args[1])
        if target is None:
            msg(sender, "That player is not online, I doubt they are busy.")
        elif target.getName() in busy_players:
            msg(sender, "Yes, %s&r is busy. Shhh..." % target.getDisplayName())
        else:
            msg(sender, "No, you're good. Feel free to chat with %s&r!" % target.getDisplayName())

    else:
        unclear(sender)
        return False
    return True

@hook.event("player.PlayerQuitEvent", "lowest")
def on_player_leave(event):
    try:
        busy_players.remove(event.getPlayer().getName())
    except:
        pass

#---- Dicode for catching any bothering of busy people ----

reply_targets = {}
override_perm = "utils.imbusy.override"

def whisper(sender, target_name):
    target = server.getPlayer(target_name)

    if target is not None:
        if target is not sender and not sender.hasPermission(override_perm) and target.getName() in busy_players:
            msg(sender, "&c[&fBUSY&c] %s&r is busy!" % target.getDisplayName())
            return False

        reply_targets[sender.getName()] = target.getName()

        # allow the target to reply regardless of sender being busy
        if target.getName() in reply_targets:
            del reply_targets[target.getName()]
    return True

def reply(sender):
    if sender.getName() in reply_targets:
        target = server.getPlayer(reply_targets[sender.getName()])
        if target is not None:
            if target is not sender and not sender.hasPermission(override_perm) and target.getName() in busy_players:
                msg(sender, "&c[&fBUSY&c] %s&r is busy!" % target.getDisplayName())
                return False

            # allow the target to reply regardless of sender being busy
            if target.getName() in reply_targets:
                del reply_targets[target.getName()]
    return True

class CommandWrapper(Command):

    def __init__(self, wrapped, checker):
        Command.__init__(self, wrapped.getName())
        self.setDescription(wrapped.getDescription())
        self.setPermission(wrapped.getPermission())
        self.setUsage(wrapped.getUsage())
        self.setAliases(wrapped.getAliases())
        self.wrapped = wrapped
        self.checker = checker

    def execute(self, sender, label, args):
        try:
            if self.checker(sender, args):
                return self.wrapped.execute(sender, label, args)
        except:
            error(trace())
        return True

    def tabComplete(self, sender, alias, args):
        return self.wrapped.tabComplete(sender, alias, args)

def msg_command_checker(sender, args):
    return len(args) <= 1 or whisper(sender, args[0])

def reply_command_checker(sender, args):
    return len(args) == 0 or reply(sender)

def tpa_command_checker(sender, args):
    if len(args) == 0:
        return True
    target = server.getPlayer(args[0])
    if target is not None and target is not sender and not sender.hasPermission(override_perm) and target.getName() in busy_players:
        msg(sender, "&c[&fBUSY&c] %s&r is busy!" % target.getDisplayName())
        return False
    return True

def tpahere_command_checker(sender, args):
    return tpa_command_checker(sender, args)

def mail_command_checker(sender, args):
    if len(args) < 3 or args[0].lower() != "send":
        return True
    target = server.getPlayer(args[1])
    if target is not None and target is not sender and not sender.hasPermission(override_perm) and target.getName() in busy_players:
        msg(sender, "&c[&fBUSY&c] %s&r is busy!" % target.getDisplayName())
        return False
    return True

@hook.event("player.PlayerCommandPreprocessEvent", "monitor")
def on_player_command_preprocess(event):
    message = event.getMessage().split(" ")
    if len(message) > 1 and message[0].lower() in ("/tell", "/minecraft:tell") and not whisper(event.getPlayer(), message[1]):
        event.setCancelled(True)

@hook.enable
def replace_ess_commands():

    try:
        map_field = server.getPluginManager().getClass().getDeclaredField("commandMap")
        map_field.setAccessible(True)
        command_map = map_field.get(server.getPluginManager())

        commands_field = command_map.getClass().getDeclaredField("knownCommands")
        commands_field.setAccessible(True)
        map = commands_field.get(command_map)

        ess_msg_cmd = map.get("essentials:msg")
        ess_reply_cmd = map.get("essentials:reply")
        ess_tpa_cmd = map.get("essentials:tpa")
        ess_tpahere_cmd = map.get("essentials:tpahere")
        ess_mail_cmd = map.get("essentials:mail")

        msg_cmd_wrapper = CommandWrapper(ess_msg_cmd, msg_command_checker)
        reply_cmd_wrapper = CommandWrapper(ess_reply_cmd, reply_command_checker)
        tpa_cmd_wrapper = CommandWrapper(ess_tpa_cmd, tpa_command_checker)
        tpahere_cmd_wrapper = CommandWrapper(ess_tpahere_cmd, tpahere_command_checker)
        mail_cmd_wrapper = CommandWrapper(ess_mail_cmd, mail_command_checker)

        iterator = map.entrySet().iterator()
        while iterator.hasNext():
            entry = iterator.next()
            value = entry.getValue()
            if value is ess_msg_cmd:
                entry.setValue(msg_cmd_wrapper)
                info("[imbusy] wrapped /" + entry.getKey())
            elif value is ess_reply_cmd:
                entry.setValue(reply_cmd_wrapper)
                info("[imbusy] wrapped /" + entry.getKey())
            elif value is ess_tpa_cmd:
                entry.setValue(tpa_cmd_wrapper)
                info("[imbusy] wrapped /" + entry.getKey())
            elif value is ess_tpahere_cmd:
                entry.setValue(tpahere_cmd_wrapper)
                info("[imbusy] wrapped /" + entry.getKey())
            elif value is ess_mail_cmd:
                entry.setValue(mail_cmd_wrapper)
                info("[imbusy] wrapped /" + entry.getKey())

    except:
        error("[Imbusy] Failed to wrap essentials commands")
        error(trace())
<commit_msg>Make /busy a toggle, move help page to /busy help. Changed a few messages<commit_after># I'M BUSY! Plugin by Curs3d #
##############################
# Concept by CookieManors :D #
# http://bit.ly/1GnNPW8      #
##############################
# This plugin permits users to
# send a command that renders
# them "busy", not letting them
# to get tpa requests or direct
# messages, except from console.
# On restart, all busy data will
# be cleared.

from helpers import *
from basecommands import simplecommand
import org.bukkit.command.Command as Command
from traceback import format_exc as trace

busy_players = []

def unclear(sender):
    msg(sender, "Umm, what? Sorry, directions unclear, got head stuck in washing machine")

@hook.command("busy",
    aliases = ["focus"],
    usage = "/<command> <on|off|status>",
    description = "Sets busy mode on, you cannot recieve tpas and MSGs"
    )
def on_busy_command(sender, cmd, label, args):

    if not is_player(sender):
       msg(sender, "Sorry, Console cannot be busy")
       return True

    plugin_header(recipient = sender, name = "I'M BUSY!")

    if not sender.hasPermission("utils.busy.allowed"):
        noperm(sender)
        return True

    sender_name = sender.getName()

    if len(args) == 0:
        if sender_name in busy_players:
            busy_players.remove(sender_name)
            msg(sender, "Your busy status was removed, you can be bothered again")
        else:
            busy_players.append(sender_name)
            broadcast(None, "&c[&2Busy&c] %s&r is now busy, don't even TRY bothering them!" % sender.getDisplayName())

    elif len(args) == 1:
        if args[0].lower() == "on":
            if sender_name in busy_players:
                msg(sender, "You cannot be even more focused than this without being a jedi!")
            else:
                busy_players.append(sender_name)
                broadcast(None, "&c[&2Busy&c] %s&r is now busy, don't even TRY bothering them!" % sender.getDisplayName())

        elif args[0].lower() == "off":
            try:
                busy_players.remove(sender_name)
                msg(sender, "Your busy status was removed, you can be bothered again")
            except ValueError:
                msg(sender, "You are not busy! You cannot be even less busy! Are you perhaps bored?")

        elif args[0].lower() == "status":
            if sender_name in busy_players:
                msg(sender, "You are super-duper busy and concentrated right now. Think, think, think!")
            else:
                msg(sender, "You are completely unable to focus right now.")

        elif args[0].lower() in ("?", "help"):
            msg(sender, "Let's you put yourself in busy status, preventing pms and tpa requests from other players")
            msg(sender, "\nCommands:")
            msg(sender, "/busy: toggles busy status")
            msg(sender, "/busy on: turns on busy status")
            msg(sender, "/busy off: turns off busy status")
            msg(sender, "/busy status [player]: shows your or [player]'s current busy status.")
        else:
            unclear(sender)
            return False

    elif len(args) == 2 and args[0] == "status":
        target = server.getPlayer(args[1])
        if target is None:
            msg(sender, "That player is not online, they may be busy IRL, we never know")
        elif target.getName() in busy_players:
            msg(sender, "Yes, %s&r is busy. Shhh..." % target.getDisplayName())
        else:
            msg(sender, "No, you're good. Feel free to chat with %s&r!" % target.getDisplayName())

    else:
        unclear(sender)
        return False
    return True

@hook.event("player.PlayerQuitEvent", "lowest")
def on_player_leave(event):
    try:
        busy_players.remove(event.getPlayer().getName())
    except:
        pass

#---- Dicode for catching any bothering of busy people ----

reply_targets = {}
override_perm = "utils.imbusy.override"

def whisper(sender, target_name):
    target = server.getPlayer(target_name)

    if target is not None:
        if target is not sender and not sender.hasPermission(override_perm) and target.getName() in busy_players:
            msg(sender, "&c[&fBUSY&c] %s&r is busy!" % target.getDisplayName())
            return False

        reply_targets[sender.getName()] = target.getName()

        # allow the target to reply regardless of sender being busy
        if target.getName() in reply_targets:
            del reply_targets[target.getName()]
    return True

def reply(sender):
    if sender.getName() in reply_targets:
        target = server.getPlayer(reply_targets[sender.getName()])
        if target is not None:
            if target is not sender and not sender.hasPermission(override_perm) and target.getName() in busy_players:
                msg(sender, "&c[&fBUSY&c] %s&r is busy!" % target.getDisplayName())
                return False

            # allow the target to reply regardless of sender being busy
            if target.getName() in reply_targets:
                del reply_targets[target.getName()]
    return True

class CommandWrapper(Command):

    def __init__(self, wrapped, checker):
        Command.__init__(self, wrapped.getName())
        self.setDescription(wrapped.getDescription())
        self.setPermission(wrapped.getPermission())
        self.setUsage(wrapped.getUsage())
        self.setAliases(wrapped.getAliases())
        self.wrapped = wrapped
        self.checker = checker

    def execute(self, sender, label, args):
        try:
            if self.checker(sender, args):
                return self.wrapped.execute(sender, label, args)
        except:
            error(trace())
        return True

    def tabComplete(self, sender, alias, args):
        return self.wrapped.tabComplete(sender, alias, args)

def msg_command_checker(sender, args):
    return len(args) <= 1 or whisper(sender, args[0])

def reply_command_checker(sender, args):
    return len(args) == 0 or reply(sender)

def tpa_command_checker(sender, args):
    if len(args) == 0:
        return True
    target = server.getPlayer(args[0])
    if target is not None and target is not sender and not sender.hasPermission(override_perm) and target.getName() in busy_players:
        msg(sender, "&c[&fBUSY&c] %s&r is busy!" % target.getDisplayName())
        return False
    return True

def tpahere_command_checker(sender, args):
    return tpa_command_checker(sender, args)

def mail_command_checker(sender, args):
    if len(args) < 3 or args[0].lower() != "send":
        return True
    target = server.getPlayer(args[1])
    if target is not None and target is not sender and not sender.hasPermission(override_perm) and target.getName() in busy_players:
        msg(sender, "&c[&fBUSY&c] %s&r is busy!" % target.getDisplayName())
        return False
    return True

@hook.event("player.PlayerCommandPreprocessEvent", "monitor")
def on_player_command_preprocess(event):
    message = event.getMessage().split(" ")
    if len(message) > 1 and message[0].lower() in ("/tell", "/minecraft:tell") and not whisper(event.getPlayer(), message[1]):
        event.setCancelled(True)

@hook.enable
def replace_ess_commands():

    try:
        map_field = server.getPluginManager().getClass().getDeclaredField("commandMap")
        map_field.setAccessible(True)
        command_map = map_field.get(server.getPluginManager())

        commands_field = command_map.getClass().getDeclaredField("knownCommands")
        commands_field.setAccessible(True)
        map = commands_field.get(command_map)

        ess_msg_cmd = map.get("essentials:msg")
        ess_reply_cmd = map.get("essentials:reply")
        ess_tpa_cmd = map.get("essentials:tpa")
        ess_tpahere_cmd = map.get("essentials:tpahere")
        ess_mail_cmd = map.get("essentials:mail")

        msg_cmd_wrapper = CommandWrapper(ess_msg_cmd, msg_command_checker)
        reply_cmd_wrapper = CommandWrapper(ess_reply_cmd, reply_command_checker)
        tpa_cmd_wrapper = CommandWrapper(ess_tpa_cmd, tpa_command_checker)
        tpahere_cmd_wrapper = CommandWrapper(ess_tpahere_cmd, tpahere_command_checker)
        mail_cmd_wrapper = CommandWrapper(ess_mail_cmd, mail_command_checker)

        iterator = map.entrySet().iterator()
        while iterator.hasNext():
            entry = iterator.next()
            value = entry.getValue()
            if value is ess_msg_cmd:
                entry.setValue(msg_cmd_wrapper)
                info("[imbusy] wrapped /" + entry.getKey())
            elif value is ess_reply_cmd:
                entry.setValue(reply_cmd_wrapper)
                info("[imbusy] wrapped /" + entry.getKey())
            elif value is ess_tpa_cmd:
                entry.setValue(tpa_cmd_wrapper)
                info("[imbusy] wrapped /" + entry.getKey())
            elif value is ess_tpahere_cmd:
                entry.setValue(tpahere_cmd_wrapper)
                info("[imbusy] wrapped /" + entry.getKey())
            elif value is ess_mail_cmd:
                entry.setValue(mail_cmd_wrapper)
                info("[imbusy] wrapped /" + entry.getKey())

    except:
        error("[Imbusy] Failed to wrap essentials commands")
        error(trace())
<|endoftext|>


<commit_before>from aiohttp import web

import trafaret as t
from trafaret.keys import subdict

def author_validation(data):
	"""Test that first author exist in list of all authors."""
	if data['first_author'] not in data['authors']:
		raise t.DataError('first_author must exist in authors')

authors = subdict(
    'authors',
    t.Key('bookFirstAuthor', to_name='first_author', trafaret=t.String(max_length=10)),
    t.Key('bookAuthors', to_name='authors', trafaret=t.List(t.String(max_length=10))),
    trafaret=author_validation,
)

create_book_chacker = t.Dict({
   t.Key('bookTitle', to_name='title'): t.String,
   t.Key('bookPageCount', to_name='pages'): t.Int,
   t.Key('bookDescription', to_name='description'): t.String(min_length=20),
   t.Key('bookPrice', to_name='price', default=100): t.Int >= 100,
   t.Key('bookIsFree', optional=True, to_name='is_free'): t.Bool,
}) + t.Dict(authors)

update_user_chacker = create_book_chacker + {"id": t.Int}

users = {}

from functools import wraps

def with_error(fn):
    """
    This is decorator for wrapping web handlers which need to represent
    errors connected with validation if they exist.
    """

    @wraps(fn)
    async def inner(*args, **kwargs):
        try:
            return await fn(*args, **kwargs)
        except t.DataError as e:
            return web.json_response({
                'errors': e.as_dict()
            })

    return inner

def prepare_data_for_create_book(data):
    valid_data = create_book_chacker.check(data)

    # do something else
    ...

    return valid_data

def prepare_data_for_update_book(data):
    valid_data = update_user_chacker.check(data)

    # do something else
    ...

    return valid_data

@with_error
async def create_book(req):
	raw_data = await req.json()
	data = prepare_data_for_create_book(raw_data)

	# do something
	...

	return web.json_response({"created": True})

@with_error
async def update_book(req):
	raw_data = await req.json()
	data = prepare_data_for_update_book(raw_data)

	# do something
	...

	return web.json_response({"updated": True})

app = web.Application()

app.add_routes([
	web.post('/', create_book),
	web.put('/', update_book)
])

web.run_app(app, port=9000)
<commit_msg>docs: added web use<commit_after><|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import discord
from discord.ext import commands
import asyncio
import sys
import logging
import aiohttp
import json
import textwrap
from subprocess import check_output
from other import ownerchecks

logging.basicConfig(level=logging.INFO)
description = '''beep boop :)'''
bot = commands.Bot(command_prefix='^', description=description)
config = json.loads(open('config.json').read())

@bot.command()
async def k():
  """k"""
  await bot.say('k')

@bot.command()
async def fuck():
  """fuck"""
  await bot.say('fuck')

@bot.command()
async def ping():
  """Ping? Pong."""
  em = discord.Embed(title='Pong!', description='I am currently alive.', colour=0x6906E8)
  em.set_author(name='lolbot', icon_url=bot.user.default_avatar_url)
  await bot.say(embed=em)

@bot.command()
async def about():
  """Information about lolbot."""
  em = discord.Embed(title='lolbot version 1.0', description='Written by lold. (c) 2017 lold, all rights reserved.\nDiscord.py version: ' + discord.__version__ + '\nPython version: ' + sys.version + '\nWant to support lolbot and other projects? Donate to my ko-fi (https://ko-fi.com/A753OUG) or PayPal.me (https://paypal.me/ynapw)', colour=0x6906E8)
  em.set_author(name='lolbot, written by lold', icon_url=bot.user.default_avatar_url)
  await bot.say(embed=em)

@bot.command(pass_context=True)
async def suggest( ctx, *, suggestion: str ):
  """Got suggestions?"""
  await bot.say('Feedback has been forwarded on to the mailbox.')
  await bot.say(config['sugchannel'], 'Suggestion submitted: `' + str(suggestion) + '`')

@bot.command()
async def cat():
  with aiohttp.ClientSession() as session:
    """Random cat images. Awww, so cute! Powered by random.cat"""
    async with session.get('https://random.cat/meow') as r:
      if r.status == 200:
        js = await r.json()
        em = discord.Embed(title='lolbot', description='Here is your cat image, as requested.', colour=0x6906E8)
        em.set_author(name='lolbot', icon_url=bot.user.default_avatar_url)
        em.set_image(url=js['file'])
        await bot.say(embed=em)

@bot.command()
async def echo(*, message: str):
  """Self-explanatory."""
  await bot.say(message)

@bot.command()
async def httpcat(*, http_id: str):
  """http.cat images - ^httpcat <http code>"""
  httpcat_em = discord.Embed(title='lolbot', description='http.cat - here is your picture!', colour=0x6906E8)
  httpcat_em.set_image(url='https://http.cat/' + http_id + '.jpg')
  await bot.say(embed=httpcat_em)

# slice's eval code :^)
@bot.command(hidden=True, pass_context=True)
@ownerchecks.is_owner()
async def eval(self, ctx, *, code: str):
  """Because everyone needs a good eval once in a while."""
  env = {
    'bot': ctx.bot,
    'ctx': ctx,
    'msg': ctx.message,
    'guild': ctx.guild,
    'channel': ctx.channel,
    'me': ctx.message.author,
    'get': discord.utils.get,
    'find': discord.utils.find,
  }

  fmt_exception = '```py\n>>> {}\n\n{}: {}```'

  env.update(globals())

  indented_code = textwrap.indent(code, '    ')
  wrapped_code = 'async def _eval_code():\n' + indented_code
  try:
      exec(wrapped_code, env)
      return_value = await env['_eval_code']()
      if return_value is not None:
        await ctx.send(return_value)
  except Exception as e:
      name = type(e).__name__
      await ctx.send(fmt_exception.format(code, name, e))
      return
@bot.command(hidden=True)
@ownerchecks.is_owner()
async def reboot():
  """Duh. Owner only"""
  await bot.say('Second please.')
  logging.info('Restart requested')
  await bot.change_presence(game=discord.Game(name='Restarting'))
  check_output(['sh', 'bot.sh'])
  await bot.logout()

@bot.command(hidden=True)
@ownerchecks.is_owner()
async def game(*, game: str):
  """Changes playing status"""
  await bot.change_presence(game=discord.Game(name=game + ' | ^help | v2.0'))

@bot.command()
async def shibe():
  with aiohttp.ClientSession() as shibe:
    """Random shibes, powered by shibe.online"""
    async with shibe.get('http://shibe.online/api/shibes?count=1&urls=true&httpsUrls=true') as shibeGet:
      if shibeGet.status == 200:
        shibeJson = await shibeGet.json()
        shibeEmbed = discord.Embed(name='shibe.online', colour=0x6906E8)
        shibeEmbed.set_image(url=shibeJson[0])
        await bot.say(embed=shibeEmbed)

@bot.event
async def on_server_join( server ):
  logging.info('Joined server' + str(server.name))
  logging.info('Server ID' + str(server.id))

async def botstats():
  async with aiohttp.ClientSession() as session:
    payload = json.dumps({
      'server_count': len(bot.servers)
    })

    headers = {
      'authorization': config['dbots'],
      'content-type': 'application/json'
    }
    dbl_headers = {
      'authorization': config['dbl'],
      'content-type': 'application/json'
    }

    dbots_url = 'https://bots.discord.pw/api/bots' + config['botid'] + 'stats'
    dbl_url = 'https://discordbots.org/api/bots' + config['botid'] + 'stats'
    async with session.post(dbl_url, data=payload, headers=dbl_headers) as dbl_resp:
      logging.info('dbl: posted with code' + await dbl_resp.status())
    async with session.post(dbots_url, data=payload, headers=headers) as resp:
      logging.info('dbots: posted with code' + await resp.status())
    await asyncio.sleep(60 * 60) # report to DBL/dbots every hour

try:
  @bot.event
  async def on_ready():
    logging.info('lolbot - ready')
    loop = asyncio.get_event_loop()
    serverpoll = loop.create_task(botstats())
    logging.info('Bot post loop initalized')
    await bot.change_presence(game=discord.Game(name='with APIs. | ^help | v2.0'))
    logging.info('Playing status changed')
except ImportError:
  logging.warn('Module(s) could not be found/not installed')
  logging.warn('Installing automatically')
  check_output(['pip', 'install', '-r', 'requirements.txt'])
  sys.exit('Please relaunch lolbot')

try:
  bot.run(config['token'])
except FileNotFoundError:
  logging.error('I can not find config.json!')
  logging.error('Are you sure you are in the same folder as it?')

<commit_msg>[stats] REEEEE<commit_after># -*- coding: utf-8 -*-
import discord
from discord.ext import commands
import asyncio
import sys
import logging
import aiohttp
import json
import textwrap
from subprocess import check_output
from other import ownerchecks

logging.basicConfig(level=logging.INFO)
description = '''beep boop :)'''
bot = commands.Bot(command_prefix='^', description=description)
config = json.loads(open('config.json').read())

@bot.command()
async def k():
  """k"""
  await bot.say('k')

@bot.command()
async def fuck():
  """fuck"""
  await bot.say('fuck')

@bot.command()
async def ping():
  """Ping? Pong."""
  em = discord.Embed(title='Pong!', description='I am currently alive.', colour=0x6906E8)
  em.set_author(name='lolbot', icon_url=bot.user.default_avatar_url)
  await bot.say(embed=em)

@bot.command()
async def about():
  """Information about lolbot."""
  em = discord.Embed(title='lolbot version 1.0', description='Written by lold. (c) 2017 lold, all rights reserved.\nDiscord.py version: ' + discord.__version__ + '\nPython version: ' + sys.version + '\nWant to support lolbot and other projects? Donate to my ko-fi (https://ko-fi.com/A753OUG) or PayPal.me (https://paypal.me/ynapw)', colour=0x6906E8)
  em.set_author(name='lolbot, written by lold', icon_url=bot.user.default_avatar_url)
  await bot.say(embed=em)

@bot.command(pass_context=True)
async def suggest( ctx, *, suggestion: str ):
  """Got suggestions?"""
  await bot.say('Feedback has been forwarded on to the mailbox.')
  await bot.say(config['sugchannel'], 'Suggestion submitted: `' + str(suggestion) + '`')

@bot.command()
async def cat():
  with aiohttp.ClientSession() as session:
    """Random cat images. Awww, so cute! Powered by random.cat"""
    async with session.get('https://random.cat/meow') as r:
      if r.status == 200:
        js = await r.json()
        em = discord.Embed(title='lolbot', description='Here is your cat image, as requested.', colour=0x6906E8)
        em.set_author(name='lolbot', icon_url=bot.user.default_avatar_url)
        em.set_image(url=js['file'])
        await bot.say(embed=em)

@bot.command()
async def echo(*, message: str):
  """Self-explanatory."""
  await bot.say(message)

@bot.command()
async def httpcat(*, http_id: str):
  """http.cat images - ^httpcat <http code>"""
  httpcat_em = discord.Embed(title='lolbot', description='http.cat - here is your picture!', colour=0x6906E8)
  httpcat_em.set_image(url='https://http.cat/' + http_id + '.jpg')
  await bot.say(embed=httpcat_em)

# slice's eval code :^)
@bot.command(hidden=True, pass_context=True)
@ownerchecks.is_owner()
async def eval(self, ctx, *, code: str):
  """Because everyone needs a good eval once in a while."""
  env = {
    'bot': ctx.bot,
    'ctx': ctx,
    'msg': ctx.message,
    'guild': ctx.guild,
    'channel': ctx.channel,
    'me': ctx.message.author,
    'get': discord.utils.get,
    'find': discord.utils.find,
  }

  fmt_exception = '```py\n>>> {}\n\n{}: {}```'

  env.update(globals())

  indented_code = textwrap.indent(code, '    ')
  wrapped_code = 'async def _eval_code():\n' + indented_code
  try:
      exec(wrapped_code, env)
      return_value = await env['_eval_code']()
      if return_value is not None:
        await ctx.send(return_value)
  except Exception as e:
      name = type(e).__name__
      await ctx.send(fmt_exception.format(code, name, e))
      return
@bot.command(hidden=True)
@ownerchecks.is_owner()
async def reboot():
  """Duh. Owner only"""
  await bot.say('Second please.')
  logging.info('Restart requested')
  await bot.change_presence(game=discord.Game(name='Restarting'))
  check_output(['sh', 'bot.sh'])
  await bot.logout()

@bot.command(hidden=True)
@ownerchecks.is_owner()
async def game(*, game: str):
  """Changes playing status"""
  await bot.change_presence(game=discord.Game(name=game + ' | ^help | v2.0'))

@bot.command()
async def shibe():
  with aiohttp.ClientSession() as shibe:
    """Random shibes, powered by shibe.online"""
    async with shibe.get('http://shibe.online/api/shibes?count=1&urls=true&httpsUrls=true') as shibeGet:
      if shibeGet.status == 200:
        shibeJson = await shibeGet.json()
        shibeEmbed = discord.Embed(name='shibe.online', colour=0x6906E8)
        shibeEmbed.set_image(url=shibeJson[0])
        await bot.say(embed=shibeEmbed)

@bot.event
async def on_server_join( server ):
  logging.info('Joined server' + str(server.name))
  logging.info('Server ID' + str(server.id))

async def botstats():
  async with aiohttp.ClientSession() as session:
    payload = json.dumps({
      'server_count': len(bot.servers)
    })

    headers = {
      'authorization': config['dbots'],
      'content-type': 'application/json'
    }
    dbl_headers = {
      'authorization': config['dbl'],
      'content-type': 'application/json'
    }

    dbots_url = 'https://bots.discord.pw/api/bots' + config['botid'] + 'stats'
    dbl_url = 'https://discordbots.org/api/bots' + config['botid'] + 'stats'
    async with session.post(dbl_url, data=payload, headers=dbl_headers) as dbl_resp:
      logging.info('dbl: posted with code' + print(await dbl_resp.status()))
    async with session.post(dbots_url, data=payload, headers=headers) as resp:
      logging.info('dbots: posted with code' + print(await resp.status()))
    await asyncio.sleep(60 * 60) # report to DBL/dbots every hour

try:
  @bot.event
  async def on_ready():
    logging.info('lolbot - ready')
    loop = asyncio.get_event_loop()
    serverpoll = loop.create_task(botstats())
    logging.info('Bot post loop initalized')
    await bot.change_presence(game=discord.Game(name='with APIs. | ^help | v2.0'))
    logging.info('Playing status changed')
except ImportError:
  logging.warn('Module(s) could not be found/not installed')
  logging.warn('Installing automatically')
  check_output(['pip', 'install', '-r', 'requirements.txt'])
  sys.exit('Please relaunch lolbot')

try:
  bot.run(config['token'])
except FileNotFoundError:
  logging.error('I can not find config.json!')
  logging.error('Are you sure you are in the same folder as it?')

<|endoftext|>


<commit_before>from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.stem.porter import PorterStemmer
import getopt
import sys
import os
import io
import string
import pickle

def build_dict(docs):
	dictionary = set()
	for doc_id, doc in docs.items():
		dictionary.update(doc)

	dictionary = list(dictionary)
	dictionary.sort()

	return dictionary

def build_postings(dictionary):
	postings = {}
	for term in dictionary:
		postings[term] = []

	return postings

def populate_postings(docs, postings):
	for doc_id, doc in docs.items():
		for term in set(doc):
			postings[term].append(doc_id)

def load_data(dir_doc):
	docs = {}
	for dirpath, dirnames, filenames in os.walk(dir_doc):
		for name in filenames:
			file = os.path.join(dirpath, name)
			with io.open(file, 'r+') as f:
				docs[name] = f.read()

	return docs

def preprocess(docs):
	stemmer = PorterStemmer()
	punctuations = set(string.punctuation)
	processed_docs = {}
	for doc_id, doc in docs.items():
		processed_docs[doc_id] = set([stemmer.stem(token) for token in word_tokenize(doc.lower())])
		processed_docs[doc_id].difference_update(punctuations)

	return processed_docs

def usage():
	print("usage: " + sys.argv[0] + " -i directory-of-documents -d dictionary-file -p postings-file")

if __name__ == '__main__':
	dir_doc = dict_file = postings_file = None
	try:
		opts, args = getopt.getopt(sys.argv[1:], 'i:d:p:')
	except getopt.GetoptError as err:
		usage()
		sys.exit(2)
	for o, a in opts:
		if o == '-i':
			dir_doc = a
		elif o == '-d':
			dict_file = a
		elif o == '-p':
			postings_file = a
		else:
			assert False, "unhandled option"
	if dir_doc == None or dict_file == None or postings_file == None:
		usage()
		sys.exit(2)

	docs = load_data(dir_doc)
	docs = preprocess(docs)
	dictionary = build_dict(docs)
	postings = build_postings(dictionary)
	populate_postings(docs, postings)

	with io.open(dict_file, 'wb+') as f:
		pickle.dump(dictionary, f)

	with io.open(postings_file, 'wb+') as f:
		pickle.dump(postings, f)
<commit_msg>Removed unnecessary + sign from file open flags<commit_after>from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.stem.porter import PorterStemmer
import getopt
import sys
import os
import io
import string
import pickle

def build_dict(docs):
	dictionary = set()
	for doc_id, doc in docs.items():
		dictionary.update(doc)

	dictionary = list(dictionary)
	dictionary.sort()

	return dictionary

def build_postings(dictionary):
	postings = {}
	for term in dictionary:
		postings[term] = []

	return postings

def populate_postings(docs, postings):
	for doc_id, doc in docs.items():
		for term in set(doc):
			postings[term].append(doc_id)

def load_data(dir_doc):
	docs = {}
	for dirpath, dirnames, filenames in os.walk(dir_doc):
		for name in filenames:
			file = os.path.join(dirpath, name)
			with io.open(file, 'r') as f:
				docs[name] = f.read()

	return docs

def preprocess(docs):
	stemmer = PorterStemmer()
	punctuations = set(string.punctuation)
	processed_docs = {}
	for doc_id, doc in docs.items():
		processed_docs[doc_id] = set([stemmer.stem(token) for token in word_tokenize(doc.lower())])
		processed_docs[doc_id].difference_update(punctuations)

	return processed_docs

def usage():
	print("usage: " + sys.argv[0] + " -i directory-of-documents -d dictionary-file -p postings-file")

if __name__ == '__main__':
	dir_doc = dict_file = postings_file = None
	try:
		opts, args = getopt.getopt(sys.argv[1:], 'i:d:p:')
	except getopt.GetoptError as err:
		usage()
		sys.exit(2)
	for o, a in opts:
		if o == '-i':
			dir_doc = a
		elif o == '-d':
			dict_file = a
		elif o == '-p':
			postings_file = a
		else:
			assert False, "unhandled option"
	if dir_doc == None or dict_file == None or postings_file == None:
		usage()
		sys.exit(2)

	docs = load_data(dir_doc)
	docs = preprocess(docs)
	dictionary = build_dict(docs)
	postings = build_postings(dictionary)
	populate_postings(docs, postings)

	with io.open(dict_file, 'wb') as f:
		pickle.dump(dictionary, f)

	with io.open(postings_file, 'wb') as f:
		pickle.dump(postings, f)
<|endoftext|>


<commit_before>#!/usr/bin/python

import cgi
import Cookie
import uuid
import os
import ebooker

cookie_data = {}

if 'HTTP_COOKIE' in os.environ:
    cookies = os.environ['HTTP_COOKIE']
    cookies = cookies.split('; ')

    for cookie in cookies:
        cookie = cookie.split('=')
        cookie_data[cookie[0]] = cookie[1]

if "session_id" not in cookie_data:
    session_id = uuid.uuid4()
    cookie = Cookie.SimpleCookie()
    cookie['session_id'] = session_id
    cookie['session_id']['expires'] = 24 * 60 * 60
    print cookie
else:
    session_id = cookie_data["session_id"]

session = ebooker.load_or_create_session(session_id)

#form = cgi.FieldStorage()
#message = form.getvalue("message", "(no message)")

print """Content-type: text/html"""
print
print """
<!DOCTYPE html>

    <title>featherlib ebooker</title>
    <meta charset="utf-8"/>
    <link rel="icon" type="image/png" href="favicon.png"/>
    <link href="styles/default-style.css" rel="stylesheet" type="text/css"/>

featherlib ebooker

Make epubs in one simple form.

        Here's how:

Add title, author and optionally additional information about the document

Paste the text for each chapter into the chapter input fields

Click Make epub, then wait for the file dialog to save your epub

    <form id="docForm" method="post" action="index.py">
        Document name

        <input type="text" name="doc-name" id="doc-name"/>

        Author

        <input type="text" name="doc-author" id="doc-author"/>

        Expand

            CSS

            <input type="text" name="doc-css" id="doc-css"/>

            Chapter 1

            <input type="text" name="chapter-1-name" id="chapter-1-name"/>

            <textarea name="chapter-1-content" id="chapter-1-content"></textarea>

        Add chapter

        <button type="submit" name="save" id="save">Save</button>
        <button type="submit" name="create" id="create">Create epub</button>

        <input type="hidden" name="no-of-chapters" id="no-of-chapters" value="1"/>
    </form>

"""<commit_msg>Fix missing cast to string for session id generated from uuid module.<commit_after>#!/usr/bin/python

import cgi
import Cookie
import uuid
import os
import ebooker

cookie_data = {}

if 'HTTP_COOKIE' in os.environ:
    cookies = os.environ['HTTP_COOKIE']
    cookies = cookies.split('; ')

    for cookie in cookies:
        cookie = cookie.split('=')
        cookie_data[cookie[0]] = cookie[1]

if "session_id" not in cookie_data:
    session_id = str(uuid.uuid4())
    cookie = Cookie.SimpleCookie()
    cookie['session_id'] = session_id
    cookie['session_id']['expires'] = 24 * 60 * 60
    print cookie
else:
    session_id = cookie_data["session_id"]

session = ebooker.load_or_create_session(session_id)

#form = cgi.FieldStorage()
#message = form.getvalue("message", "(no message)")

print """Content-type: text/html"""
print
print """
<!DOCTYPE html>

    <title>featherlib ebooker</title>
    <meta charset="utf-8"/>
    <link rel="icon" type="image/png" href="favicon.png"/>
    <link href="styles/default-style.css" rel="stylesheet" type="text/css"/>

featherlib ebooker

Make epubs in one simple form.

        Here's how:

Add title, author and optionally additional information about the document

Paste the text for each chapter into the chapter input fields

Click Make epub, then wait for the file dialog to save your epub

    <form id="docForm" method="post" action="index.py">
        Document name

        <input type="text" name="doc-name" id="doc-name"/>

        Author

        <input type="text" name="doc-author" id="doc-author"/>

        Expand

            CSS

            <input type="text" name="doc-css" id="doc-css"/>

            Chapter 1

            <input type="text" name="chapter-1-name" id="chapter-1-name"/>

            <textarea name="chapter-1-content" id="chapter-1-content"></textarea>

        Add chapter

        <button type="submit" name="save" id="save">Save</button>
        <button type="submit" name="create" id="create">Create epub</button>

        <input type="hidden" name="no-of-chapters" id="no-of-chapters" value="1"/>
    </form>

"""<|endoftext|>


<commit_before>import datetime
import json
import csv
import os
from flask import Flask, render_template, url_for, redirect, request, flash

app = Flask(__name__)
app.config.update(dict(Tracker=None))

class TimeTracker(object):
    def __init__(self, subjects, timer_file, logger_file):
        self.subjects = subjects
        self.timer_file = timer_file
        self.logger_file = logger_file
        self.start_time = None

    def __str__(self):
        return "TimeTracker: timer_file: %s, logger_file: %s, subjects: %s" % (
            self.timer_file,
            self.logger_file,
            ", ".join([s.name for s in self.subjects])
        )

    def start_timer(self):
        if self.start_time is None:
            self.start_time = datetime.datetime.now()
            # Write the time to a temp file as a backup
            with open("/tmp/timetracker.tmp", "w") as tmpfile:
                tmpfile.write(self.start_time.isoformat())
            return redirect(url_for("index"))
        else:
            flash("You've already started the timer.")

    def stop_timer(self):
        if self.start_time is not None:
            times = [
                self.start_time.isoformat(),
                datetime.datetime.now().isoformat()
            ]
            with open(self.timer_file, "a") as tfile:
                csvwriter = csv.writer(tfile)
                csvwriter.writerow(times)
            return redirect(url_for("index"))
        else:
            if os.path.exists("/tmp/timetracker.tmp"):
                pass
            else:
                flash("You haven't started the timer yet.")

    def log_subject(self, subject, minutes_worked):
        if self.start_time is None:
            flash("You haven't started the timer yet.")
        else:
            log_entry = [
                minutes_worked,
                datetime.datetime.now().isoformat(),
                subject
            ]
            with open(self.logger_file, "a") as lfile:
                csvwriter = csv.writer(lfile)
                csvwriter.writerow(log_entry)
            return redirect(url_for("index"))

@app.route("/")
def index():
    subjects = app.config.Tracker.subjects
    return render_template(
        "index.html",
        subjects=subjects
    )

@app.route("/start-timer", methods=["POST"])
def start_timer():
    flash("Timer started")
    return app.config.Tracker.start_timer()

@app.route("/stop-timer", methods=["POST"])
def stop_timer():
    flash("Timer stopped")
    return app.config.Tracker.stop_timer()

@app.route("/log-subject", methods=["POST"])
def log_subject():
    flash("%i minutes of %s logged" % (
        request.form["minutes-worked"],
        request.form["subject"])
    )
    return app.config.Tracker.log_subject(
        request.form["subject"],
        request.form["minutes-worked"]
    )

def main():
    rawcfg = open("timetracker.json", "r")
    cfg = json.load(rawcfg)
    app.config.Tracker = TimeTracker(
        cfg['subjects'],
        cfg['timer-file'],
        cfg['logger-file']
    )

main()
<commit_msg>Add secret key so flashing works<commit_after>import datetime
import json
import csv
import os
from flask import Flask, render_template, url_for, redirect, request, flash

app = Flask(__name__)
app.config.update(dict(Tracker=None))

class TimeTracker(object):
    def __init__(self, subjects, timer_file, logger_file):
        self.subjects = subjects
        self.timer_file = timer_file
        self.logger_file = logger_file
        self.start_time = None

    def __str__(self):
        return "TimeTracker: timer_file: %s, logger_file: %s, subjects: %s" % (
            self.timer_file,
            self.logger_file,
            ", ".join([s.name for s in self.subjects])
        )

    def start_timer(self):
        if self.start_time is None:
            self.start_time = datetime.datetime.now()
            # Write the time to a temp file as a backup
            with open("/tmp/timetracker.tmp", "w") as tmpfile:
                tmpfile.write(self.start_time.isoformat())
            return redirect(url_for("index"))
        else:
            flash("You've already started the timer.")

    def stop_timer(self):
        if self.start_time is not None:
            times = [
                self.start_time.isoformat(),
                datetime.datetime.now().isoformat()
            ]
            with open(self.timer_file, "a") as tfile:
                csvwriter = csv.writer(tfile)
                csvwriter.writerow(times)
            return redirect(url_for("index"))
        else:
            if os.path.exists("/tmp/timetracker.tmp"):
                pass
            else:
                flash("You haven't started the timer yet.")

    def log_subject(self, subject, minutes_worked):
        if self.start_time is None:
            flash("You haven't started the timer yet.")
        else:
            log_entry = [
                minutes_worked,
                datetime.datetime.now().isoformat(),
                subject
            ]
            with open(self.logger_file, "a") as lfile:
                csvwriter = csv.writer(lfile)
                csvwriter.writerow(log_entry)
            return redirect(url_for("index"))

@app.route("/")
def index():
    subjects = app.config.Tracker.subjects
    return render_template(
        "index.html",
        subjects=subjects
    )

@app.route("/start-timer", methods=["POST"])
def start_timer():
    flash("Timer started")
    return app.config.Tracker.start_timer()

@app.route("/stop-timer", methods=["POST"])
def stop_timer():
    flash("Timer stopped")
    return app.config.Tracker.stop_timer()

@app.route("/log-subject", methods=["POST"])
def log_subject():
    flash("%i minutes of %s logged" % (
        request.form["minutes-worked"],
        request.form["subject"])
    )
    return app.config.Tracker.log_subject(
        request.form["subject"],
        request.form["minutes-worked"]
    )

def main():
    rawcfg = open("timetracker.json", "r")
    cfg = json.load(rawcfg)
    app.config.Tracker = TimeTracker(
        cfg['subjects'],
        cfg['timer-file'],
        cfg['logger-file']
    )
    with open("secret.key", "r") as sk:
        app.secret_key = sk.read()

main()
<|endoftext|>


<commit_before>"""
lolbot - by S Stewart
Under MIT License
Copyright (c) S Stewart 2017

I am looking for developers.
Make a PR if you can help.

Hall of fame:
- Discord API - #python_discord-py
- Discord Bots - #development
and lastly, the Discord.py docs.
I wouldn't be here without them.
"""
# -*- coding: utf-8 -*-
import logging
logging.basicConfig(format='[%(levelname)s] - %(message)s', level=logging.INFO)
from subprocess import check_output
import sys
try:
  import discord
  from discord.ext import commands
except ImportError:
  logging.warn('Module(s) could not be found/not installed')
  logging.warn('Installing automatically')
  check_output(['pip', 'install', '-r', 'requirements.txt'])
  sys.exit('Please relaunch lolbot')
else:
  logging.info('Found library, continuing')
import aiohttp
import json
import time
import datetime
from random import choice as rchoice
try:
  config = json.loads(open('config.json').read())
except FileNotFoundError:
  logging.debug('Can\'t open config to start bot..')
  sys.exit('Fatal error')
except IOError:
  logging.debug('Can\'t open config to start bot..')
  sys.exit('Fatal error')
description = '''beep boop :)'''
bot = commands.AutoShardedBot(command_prefix='^', description=description)
startepoch = int(time.time())

session = aiohttp.ClientSession()

@bot.command()
async def k(ctx):
  """k"""
  await ctx.send('k')

@bot.command()
async def fuck(ctx):
  """fuck"""
  await ctx.send('fuck')

@bot.command()
async def ping(ctx):
  """Ping? Pong."""
  em = discord.Embed(title='Pong!', description='I am currently alive.', colour=0x690E8)
  em.set_author(name='lolbot')
  await ctx.send(embed=em)

@bot.command()
async def about(ctx):
  """Information about lolbot."""
  em = discord.Embed(title='lolbot', description='Written by lold. (c) 2017 lold, all rights reserved. \nWant to support lolbot and other projects? Donate to my ko-fi (https://ko-fi.com/A753OUG) or PayPal.me (https://paypal.me/ynapw)', colour=0x690E8)
  em.set_author(name='lolbot, written by lold')
  await ctx.send(embed=em)

@bot.command(pass_context=True)
async def suggest( ctx, *, suggestion: str ):
  """Got suggestions?"""
  await ctx.send('Feedback has been forwarded on to the mailbox.')
  await ctx.send(config['sugchannel'], 'Suggestion submitted: `' + str(suggestion) + '`')

@bot.command()
async def cat(ctx):
  """Random cat images. Awww, so cute! Powered by random.cat"""
  async with session.get('https://random.cat/meow') as r:
    if r.status == 200:
      js = await r.json()
      em = discord.Embed(name='random.cat', colour=0x690E8)
      em.set_image(url=js['file'])
      await ctx.send(embed=em)

@bot.command()
async def echo(ctx, *, message: str):
  """Self-explanatory."""
  await ctx.send(message)

@bot.command()
async def httpcat(ctx, *, http_id: str):
  """http.cat images - ^httpcat <http code>"""
  httpcat_em = discord.Embed(name='http.cat', colour=0x690E8)
  httpcat_em.set_image(url='https://http.cat/' + http_id + '.jpg')
  await ctx.send(embed=httpcat_em)

@bot.command(hidden=True, name='eval')
@commands.is_owner()
async def evalboi(ctx, *, code: str):
  """Because everyone needs a good eval once in a while."""
  try:
    result = eval(code)
  except Exception as e:
    evalError = discord.Embed(title='Error', description='You made non-working '
    'code, congrats you fucker.\n**Error:**\n```' + e + ' ```', colour=0x690E8)
    await ctx.send(embed=evalError)
  else:
    evalDone = discord.Embed(title='Eval', description='Okay, I evaluated that '
    'for you.\n**Results:**\n```' + str(result) + '```', colour=0x690E8)
    await ctx.send(embed=evalDone)

@bot.command(hidden=True)
@commands.is_owner()
async def reboot(ctx):
  """Duh. Owner only"""
  rebootPend = discord.Embed(title='Rebooting', description='Rebooting...', colour=0x690E8)
  await ctx.send(embed=rebootPend)
  try:
    check_output(['sh', 'bot.sh'])
    logging.info('reboot requested')
    logging.info('hoping it goes well now')
  except:
    logging.error('pls tell lold to fix his code')
  else:
    await bot.logout()

@bot.command(hidden=True)
@commands.is_owner()
async def game(*, game: str):
  """Changes playing status"""
  await bot.change_presence(game=discord.Game(name=game + ' | ^help | v3.0'))

@bot.command()
async def shibe(ctx):
  """Random shibes, powered by shibe.online"""
  async with session.get('http://shibe.online/api/shibes?count=1&urls=true&httpsUrls=true') as shibeGet:
      if shibeGet.status == 200:
        shibeJson = await shibeGet.json()
        shibeEmbed = discord.Embed(name='shibe.online', colour=0x690E8)
        shibeEmbed.set_image(url=shibeJson[0])
        await ctx.send(embed=shibeEmbed)

@bot.command()
async def uptime(ctx):
  """Shows uptime of lolbot"""
  upEm = discord.Embed(title='Uptime', colour=0x690E8)
  startedOn = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(startepoch))
  #timeUp = get_up()
  upEm.add_field(name='Started on', value=startedOn)
  #upEm.add_field(name='Uptime', value=timeUp)
  try:
    await ctx.send(embed=upEm)
  except:
    await ctx.send('Could not send due to a error. Tell lold to fix it pls')

@bot.command()
async def stats(ctx):
  """A few stats."""
  # get_owner = bot.get_user_info(config['ownerid'])
  statInfo = await ctx.bot.application_info()
  statEmbed = discord.Embed(title='lolbot stats', description='This bot is'
  'powered by [lolbot](https://github.com/xshotD/lolbot),'
  ' a fast and powerful Python bot.', colour=0x690E8)
  statEmbed.add_field(name='Owner', value=statInfo.owner.mention)
  statEmbed.add_field(name='Python', value=sys.version)
  statEmbed.add_field(name='Servers', value=len(bot.guilds))
  statPool = ['What have you done now?', 'Why should I do this again?', 'Oh..',
  'Where did the RAM go?', 'grumble grumble', 'Please hold.', 'No, just, no.',
  'Have you tried rebooting?', 'memework makes the dreamwork!']
  statEmbed.set_footer(text=rchoice(statPool))
  try:
    await ctx.send(embed=statEmbed)
  except:
    await ctx.send('Sorry, I can\'t send the Embed.')
    await ctx.send('Maybe I don\'t have Embed Links permission?')
  else:
    pass

@bot.command(name='8ball')
async def an8ball(ctx, *, question: str):
  pool = ['It is certain', 'Outlook good', 'You may rely on it', 'Ask again later', 'Concentrate and ask again',
  'Reply hazy, try again', 'My reply is no', 'My sources say no']
  ans = rchoice(pool)
  emb = discord.Embed(title='The Magic 8-ball', description='**Question: ' +
   str(question) + '**\nAnswer: ' + str(ans), colour=0x690E8)
  await ctx.send(embed=emb)

@bot.event
async def on_guild_join( guild ):
  logging.info('Joined guild ' + str(guild.name) + 'ID: ' + str(guild.id))
  await botstats()

@bot.event
async def on_guild_remove( guild ):
  logging.info('Left ' + str(guild.name))
  await botstats()

# danny code frankenstein :P
async def botstats():
    payload = json.dumps({
      'server_count': len(bot.guilds)
    })

    headers = {
      'authorization': config['dbots'],
      'content-type': 'application/json'
    }
    dbl_headers = {
      'authorization': config['dbl'],
      'content-type': 'application/json'
    }

    dbots_url = 'https://bots.discord.pw/api/bots/' + config['botid'] + '/stats'
    dbl_url = 'https://discordbots.org/api/bots/' + config['botid'] + '/stats'
    async with session.post(dbl_url, data=payload, headers=dbl_headers) as dbl_resp:
      logging.info('dbl: posted with code' + str(dbl_resp.status))
    async with session.post(dbots_url, data=payload, headers=headers) as resp:
      logging.info('dbots: posted with code' + str(resp.status))

"""Stolen from Red which was stolen from R. Danny
Currently not working so commented out
def get_up(self, *, brief=False):
  now = datetime.datetime.utcnow()
  delta = now - self.bot.uptime
  hours, remainder = divmod(int(delta.total_seconds()), 3600)
  minutes, seconds = divmod(remainder, 60)
  days, hours = divmod(hours, 24)

  if not brief:
    if days:
      fmt = '{d} days, {h} hours, {m} minutes, and {s} seconds'
    else:
      fmt = '{h} hours, {m} minutes, and {s} seconds'
    else:
      fmt = '{h}h {m}m {s}s'
    if days:
      fmt = '{d}d ' + fmt

  return fmt.format(d=days, h=hours, m=minutes, s=seconds)
"""
@bot.event
async def on_ready():
  logging.info('lolbot - ready')
  await bot.change_presence(game=discord.Game(name='with APIs. | ^help | v3.0'))
  logging.info('Playing status changed')

bot.run(config['token'])

<commit_msg>[uptime] rework uptime logic - use integers/time.time<commit_after>"""
lolbot - by S Stewart
Under MIT License
Copyright (c) S Stewart 2017

I am looking for developers.
Make a PR if you can help.

Hall of fame:
- Discord API - #python_discord-py
- Discord Bots - #development
and lastly, the Discord.py docs.
I wouldn't be here without them.
"""
# -*- coding: utf-8 -*-
import logging
logging.basicConfig(format='[%(levelname)s] - %(message)s', level=logging.INFO)
from subprocess import check_output
import sys
try:
  import discord
  from discord.ext import commands
except ImportError:
  logging.warn('Module(s) could not be found/not installed')
  logging.warn('Installing automatically')
  check_output(['pip', 'install', '-r', 'requirements.txt'])
  sys.exit('Please relaunch lolbot')
else:
  logging.info('Found library, continuing')
import aiohttp
import json
import time
import datetime
from random import choice as rchoice
try:
  config = json.loads(open('config.json').read())
except FileNotFoundError:
  logging.debug('Can\'t open config to start bot..')
  sys.exit('Fatal error')
except IOError:
  logging.debug('Can\'t open config to start bot..')
  sys.exit('Fatal error')
description = '''beep boop :)'''
bot = commands.AutoShardedBot(command_prefix='^', description=description)
startepoch = int(time.time())

session = aiohttp.ClientSession()

@bot.command()
async def k(ctx):
  """k"""
  await ctx.send('k')

@bot.command()
async def fuck(ctx):
  """fuck"""
  await ctx.send('fuck')

@bot.command()
async def ping(ctx):
  """Ping? Pong."""
  em = discord.Embed(title='Pong!', description='I am currently alive.', colour=0x690E8)
  em.set_author(name='lolbot')
  await ctx.send(embed=em)

@bot.command()
async def about(ctx):
  """Information about lolbot."""
  em = discord.Embed(title='lolbot', description='Written by lold. (c) 2017 lold, all rights reserved. \nWant to support lolbot and other projects? Donate to my ko-fi (https://ko-fi.com/A753OUG) or PayPal.me (https://paypal.me/ynapw)', colour=0x690E8)
  em.set_author(name='lolbot, written by lold')
  await ctx.send(embed=em)

@bot.command(pass_context=True)
async def suggest( ctx, *, suggestion: str ):
  """Got suggestions?"""
  await ctx.send('Feedback has been forwarded on to the mailbox.')
  await ctx.send(config['sugchannel'], 'Suggestion submitted: `' + str(suggestion) + '`')

@bot.command()
async def cat(ctx):
  """Random cat images. Awww, so cute! Powered by random.cat"""
  async with session.get('https://random.cat/meow') as r:
    if r.status == 200:
      js = await r.json()
      em = discord.Embed(name='random.cat', colour=0x690E8)
      em.set_image(url=js['file'])
      await ctx.send(embed=em)

@bot.command()
async def echo(ctx, *, message: str):
  """Self-explanatory."""
  await ctx.send(message)

@bot.command()
async def httpcat(ctx, *, http_id: str):
  """http.cat images - ^httpcat <http code>"""
  httpcat_em = discord.Embed(name='http.cat', colour=0x690E8)
  httpcat_em.set_image(url='https://http.cat/' + http_id + '.jpg')
  await ctx.send(embed=httpcat_em)

@bot.command(hidden=True, name='eval')
@commands.is_owner()
async def evalboi(ctx, *, code: str):
  """Because everyone needs a good eval once in a while."""
  try:
    result = eval(code)
  except Exception as e:
    evalError = discord.Embed(title='Error', description='You made non-working '
    'code, congrats you fucker.\n**Error:**\n```' + e + ' ```', colour=0x690E8)
    await ctx.send(embed=evalError)
  else:
    evalDone = discord.Embed(title='Eval', description='Okay, I evaluated that '
    'for you.\n**Results:**\n```' + str(result) + '```', colour=0x690E8)
    await ctx.send(embed=evalDone)

@bot.command(hidden=True)
@commands.is_owner()
async def reboot(ctx):
  """Duh. Owner only"""
  rebootPend = discord.Embed(title='Rebooting', description='Rebooting...', colour=0x690E8)
  await ctx.send(embed=rebootPend)
  try:
    check_output(['sh', 'bot.sh'])
    logging.info('reboot requested')
    logging.info('hoping it goes well now')
  except:
    logging.error('pls tell lold to fix his code')
  else:
    await bot.logout()

@bot.command(hidden=True)
@commands.is_owner()
async def game(*, game: str):
  """Changes playing status"""
  await bot.change_presence(game=discord.Game(name=game + ' | ^help | v3.0'))

@bot.command()
async def shibe(ctx):
  """Random shibes, powered by shibe.online"""
  async with session.get('http://shibe.online/api/shibes?count=1&urls=true&httpsUrls=true') as shibeGet:
      if shibeGet.status == 200:
        shibeJson = await shibeGet.json()
        shibeEmbed = discord.Embed(name='shibe.online', colour=0x690E8)
        shibeEmbed.set_image(url=shibeJson[0])
        await ctx.send(embed=shibeEmbed)

@bot.command()
async def uptime(ctx):
  """Shows uptime of lolbot"""
  upEm = discord.Embed(title='Uptime', colour=0x690E8)
  startedOn = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(startepoch))
  #timeUp = get_up()
  upEpoch = int(time.time) - startepoch
  upEm.add_field(name='Started on', value=startedOn)
  upEm.add_field(name='Uptime', time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime(upEpoch)))
  try:
    await ctx.send(embed=upEm)
  except Exception as ex:
    await ctx.send('**ERROR** Please report this to lold#6978\n```' + ex + '\n```')

@bot.command()
async def stats(ctx):
  """A few stats."""
  # get_owner = bot.get_user_info(config['ownerid'])
  statInfo = await ctx.bot.application_info()
  statEmbed = discord.Embed(title='lolbot stats', description='This bot is'
   'powered by [lolbot](https://github.com/xshotD/lolbot),'
  ' a fast and powerful Python bot.', colour=0x690E8)
  statEmbed.add_field(name='Owner', value=statInfo.owner.mention)
  statEmbed.add_field(name='Python', value=sys.version)
  statEmbed.add_field(name='Servers', value=len(bot.guilds))
  statPool = ['What have you done now?', 'Why should I do this again?', 'Oh..',
  'Where did the RAM go?', 'grumble grumble', 'Please hold.', 'No, just, no.',
  'Have you tried rebooting?', 'memework makes the dreamwork!']
  statEmbed.set_footer(text=rchoice(statPool))
  try:
    await ctx.send(embed=statEmbed)
  except:
    await ctx.send('Sorry, I can\'t send the Embed.')
    await ctx.send('Maybe I don\'t have Embed Links permission?')
  else:
    pass

@bot.command(name='8ball')
async def an8ball(ctx, *, question: str):
  pool = ['It is certain', 'Outlook good', 'You may rely on it', 'Ask again later', 'Concentrate and ask again',
  'Reply hazy, try again', 'My reply is no', 'My sources say no']
  ans = rchoice(pool)
  emb = discord.Embed(title='The Magic 8-ball', description='**Question: ' +
   str(question) + '**\nAnswer: ' + str(ans), colour=0x690E8)
  await ctx.send(embed=emb)

@bot.event
async def on_guild_join( guild ):
  logging.info('Joined guild ' + str(guild.name) + 'ID: ' + str(guild.id))
  await botstats()

@bot.event
async def on_guild_remove( guild ):
  logging.info('Left ' + str(guild.name))
  await botstats()

# danny code frankenstein :P
async def botstats():
    payload = json.dumps({
      'server_count': len(bot.guilds)
    })

    headers = {
      'authorization': config['dbots'],
      'content-type': 'application/json'
    }
    dbl_headers = {
      'authorization': config['dbl'],
      'content-type': 'application/json'
    }

    dbots_url = 'https://bots.discord.pw/api/bots/' + config['botid'] + '/stats'
    dbl_url = 'https://discordbots.org/api/bots/' + config['botid'] + '/stats'
    async with session.post(dbl_url, data=payload, headers=dbl_headers) as dbl_resp:
      logging.info('dbl: posted with code' + str(dbl_resp.status))
    async with session.post(dbots_url, data=payload, headers=headers) as resp:
      logging.info('dbots: posted with code' + str(resp.status))

"""Stolen from Red which was stolen from R. Danny
Currently not working so commented out
def get_up(self, *, brief=False):
  now = datetime.datetime.utcnow()
  delta = now - self.bot.uptime
  hours, remainder = divmod(int(delta.total_seconds()), 3600)
  minutes, seconds = divmod(remainder, 60)
  days, hours = divmod(hours, 24)

  if not brief:
    if days:
      fmt = '{d} days, {h} hours, {m} minutes, and {s} seconds'
    else:
      fmt = '{h} hours, {m} minutes, and {s} seconds'
    else:
      fmt = '{h}h {m}m {s}s'
    if days:
      fmt = '{d}d ' + fmt

  return fmt.format(d=days, h=hours, m=minutes, s=seconds)
"""
@bot.event
async def on_ready():
  logging.info('lolbot - ready')
  await bot.change_presence(game=discord.Game(name='with APIs. | ^help | v3.0'))
  logging.info('Playing status changed')

bot.run(config['token'])

<|endoftext|>


<commit_before># the lolbot core
# (c) 2017 S Stewart under MIT License

# -*- coding: utf-8 -*-

# built in modules go first.
import json
import logging
import random
import sys
import time
import traceback
logging.basicConfig(format='[%(levelname)s] - %(message)s', level=logging.INFO)

# import the rest

import aiohttp
import discord
from discord.ext import commands

# Make datadog also a optional dep
try:
    from datadog import statsd
except ImportError:
    logging.warning('datadog: datadog not installed')
    logging.warning('datadog: disabled data sending')
    datadogImported = False
else:
    logging.info('datadog: enabled data sending')
    datadogImported = True

description = '''Just a bot :)'''
exts = ['bots', 'donate', 'eval', 'fun', 'nekos', 'owner', 'stats', 'utility']

class Lul(commands.AutoShardedBot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.config = json.load(open('config.json'))
        self.session = aiohttp.ClientSession()
        if self.config['debug']:
            if self.config['channel'] == "":
                logging.error('debug: you need a channel for debug mode! are you dumb?')
                sys.exit(1)
            else:
                self.debugOK = True
        else:
            self.debugOK = False
        self.checkfail = ['heck off', 'You died! [REAL] [Not clickbait]',  'succ my rod', 'no u',
        'lol no', 'me too thanks', 'are you kidding me', 'kek']
        self.badarg = ['You need to put more info than this!', 'I didn\'t understan'
        'd that.', 'Sorry, can\'t process that.',
        'Read ' + self.config['prefix'] + 'help <command> for instructions.', 'Hmm?']
        # To be fair, we should record the init time after everything is ready
        self.init_time = time.time()

    async def on_ready(self):
        logging.info('lolbot - ready')
        # note that we use " instead of ' here
        # this is a limitation of the fstring parser
        await bot.change_presence(game=discord.Game(name=f'{self.config["prefix"]}help | v6.2', type=1, url='https://twitch.tv/monstercat'))
        logging.info('Playing status changed')

    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.errors.CheckFailure):
            await ctx.send(f'Permissions error: {random.choice(self.checkfail)}')
        elif isinstance(error, commands.errors.BadArgument):
            await ctx.send(f'Bad argument error: {random.choice(self.badarg)}')
        elif isinstance(error, commands.errors.MissingRequiredArgument):
            await ctx.send(f'Missing argument: {random.choice(self.badarg)}')
        elif isinstance(error, commands.errors.CommandInvokeError):
            if self.debugOK == True:
                # thanks jose
                tb = ''.join(traceback.format_exception(
                    type(error.original), error.original,
                    error.original.__traceback__
                ))
                await ctx.send('A error occured, sorry... This issue has been reported.')
                await self.get_channel(self.config['channel']).send(f'Something happened - Logs: ```\n{tb}\n```')
            else:
                logging.error('A error occured.', exc_info=True)
                await ctx.send('A error occured, sorry...')
config = json.load(open('config.json'))
bot = Lul(command_prefix=config['prefix'], description=description)

if __name__ == '__main__':
    for ext in exts:
        try:
            bot.load_extension(f'cogs.{ext}')
        except Exception:
            logging.error(f'Error while loading {ext}', exc_info=True)
        else:
            logging.info(f'Successfully loaded {ext}')

bot.run(config['token'])
<commit_msg>core[stats]: moving stats to other file<commit_after># the lolbot core
# (c) 2017 S Stewart under MIT License

# -*- coding: utf-8 -*-

# built in modules go first.
import json
import logging
import random
import sys
import time
import traceback
logging.basicConfig(format='[%(levelname)s] - %(message)s', level=logging.INFO)

# import the rest

import aiohttp
import discord
from discord.ext import commands

description = '''Just a bot :)'''
exts = ['bots', 'donate', 'eval', 'fun', 'nekos', 'owner', 'stats', 'utility']

class Lul(commands.AutoShardedBot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.config = json.load(open('config.json'))
        self.session = aiohttp.ClientSession()
        if self.config['debug']:
            if self.config['channel'] == "":
                logging.error('debug: you need a channel for debug mode! are you dumb?')
                sys.exit(1)
            else:
                self.debugOK = True
        else:
            self.debugOK = False
        self.checkfail = ['heck off', 'You died! [REAL] [Not clickbait]',  'succ my rod', 'no u',
        'lol no', 'me too thanks', 'are you kidding me', 'kek']
        self.badarg = ['You need to put more info than this!', 'I didn\'t understan'
        'd that.', 'Sorry, can\'t process that.',
        'Read ' + self.config['prefix'] + 'help <command> for instructions.', 'Hmm?']
        # To be fair, we should record the init time after everything is ready
        self.init_time = time.time()

    async def on_ready(self):
        logging.info('lolbot - ready')
        # note that we use " instead of ' here
        # this is a limitation of the fstring parser
        await bot.change_presence(game=discord.Game(name=f'{self.config["prefix"]}help | v6.2', type=1, url='https://twitch.tv/monstercat'))
        logging.info('Playing status changed')

    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.errors.CheckFailure):
            await ctx.send(f'Permissions error: {random.choice(self.checkfail)}')
        elif isinstance(error, commands.errors.BadArgument):
            await ctx.send(f'Bad argument error: {random.choice(self.badarg)}')
        elif isinstance(error, commands.errors.MissingRequiredArgument):
            await ctx.send(f'Missing argument: {random.choice(self.badarg)}')
        elif isinstance(error, commands.errors.CommandInvokeError):
            if self.debugOK == True:
                # thanks jose
                tb = ''.join(traceback.format_exception(
                    type(error.original), error.original,
                    error.original.__traceback__
                ))
                await ctx.send('A error occured, sorry... This issue has been reported.')
                await self.get_channel(self.config['channel']).send(f'Something happened - Logs: ```\n{tb}\n```')
            else:
                logging.error('A error occured.', exc_info=True)
                await ctx.send('A error occured, sorry...')
config = json.load(open('config.json'))
bot = Lul(command_prefix=config['prefix'], description=description)

if __name__ == '__main__':
    for ext in exts:
        try:
            bot.load_extension(f'cogs.{ext}')
        except Exception:
            logging.error(f'Error while loading {ext}', exc_info=True)
        else:
            logging.info(f'Successfully loaded {ext}')

bot.run(config['token'])
<|endoftext|>


<commit_before>from gevent import monkey
monkey.patch_all()

import time
from threading import Thread
import settings
import requests
from flask import Flask
from flask.ext.socketio import SocketIO, emit

app = Flask(__name__)
app.debug = True

if not app.debug:
    import logging
    file_handler = logging.FileHandler('production.log')
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

socketio = SocketIO(app)
thread = None

class StorjAPI:
	@staticmethod
	def getNodeStatus():
		r = requests.get(app.config['NODE_URL'] + '/api/status')
		return r.json()

def status_thread():
    while True:
        time.sleep(10)
        socketio.emit('status', StorjAPI.getNodeStatus(), namespace='/metadisk')

@socketio.on('status')
def node_status():
	socketio.emit('status', StorjAPI.getNodeStatus())

@socketio.on('connect', namespace='/metadisk')
def metadisk_connect():
	global thread
	if thread is None:
		thread = Thread(target=status_thread)
		thread.start()
	print('Client has connected.')

@socketio.on('disconnect', namespace='/metadisk')
def metadisk_disconnect():
    print('Client has disconnected.')

if __name__ == '__main__':
	socketio.run(app)<commit_msg>Correctly load settings into flask config<commit_after>from gevent import monkey
monkey.patch_all()

import time
from threading import Thread
import settings
import requests
from flask import Flask
from flask.ext.socketio import SocketIO, emit

app = Flask(__name__)
app.config.from_object('settings')
app.debug = True

if not app.debug:
    import logging
    file_handler = logging.FileHandler('production.log')
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

socketio = SocketIO(app)
thread = None

class StorjAPI:
	@staticmethod
	def getNodeStatus():
		r = requests.get(app.config['NODE_URL'] + '/api/status')
		return r.json()

def status_thread():
    while True:
        time.sleep(10)
        socketio.emit('status', StorjAPI.getNodeStatus(), namespace='/metadisk')

@socketio.on('status')
def node_status():
	socketio.emit('status', StorjAPI.getNodeStatus())

@socketio.on('connect', namespace='/metadisk')
def metadisk_connect():
	global thread
	if thread is None:
		thread = Thread(target=status_thread)
		thread.start()
	print('Client has connected.')

@socketio.on('disconnect', namespace='/metadisk')
def metadisk_disconnect():
    print('Client has disconnected.')

if __name__ == '__main__':
	socketio.run(app)<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, io
import sys, getopt
import random

from openpyxl import load_workbook

# input: words list
# output
#   1. random matrix view with colume and row parameter
#
#

def MatrixFromXLS(filepath):
    print filepath
    wb = load_workbook(filename=filepath, read_only=True, data_only=True)
    worksheets = wb.get_sheet_names()
    print worksheets
    words = {}
    for sheetname in worksheets:
        ws = wb[sheetname]
        words[sheetname] = []
        for row in ws.rows:
            if row[1].value == None:
                if row[0].value != None:
                    words[sheetname].append('%-16s' % row[0].value)
            else:
                if isinstance(row[1].value,float):
                    words[sheetname].append('%-16s' % str(row[0].value))
                else:
                    words[sheetname].append('%-16s' % row[1].value)

    return words

def MatrixFromRawTxt(inputfile):
    content = []
    with open(inputfile) as f:
        for line in f.readlines():
            word = line.strip().rstrip('\n')
            if  word != '':
                content.append(word)

    random.shuffle(content)
    print {'allinone':content}

def CreateMatrixFile(content, outputfile, columns):
    with io.open(outputfile, 'w', encoding='utf8') as of:
        for key in content:
            k = 1
            wordline = ''
            of.writelines(u'\n')
            of.writelines(key.decode('ascii'))
            of.writelines(u'\n')
            for word in content[key]:

                if k % columns == 0:
                    wordline += word.strip()
                    wordline +=u'\n'
                    of.writelines(wordline)
                    wordline = ''
                else:
                    wordline += word

                k+=1
            if wordline != '':
                print wordline

if __name__ == '__main__':

    inputfile = ''
    outputfile = ''
    columns = 5
    try:
        opts, args = getopt.getopt(sys.argv[1:],"hi:o:c:",["ifile=","ofile=","columns="])
    except getopt.GetoptError:
        print 'test.py -i <inputfile> -o <outputfile>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'test.py -i <inputfile> -o <outputfile>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
        elif opt in ("-c", "--columns"):
            columns = int(arg)
    print 'Input file is "', inputfile
    print 'Output file is "', outputfile

    dat = MatrixFromXLS(inputfile)
    #MatrixFromRawTxt(inputfile,outputfile,columns)
    CreateMatrixFile(dat,outputfile,columns)

   <commit_msg>durone<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, io
import sys, getopt
import random

from openpyxl import load_workbook

# input: words list
# output
#   1. random matrix view with colume and row parameter
#
#

def MatrixFromXLS(filepath, sel_sheet):
    print filepath
    wb = load_workbook(filename=filepath, read_only=True, data_only=True)
    worksheets = wb.get_sheet_names()
    print worksheets
    words = {}

    for sheetname in worksheets:
        if sel_sheet is not None and sheetname != sel_sheet:
            continue
        ws = wb[sheetname]
        words[sheetname] = []
        for row in ws.rows:
            if row[1].value == None:
                if row[0].value != None:
                    words[sheetname].append('%-16s' % row[0].value)
            else:
                if isinstance(row[1].value,float):
                    words[sheetname].append('%-16s' % str(row[0].value))
                else:
                    words[sheetname].append('%-16s' % row[1].value)

    return words

def MatrixFromRawTxt(inputfile):
    content = []
    with open(inputfile) as f:
        for line in f.readlines():
            word = line.strip().rstrip('\n')
            if  word != '':
                content.append(word)

    random.shuffle(content)
    print {'allinone':content}

def CreateMatrixFile(content, outputfile, columns):
    with io.open(outputfile, 'w', encoding='utf8') as of:
        for key in content:
            k = 1
            wordline = ''
            of.writelines(u'\n')
            of.writelines(key.decode('ascii'))
            of.writelines(u'\n')
            for word in content[key]:

                if k % columns == 0:
                    wordline += word.strip()
                    wordline +=u'\n'
                    of.writelines(wordline)
                    wordline = ''
                else:
                    wordline += word

                k+=1
            if wordline != '':
                print wordline

if __name__ == '__main__':

    inputfile = ''
    outputfile = ''
    columns = 5
    sheetname = None
    try:
        opts, args = getopt.getopt(sys.argv[1:],"hi:o:c:s:",["ifile=","ofile=","columns=","sheet="])
    except getopt.GetoptError:
        print 'test.py -i <inputfile> -o <outputfile>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'test.py -i <inputfile> -s <xls sheet name> -o <outputfile> -c <numbers>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
        elif opt in ("-c", "--columns"):
            columns = int(arg)
        elif opt in ("-s","--sheet"):
            sheetname = arg

    print 'Input file is "', inputfile
    print 'Output file is "', outputfile

    dat = MatrixFromXLS(inputfile, sheetname)
    #MatrixFromRawTxt(inputfile,outputfile,columns)
    CreateMatrixFile(dat,outputfile,columns)

   <|endoftext|>