Exemple #1
0
def receive():
    try:
        run(request.json)
        return "Hello"
    except Exception as e:
        print(e)
        return "error of some description"
Exemple #2
0
def start(name):
    f = open('auth.txt', 'w')
    f.write(user_txt.get() + '\n')
    f.write(pwd_txt.get() + '\n')
    f.write(name.get())
    f.close()
    bot.run()
def receive():
    try:
        update = request.json
        run(update)
        return ""
    except Exception as e:
        print(e)
        return ""
def run_bot(bot=bot):
    rpc = GrapheneAPI(config.wallet_host, config.wallet_port, "", "")
    if rpc.is_locked():
        rpc.unlock(config.wallet_password)

    print(str(datetime.now()) + "| Starting bot...")
    bot.init(config)
    time.sleep(6)
    print(str(datetime.now()) + "| Running the bot")
    bot.run()
Exemple #5
0
def lambda_handler(event, context):
    # Load configuration variables
    f = open("config.json", "r")
    c = json.loads(f.read())

    path = ""
    jdata = {}
    if event:
        if "queryStringParameters" in event and event[
                "queryStringParameters"] is not None:
            if "update" in event["queryStringParameters"]:
                path = "update"

        if event["body"] and event["body"] != "":
            jdata = json.loads(event["body"])

    # Need to find path for webhook updates. Either /update or ?update.
    print(event, context)
    r = bot.run(c, jdata, path)

    if r:
        if "body" in r:
            if "statusCode" in r:
                return {'statusCode': r["statusCode"], 'body': r["body"]}
            else:
                return {'statusCode': 200, 'body': r["body"]}
        else:
            if "statusCode" in r:
                return {'statusCode': r["statusCode"], 'body': ""}

    return {'statusCode': 200, 'body': "success"}
Exemple #6
0
def main():
    logging.basicConfig(
        level=config.log_lvl,
        format="%(name)s [%(levelname)s] [%(asctime)s]: %(message)s",
    )

    try:
        os.mkdir(config.db_dir, 0o755)
    except FileExistsError:
        pass
    except Exception as e:
        logging.error("Couldn't create dir {}. Message: {}".format(
            config.db_dir, e))
        exit(1)

    run()

    exit(0)
Exemple #7
0
def getData():
    data = request.json
    app.logger.debug(data)
    if data['type'] == 'confirmation' and data['group_id'] == os.environ['group_id']:
        return os.environ['access_string']

    # process responce
    app.logger.debug(bot.run(data, make_request))

    # send answer
    return "ok"
def catch_all(path):
    get_update = request.args.get('update')
    if get_update is not None:
        if not path:
            path = "update"

    try:
        jdata = request.get_json(force=True)
    except:
        jdata = {}

    r = bot.run(cfg, jdata, path)

    if r:
        if "body" in r:
            if "statusCode" in r:
                return r["body"], r["statusCode"]
            else:
                return r["body"]
        else:
            if "statusCode" in r:
                return "", r["statusCode"]

    return ""
Exemple #9
0
def main():
    bot.run()
Exemple #10
0
                            "schedule in HSE")
    parser.add_argument('action',
                        type=str,
                        help="run|update_schedules|init_db")
    parser.add_argument('--token',
                        '-t',
                        type=str,
                        default="TEST",
                        help="api token name (from config) for access to bot")
    parser.add_argument('--workers',
                        '-w',
                        type=int,
                        default=10,
                        help="number of workers for running bot")
    return parser.parse_args()


if __name__ == '__main__':
    args = parse_argv()
    if args.action == "update_schedules":
        bot.update_schedules.main()
    elif args.action == "init_db":
        bot.init_db()
    elif args.action == "run":
        bot.run(token=TOKENS.get(args.token.upper(), TOKENS["TEST"]),
                logger_level=LOGGING_LEVELS.get(args.token.upper(),
                                                logging.DEBUG),
                workers=args.workers)
    else:
        print(f"Wrong command: {args.action}", file=sys.stderr)
Exemple #11
0
            else:
                with open(i) as f:
                    yield json.load(f)

    async def wait_for_slot_in_gateway_queue():
        try:
            async with aiohttp.ClientSession() as session:
                async with session.post('http://127.0.0.1:7023/',
                                        timeout=5) as resp:
                    wait_until = float(await resp.text())
                    cur_time = time.time()
                    sleep_time = wait_until - cur_time
                    if sleep_time > 0:
                        print(
                            f'Sleeping in gateway queue for {sleep_time} seconds'
                        )
                        await asyncio.sleep(sleep_time)
        except aiohttp.ClientConnectorError:
            print('Could not find gateway queue to connect to')

    asyncio.get_event_loop().run_until_complete(
        wait_for_slot_in_gateway_queue())

    parameters = retrieve_parameters()

    warnings.simplefilter('default')
    logging.basicConfig(level=logging.INFO)
    logging.getLogger('discord.state').setLevel(logging.ERROR)

    bot.run(parameters)
Exemple #12
0
    for k in kinders.values():
        sheet[ALPH[last_col + 1] + k[0]] = make_count_str(k[3], "\n")
    sheet[ALPH[last_col + 1] + str(int_offset - 1)] = "Итог"

    xlsx.save(stream)
    xlsx.close()
    stream.seek(0)
    return stream.getvalue()


def make_count_str(data, div=""):
    s = ""
    for t, c in Counter(data).items():
        s += (str(c) + "-" + t) if c > 1 else t
        s += div
    return s


if __name__ == '__main__':
    bot_listener = Thread(target=lambda: bot.run(tele_bot), daemon=True)
    bot_db_sender = Thread(target=lambda: bot.db_auto_sender(tele_bot),
                           daemon=True)
    bot_zip_sender = Thread(target=lambda: bot.zip_auto_sender(tele_bot),
                            daemon=True)

    bot_listener.start()
    bot_zip_sender.start()
    bot_db_sender.start()

    app.run(host=HOST, port=PORT)
Exemple #13
0
with open('RAM map.asm', 'r') as f:
    for line in f:
        if 'VRAM during main gameplay' in line:
            break

        match = re.match(r'\s*\$([0-9A-F]+)(?::([0-9A-F]+))?(:|\.\.).+', line,
                         re.IGNORECASE)
        if not match:
            continue

        address = int(match[1], 16)
        if match[2]:
            address = address << 16 | int(match[2], 16)
        else:
            address |= 0x7E0000

        ramMap[address] = match[0]

ramMapKeys = list(ramMap.keys())

# Load miscellaneous JSON files
with open('pokemon.json', 'r') as f:
    pokemon = json.load(f)

# Start daemons
for task in daemons.tasks:
    bot.loop.create_task(task(bot))

# Main #
bot.run(args.config['token'])
Exemple #14
0
            element = WebDriverWait(browser, 10).until(
                EC.presence_of_element_located((By.TAG_NAME, "div")))
            if not element:
                logging.error('[{}/{}] Proxy could not load URL: {}'.format(
                    i + 1, len(proxies), PRODUCT_URL))

            logging.info('[{}/{}] Proxy Test Success'.format(
                i + 1, len(proxies)))

            faceless_browsers.append({
                'browser': browser,
                'user_agent': user_agent,
                'proxy': proxy
            })
        except TimeoutException:
            logging.error('[{}/{}] Proxy Time-out: {}'.format(
                i + 1, len(proxies), proxy))
            continue
        except Exception as e:
            logging.error('[{}/{}] {}'.format(i + 1, len(proxies), e))
            continue

    if len(faceless_browsers) > 0:
        print("\nWorking proxies: {} - starting script..".format(
            len(faceless_browsers)))

        run(PRODUCT_URL, faceless_browsers)
    else:
        print("\nNo working proxies found.")
Exemple #15
0
from bot import run

run()
Exemple #16
0
import praw
import bot

#getting the list of comments id's replied to
comments_replied = bot.get_comments_replied()

#logs in and authenticates your bot
#login is in the bot.py file
login = bot.authenticate()

#runs forever so long as you are running
#your script
while True:
    bot.run(login, comments_replied)
  except Exception, e:
    bot_logger(['error', e])
  
  min_elapsed += 600

  bot_logger('done')
  
  #TODO 
  #POST TO BLOCKCHAIN VIA XCP FEED
  #FORMAT:
  #"REQ: command[0] \n"
  #"REPLY: c.reply()"

def runloop(self)
  '''Default run loop for blocktrailbot'''
  reddit_msgs.refresh() #refresh feed with new data 

  for thing in reddit_msgs.children:
    if thing.was_comment: #if the current thing is a comment get ready to reply
      self.parsecmd( thing.body , '@@' ) #commands are prefixed with '@@' and parsed from comment body
      self.parseargs( thing.body, '@') #args are prefixed with '@' and parsed from comment body 
      self.runtask( self.command , self.args + [thing] ) 

bot = bot.BasicBot(600, runloop, parser ) #create bot
bot.register('examine', examine) #register task to run

while True:
  bot.run() #Run one iteration
  bot.sleep() #Sleep
Exemple #18
0
def main():
    bot = Central()
    bot.run()
Exemple #19
0
def run():
    result = bot.run()
    return json.dumps(result)
Exemple #20
0
import bot

bot.run(config_path='config.json')
Exemple #21
0
import praw
import bot

reddit = bot.authenticate()
while True:
    try:
        bot.run(reddit)
    except Exception as e:
        print(e)
        continue
Exemple #22
0
def main():
    bot = MyWXBot()
    bot.DEBUG = True
    bot.conf['qr'] = 'tty'
    bot.run()
Exemple #23
0
async def __main__():

	try:
		ipd_logger     = setup_logs('ipd',     'logs/ipd.log')
		opts_logger    = setup_logs('opts',    'logs/ipd-blacklist.log')
		discord_logger = setup_logs('discord', 'logs/ipd-discord.log')

		config = load_config()

		bot = config['bot'] = ImperialProbeDroid(command_prefix=config['prefix'])
		bot.config = config
		bot.logger = ipd_logger
		bot.redis = config.redis

		from embed import EmbedManager
		bot.embed = EmbedManager(bot)

		from crinolo import CrinoloStats
		bot.stats = CrinoloStats(BaseUnit.get_ship_crews())

		from boterrors import BotErrors
		bot.errors = BotErrors(bot)

		from botoptions import BotOptions
		bot.options = BotOptions(bot)

		import client
		bot.client = client.SwgohClient(bot)

		from chatcog import ChatCog
		bot.add_cog(ChatCog(bot))

		from ticketscog import TicketsCog
		bot.add_cog(TicketsCog(bot))

		from twcog import TWCog
		bot.add_cog(TWCog(bot))

		from tbcog import TBCog
		bot.add_cog(TBCog(bot))

		token = config['token']
		if 'env' in config:
			env = config['env']
			token = config['tokens'][env]

		try:
			bot.run(token)

		except Exception as err:
			print('Run was interrupted!')
			print(err)
			print(traceback.format_exc())

		await bot.logout()
		print('Bot quitting!')

	except Exception as err:
		print('bot initialization interrupted!')
		print(err)
		print(traceback.format_exc())
Exemple #24
0
import pyximport; pyximport.install()
import bot as sky
 
sky.run()
 def onStarted(self, button):
     if self.ui.widgets.status.text == "Status: stopped":
         bot.run()
         self.ui.widgets.status.set_text("Status: started")
     else:
         self.ui.widgets.status.set_text("Status: stopped")
Exemple #26
0
import pyximport
pyximport.install()
import bot as sky

sky.run()
Exemple #27
0
def main():
    load_dotenv()
    bot.run()
if sys.version_info <= (3, 0):
    sys.stdout.write("Could not start: requires Python 3.x, not Python 2.x\n")
    sys.exit(1)

if __name__ == '__main__':
    from bot import run
    from config import PRODUCT_URL, PROXIES, _V, USE_PROXIES

    url = PRODUCT_URL
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(levelname)s: %(message)s')

    # General output information before start, (tbh need to art ASCII art)
    print(
        "\nAdidas Multi Session by YZY.io (BETA) \n"
        "Thank you for testing the script, you are on version {}\n".format(_V))
    print("Proxies loaded: {}".format(len(PROXIES)))

    if USE_PROXIES and len(PROXIES) == 0:
        print("USE_PROXIES = True but no proxies loaded..")
        sys.exit(1)

    if PRODUCT_URL is not '' or not None:
        url = PRODUCT_URL
        print("Product URL: {}".format(PRODUCT_URL))
    else:
        url = input("Product URL: ")

    run(url)
Exemple #29
0
with open('RAM map.asm', 'r') as f:
    for line in f:
        if 'VRAM during main gameplay' in line:
            break

        match = re.match(r'\s*\$([0-9A-F]+)(?::([0-9A-F]+))?(:|\.\.).+', line, re.IGNORECASE)
        if not match:
            continue

        address = int(match[1], 16)
        if match[2]:
            address = address << 16 | int(match[2], 16)
        else:
            address |= 0x7E0000

        ramMap[address] = match[0]

ramMapKeys = list(ramMap.keys())

# Load miscellaneous JSON files
with open('pokemon.json', 'r') as f:
    pokemon = json.load(f)

# Start daemons
for task in daemons.tasks:
    bot.loop.create_task(task(bot))

# Main #
bot.run(args.config['token'])
Exemple #30
0
def loop():
    try:
        run()
    except:
        loop()
Exemple #31
0
def run_bot():
    return bot.run()
Exemple #32
0
def main():
    promserver_thread = threading.Thread(target=promserver.run)
    promserver_thread.start()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(bot.run())
Exemple #33
0
import bot

bot.run()
Exemple #34
0
def main():
    bot = HispaTroll()
    bot.run()
Exemple #35
0
    def retrieve_parameters():
        for i in sys.argv[1:]:
            if re.fullmatch(r'\w+\.env', i):
                yield json.loads(os.environ.get(i[:-4]))
            elif i.startswith('{') and i.endswith('}'):
                yield json.loads(i)
            else:
                with open(i) as f:
                    yield json.load(f)

    async def wait_for_slot_in_gateway_queue():
        try:
            async with aiohttp.ClientSession() as session:
                async with session.post('http://127.0.0.1:7023/',
                                        timeout=5) as resp:
                    wait_until = float(await resp.text())
                    cur_time = time.time()
                    sleep_time = wait_until - cur_time
                    if sleep_time > 0:
                        print(
                            f'Sleeping in gateway queue for {sleep_time} seconds'
                        )
                        await asyncio.sleep(sleep_time)
        except aiohttp.ClientConnectorError:
            print('Could not find gateway queue to connect to')

    asyncio.get_event_loop().run_until_complete(
        wait_for_slot_in_gateway_queue())

    bot.run(retrieve_parameters())
import bot

# Load the configuration
import config

if __name__ == '__main__':

    # initialize the bot infrastructure with our settings
    bot.init(config)

    # execute the bot(s) just once
    bot.run()
Exemple #37
0
    }

configRepo = ConfigRepository(get_default_config)
player = Player()

def on_reboot():
    if (env.is_windows): # windows
        os.system('youtube-dl --rm-cache-dir')
        os.system('git pull')
        os.system('start startup.py')
        os.kill(os.getpid(), 9)
    else: # linux
        os.system('git pull')
        os.kill(os.getpid(), 9)


extensions = [
    PlayerExtension(player),
    YoutubeExtension(player, configRepo),
    GachiExtension(player, configRepo),
    AliasExtension(configRepo),
    BotExideExtension(on_reboot),
    VkExtension(player, configRepo)
]

bot = BotExide(extensions, configRepo)
try:
    bot.run(env.discord_token)
finally:
    for e in extensions:
        e.dispose()
Exemple #38
0
verbose = False
for o, a in opts:
	if o == "-v":
		verbose = True
	elif o in ("-h", "--help"):
		alphaBotUtility.usage()
		sys.exit()
	elif o in ("-k", "--handleOK"):
		handleOK = True
	elif o in ("-d", "--debug"):
		debug = True
	elif o in ("-r", "--report"):
		report.reportDirectory = str(a)
	elif o in ("-e", "--explorer"):
		report = str(a)
		reportExplorer.analyseReport(report)
		sys.exit()
	elif o in ("-l", "--exploreLatest"):
		reportExplorer.analyseReport(None)
		sys.exit()
	else:
		assert False, "unhandled option"

captchaDir = "./captcha"
if not os.path.exists(captchaDir):
    os.makedirs(captchaDir)

initialization.initialize(handleOK=handleOK)

bot.run(handleOK=handleOK, debug=debug)