Example #1
0
class Manager(object):
    def __init__(self, config_file, no_olad):
        self.no_olad = no_olad
        if not self.no_olad:
            self.wrapper = ClientWrapper()
        else:
            self.wrapper = None
        self._config = Config(config_file, self)
        self.fixture_types = self._config.load_fixture_types()
        self.constants = self._config.load_constants()
        self.fixtures = self._config.load_fixtures()
        self.scenes = self._config.load_scenes()
        self.set_scene(self.scenes[self._config.load_default_scene()])
        self.win = MyWindow(self)

    def set_scene(self, scene, reset=True):
        self.current_scene = scene
        if reset:
            self.current_scene.reset()
        if hasattr(self, 'win'):
            source = self.win.builder.get_object('source')
            model = source.get_model()
            for i, item in enumerate(model):
                if item[0] == self.current_scene.name:
                    source.set_active(i)

    def run(self):
        rdata = array.array('B')
        for i in range(0, 512):
            rdata.append(0)

        # Use the scene to set the fixtures values
        for fixture, values in self.current_scene.fixtures.iteritems():
            for chan, value in values.iteritems():
                # chan_value = self.fixtures[fixture.name].chans[chan]
                self.fixtures[fixture.name].values[chan] = cap(value)
                if not self.fixtures[fixture.name].override.get(chan, None):
                    self.fixtures[fixture.name].sliders[chan].set_value(value)

        for fixture_name, fixture in self.fixtures.iteritems():
            # print fixture.values
            for chan, value in fixture.values.iteritems():
                if self.fixtures[fixture.name].override.get(chan, None):
                    value = int(self.fixtures[fixture.name].sliders[chan].get_value())
                chan_value = self.fixtures[fixture.name].chans[chan]
                rdata[fixture.start_address + chan_value - 2] = value
        if not self.no_olad:
            try:
                self.wrapper.Client().SendDmx(1, rdata, DmxSent)
            except:
                st = time.time()
                self.wrapper.Stop()
                self.wrapper = ClientWrapper()
                print "We had to reset"
                print time.time() - st
        GObject.timeout_add(10, self.run)
Example #2
0
 def __init__(self,conf,filename,source):
     self.conf = conf
     self.filename = filename
     self.source = source
     
     configs = Config.getConfig()
     self.batchSize = configs['sys']['db.batch.size']
Example #3
0
 def execute(self):
     configs = Config.getConfig()
     self.logger.info("Ready to parser url !")
     
     urlTemples = []
     
     for key in configs['game.alawar'].keys():
         if key.startswith('url'):
             attr = key.split(".")
             table = attr[1]
             locale = attr[2]
             urlTemple = configs['game.alawar'][key]
             urlTemples.append([urlTemple,table,locale])
     
     for urlTemple in urlTemples:
         if self.table is not None and urlTemple[1] != self.table:
             continue
         
         cf = configs['game.alawar']
         urls = StaticUtil.convertUrl(urlTemple, cf)
         self.logger.info("Parser xml convert count[%d]!" % len(urls));
         for conf in urls:
             filepath = os.path.join(StaticUtil.mkdir(configs['game.alawar']['data_path'], conf),
                                     StaticUtil.getTimeStrForFold() + "alawar.xml")
             #filepath = Config.configs['game.alawar']['data_path'] +StaticUtil.getPara(conf)+ StaticUtil.getTimeStrForFold() + "alawar.xml"
             download = DownloadHandler(conf, filepath, GcpConstant.Source.Alawar)
             TaskRun.getInstance().submit(download)
             
             self.logger.info("Parser xml[%s] name , url[%s] end !"%(filepath,conf));
Example #4
0
 def __init__(self,conf,filename,source):
     self.conf = conf
     self.filename = filename
     self.source = source
     
     configs = Config.getConfig()
     self.batchSize = configs['sys']['db.batch.size']
     self.sitePrix = configs['game.bigfish']['dtd'][1]
     self.assets =  configs['game.bigfish']['dtd'][2]
Example #5
0
 def __init__(self):  
     self.cursor = None
     configs = Config.getConfig()
     self.host = configs['db']['db_host']
     self.user = configs['db']['db_user']
     self.pwd = configs['db']['db_pass']
     self.db = configs['db']['db_db']
     self.conn = None
     try:
         self.conn = MySQLdb.Connect(host=self.host, user=self.user, passwd=self.pwd, db=self.db, charset="utf8", use_unicode="True") 
     except MySQLdb.Error, e:
         print e
         print "can't connect database error num %d the desc is %s" % (e[0], e[1])
Example #6
0
 def __init__(self, config_file, no_olad):
     self.no_olad = no_olad
     if not self.no_olad:
         self.wrapper = ClientWrapper()
     else:
         self.wrapper = None
     self._config = Config(config_file, self)
     self.fixture_types = self._config.load_fixture_types()
     self.constants = self._config.load_constants()
     self.fixtures = self._config.load_fixtures()
     self.scenes = self._config.load_scenes()
     self.set_scene(self.scenes[self._config.load_default_scene()])
     self.win = MyWindow(self)
Example #7
0
    def execute(self):
        
        StaticUtil.remove(self.filename)
        
        configs = Config.getConfig()
        dowLoadNum = configs['sys']['download.num']
        
        DownloadHandler.Threads_lock.acquire()
        try:
            #self.logger.info("Download Num is %d , MaxNum is %d ."%(DownloadHandler.dowNum,dowLoadNum));
                
            if DownloadHandler.dowNum >= dowLoadNum:
                TaskRun.getInstance().submit(self)
                #self.logger.info("Now file[%s] download go back ."%self.filename);
                return
            DownloadHandler.dowNum += 1
        finally:
            DownloadHandler.Threads_lock.release()

        try:
            
            self.logger.info("Download file[%s] start , %s !"%(self.filename,self.source))
            download = Download(self.url, self.filename)
            download.executeDown();
            
            if self.source == GcpConstant.Source.Bigfish:
                parse = lib.gcp.handler.bigfish.FeatureParserHandler.FeatureParserHandler(self.filename, self.source,self.conf);
                TaskRun.getInstance().submit(parse)
            elif  self.source == GcpConstant.Source.Alawar:
                parse = lib.gcp.handler.alawar.FeatureParserHandler.FeatureParserHandler(self.filename, self.source,self.conf);
                TaskRun.getInstance().submit(parse)
            
        except Exception , e:
            self.logger.error("Download file[%s] error !"%self.filename)
            
            #re load
            self.logger.info("Reload filename[%s] cfg[%s]",(self.filename,self.conf))
            download = DownloadHandler(self.conf, self.filename, self.source)
            TaskRun.getInstance().submit(download)
            
            self.logger.exception(e)
Example #8
0
 def test_Parse(self):
     # Test input data of None.
     target = Config._Parse(None)
     self.assertEquals(len(target), 0, 'Input data of None is not working.')
     
     # Test input data of empty string.
     target = Config._Parse('')
     self.assertEquals(len(target), 0, 'Input data of empty string is not working.')
     
     # Test basic key-value pair.
     target = Config._Parse('left=right')
     self.assertEquals(len(target), 1, 'Basic key-value pair is not being read properly. Expected 1 result.')
     self.assertEquals(target['left'], 'right', 
         'Basic key-value pair is not being read properly. Expected "left" = "right".')
     
     # Test key and value whitespace trimming.
     target = Config._Parse(' le ft  =\tright  \t ')
     self.assertEquals(len(target), 1, 'Key-value pair whitespace trimming is not working. Expected 1 result.')
     self.assertEquals(target['le ft'], 'right', 
         'Key-value pair whitespace trimming is not working. Expected "le ft" = "right".')
 
     # Test multiple key-value pairs.
     target = Config._Parse('first=value1\nsecond=value2')
     self.assertEquals(len(target), 2, 'Multiple key-value pairs are not working. Expected 2 results.')
     self.assertEquals(target['first'], 'value1', 
         'Multiple key-value pairs are not working. Expected "first" = "value1".')
     self.assertEquals(target['second'], 'value2', 
         'Multiple key-value pairs are not working. Expected "second" = "value2".')
     
     # Test that empty lines are ignored.
     target = Config._Parse('\n\na=1\n\n\nb=2\n\n')
     self.assertEquals(len(target), 2, 'Empty lines are not being ignored. Expected 2 results.')
     self.assertEquals(target['a'], '1', 'Empty lines are not being ignored. Expected a = 1.')
     self.assertEquals(target['b'], '2', 'Empty lines are not being ignored. Expected b = 2.')
 
     # Test full line commenting.
     target = Config._Parse('#commented\na=2')
     self.assertEquals(len(target), 1, 'Full line comments not being ignored. Expected 1 result.')
     self.assertEquals(target['a'], '2', 'Full line comments not being ignored. Expected a = 2.')
Example #9
0
 async def fantasy_set_status(self, ctx, *status_message):
     """Sets the dsc status message or removes it if no message is given"""
     self.fantasy_conf()['status'] = " ".join(status_message)
     Config().save(self)
     await ctx.send(self.fantasy_lang('status_set'))
Example #10
0
    async def fantasy_set_host(self, ctx, user: discord.Member):
        """Sets the Fantasy Organisator"""

        self.fantasy_conf()['supercommish_id'] = user.id
        Config().save(self)
        await ctx.send(self.fantasy_lang('new_supercommish_set'))
Example #11
0
 async def fantasy_set_datalink(self, ctx, link):
     link = utils.clear_link(link)
     self.fantasy_conf()['datalink'] = link
     Config().save(self)
     await ctx.send(self.fantasy_lang('datalink_set'))
Example #12
0
async def write_admin_channel(bot: Bot, message):
    """Writes the given message or embed to the admin channel"""
    await _write_to_channel(bot, Config().ADMIN_CHAN_ID, message, "admin")
Example #13
0
    if files == 1:
        is_only_one_game = True
        current_proc = subprocess.Popen(emulator_command)
        current_proc.wait()
    else:
        is_only_one_game = False


if __name__ == "__main__":
    global current_proc
    global is_only_one_game
    current_proc = None
    reset_handler = GPIOButtonHandler(return_to_menu, 13)
    reset_handler.start()
    
    conf = Config()
    
    is_only_one_game = True
    while is_only_one_game:
        start_game_if_alone(conf)
    
    player = Player()
    screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN) #0,6671875 and 0,(6) of HD resoultion
    
    menu = Menu(conf, player)
    menu.set_dir(conf.get_conf_for_label('root')['dir'])
    menu.render(screen, full_update = True)
    
    pygame.joystick.init()
    joystick = pygame.joystick.Joystick(0)
    joystick.init()
Example #14
0
import os

from flask import Flask, request
import telebot
from telebot import types
import re
import matplotlib.pyplot as plt

import mth
from conf import Config
from ans import Answers
from mth import Math
from parse import parse_command
import _sqlite3

bot_token = Config.get_token()

bot = telebot.TeleBot(bot_token)

server = Flask(__name__)

hook_url = Config.get_url()


@bot.edited_message_handler(regexp=r"^\/tex .+")
def edited_convert_latex(message):
    convert_latex(message)


@bot.message_handler(commands=['start'])
def start_message(message):
Example #15
0
 async def cmd_guidelines(self, ctx):
     # await ctx.send("MAKE BETTER; <https://github.com/gobo7793/Geckarbot/wiki/Command-Guidelines>")
     await ctx.send("<{}>".format(Config.get(self)['guidelines']))
Example #16
0
__author__ = 'Elf'



import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado
import  os

from tornado.options import options, define

from api_virastar.url.main_url import url_pattern
from conf import Config

config = Config()

define("port", default=config.web['port'], help="run on the given port", type=int)


class WebSystemApplication(tornado.web.Application):
    def __init__(self):
        handlers = url_pattern
        settings = dict(
            debug=True,
            autoreload=True,
            template_path = os.path.join(os.path.dirname(__file__), "api_virastar/template"),
            static_path = os.path.join(os.path.dirname(__file__),"api_virastar/static")
        )
        tornado.web.Application.__init__(self, handlers, **settings)
Example #17
0
class Plugin(BasePlugin, name="Feedback"):
    def __init__(self, bot):
        super().__init__(bot)
        bot.register(self)

        self.storage = Storage.get(self)
        self.complaints = {}
        self.highest_id = None

        # Load complaints from storage
        if self.storage is None:
            self.storage = deepcopy(self.default_storage())
        else:
            print("Feedback storage: {}".format(self.storage))
            str_keys_to_int(self.storage["complaints"])
        for cid in self.storage["complaints"]:
            self.complaints[cid] = Complaint.deserialize(
                self.bot, cid, self.storage["complaints"][cid])

        # Migration 1.7 -> 1.8
        if "bugscore" not in self.storage:
            self.storage["bugscore"] = {}
            Storage.save(self)

        self.get_new_id(init=True)

    def default_storage(self):
        return {
            "complaints": {},
            "bugscore": {},
        }

    def get_new_id(self, init=False):
        """
        Acquires a new complaint id
        :param init: if True, only sets self.highest_id but does not return anything. Useful for plugin init.
        :return: free unique id that can be used for a new complaint
        """
        if self.highest_id is None:
            self.highest_id = 0
            for el in self.complaints:
                if el > self.highest_id:
                    self.highest_id = el
        if not init:
            self.highest_id += 1
            return self.highest_id

    def write(self):
        r = {}
        for el in self.complaints:
            complaint = self.complaints[el]
            r[complaint.id] = complaint.serialize()
        Storage.get(self)["complaints"] = r
        Storage.save(self)

    @commands.group(
        name="redact",
        invoke_without_command=True,
        help="Redacts the list of complaints (i.e. read and delete)",
        usage="[del x]",
        description=
        "Returns the accumulated feedback. Use [del x] to delete feedback #x.")
    @commands.has_any_role(Config().ADMIN_ROLE_ID, Config().BOTMASTER_ROLE_ID)
    async def redact(self, ctx):
        # Printing complaints
        if len(self.complaints) == 0:
            await ctx.send(Lang.lang(self, "redact_no_complaints"))
            return

        msgs = utils.paginate([el for el in self.complaints.values()],
                              prefix=Lang.lang(self, "redact_title"),
                              delimiter="\n\n",
                              msg_prefix="_ _\n",
                              f=to_msg)
        for el in msgs:
            await ctx.send(el)

    @redact.command(name="del", help="Deletes a complaint", usage="<#>")
    async def delete(self, ctx, complaint: int):
        # Delete
        try:
            del self.complaints[complaint]
        except KeyError:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, "redact_del_not_found", complaint))
            return
        # await ctx.send(lang['complaint_removed'].format(i))
        await ctx.message.add_reaction(Lang.CMDSUCCESS)
        self.write()

    @redact.command(name="search",
                    help="Finds all complaints that contain all search terms",
                    usage="<search terms>")
    async def search(self, ctx, *args):
        if len(args) == 0:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, "redact_search_args"))
            return

        r = []
        for i in self.complaints:
            complaint = self.complaints[i]
            found = True
            for searchterm in args:
                # Search check
                if searchterm.lower() not in complaint.to_message().lower():
                    found = False
                    break
            if not found:
                continue

            # Search result
            r.append(complaint)

        if not r:
            await ctx.send(Lang.lang(self, "redact_search_not_found"))
            return

        msgs = utils.paginate(r,
                              prefix=Lang.lang(self, "redact_search_title"),
                              delimiter="\n\n",
                              f=to_msg)
        for el in msgs:
            await ctx.send(el)

    @commands.command(
        name="complain",
        help="Takes a complaint and stores it",
        usage="<message>",
        description="Delivers a feedback message. "
        "The admins and botmasters can then read the accumulated feedback. "
        "The bot saves the feedback author, "
        "the message and a link to the message for context.")
    async def complain(self, ctx, *args):
        msg = ctx.message
        complaint = Complaint.from_message(self, msg)
        self.complaints[complaint.id] = complaint
        await ctx.message.add_reaction(Lang.CMDSUCCESS)
        # await msg.channel.send(lang["complaint_received"])
        self.write()

    """
    Bugscore
    """

    async def bugscore_show(self, ctx):
        users = sorted(sorted(
            [(utils.get_best_username(
                discord.utils.get(self.bot.guild.members, id=user)), n)
             for (user, n) in self.storage["bugscore"].items()],
            key=lambda x: x[0].lower()),
                       key=lambda x: x[1],
                       reverse=True)
        lines = ["{}: {}".format(user, p) for (user, p) in users]
        for msg in utils.paginate(lines,
                                  prefix="{}\n".format(
                                      Storage.lang(self, "bugscore_title"))):
            await ctx.send(msg)

    async def bugscore_del(self, ctx, user):
        if discord.utils.get(ctx.author.roles,
                             id=Config().BOTMASTER_ROLE_ID) is None:
            await ctx.message.add_reaction(Lang.CMDNOPERMISSIONS)
            return
        try:
            user = await commands.MemberConverter().convert(ctx, user)
        except (commands.CommandError, IndexError):
            await ctx.send(Lang.lang(self, "bugscore_user_not_found", user))
            await ctx.message.add_reaction(Lang.CMDERROR)
            return

        if user.id in self.storage["bugscore"]:
            del self.storage["bugscore"][user.id]
            Storage.save(self)
            await ctx.message.add_reaction(Lang.CMDSUCCESS)
        else:
            await ctx.message.add_reaction(Lang.CMDNOCHANGE)

    @commands.has_any_role(Config().BOTMASTER_ROLE_ID)
    async def bugscore_increment(self, ctx, user, increment):
        if discord.utils.get(ctx.author.roles,
                             id=Config().BOTMASTER_ROLE_ID) is None:
            await ctx.message.add_reaction(Lang.CMDNOPERMISSIONS)
            return

        # find user
        try:
            user = await commands.MemberConverter().convert(ctx, user)
        except (commands.CommandError, IndexError):
            await ctx.send(Lang.lang(self, "bugscore_user_not_found", user))
            await ctx.message.add_reaction(Lang.CMDERROR)
            return

        try:
            increment = int(increment)
        except (ValueError, TypeError):
            await ctx.send(Lang.lang(self, "bugscore_nan", increment))
            await ctx.message.add_reaction(Lang.CMDERROR)
            return

        if user.id in self.storage["bugscore"]:
            self.storage["bugscore"][user.id] += increment
        else:
            self.storage["bugscore"][user.id] = increment
        if self.storage["bugscore"][user.id] <= 0:
            del self.storage["bugscore"][user.id]
        Storage.save(self)
        await ctx.message.add_reaction(Lang.CMDSUCCESS)

    @commands.command(
        name="bugscore",
        help="High score for users who found bugs",
        description="Shows the current bug score.\n\n"
        "Admins:\n!bugscore <user> [increment]\n!bugscore del <user>")
    async def bugscore(self, ctx, *args):
        if len(args) == 0:
            await self.bugscore_show(ctx)
            return

        if len(args) == 2 and args[0] == "del":
            await self.bugscore_del(ctx, args[1])
            return

        increment = 1
        if len(args) == 2:
            increment = args[1]

        if len(args) > 2:
            await ctx.send(Lang.lang(self, "bugscore_args"))
            return

        await self.bugscore_increment(ctx, args[0], increment)
Example #18
0
class Automate:

    #Initialize logging
    log = log()

    #Helper function to initialize configuration parameters
    def readConfig(self):
        self.__configuration__ = Config()
        status = self.__configuration__.read_config()
        if status == 1:
            log.logger.info("Configuration read success")
        else:
            log.logger.info(
                "Configuration read not successful! Exiting automation script")
            sys.exit()

    #Helper function to get the files from a directory
    def GetFiles(self, paths):
        files = []
        for file in os.listdir(paths):
            files.append(file)
        return files

    #Helper function to copy files from a src dir to dest dir
    def copyFiles(self, src_folder, dest_folder, added):
        if src_folder == "" or dest_folder == "":
            log.logger.error('Source or Destination Folder does not exists')
            return 0

        if not os.listdir(src_folder):
            log.logger.error('No files found in src folder')
            return 0

        #for file in os.listdir(src_folder):
        for file in added:
            # print ("File being moved -----> " + file)
            full_file_name = os.path.join(src_folder, file)
            if os.path.isfile(full_file_name):
                try:
                    shutil.copy(full_file_name, dest_folder)
                except shutil.Error as e:
                    log.logger.error('Could not copy the files %s', e)
                    return 0
        return 1

    #Helper function to rename the rendered trec file embedded HTML to index.html
    def renameFile(self, path, tochangefilename):
        fileName = os.listdir(path)
        for files in fileName:
            if (files == tochangefilename):
                os.rename(path + "\\" + tochangefilename,
                          path + "\\" + "index.html")
                return 1
        return 0

    #Helper function to calculate wait time for rendering based on File Size
    def renderTime(self, file, renderingPerMB):
        st = os.stat(file)
        sizeBytes = st.st_size
        sizeBytes /= (1024 * 1024)
        renderTime = sizeBytes * renderingPerMB
        renderTime /= 1000
        return renderTime

    #Helper function Check is a duplicate exists and delete the duplicate folder
    def check_duplicate(self, filename, filePath):
        directories = os.listdir(filePath)
        for dir in directories:
            if dir == filename:
                shutil.rmtree(filePath + '\\' + filename)
                return 1
        return 0

    #Helper function Check if the file to render is copied completely before rendering
    def IsCopyFinished(self, fileName):
        timeout = 3600  # [seconds]
        timeout_start = time.time()
        if os.path.exists(fileName):
            while time.time() < timeout_start + timeout:
                try:
                    with io.FileIO(fileName, "r+") as fileObj:
                        log.logger.info("File loading completed.")
                        return 1
                except IOError as ioe:
                    pass
        log.logger.info("Issue with file.")
        return 0
Example #19
0
 def configurar(self):
     self.sonido_boton.reproducir()
     pilas.almacenar_escena(Config(self.nombre))
Example #20
0
 def configure(self, plugin):
     Config().load(plugin)
     Storage().load(plugin)
     Lang().remove_from_cache(plugin)
Example #21
0
def main():
    Config().load_bot_config()
    injections.pre_injections()
    logging_setup()
    logging.getLogger(__name__).debug("Debug mode: on")
    bot = Geckarbot(command_prefix='!')
    injections.post_injections(bot)
    logging.info("Loading core plugins")
    bot.load_plugins(Config().CORE_PLUGIN_DIR)

    @bot.event
    async def on_ready():
        """Loads plugins and prints on server that bot is ready"""
        guild = discord.utils.get(bot.guilds, id=Config().SERVER_ID)
        bot.guild = guild

        logging.info("Loading plugins")
        bot.load_plugins(Config().PLUGIN_DIR)

        logging.info(f"{bot.user} is connected to the following server:\n"
                     f"{guild.name}(id: {guild.id})")

        members = "\n - ".join([member.name for member in guild.members])
        logging.info(f"Server Members:\n - {members}")

        await utils.write_debug_channel(
            bot, f"Geckarbot {Config().VERSION} connected on "
            f"{guild.name} with {len(guild.members)} users.")

    if not Config().DEBUG_MODE:

        @bot.event
        async def on_error(event, *args, **kwargs):
            """On bot errors print error state in debug channel"""
            exc_type, exc_value, exc_traceback = sys.exc_info()

            if (exc_type is commands.CommandNotFound
                    or exc_type is commands.DisabledCommand):
                return

            embed = discord.Embed(title=':x: Error', colour=0xe74c3c)  # Red
            embed.add_field(name='Error', value=exc_type)
            embed.add_field(name='Event', value=event)
            embed.description = '```python\n{}\n```'.format("".join(
                traceback.format_exception(exc_type, exc_value,
                                           exc_traceback)))
            embed.timestamp = datetime.datetime.utcnow()
            await utils.write_debug_channel(bot, embed)

        @bot.event
        async def on_command_error(ctx, error):
            """Error handling for bot commands"""
            # No command or ignoring list handling
            if isinstance(
                    error,
                (commands.CommandNotFound, commands.DisabledCommand)):
                return
            if isinstance(error, ignoring.UserBlockedCommand):
                await ctx.send("User {} has blocked the command.".format(
                    utils.get_best_username(error.user)))

            # Check Failures
            elif isinstance(error,
                            (commands.MissingRole, commands.MissingAnyRole)):
                await ctx.send(
                    "You don't have the correct role for this command.")
            elif isinstance(error, commands.NoPrivateMessage):
                await ctx.send("Command can't be executed in private messages."
                               )
            elif isinstance(error, commands.CheckFailure):
                await ctx.send("Permission error.")

            # User input errors
            elif isinstance(error, commands.MissingRequiredArgument):
                await ctx.send("Required argument missing: {}".format(
                    error.param))
            elif isinstance(error, commands.TooManyArguments):
                await ctx.send("Too many arguments given.")
            elif isinstance(error, commands.BadArgument):
                await ctx.send("Error on given argument: {}".format(error))
            elif isinstance(error, commands.UserInputError):
                await ctx.send("Wrong user input format: {}".format(error))

            # Other errors
            else:
                # error handling
                embed = discord.Embed(title=':x: Command Error',
                                      colour=0xe74c3c)  # Red
                embed.add_field(name='Error', value=error)
                embed.add_field(name='Command', value=ctx.command)
                embed.add_field(name='Message',
                                value=ctx.message.clean_content)
                embed.description = '```python\n{}\n```'.format("".join(
                    traceback.TracebackException.from_exception(
                        error).format()))
                embed.timestamp = datetime.datetime.utcnow()
                await utils.write_debug_channel(bot, embed)
                await ctx.send("Error while executing command.")

    @bot.event
    async def on_message(message):
        """Basic message and ignore list handling"""

        # DM handling
        if message.guild is None:
            if await bot.dm_listener.handle_dm(message):
                return

        # user on ignore list
        if bot.ignoring.check_user(message.author):
            return

        # debug mode whitelist
        if not permChecks.whitelist_check(message.author):
            return

        await bot.process_commands(message)

    @bot.check
    async def command_disabled(ctx):
        """
        Checks if a command is disabled or blocked for user.
        This check will be executed before other command checks.
        """
        if bot.ignoring.check_command(ctx):
            raise commands.DisabledCommand()
        if bot.ignoring.check_user_command(ctx.author,
                                           ctx.command.qualified_name):
            raise commands.DisabledCommand()
        return True

    bot.run(Config().TOKEN)
Example #22
0
 def resolveEntity(self, publicId, systemId):
     configs = Config.getConfig()
     return configs['game.alawar']['dtd']+systemId
Example #23
0
def printme(text):
    Config.printme("MOTION:", text)
Example #24
0
        exit(1)

    # try to get board firmata version
    # this fails most of the times
    if args.v:
        v = board.get_firmata_version()
        try:
            print("{0}.{1}".format(v[0], v[1]))
            exit(0)
        except (NameError, TypeError):
            print("could not get board firmata version")
            exit(1)

    # handle configuration file
    if args.f:
	config = Config(args.f)
    else:
	config = Config()

    # turn off board led
    led = board.get_pin('d:13:o')
    led.write(0)

    # configuring pins
    ch1 = Channel(board.get_pin('d:9:o'), config.get_boardname(1))
    ch2 = Channel(board.get_pin('d:8:o'), config.get_boardname(2))
    ch3 = Channel(board.get_pin('d:7:o'), config.get_boardname(3))
    ch4 = Channel(board.get_pin('d:6:o'), config.get_boardname(4))

    channels = {'1': ch1, '2': ch2, '3': ch3, '4': ch4}
Example #25
0
class Plugin(BasePlugin, name="Bot updating system"):
    def __init__(self, bot):
        super().__init__(bot)
        self.bot = bot
        self.client = restclient.Client(URL)

        self.bot.loop.run_until_complete(self.was_i_updated())
        self.state = State.IDLE

        self.to_log = None
        self.waiting_for_confirm = None
        bot.register(self)

    def get_configurable_type(self):
        return ConfigurableType.COREPLUGIN

    async def do_update(self, channel, tag):
        self.state = State.UPDATING
        await channel.send(lang["doing_update"].format(tag))
        for plugin in self.bot.plugin_objects():
            try:
                await utils.write_debug_channel(
                    self.bot,
                    "Shutting down plugin {}".format(plugin.get_name()))
                await plugin.shutdown()
            except Exception as e:
                msg = "{} while trying to shutdown plugin {}:\n{}".format(
                    str(e), plugin.get_name(), traceback.format_exc())
                await utils.write_debug_channel(self.bot, msg)

        await self.bot.close()
        with open(TAGFILE, "w") as f:
            f.write(tag)
        await self.bot.shutdown(Geckarbot.Exitcodes.UPDATE
                                )  # This signals the runscript

    def get_releases(self):
        r = self.client.make_request(ENDPOINT)
        return r

    def check_release(self):
        """
        Checks GitHub if there is a new release. Assumes that the GitHub releases are ordered by release date.
        :return: Tag of the newest release that is newer than the current version, None if there is none.
        """
        # return "1.3"  # TESTING
        # find newest release with tag (all the others are worthless anyway)
        release = None
        for el in self.get_releases():
            if "tag_name" in el:
                release = el
                break
        if release is None:
            return None

        release = release["tag_name"]
        if is_newer(release, Config().VERSION):
            return release
        return None

    async def update_news(self, channel, version=None):
        """
        Sends release notes to channel.
        :param channel: Channel to send the release notes to.
        :param version: Release version that the news should be about.
        """
        if version is None:
            version = Config().VERSION
        ver = None
        body = None
        for el in self.get_releases():
            ver = sanitize_version_s(el["tag_name"])
            logging.getLogger(__name__).debug(
                "Comparing versions: {} and {}".format(Config().VERSION, ver))
            if is_equal(sanitize_version_s(version), ver):
                body = el["body"]
                break

        if body is None:
            await channel.send(lang["err_no_news_for_version"].format(version))
            return

        # Make headlines great again!
        lines = []
        p = re.compile(r"\s*#+\s*(.*)")
        for el in body.split("\n"):
            m = p.match(el)
            if m:
                el = "**{}**".format(m.groups()[0])
            lines.append(el)

        for page in utils.paginate(lines,
                                   prefix="**Version {}:**\n".format(ver),
                                   msg_prefix="_ _\n",
                                   delimiter=""):
            await channel.send(page)

    async def was_i_updated(self):
        """
        Checks if there was an !update before the bot launch. Does cleanup and message sending.
        Does not delete TAGFILE if it had unexpected content.
        :return: True if there was a successful update, False if not
        """
        try:
            f = open(TAGFILE)
        except FileNotFoundError:
            logging.getLogger(__name__).debug("I was not !update'd.")
            return False
        except IsADirectoryError:
            logging.getLogger(__name__).error(
                "{} is a directory, I expected a file or nothing. Please clean this up."
                .format(TAGFILE))
            return False

        lines = f.readlines()
        if len(lines) > 1:
            logging.getLogger(__name__).error(
                "{} has more than 1 line. This should not happen.".format(
                    TAGFILE))
            return False
        if len(lines) == 0 or lines[0].strip() == "":
            logging.getLogger(__name__).error(
                "{} is empty. This should not happen.".format(TAGFILE))
            return False

        if lines[0].strip() == ERRORCODE:
            await utils.write_debug_channel(
                self.bot,
                "The update failed. I have no idea why. Sorry, master!")
            os.remove(TAGFILE)
            return False
        else:
            logging.getLogger(__name__).debug("I was !update'd! Yay!.")
            await utils.write_debug_channel(
                self.bot,
                "I updated successfully! One step closer towards world dominance!"
            )
            os.remove(TAGFILE)
            return True

    @commands.command(name="news", help="Presents the latest update notes.")
    async def news(self, ctx, *args):
        version = None
        if len(args) == 0:
            pass
        elif len(args) == 1:
            version = args[0]
        else:
            await ctx.message.channel.send("Too many arguments.")
            return

        await self.update_news(ctx.message.channel, version=version)

    @commands.command(name="version", help="Returns the running bot version.")
    async def version(self, ctx):
        """Returns the version"""
        await ctx.send(lang["version"].format(Config().VERSION))

    @commands.command(name="restart", help="Restarts the bot.")
    @commands.has_any_role(Config().BOTMASTER_ROLE_ID)
    async def restart(self, ctx):
        await ctx.message.add_reaction(Lang.CMDSUCCESS)
        await self.bot.shutdown(Geckarbot.Exitcodes.RESTART
                                )  # This signals the runscript

    @commands.command(name="shutdown", help="Stops the bot.")
    @commands.has_any_role(Config().BOTMASTER_ROLE_ID)
    async def shutdowncmd(self, ctx):
        await ctx.message.add_reaction(Lang.CMDSUCCESS)
        await self.bot.shutdown(Geckarbot.Exitcodes.SUCCESS
                                )  # This signals the runscript

    @commands.command(name="replace", help="Confirms an !update command.")
    async def confirm(self, ctx):
        # Check if there is an update request running
        if self.waiting_for_confirm is None:
            return

        # Check if chan and user is the same
        chancond = self.waiting_for_confirm.channel == ctx.message.channel
        usercond = self.waiting_for_confirm.author == ctx.message.author
        if not (chancond and usercond):
            return

        await utils.log_to_admin_channel(self.to_log)
        await ctx.message.add_reaction(Lang.CMDSUCCESS)
        self.to_log = None
        self.state = State.CONFIRMED

    @commands.command(
        name="update",
        help="Updates the bot if an update is available",
        description="Updates the Bot to the newest version (if available)."
        " This includes a shutdown, so be careful.")
    async def update(self, ctx, check=None):
        # Argument parsing
        if not permChecks.check_full_access(ctx.author) or check == "check":
            release = self.check_release()
            await ctx.message.add_reaction(Lang.CMDSUCCESS)
            if release is None:
                await ctx.message.channel.send(lang["no_new_version"])
            else:
                await ctx.message.channel.send(
                    lang["new_version"].format(release))
            return

        # Check state and send error messages if necessary
        if self.state == State.CHECKING or self.state == State.CONFIRMED or self.state == State.UPDATING:
            await ctx.message.channel.send(lang["err_already_updating"])
            return
        if self.state == State.WAITINGFORCONFIRM:
            if not self.waiting_for_confirm.channel == ctx.message.channel:
                await ctx.message.channel.send(lang["err_different_channel"])
            elif not self.waiting_for_confirm.author == ctx.message.author:
                await ctx.message.channel.send(lang["err_different_user"])
            return
        assert self.state == State.IDLE

        # Check for new version
        self.state = State.CHECKING
        release = self.check_release()
        if release is None:
            await ctx.message.channel.send(lang["wont_update"])
            self.state = State.IDLE
            return
        await ctx.message.add_reaction(Lang.CMDSUCCESS)
        await ctx.message.channel.send(
            lang["new_version_update"].format(release))

        # Ask for confirmation
        self.state = State.WAITINGFORCONFIRM
        self.waiting_for_confirm = ctx.message
        self.to_log = ctx
        await asyncio.sleep(
            CONFIRMTIMEOUT
        )  # This means that the bot doesn't react immediately on confirmation

        # No confirmation, cancel
        if self.state == State.WAITINGFORCONFIRM:
            self.state = State.IDLE
            await ctx.message.channel.send(lang["update_timeout"])
            return

        # Confirmation came in
        elif self.state == State.CONFIRMED:
            await self.do_update(ctx.message.channel, release)
            return
        else:
            logging.getLogger(__name__).error(
                "{}: PANIC! I am on {}, this should not happen!".format(
                    self.get_name(), self.state))
            self.state = State.IDLE
            self.waiting_for_confirm = None
Example #26
0
class Plugin(BasePlugin, name="Bot Management Commands"):
    """Commands for moderation"""

    def __init__(self, bot):
        super().__init__(bot)
        self.can_reload = True
        bot.register(self)

    def default_config(self):
        return {
            'repo_link': "https://github.com/gobo7793/Geckarbot/",
            'bot_info_link': "",
            'privacy_notes_link': "",
            'privacy_notes_lang': "",
            'profile_pic_creator': ""
        }

    def get_configurable_type(self):
        return ConfigurableType.COREPLUGIN

    ######
    # Misc commands
    ######

    # @commands.command(name="reload", help="Reloads the configuration.", usage="[plugin_name]",
    #                   description="Reloads the configuration from the given plugin."
    #                               "If no plugin given, all plugin configs will be reloaded.")
    # @commands.has_any_role(Config().ADMIN_ROLE_ID, Config().BOTMASTER_ROLE_ID)
    # async def reload(self, ctx, plugin_name=None):
    #     """Reloads the config of the given plugin or all if none is given"""
    #     await utils.log_to_admin_channel(ctx)
    #     if plugin_name is None:
    #         reconfigure(self.bot)
    #         send_msg = "Configuration of all plugins reloaded."
    #     else:
    #         send_msg = f"No plugin {plugin_name} found."
    #         for plugin in self.bot.plugins:
    #             if plugin.name == plugin_name:
    #                 if plugin.instance.can_reload:
    #                     self.bot.configure(plugin.instance)
    #                     send_msg = f"Configuration of plugin {plugin_name} reloaded."
    #                 else:
    #                     send_msg = f"Plugin {plugin_name} can't reloaded."
    #
    #     if ctx.channel.id != Config().DEBUG_CHAN_ID:
    #         await ctx.send(send_msg)
    #     await utils.write_debug_channel(self.bot, send_msg)

    @commands.command(name="plugins", help="List all plugins.")
    async def plugins(self, ctx):
        """Returns registered plugins"""
        coreplugins = [c.name for c in self.bot.plugins if c.type == ConfigurableType.COREPLUGIN]
        plugins = [c.name for c in self.bot.plugins if c.type == ConfigurableType.PLUGIN]
        subsys = []
        for modname in pkgutil.iter_modules(subsystems.__path__):
            subsys.append(modname.name)

        for msg in utils.paginate(coreplugins,
                                  prefix=Lang.lang(self, 'plugins_loaded_cp', len(coreplugins)), delimiter=", "):
            await ctx.send(msg)
        for msg in utils.paginate(plugins,
                                  prefix=Lang.lang(self, 'plugins_loaded_pl', len(coreplugins)), delimiter=", "):
            await ctx.send(msg)
        for msg in utils.paginate(subsys,
                                  prefix=Lang.lang(self, 'plugins_loaded_ss', len(coreplugins)), delimiter=", "):
            await ctx.send(msg)

    @commands.command(name="about", aliases=["git", "github"], help="Prints the credits")
    async def about(self, ctx):
        about_msg = Lang.lang(self, 'about_version', Config.VERSION, self.bot.guild.name,
                              platform.system(), platform.release(), platform.version())

        if Config.get(self)['bot_info_link']:
            about_msg += Lang.lang(self, 'about_general_info', Config.get(self)['bot_info_link'])
        about_msg += Lang.lang(self, 'about_repo', Config.get(self).get('repo_link',
                                                                           Lang.lang(self, 'about_no_repo_link')))
        if Config.get(self)['privacy_notes_link']:
            lang = ""
            if Config.get(self)['privacy_notes_lang']:
                lang = " ({})".format(Config.get(self)['privacy_notes_lang'])
            about_msg += Lang.lang(self, 'about_privacy', Config.get(self)['privacy_notes_link'], lang)

        about_msg += Lang.lang(self, 'about_devs', "Costamiri, Fluggs, Gobo77")
        if Config.get(self)['profile_pic_creator']:
            about_msg += Lang.lang(self, 'about_pfp', Config.get(self)['profile_pic_creator'])

        about_msg += Lang.lang(self, 'about_thanks')

        await ctx.send(about_msg)

    ######
    # Ignoring subsystem
    ######

    @commands.group(name="disable", invoke_without_command=True, help="Blocks user or command usage.",
                    brief="Blocks user or command usage", aliases=["ignore", "block"],
                    usage="<command> [user] [#m|#h|#d|DD.MM.YYYY|HH:MM|DD.MM.YYYY HH:MM|DD.MM. HH:MM]",
                    description="Adds a command to users ignore list to disable any interactions between the user and "
                                "the command.\n"
                                "To block command usage for the user, the command name must be the full qualified "
                                "name of the command without command prefix. If a subcommand should be blocked, "
                                "the command name must be inside quotation marks like \"disable cmd\".\n "
                                "To block other interactions than command usage itself, the command must support "
                                "blocking usage for specific users.\n"
                                "The time can be a fixed date and/or time or a duration after that the "
                                "command will be auto-removed from the ignore list. The duration unit must be set "
                                "with trailing m for minutes, h for hours or d for days. If no date/duration is "
                                "given, the user can't interact with that command forever.\n"
                                "Users can disable command interactions for themselves only, but Admins also for "
                                "other users.\n"
                                "If a user uses a command which is blocked for the user, "
                                "the bot doesn't response anything, like the command wouldn't exists.")
    async def disable(self, ctx, command, *args):
        user = ctx.author
        date_args_start_index = 0
        if len(args) > 0:
            try:
                user = await commands.MemberConverter().convert(ctx, args[0])
                date_args_start_index = 1
            except (commands.CommandError, IndexError):
                date_args_start_index = 0

        if user != ctx.author and not permChecks.check_full_access(ctx.author):
            raise commands.MissingAnyRole(Config().FULL_ACCESS_ROLES)

        until = utils.analyze_time_input(*args[date_args_start_index:])

        result = self.bot.ignoring.add_user_command(user, command, until)
        if result == IgnoreEditResult.Success:
            await ctx.message.add_reaction(Lang.CMDSUCCESS)
        elif result == IgnoreEditResult.Already_in_list:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, 'user_cmd_already_blocked', command, utils.get_best_username(user)))
        elif result == IgnoreEditResult.Until_in_past:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, 'no_time_machine'))
        await utils.log_to_admin_channel(ctx)

    @disable.command(name="user", help="Block any interaction between user and bot.",
                     usage="<user> [#m|#h|#d|DD.MM.YYYY|HH:MM|DD.MM.YYYY HH:MM|DD.MM. HH:MM]",
                     description="Adds a user to bot's ignore list to block any interaction between the user and the "
                                 "bot.\n "
                                 "The time can be a fixed date and/or time or a duration after that the user will be "
                                 "auto-removed from the ignore list. The duration unit must be set with trailing m "
                                 "for minutes, h for hours or d for days. If no date/duration is given, the user will "
                                 "be blocked forever.\n"
                                 "If a blocked user uses a command, "
                                 "the bot doesn't response anything, like the command wouldn't exists.")
    @commands.has_any_role(*Config().FULL_ACCESS_ROLES)
    async def disable_user(self, ctx, user: discord.Member, *args):
        until = utils.analyze_time_input(*args)

        result = self.bot.ignoring.add_user(user, until)
        if result == IgnoreEditResult.Success:
            await ctx.message.add_reaction(Lang.CMDSUCCESS)
        elif result == IgnoreEditResult.Already_in_list:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, 'user_already_blocked', utils.get_best_username(user)))
        elif result == IgnoreEditResult.Until_in_past:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, 'no_time_machine'))
        await utils.log_to_admin_channel(ctx)

    @disable.command(name="cmd", help="Disables a command in current channel.",
                     usage="<command> [#m|#h|#d|DD.MM.YYYY|HH:MM|DD.MM.YYYY HH:MM|DD.MM. HH:MM]",
                     description="Adds a command to bot's ignore list to disable it in current channel. The command "
                                 "name must be the full qualified name of the command without command prefix. If a "
                                 "subcommand should be blocked, the command name must be inside quotation marks like "
                                 "\"disable cmd\".\n"
                                 "The time can be a fixed date and/or time or a duration after that the command will "
                                 "be auto-removed from the ignore list. The duration unit must be set with trailing m "
                                 "for minutes, h for hours or d for days. If no date/duration is given, the command "
                                 "will be disabled forever.\n"
                                 "If a user uses a command which is blocked in the channel, "
                                 "the bot doesn't response anything, like the command wouldn't exists.\n"
                                 "Note: The command !enable can't be blocked to avoid deadlocks.")
    @commands.has_any_role(*Config().FULL_ACCESS_ROLES)
    async def disable_cmd(self, ctx, command, *args):
        if command == "enable":
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, 'enable_cant_blocked'))
            return

        until = utils.analyze_time_input(*args)

        result = self.bot.ignoring.add_command(command, ctx.channel, until)
        if result == IgnoreEditResult.Success:
            await ctx.message.add_reaction(Lang.CMDSUCCESS)
        elif result == IgnoreEditResult.Already_in_list:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, 'cmd_already_blocked', command))
        elif result == IgnoreEditResult.Until_in_past:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, 'no_time_machine'))
        await utils.log_to_admin_channel(ctx)

    @disable.command(name="list", help="Lists all blocked users and commands")
    # NOTE: Will be invoked via "!subsys"
    async def disable_list(self, ctx):
        def get_item_msg(item):
            return item.to_message()

        async def write_list(itype: IgnoreType, prefix):
            ilist = self.bot.ignoring.get_ignore_list(itype)
            if len(ilist) > 0:
                for msg in utils.paginate(ilist, prefix=prefix, f=get_item_msg):
                    await ctx.send(msg)

        if self.bot.ignoring.get_full_ignore_len() < 1:
            await ctx.send(Lang.lang(self, 'nothing_blocked'))
            return

        await write_list(IgnoreType.User, Lang.lang(self, 'list_users'))
        await write_list(IgnoreType.Command, Lang.lang(self, 'list_cmds'))
        await write_list(IgnoreType.User_Command, Lang.lang(self, 'list_usercmds'))

    @commands.group(name="enable", invoke_without_command=True, help="Unblocks user or command usage.",
                    aliases=["unignore", "unblock"],
                    description="Removes a command from users ignore list to enable any interactions between the user "
                                "and the command.\n"
                                "Users can enable command interactions for themselves only, but Admins also for "
                                "other users.")
    async def enable(self, ctx, command, user: discord.Member = None):
        if user is None:
            user = ctx.author

        if user != ctx.author and not permChecks.check_full_access(ctx.author):
            raise commands.MissingAnyRole(*Config().FULL_ACCESS_ROLES)

        result = self.bot.ignoring.remove_user_command(user, command)
        if result == IgnoreEditResult.Success:
            await ctx.message.add_reaction(Lang.CMDSUCCESS)
        elif result == IgnoreEditResult.Not_in_list:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, 'user_cmd_not_blocked', command, utils.get_best_username(user)))
        await utils.log_to_admin_channel(ctx)

    @enable.command(name="user", help="Unblock user to enable interactions between user and bot.",
                    description="Removes a user from bot's ignore list to enable any interaction between the user and "
                                "the bot.")
    @commands.has_any_role(*Config().FULL_ACCESS_ROLES)
    async def enable_user(self, ctx, user: discord.Member):
        result = self.bot.ignoring.remove_user(user)
        if result == IgnoreEditResult.Success:
            await ctx.message.add_reaction(Lang.CMDSUCCESS)
        elif result == IgnoreEditResult.Not_in_list:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, 'user_not_blocked', utils.get_best_username(user)))
        await utils.log_to_admin_channel(ctx)

    @enable.command(name="cmd", help="Enables a command in current channel.",
                    description="Removes a command from bot's ignore list to enable it in current channel. The command "
                                "name must be the full qualified name of the command without command prefix. If a "
                                "subcommand should be enabled, the command name must be inside quotation marks like "
                                "\"enable cmd\".")
    @commands.has_any_role(*Config().FULL_ACCESS_ROLES)
    async def enable_cmd(self, ctx, command):
        result = self.bot.ignoring.remove_command(command, ctx.channel)
        if result == IgnoreEditResult.Success:
            await ctx.message.add_reaction(Lang.CMDSUCCESS)
        elif result == IgnoreEditResult.Not_in_list:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send(Lang.lang(self, 'cmd_not_blocked', command))
        await utils.log_to_admin_channel(ctx)
Example #27
0
 async def version(self, ctx):
     """Returns the version"""
     await ctx.send(lang["version"].format(Config().VERSION))
Example #28
0
 def resolveEntity(self, publicId, systemId):
     configs = Config.getConfig()
     return configs['game.bigfish']['dtd'][0] + systemId
Example #29
0
    def convert_files(self, file):
        _config = Config()
        backslash = "\\"
        app_path = _config.Original_Path + backslash + file
        #print(app_path)
        Auto = Automate()
        renderTime = Auto.renderTime(app_path, _config.Rendering_wait_time)
        IsFileCopied = Auto.IsCopyFinished(app_path)
        if IsFileCopied == 0:
            return
        if os.path.exists(app_path):
            os.startfile(app_path)
        else:
            log.logger.info("Trec file does not exists")
            return
        time.sleep(_config.App_time)
        # print("Sleep End!!!")

        try:
            if os.path.exists(_config.Camtasia_Path):
                app = Application().connect(path=_config.Camtasia_Path)
            else:
                log.logger.info("Camtasia executable not found!")
                return

            # To bring the Camtasia window to the focus.
            app_dialog = app.top_window_()
            app_dialog.Minimize()
            app_dialog.Restore()
        except (ProcessNotFoundError):
            log.logger.info("Not Camtasia process found... Exiting App")
            return
        except (WindowNotFoundError):
            log.logger.info("Not found Camtasia... Exiting App")
            app.kill()
            return
        except (WindowAmbiguousError):
            log.logger.info(
                "There are too many Camtasia windows found... Exiting App")
            app.kill()
            return

        if os.path.exists(app_path):
            os.startfile(app_path)
        else:
            log.logger.info("Trec file does not exists... Exiting App")
            app.kill()
            return

        #for TRIAL
        if _config.Trial == 'YES':
            try:
                app.Window_(best_match='Dialog',
                            top_level_only=True).ChildWindow(
                                best_match='Finish').Click()
            except (MatchError):
                # print ' Not found Finish Dialog'
                log.logger.info("Not found Finish Dialog... Exiting App")
                app.kill()
                return

        time.sleep(_config.Dialog_wait_time)
        #end for TRIAL
        child_elements = app[_config.App_Name]
        #for clicking the share button
        child_elements.ClickInput(coords=(_config.Share_Btn_X,
                                          _config.Share_Btn_Y))
        child_elements.TypeKeys("{DOWN}")
        child_elements.TypeKeys("{ENTER}")
        time.sleep(_config.Dialog_wait_time)

        #for TRIAL
        if _config.Trial == 'YES':
            #for clicking the water mark button
            child_elements.Wait('visible', timeout=20)
            child_elements.ClickInput(coords=(_config.Water_Mark_Btn_X,
                                              _config.Water_Mark_Btn_Y))
            time.sleep(_config.Dialog_wait_time)
        #end for TRIAL
        for i in range(_config.Dialogs):
            time.sleep(2)
            child_elements.Wait('visible', timeout=20)

            try:
                app.Window_(best_match='Dialog',
                            top_level_only=True).ChildWindow(
                                best_match='Next').Click()
            except (MatchError):
                # print ' Not found Dialog to click the first Next. Check if coordinates are mentioned correctly in configuration.xml'
                log.logger.info(
                    "Not found Dialog to click the first Next. Check if coordinates are mentioned correctly in configuration.xml. Exiting App"
                )
                app.kill()
                return

        stripped_file_name = os.path.splitext(os.path.basename(file))[0]
        dup_dir = Auto.check_duplicate(stripped_file_name, _config.Saved_Path)
        if dup_dir == 1:
            log.logger.info(
                "Duplicate exists.The rendering will overwrite the existing directory"
            )

        try:
            app.Window_(best_match='Dialog', top_level_only=True).ChildWindow(
                title="Untitled Project",
                class_name="Edit").SetText(stripped_file_name)
        except (MatchError):
            # print ' Not found Dialog to rename the project'
            log.logger.info(
                "Not found Dialog to rename the project... Exiting App")
            app.kill()
            return
        try:
            app.Window_(
                best_match='Dialog',
                top_level_only=True).ChildWindow(best_match='Finish').Click()
        except (MatchError):
            # print ' Not found Dialog to click Finish'
            log.logger.info("Not found Dialog to click Finish... Exiting App")
            app.kill()
            return

        time.sleep(renderTime)
        app.kill_()
        time.sleep(_config.Dialog_wait_time)
        #print("Rendering Succcessful")

        return stripped_file_name
Example #30
0
class Plugin(BasePlugin, name="NFL Fantasyliga"):
    """Commands for the Fantasy game"""

    fantasymaster_role_id = 721178888050573352

    def __init__(self, bot):
        self.bot = bot
        super().__init__(bot)
        bot.register(self)

    def default_config(self):
        return {
            'league_link_a':
            "https://fantasy.espn.com/football/league/standings?leagueId=60409564",
            'league_link_b':
            "https://fantasy.espn.com/football/league/standings?leagueId=60409564",
            'commish_id_a': None,
            'commish_id_b': None,
            'state': FantasyState.NA,
            'state_end': datetime.now(),
            'status': None
        }

    def fantasy_conf(self):
        return Storage.get(self)

    def fantasy_lang(self, str_name, *args):
        return Lang.lang(self, str_name, *args)

    @commands.group(
        name="fantasy",
        help="Get and manage informations about the NFL Fantasy Game",
        description="Get the informations about the Fantasy Game or manage it. "
        "Command only works in nfl-fantasy channel."
        "Managing informations is only permitted for fantasymasters.")
    @permChecks.in_channel(Config().CHAN_IDS.get('nfl-fantasy', 0))
    async def fantasy(self, ctx):
        """Fantasy base command, return info command if no subcommand given"""
        if ctx.invoked_subcommand is None:
            await self.fantasy_info(ctx)

    @fantasy.command(name="ligen", help="Get the link to the Fantasy Leagues")
    async def fantasy_leagues(self, ctx):
        """Returns the Fantasy leagues"""
        links = self.fantasy_lang('league_links'), self.fantasy_conf(
        )['league_link_a'], self.fantasy_conf()['league_link_b']

        await ctx.send(links)

    @fantasy.command(
        name="status",
        help="Get the current informations about the current fantasy state")
    async def fantasy_status(self, ctx):
        """Returns the Fantasy status message"""
        if self.fantasy_conf()['status']:
            status_msg = self.fantasy_lang('status_base',
                                           self.fantasy_conf()['status'])
        else:
            status_msg = self.fantasy_lang('status_base',
                                           self.fantasy_lang('status_none'))

        await ctx.send(status_msg)

    @fantasy.command(name="info",
                     help="Get informations about the NFL Fantasy Game")
    async def fantasy_info(self, ctx):
        """Returns basic infos about the Fantasy game"""

        dateOutStr = self.fantasy_lang(
            'info_date_str',
            self.fantasy_conf()['state_end'].strftime('%d.%m.%Y, %H:%M'))
        if not self.fantasy_conf()['commish_id_a']:
            await ctx.send(self.fantasy_lang('must_set_commish'))
        else:
            SuperCommish = discord.utils.get(
                ctx.guild.members,
                id=self.fantasy_conf()['supercommish_id']).mention
            CommishA = discord.utils.get(
                ctx.guild.members,
                id=self.fantasy_conf()['commish_id_a']).mention
            CommishB = discord.utils.get(
                ctx.guild.members,
                id=self.fantasy_conf()['commish_id_b']).mention

        if self.fantasy_conf()['state'] == FantasyState.Sign_up:
            if self.fantasy_conf()['state_end'] > datetime.now():
                dateOutStr = self.fantasy_lang(
                    'info_date_str',
                    self.fantasy_conf()['state_end'].strftime('%d.%m.%Y'))
            else:
                dateOutStr = ""

            embed = discord.Embed(
                title=self.fantasy_lang('signup_phase_info', dateOutStr))
            embed.add_field(name=self.fantasy_lang('supercommish'),
                            value=SuperCommish)
            embed.add_field(name=self.fantasy_lang('sign_up'),
                            value=SuperCommish)

            if self.fantasy_conf()['status']:
                embed.description = self.fantasy_conf()['status']
            await ctx.send(embed=embed)

        elif self.fantasy_conf()['state'] == FantasyState.Predraft:
            embed = discord.Embed(
                title=self.fantasy_lang('predraft_phase_info', dateOutStr))

            embed.add_field(name=self.fantasy_lang('commish_a'),
                            value=CommishA)
            embed.add_field(name=self.fantasy_lang('commish_b'),
                            value=CommishB)
            embed.add_field(name=self.fantasy_lang('player_database'),
                            value=self.fantasy_conf()['datalink'],
                            inline=False)

            if self.fantasy_conf()['status']:
                embed.description = self.fantasy_conf()['status']
            await ctx.send(embed=embed)

        elif self.fantasy_conf()['state'] == FantasyState.Preseason:
            embed = discord.Embed(
                title=self.fantasy_lang('preseason_phase_info', dateOutStr))
            embed.add_field(name=self.fantasy_lang('commish_a'),
                            value=CommishA)
            embed.add_field(name=self.fantasy_lang('commish_b'),
                            value=CommishB)
            embed.add_field(name=self.fantasy_lang('league_a'),
                            value=self.fantasy_conf()['league_link_a'],
                            inline=False)
            embed.add_field(name=self.fantasy_lang('league_b'),
                            value=self.fantasy_conf()['league_link_b'],
                            inline=True)

            if self.fantasy_conf()['status']:
                embed.description = self.fantasy_conf()['status']
            await ctx.send(embed=embed)

        elif self.fantasy_conf()['state'] == FantasyState.Regular:
            embed = discord.Embed(
                title=self.fantasy_lang('regular_phase_info', dateOutStr))
            embed.add_field(name=self.fantasy_lang('commish_a'),
                            value=CommishA)
            embed.add_field(name=self.fantasy_lang('commish_b'),
                            value=CommishB)
            embed.add_field(name=self.fantasy_lang('league_a'),
                            value=self.fantasy_conf()['league_link_a'],
                            inline=False)
            embed.add_field(name=self.fantasy_lang('league_b'),
                            value=self.fantasy_conf()['league_link_b'])

            if self.fantasy_conf()['status']:
                embed.description = self.fantasy_conf()['status']
            await ctx.send(embed=embed)

        elif self.fantasy_conf()['state'] == FantasyState.Postseason:
            embed = discord.Embed(
                title=self.fantasy_lang('postseason_phase_info', dateOutStr))
            embed.add_field(name=self.fantasy_lang('commish_a'),
                            value=CommishA)
            embed.add_field(name=self.fantasy_lang('commish_b'),
                            value=CommishB)
            embed.add_field(name=self.fantasy_lang('league_a'),
                            value=self.fantasy_conf()['league_link_a'],
                            inline=False)
            embed.add_field(name=self.fantasy_lang('league_b'),
                            value=self.fantasy_conf()['league_link_b'])

            if self.fantasy_conf()['status']:
                embed.description = self.fantasy_conf()['status']
            await ctx.send(embed=embed)

        else:
            await ctx.send(self.fantasy_lang('config_error_reset'))
            embed = discord.Embed(title=self.fantasy_lang('config_error'))
            embed.add_field(name="Host ID",
                            value=str(self.fantasy_conf()['supercommish_id']))
            embed.add_field(name="Host Nick", value=SuperCommish)
            embed.add_field(name="State",
                            value=str(self.fantasy_conf()['state']))
            embed.add_field(name="Commish A", value=CommishA)
            embed.add_field(name="ID Commish A",
                            value=(self.fantasy_conf()['commish_id_a']))
            embed.add_field(name="Commish B", value=CommishB)
            embed.add_field(name="ID Commish B",
                            value=(self.fantasy_conf()['commish_id_b']))
            embed.add_field(name="State End",
                            value=str(self.fantasy_conf()['state_end']))
            embed.add_field(name="Status",
                            value=str(self.fantasy_conf()['status']))
            embed.add_field(name="Database Link",
                            value=str(self.fantasy_conf()['datalink']))
            embed.add_field(name="League Link A",
                            value=str(self.fantasy_conf()['league_link_a']))
            embed.add_field(name="League Link B",
                            value=str(self.fantasy_conf()['league_link_b']))
            await utils.write_debug_channel(self.bot, embed)

    @fantasy.group(
        name="set",
        help="Set data about the fantasy game.",
        usage="<orga|comma|commb|linka|linkb|state|stateend|datalink|status")
    @commands.has_any_role(Config().ADMIN_ROLE_ID,
                           Config().BOTMASTER_ROLE_ID,
                           Config().ROLE_IDS.get('fantasymaster', 0))
    async def fantasy_set(self, ctx):
        """Basic set subcommand, does nothing"""
        if ctx.invoked_subcommand is None:
            await ctx.send_help(self.fantasy_set)

    @fantasy_set.command(name="datalink",
                         help="Sets the link for the ESPN Players Database!",
                         usage="<link>")
    async def fantasy_set_datalink(self, ctx, link):
        link = utils.clear_link(link)
        self.fantasy_conf()['datalink'] = link
        Config().save(self)
        await ctx.send(self.fantasy_lang('datalink_set'))

    @fantasy_set.command(name="linka",
                         help="Sets the link for the Tipp-Liga A!",
                         usage="<link>")
    async def fantasy_set_linka(self, ctx, link):
        link = utils.clear_link(link)
        self.fantasy_conf()['league_link_a'] = link
        Config().save(self)
        await ctx.send(self.fantasy_lang('linka_set'))

    @fantasy_set.command(name="linkb",
                         help="Sets the link for the Tipp-Liga B!",
                         usage="<link>")
    async def fantasy_set_linkb(self, ctx, link):
        link = utils.clear_link(link)
        self.fantasy_conf()['league_link_b'] = link
        Config().save(self)
        await ctx.send(self.fantasy_lang('linkb_set'))

    @fantasy_set.command(name="orga",
                         help="Sets the Fantasy Organisator",
                         usage="<user>")
    async def fantasy_set_host(self, ctx, user: discord.Member):
        """Sets the Fantasy Organisator"""

        self.fantasy_conf()['supercommish_id'] = user.id
        Config().save(self)
        await ctx.send(self.fantasy_lang('new_supercommish_set'))

    async def fantasy_save_state(self, ctx, new_state: FantasyState):
        """Saves the new Fantasy state and prints it to user"""
        self.fantasy_conf()['state'] = new_state
        state_str = str(FantasyState(self.fantasy_conf()['state']))
        state_str = state_str[state_str.find(".") + 1:].replace("_", " ")
        Config().save(self)
        await ctx.send(self.fantasy_lang('phase_set', state_str))

    @fantasy_set.command(
        name="state",
        help=
        "Sets the Fantasy state (Sign_Up, Predraft, Preseason, Regular, Postseason)",
        usage="<sign_up|predraft|preseason|regular|postseason>")
    async def fantasy_set_state(self, ctx, state):
        """Sets the current state of the fantasy Season. (Signup phase, Pre-Draft, Preseason, Regular Season, Postseason))"""
        if state.lower() == "sign_up":
            await self.fantasy_save_state(ctx, FantasyState.Sign_up)
        elif state.lower() == "predraft":
            await self.fantasy_save_state(ctx, FantasyState.Predraft)
        elif state.lower() == "preseason":
            await self.fantasy_save_state(ctx, FantasyState.Preseason)
        elif state.lower() == "regular":
            await self.fantasy_save_state(ctx, FantasyState.Regular)
        elif state.lower() == "postseason":
            await self.fantasy_save_state(ctx, FantasyState.Postseason)
        else:
            await ctx.send(self.fantasy_lang('invalid_phase'))

    @fantasy_set.command(name="comma",
                         help="Sets the Commissioner of League A",
                         usage="<user>")
    async def dsc_set_comm_a(self, ctx, user: discord.Member):
        """Sets the Commissioner for League A"""
        self.fantasy_conf()['commish_id_a'] = user.id
        Config().save(self)
        await ctx.send(self.fantasy_lang('new_commish_a_set'))

    @fantasy_set.command(name="commb",
                         help="Sets the Commissioner of League B",
                         usage="<user>")
    async def dsc_set_comm_b(self, ctx, user: discord.Member):
        """Sets the Commissioner for League B"""
        self.fantasy_conf()['commish_id_b'] = user.id
        Config().save(self)
        await ctx.send(self.fantasy_lang('new_commish_b_set'))

    @fantasy_set.command(
        name="stateend",
        help="Sets the state end date",
        usage="DD.MM.YYYY [HH:MM]",
        description="Sets the end date and time for all the phases. "
        "If no time is given, 23:59 will be used.")
    async def fantasy_set_state_end(self, ctx, dateStr, timeStr=None):
        """Sets the end date (and time) of the current Fantasy state"""
        if not timeStr:
            timeStr = "23:59"
        self.fantasy_conf()['state_end'] = datetime.strptime(
            f"{dateStr} {timeStr}", "%d.%m.%Y %H:%M")
        Config().save(self)
        await ctx.send(self.fantasy_lang('state_end_set'))

    @fantasy_set.command(
        name="status",
        help="Sets the status message",
        usage="[message]",
        description=
        "Sets a status message for additional informations. To remove give no message."
    )
    async def fantasy_set_status(self, ctx, *status_message):
        """Sets the dsc status message or removes it if no message is given"""
        self.fantasy_conf()['status'] = " ".join(status_message)
        Config().save(self)
        await ctx.send(self.fantasy_lang('status_set'))
Example #31
0
class Plugin(BasePlugin,
             name="Bot status commands for monitoring and debug purposes"):
    def __init__(self, bot):
        self.bot = bot
        super().__init__(bot)
        bot.register(self)

    def get_configurable_type(self):
        return ConfigurableType.COREPLUGIN

    @commands.command(name="subsys", help="Shows registrations on subsystems")
    @commands.has_any_role(Config().BOTMASTER_ROLE_ID)
    async def subsys(self, ctx):
        for msg in utils.paginate(self.bot.reaction_listener.callbacks,
                                  prefix="**Reactions registrations:**\n",
                                  suffix="\n"):
            await ctx.send(msg)
        for msg in utils.paginate(self.bot.timers.jobs,
                                  prefix="**Timer registrations:**\n",
                                  suffix="\n"):
            await ctx.send(msg)
        for msg in utils.paginate(self.bot.dm_listener.callbacks,
                                  prefix="**DM Listeners:**\n",
                                  suffix="\n"):
            await ctx.send(msg)

        await ctx.invoke(self.bot.get_command("disable list"))

    @commands.command(name="storagedump",
                      help="Dumps plugin storage",
                      usage="<plugin name>")
    @commands.has_any_role(Config().BOTMASTER_ROLE_ID)
    async def storagedump(self, ctx, name):
        plugin = converter.get_plugin_by_name(self.bot, name)
        if plugin is None:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send("Plugin {} not found.".format(name))
            return
        await ctx.message.add_reaction(Lang.CMDSUCCESS)

        dump = pprint.pformat(Storage.get(plugin), indent=4).split("\n")
        prefix = ""
        if not Storage.has_structure(plugin):
            prefix = "**Warning: plugin {} does not have a storage structure.** " \
                     "This is the default storage.".format(name)
        for el in utils.paginate(dump,
                                 prefix=prefix,
                                 msg_prefix="```",
                                 msg_suffix="```"):
            await ctx.send(el)

    @commands.command(name="configdump",
                      help="Dumps plugin config",
                      usage="<plugin name>")
    @commands.has_any_role(Config().BOTMASTER_ROLE_ID)
    # NOTE: Will be invoked via "!dsc set config"
    async def configdump(self, ctx, name):
        plugin = converter.get_plugin_by_name(self.bot, name)
        if plugin is None:
            await ctx.message.add_reaction(Lang.CMDERROR)
            await ctx.send("Plugin {} not found.".format(name))
            return
        await ctx.message.add_reaction(Lang.CMDSUCCESS)

        dump = pprint.pformat(Config.get(plugin), indent=4).split("\n")
        prefix = ""
        if not Config.has_structure(plugin):
            prefix = "**Warning: plugin {} does not have a config structure.** " \
                     "This is the default config.".format(name)
        for el in utils.paginate(dump,
                                 prefix=prefix,
                                 msg_prefix="```",
                                 msg_suffix="```"):
            await ctx.send(el)
Example #32
0
 async def fantasy_set_linkb(self, ctx, link):
     link = utils.clear_link(link)
     self.fantasy_conf()['league_link_b'] = link
     Config().save(self)
     await ctx.send(self.fantasy_lang('linkb_set'))
Example #33
0
#!/usr/bin/env python

"""
Real time log files watcher supporting log rotation.

Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>
License: MIT
"""
from conf import Config
import os
import time
import errno
import stat
import smtplib

config = Config()
conf =  config.getconfig('acl-hive.cfg')

log_location=conf['mnt_log_location']
smtp_host=conf['mnt_smtp_host']
smtp_user=conf['mnt_smtp_user']
smtp_passwd=conf['mnt_smtp_passwd']
sender = conf['mnt_sender']
receivers = conf['mnt_receivers'].split(',')

class LogWatcher(object):
    """Looks for changes in all files of a directory.
    This is useful for watching log file changes in real-time.
    It also supports files rotation.

    Example:
Example #34
0
 async def dsc_set_comm_b(self, ctx, user: discord.Member):
     """Sets the Commissioner for League B"""
     self.fantasy_conf()['commish_id_b'] = user.id
     Config().save(self)
     await ctx.send(self.fantasy_lang('new_commish_b_set'))
Example #35
0
async def write_debug_channel(bot: Bot, message):
    """Writes the given message or embed to the debug channel"""
    await _write_to_channel(bot, Config().DEBUG_CHAN_ID, message, "debug")
Example #36
0
# -*- coding: utf-8 -*-
import os

from conf import Config
from data import get_dataloader
from train import train
from validation import val
from model import Model
from torch import nn

os.environ["CUDA_VISIBLE_DEVICES"] = "4"

if __name__ == "__main__":
    conf = Config()
    for i in range(1):
        datasets_train, datasets_val = get_dataloader(conf)
        model = Model(conf).to(conf.device)
        model = nn.DataParallel(model)
        opt = optim.Adam(model.parameters(),
                         lr=conf.LR,
                         weight_decay=conf.weight_decay)
        criterion = nn.CrossEntropyLoss(weight=conf.weight).to(conf.device)
        loss_logs1, loss_logs2 = [], []
        acc_logs1, acc_logs2 = [], []
        for epoch in range(conf.max_epoch):
            train(opt, criterion, datasets_train, model, i, epoch, loss_logs1,
                  acc_logs1)
            val(criterion, datasets_val, model, i, epoch, loss_logs2,
                acc_logs2)
Example #37
0
    randRGB_start = 30
    randRGB_end = 120

    def baseDraw(self, drawer):
        '''波浪线'''
        pass

    def run(self,
            img_num=1,
            font_path='./fonts/times.ttf',
            bg_color=(165, 165, 165),
            text_color=None):  # bg_color=(165, 165, 165)
        for index in range(img_num):
            self.save_img(index,
                          font_path,
                          bg_color=bg_color,
                          text_color=text_color)


if __name__ == '__main__':
    config = Config(code_type=400)

    # ImgCoder(config).run(img_num=1)
    # WxImgCoder(config).run()

    # create_verifycode_img(1, config)

    for i in range(2):
        # Process(target=ImgCoder(config).run(img_num=1)).start()
        Process(target=create_verifycode_img, args=(5, config)).start()
Example #38
0
from conf import Config
from lib.gcp.util.Logger import LoggerFactory
from lib.core.TaskRun import TaskRun
import lib.gcp.handler.bigfish.UrlParserHandler
import lib.gcp.handler.alawar.UrlParserHandler
from lib.core.TimeScheduler import TimeScheduler
from apscheduler.threadpool import ThreadPool
from lib.gcp.handler.TagHandler import TagHandler
from lib.gcp.handler.GenreEnnameHandler import GenreEnnameHandler

if __name__ == '__main__':
 
    logger = LoggerFactory.getLogger()
    
    #thread pool
    configs = Config.getConfig()
    poolmin = configs['sys']['threadpool.min']
    poolmax = configs['sys']['threadpool.max']
    keep = configs['sys']['threadpool.keep']
    pool = ThreadPool(poolmin,poolmax,keep);
    
    logger.info("Ready to start Task !");
    TaskRun.getInstance().start(treadpool= pool);
    logger.info("Start Task end!");
    
    logger.info("Ready to start Scheduler !");
    TimeScheduler.getInstance().init(pool);
    TimeScheduler.getInstance().registerInterval(lib.gcp.handler.alawar.UrlParserHandler.UrlParserHandler(),
                                                 days = 1,start_date ='2014-11-02 00:00:00')
    
    TimeScheduler.getInstance().registerInterval(lib.gcp.handler.bigfish.UrlParserHandler.UrlParserHandler('game'),
Example #39
0
def go(Admin, Password):
    file = open('CONFIG.txt', 'a')
    file.close()
    from conf import Config
    manager = Config()
    manager.setup_main_db()
    manager.set_users_db()
    from conf import load_in
    settings = load_in()
    conn = sqlite3.connect(settings['MAIN_DB'])
    conn.execute("CREATE TABLE IF NOT EXISTS {tn} (id INTEGER,"
                 "email TEXT,"
                 "email_verified INTEGER,"
                 "username TEXT,"
                 "password TEXT,"
                 "data_tables TEXT,"
                 "logged_in INTEGER, "
                 "subscribed INTEGER,"
                 "charts TEXT,"
                 "models TEXT,"
                 "groups TEXT,"
                 "first_name TEXT,"
                 "last_name TEXT,"
                 "friends TEXT,"
                 "active INTEGER,"
                 "reset_request INTEGER,"
                 "data_sources TEXT,"
                 "projects TEXT,"
                 "is_authenticated INTEGER,"
                 "PRIMARY KEY (username))".format(tn='users'))
    conn.commit()
    conn.execute("""INSERT INTO users VALUES ('{id}',
                          '{email}',
                          '{email_verified}',
                          '{username}',
                          '{password}',
                          '{data_tables}',
                           {logged_in},
                           {subscribed},
                           '{charts}',
                           '{models}',
                           '{groups}',
                           '{first_name}',
                           '{last_name}',
                           '{friends}',
                           {active},
                           {reset_request},
                           '{data_sources}',
                           '{projects}',
                           {is_authenticated})""".format(
        id=1,
        email='*****@*****.**',
        email_verified=1,
        username=Admin,
        password=make_password(Password),
        data_tables='',
        logged_in=1,
        subscribed=0,
        charts="",
        models="",
        groups="",
        first_name="",
        last_name="",
        friends="",
        active=1,
        reset_request=0,
        data_sources="",
        projects="",
        is_authenticated=0))
    conn.commit()
    conn.close()
    from Manager._FileController import FileController
    FileController().file_handler(Admin)
Example #40
0
 def cog_check(self, ctx):
     role = discord.utils.get(ctx.author.roles,
                              id=Config().BOTMASTER_ROLE_ID)
     if role is None:
         raise commands.MissingRole(Config().BOTMASTER_ROLE_ID)
     return True
Example #41
0
from conf import Config

from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base

config = Config("test.yaml")


class SourceDB():
    def __init__(self):
        self.base = automap_base()
        self.engine = create_engine(config.sourceURI)
        self.base.prepare(self.engine, reflect=True)
        self.session = Session(self.engine, autocommit=False, autoflush=False)


class DestinationDB():
    def __init__(self):
        self.base = automap_base()
        self.engine = create_engine(config.destinationURI)
        self.base.prepare(self.engine, reflect=True)
        self.session = Session(self.engine, autocommit=False, autoflush=False)
Example #42
0
 def get_api_client(self):
     """Returns a client to access Google Sheets API for the dsc contestdoc sheet"""
     return sheetsclient.Client(Config.get(self)['contestdoc_id'])
     pass
Example #43
0
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.options
import tornado
import os
from urls import url_patterns
from tornado.options import options, define
from conf import Config

sh_connection = Config()
define("port",
       default=sh_connection.web['port'],
       help="run on the given port",
       type=int)


class PortalSystemApplication(tornado.web.Application):
    def __init__(self):
        handlers = url_patterns
        settings = dict(
            debug=True,
            autoreload=True,
            # cookie_secret=sh_connection.auth_system['cookie_secret'],
            # xsrf_cookies=True,
            # login_url=sh_connection.packages['AUTHENTICATE_SYSTEM'] + '/user/login',
            # logout_url=sh_connection.packages['AUTHENTICATE_SYSTEM'] + '/user/logout',
            # packages=sh_connection.packages,
            template_path=os.path.join(os.path.dirname(__file__), "template"),
            static_path=os.path.join(os.path.dirname(__file__), "static"))
        tornado.web.Application.__init__(self, handlers, **settings)