Beispiel #1
0
    def __init__(self, login, password,
                 like_per_day=1000,
                 media_max_like=10,
                 media_min_like=0,
                 follow_per_day=0,
                 follow_time=5 * 60 * 60,
                 unfollow_per_day=0,
                 comments_per_day=0,
                 tag_list=['cat', 'car', 'dog'],
                 max_like_for_one_tag=5,
                 log_mod=0):

        super(InstaBot, self).__init__()

        self.time_in_day = 24 * 60 * 60
        # Like
        self.like_per_day = like_per_day
        if self.like_per_day != 0:
            self.like_delay = self.time_in_day / self.like_per_day

        # Follow
        self.follow_time = follow_time
        self.follow_per_day = follow_per_day
        if self.follow_per_day != 0:
            self.follow_delay = self.time_in_day / self.follow_per_day

        # Unfollow
        self.unfollow_per_day = unfollow_per_day
        if self.unfollow_per_day != 0:
            self.unfollow_delay = self.time_in_day / self.unfollow_per_day

        # Comment
        self.comments_per_day = comments_per_day
        if self.comments_per_day != 0:
            self.comments_delay = self.time_in_day / self.comments_per_day

        # Don't like if media have more than n likes.
        self.media_max_like = media_max_like
        # Don't like if media have less than n likes.
        self.media_min_like = media_min_like
        # Auto mod seting:
        # Default list of tag.
        self.tag_list = tag_list
        # Get random tag, from tag_list, and like (1 to n) times.
        self.max_like_for_one_tag = max_like_for_one_tag

        self.media_by_tag = []

        log_string = 'Insta Bot v1.1 start at %s:' % \
                     (datetime.datetime.now().strftime("%d.%m.%Y %H:%M"))
        logger.info(log_string)

        session = requests.Session()
        # create a new user and log the user into the session
        self.user = User(session, login, password)
        self.user.login()
        self.API = API(self.user)

        signal.signal(signal.SIGTERM, self.cleanup)
        atexit.register(self.cleanup)
Beispiel #2
0
 def strategy_loop(self, color):
     api = API(color)
     while True:
         try:
             data = yield self.stream.read_until('\n')
             data = json.loads(data)
             if data.get('message') == 'down':
                 break
             turn = api.turn(data)
             yield self.stream.write(self.dump_message(turn))
         except StreamClosedError:
             IOLoop.instance().stop()
Beispiel #3
0
class Media(object):
    def __init__(self, user, tag_list):
        self.user = user
        self.API = API(self.user)
        self.tag_list = tag_list
        self.current_media = []

        # TODO max number of items to remember, when too many reset pointer

    def get_next_item(self):
        return self.API.get_media_id_by_tag(random.choice(self.tag_list))[0]

    def get_media(self):
        return self.API.get_media_id_by_tag(random.choice(self.tag_list))
Beispiel #4
0
class Client:
    def __init__(self, loop, solution_id):
        self.solution_id = solution_id
        self.api = API()
        self.loop = loop
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
        self.sock.setblocking(False)

    async def ask_for_grant(self, reader, writer):
        await self.send_to_server({'solution_id': self.solution_id}, writer)

        data = await reader.readuntil(b'\n')
        data = json.loads(data)
        grant = data.get('message') == 'beginning'
        return grant, reader

    async def send_to_server(self, message, writer):
        message = json.dumps(message).encode('unicode_escape') + b'\n'
        writer.write(message)
        return await writer.drain()

    async def start(self, host, port):
        reader, writer = await open_connection(host, port)
        grant, reader = await self.ask_for_grant(reader, writer)
        while grant:
            data = await reader.readuntil(b'\n')
            data = json.loads(data)

            if data.get('message') == 'down':
                break

            actions = self.api.generate_actions(data)
            await self.send_to_server(actions, writer)
Beispiel #5
0
    def set(_id: str, status: str) -> None:  # TODO: Annotate status
        if API.db is not None:
            API.db.jobs.update_one({"_id": _id}, {"$set": {"status": status}})
        else:
            client = API.create_mongo()
            db = client.dune

            db.jobs.update_one({"_id": _id}, {"$set": {"status": status}})

            client.close()
Beispiel #6
0
class WorldHandler(object):
    api = API()
    red_client = None
    blue_client = None
    ticks_count = int(os.environ.get('TICKS_COUNT', 4000))
    result = []

    client_player = {}

    @tornado.gen.coroutine
    def connect(self, stream, address):
        current_client = Client(stream)
        try:
            messages = yield current_client.read_messages()
            solution_id = int(messages.get('solution_id'))
        except (ValueError, TypeError):
            solution_id = None
        except StreamClosedError:
            solution_id = None
        current_client.set_solution_id(solution_id)

        if self.red_client is None:
            self.red_client = current_client
        elif self.blue_client is None:
            self.blue_client = current_client
            self.start()
        else:
            pass

    def shutdown(self):
        if not self.blue_client.is_close:
            self.blue_client.send({'message': 'down'})
            self.blue_client.close()

        if not self.red_client.is_close:
            self.red_client.send({'message': 'down'})
            self.red_client.close()

        tornado.ioloop.IOLoop.instance().stop()

    @staticmethod
    def write_result(data):
        f = open(
            '{}/../visualizer/game.js'.format(
                os.path.dirname(os.path.realpath(__file__))), 'w')
        f.write("var data = ")
        f.write(json.dumps(data, indent=4))
        f.write(";")
        f.close()

    @tornado.gen.coroutine
    def start(self):
        self.api.create_players(self.red_client, self.blue_client)
        self.red_client.send({'message': 'beginning', 'color': 'FIRST_PLAYER'})
        self.blue_client.send({
            'message': 'beginning',
            'color': 'SECOND_PLAYER'
        })

        for _ in range(0, self.ticks_count):
            blue_message = []
            if not self.blue_client.is_close:
                self.blue_client.send(
                    self.api.get_world_state_for(self.blue_client))
                blue_message = yield self.blue_client.read_messages()

            red_message = []
            if not self.red_client.is_close:
                self.red_client.send(
                    self.api.get_world_state_for(self.red_client))
                red_message = yield self.red_client.read_messages()

            self.api.apply_commands(blue_message, self.blue_client)
            self.api.apply_commands(red_message, self.red_client)
            self.api.tick()
            self.result.append(self.api.get_visio_state())

        try:
            self.write_result({
                'config': settings.BUILDING_VISIO,
                'game_data': self.result,
                'players': {
                    "FIRST_PLAYER": self.red_client.solution_id,
                    "SECOND_PLAYER": self.blue_client.solution_id,
                }
            })
        except Exception as e:
            print e

        self.shutdown()
#! /usr/bin/env python
# coding:utf-8

import os

from core.api import API

API.init()

if __name__ == "__main__":
    port = int(
        os.environ.get(
            'PORT',
            5000
        )
    )
    API.app.run(
        host='0.0.0.0',
        port=port
    )
Beispiel #8
0
# -*- coding: utf-8 -*-

# inputs

import sys
import platform
import argparse

from core.api import API
from core.api import OSs
from core.api import Methods
from core.api import Formats
from core.interface import print_line
from core.interface import print_logo

api = API()


def create_parser():
    """
    Create argument parser.
    :return: parser
    """

    parser = argparse.ArgumentParser(description="SurePatch Argument Parser")

    parser.add_argument('--action',
                        type=str,
                        required=False,
                        help='Define action: '
                        'save_config, '
Beispiel #9
0
 def __init__(self, user, media):
     self.user = user
     self.media = media
     self.API = API(self.user)
Beispiel #10
0
 def __init__(self, user, tag_list):
     self.user = user
     self.API = API(self.user)
     self.tag_list = tag_list
     self.current_media = []
Beispiel #11
0
 def __init__(self, loop, solution_id):
     self.solution_id = solution_id
     self.api = API()
     self.loop = loop
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
     self.sock.setblocking(False)
Beispiel #12
0
from core.api import API
from core.api import OSs
from core.api import Methods
from core.api import Formats
from core.interface import print_line
from core.interface import print_logo
from core.os_parameters import get_os_platform
from core.os_parameters import get_os_version
from core.os_parameters import get_os_sp
from core.os_parameters import get_os_release
from core.os_parameters import get_os_machine

# -------------------------------------------------------------------------
# Define main API
# -------------------------------------------------------------------------
surepatch_api = API()

# -------------------------------------------------------------------------
# Create command line parser
# -------------------------------------------------------------------------

def create_parser():
    """
    Create argument parser.
    :return: parser
    """

    parser = argparse.ArgumentParser(
        description="SurePatch Argument Parser")

    parser.add_argument(
Beispiel #13
0
class InstaBot(object):
    """
    Instagram bot v 1.0
    like_per_day=1000 - How many likes set bot in one day.

    media_max_like=10 - Don't like media (photo or video) if it have more than
    media_max_like likes.

    media_min_like=0 - Don't like media (photo or video) if it have less than
    media_min_like likes.

    tag_list = ['cat', 'car', 'dog'] - Tag list to like.

    max_like_for_one_tag=5 - Like 1 to max_like_for_one_tag times by row.

    log_mod = 0 - Log mod: log_mod = 0 log to console, log_mod = 1 log to file,
    log_mod = 2 no log.

    https://github.com/LevPasha/instabot.py
    """
    # List of user_id, that bot follow
    bot_follow_list = []

    # Other.
    media_by_tag = 0

    # For new_auto_mod
    next_iteration = {"Like": 0, "Follow": 0, "Unfollow": 0, "Comments": 0}

    def __init__(self, login, password,
                 like_per_day=1000,
                 media_max_like=10,
                 media_min_like=0,
                 follow_per_day=0,
                 follow_time=5 * 60 * 60,
                 unfollow_per_day=0,
                 comments_per_day=0,
                 tag_list=['cat', 'car', 'dog'],
                 max_like_for_one_tag=5,
                 log_mod=0):

        super(InstaBot, self).__init__()

        self.time_in_day = 24 * 60 * 60
        # Like
        self.like_per_day = like_per_day
        if self.like_per_day != 0:
            self.like_delay = self.time_in_day / self.like_per_day

        # Follow
        self.follow_time = follow_time
        self.follow_per_day = follow_per_day
        if self.follow_per_day != 0:
            self.follow_delay = self.time_in_day / self.follow_per_day

        # Unfollow
        self.unfollow_per_day = unfollow_per_day
        if self.unfollow_per_day != 0:
            self.unfollow_delay = self.time_in_day / self.unfollow_per_day

        # Comment
        self.comments_per_day = comments_per_day
        if self.comments_per_day != 0:
            self.comments_delay = self.time_in_day / self.comments_per_day

        # Don't like if media have more than n likes.
        self.media_max_like = media_max_like
        # Don't like if media have less than n likes.
        self.media_min_like = media_min_like
        # Auto mod seting:
        # Default list of tag.
        self.tag_list = tag_list
        # Get random tag, from tag_list, and like (1 to n) times.
        self.max_like_for_one_tag = max_like_for_one_tag

        self.media_by_tag = []

        log_string = 'Insta Bot v1.1 start at %s:' % \
                     (datetime.datetime.now().strftime("%d.%m.%Y %H:%M"))
        logger.info(log_string)

        session = requests.Session()
        # create a new user and log the user into the session
        self.user = User(session, login, password)
        self.user.login()
        self.API = API(self.user)

        signal.signal(signal.SIGTERM, self.cleanup)
        atexit.register(self.cleanup)

    def cleanup(self):
        # Unfollow all bot follow
        if len(self.bot_follow_list) > 0:
            for f in self.bot_follow_list:
                log_string = "Try to unfollow: %s" % (f[0])
                logger.info(log_string)
                self.API.unfollow(f[0])
                self.bot_follow_list.remove(f)

        # Logout
        if self.user.login_status:
            self.user.logout()

    def new_auto_mod(self):
        # ------------------- Get media_id -------------------
        if len(self.media_by_tag) == 0:
            self.media_by_tag = self.API.get_media_id_by_tag(random.choice(self.tag_list))

        media = Media(self.user, self.tag_list)
        # ------------------- Like -------------------
        like_bot = LikeBot(self.user, media, self.media_max_like, self.media_min_like)
        like_bot.run(3)
        # ------------------- Follow -------------------
        follow_bot = FollowBot(self.user, media)
        follow_bot.run(3)
        # ------------------- Comment -------------------
        comment_maker = CommentMaker()
        comment_bot = CommentBot(self.user, media, comment_maker)
        comment_bot.run(3)
        # ------------------- Unfollow All -------------------
        self.new_auto_mod_unfollow()
        # ------------------- Unfollow Non Folbacks -------------------
        # self.new_auto_mod_unfollow()

        # Bot iteration in 1 sec
        # print("Tic!")

    def new_auto_mod_unfollow(self):
        if time.time() > self.next_iteration["Unfollow"] and \
                        self.unfollow_per_day != 0 and len(self.bot_follow_list) > 0:
            for f in self.bot_follow_list:
                if time.time() > (f[1] + self.follow_time):

                    log_string = "Try to unfollow: %s" % (f[0])
                    logger.info(log_string)

                    if self.API.unfollow(f[0]):
                        self.bot_follow_list.remove(f)
                        self.next_iteration["Unfollow"] = time.time() + self.add_time(self.unfollow_delay)

    def add_time(self, time):
        """ Make some random for next iteration"""
        return time * 0.9 + time * 0.2 * random.random()