Exemple #1
0
	def onSourceRowChanged(self, sourceModel, sourcePath, sourceIter):
		# get needed values from source model
		try:
			sourceRow = sourceModel[sourceIter]
			sourceRowName = sourceRow[SettingModel.COLUMN_NAME]
		except ValueError:
			return
		# update reference to bots-row
		if sourceRow.parent == None and sourceRowName == SettingModel.ROW_BOTS:
			self.botsRowReference = gtk.TreeRowReference(sourceModel, sourceRow.path)
		# check that the changed row is a bot row, ignore others
		if sourceRow.parent != None and self.botsRowReference != None and sourceRow.parent.path == self.botsRowReference.get_path():
			bot = None
			# try to find an existing bot
			for row in self:
				if sourceRow.path == row[self.COLUMN_SOURCEROWREFERENCE].get_path():
					bot = row[self.COLUMN_BOTOBJECT]
					break
			# if bot was found, update it
			if bot:
				if bot.getName() != sourceRowName:
					raise NotImplementedError('Changing bot name is not implemented')
			# if bot was not found, create it
			else:
				bot = Bot(sourceRowName, self.sourceModel)
				bot.connect('notify::apiAccessible', self.onBotPropertyChanged)
				bot.connect('notify::isRunning', self.onBotPropertyChanged)
				sourceRef = gtk.TreeRowReference(sourceModel, sourceRow.path)
				self.append((bot, sourceRef))
Exemple #2
0
 def add_bot(self, name):
     bot = Bot(self)
     bot.name = name
     self.bots.append(bot)
     if self.running:
         bot.connect(self.host, self.port)
     return bot
Exemple #3
0
class Spinner():
    """
    This is our spinner class, it's what keeps the bot alive.
    It will run until a QuitEvent has been sent out.
    It consumes the event dispatchers queue and then sleeps for 0.01 seconds to reduce overhead.
    """
    def __init__(self, parameters):
        fileName, self.coreFile, self.moduleFile, GUI = parameters;
        self.read_config("all")
        self.ed         = botinfo.bot_info["ed"] = eventdispatcher.EventDispatcher()
        self.alive      = True
        self.bot        = Bot(self.ed)
        self._connection = [
            self.ed.add(QuitEvent, Wbm(self.quit)),
            self.ed.add(ReloadconfigEvent, Wbm(self.read_config))
        ]
        self.bot.start()
        
    
    def tick(self):
        self.ed.consume_event_queue()
        return self.alive
        
    def quit(self, event):
        self.alive = False
        
    def read_config(self, event):
        botinfo.bot_info.update(botinfo.read_config("core", self.coreFile))
        botinfo.bot_info.update(botinfo.read_config("modules", self.moduleFile))
Exemple #4
0
 def POST(self):
   """ Handle request to get a bot's move """
   
   # Make sure responses aren't cached by client
   web.header('Content-Type', 'text/plain')
   web.header('Cache-Control', 'no-cache, no-store, no-transform')
   web.header('Expires', '0')
   web.header('Pragma', 'no-cache')
   
   if web.input()['state']:
     from state import State
     from move import COLLAPSE
     # Load the state of the game
     game = State(web.input()['state'])
     last_move = game.moves[-1]
     response = ""
     from bot import Bot
     # Is it the bot's turn?
     if not game.outcome and last_move and     \
           last_move.player == 1 and           \
           last_move.type != COLLAPSE:
       # if response = self.debug(game): return response
       response = Bot.play_move(game, int(web.input()['difficulty']))
     # Is the game over?
     if game.outcome: Bot.learn(game)
     return response
Exemple #5
0
def process_message(self, messageId):
    try:
        messageInst = MessageTask.objects.get(pk=messageId)

        if not messageInst.message.startswith(BOT_USERNAME_PREFIX):
            return False

        bot = Bot()
        command = bot.get_own_command(messageInst.message)

        if command:
            try:
                response = command(message=messageInst.message, fromMessageId=messageInst.pk).run()
            except KeyboardInterrupt as ex:
                response = str(ex)
        else:
            response = "Command not found"

        MessageTask.objects.create(
            c_dest=MessageTask.C_DEST_OUTGOING,
            message=response,
            user = messageInst.user,
            respond_to=messageInst
        )
    except MessageTask.DoesNotExist:
        return False
Exemple #6
0
def run(N):
    """ Runs N episodes of a given length and then runs a demo with greedy policy
	"""
    agent = Agent()

    data = read_data('./data/q.dat')
    if data is not None:
        agent.Q = data

    for i in range(N):
        bot = Bot()
        run_episode(bot, agent, None, draw=False, policy='eps_greedy')
    # if bot.center[1] > 7: print "robot moved on: %i steps" % bot.center[1]

    pg.init()
    pg.display.init()
    surf = pg.display.set_mode((800, 600))
    surf.fill((0, 0, 0))
    pg.display.flip()
    print "Surf1:", surf

    bot = Bot()
    bot.info()
    run_episode(bot, agent, surf, draw=True, policy='eps_greedy', episode_len=60)
    print "Robot's moves:\n", bot.path
    print "Robot walked %i m" % bot.center[1]
    print "Last state value=%.1f" % agent.get_state_value(bot.get_state())
    write_data(agent.Q, "data/q.dat")
    write_path(agent.Q_values, "data/path.csv")
Exemple #7
0
def main():

    # run this from the home
    # https://www.facebook.com/appcenter/diamonddash?
    # fb_source=appcenter_getting_started&fbsid=114
    # with firefox at default zoom (cmd+0 -> default zoom)
    play_button = match('imgs/play.png')
    if play_button:
        #bottom_right = [play_button[0] - 61, play_button[1] + 102]
        #top_left = [play_button[0] - 463, play_button[1] - 258]
        mouseclick(play_button[0], play_button[1])
        mouseclick(play_button[0], play_button[1])
        time.sleep(3)
        play_button = match('imgs/play2.png')
        if play_button:
            mouseclick(play_button[0], play_button[1])

    bottom_right = [486, 686]
    top_left = [86, 326]
    # the game has started
    time.sleep(4)
    print 'start'
    # get top left point and bottom right
    diamond_width = (bottom_right[0] - top_left[0]) / (GRID_WIDTH)
    diamond_height = (bottom_right[1] - top_left[1]) / (GRID_HEIGHT)

    b = Bot(
        #[top_left[0] - diamond_width / 2, top_left[1] - diamond_height / 2],
        [top_left[0], top_left[1]],
        GRID_WIDTH, GRID_HEIGHT, diamond_width, diamond_height,
        SENSITIVITY, COUNTER_THRESHOLD)
    while b.running:
        b.next()
Exemple #8
0
 def on_message(self, data):
     """
     Callback when new message received vie the socket.
     """
     logging.info('Received new message %r', data)
     
     #noone can write in the "rooms"
     if self.room == 'rooms' or self.room == 'help':
         return
     
     
     try:
         # Parse input to message dict.
         datadecoded = tornado.escape.json_decode(data)
         message = {
             '_id': ''.join(random.choice(string.ascii_uppercase) for i in range(12)),
             #'from': self.get_secure_cookie('user', str(datadecoded['user'])),
             'from': self.application.usernames[self.get_secure_cookie('user')],
             'body': tornado.escape.linkify(datadecoded["body"]),
         }
         if not message['from']:
             logging.warning("Error: Authentication missing")
             message['from'] = 'Guest'
             
         if str(message['body'])[0] == '!':
             box_bot = Bot(self)
             box_bot.makeBot(message)
             return
         
     except Exception, err:
         # Send an error back to client.
         self.write_message({'error': 1, 'textStatus': 'Bad input data ... ' + str(err) + data})
         return
def main():
    bot = Bot(BTSUSERNAME, BTSPASSWORD, activeDate=date(2014,8,1))
    # bot.choose_players(p1=('Victor', 'Martinez', 'det'), p2=())
    # import pdb
    # pdb.set_trace()
    bot.choose_players( p1=('Denard', 'Span', 'wsh'), 
                        p2=())
	def test_noun_verb2(self):
		bot = Bot()
		bot_input = "David is running quickly"
		bot.tell(bot_input)
		verbs = bot.knowledge.get_verbs()
		verb = verbs[0]
		self.assertEqual(verb.word, "running")
	def test_noun_verb_inquiry_who_no_obj_match(self):
		bot = Bot()
		bot_input1 = "David is hugging a tomato"
		bot_input2 = "Who is hugging?"
		expected_response = "David."
		bot.tell(bot_input1)
		response = bot.tell(bot_input2)
		self.assertEqual(response, expected_response)
	def test_noun_verb_inquiry_false2(self):
		bot = Bot()
		bot_input1 = "David is hugging a tomato"
		bot_input2 = "Is David hugging a cucumber?"
		expected_response = "No."
		bot.tell(bot_input1)
		response = bot.tell(bot_input2)
		self.assertEqual(response, expected_response)
	def test_noun_verb_inquiry_false1(self):
		bot = Bot()
		bot_input1 = "David is running quickly"
		bot_input2 = "Is David eating?"
		expected_response = "No."
		bot.tell(bot_input1)
		response = bot.tell(bot_input2)
		self.assertEqual(response, expected_response)
	def test_noun_is_noun_false(self):
		bot = Bot()
		bot_input1 = "the giraffe is an animal"
		bot_input2 = "the animal is a giraffe"
		expected_response = "That is impossible."
		bot.tell(bot_input1)
		response = bot.tell(bot_input2)
		self.assertEqual(response, expected_response)
	def test_person_adj_inquiry_false(self):
		bot = Bot()
		bot_input1 = "David is sweet"
		bot_input2 = "is David cute?"
		expected_response = "I don't have that information."
		bot.tell(bot_input1)
		response = bot.tell(bot_input2)
		self.assertEqual(response, expected_response)
	def test_adj_inquiry2(self):
		bot = Bot()
		bot_input1 = "David is cute"
		bot_input2 = "who is cute?"
		expected_response = "David."
		bot.tell(bot_input1)
		response = bot.tell(bot_input2)
		self.assertEqual(response, expected_response)
Exemple #17
0
   def __init__(self, channel, nickname, server, port):
      Bot.__init__(self) 

      self.idle = {}
      self.resumeState = {}

      self.adapter = TestBot(self, channel, nickname, server, port)
      self.adapter.start()
	def test_noun_verb_inquiry_who_obj_no_match(self):
		bot = Bot()
		bot_input1 = "David is eating a giraffe"
		bot_input2 = "Who is eating a cake?"
		expected_response = "No one."
		bot.tell(bot_input1)
		response = bot.tell(bot_input2)
		self.assertEqual(response, expected_response)
	def test_personal_inquiry4(self):
		bot = Bot()
		bot_input1 = "David is cute."
		bot_input2 = "tell me about David?"
		expected_response = "David is cute."
		bot.tell(bot_input1)
		response = bot.tell(bot_input2)
		self.assertEqual(response, expected_response)
	def test_person_adj_inquiry_true(self):
		bot = Bot()
		bot_input1 = "David is cute"
		bot_input2 = "is David cute?"
		expected_response = "Yes."
		bot.tell(bot_input1)
		response = bot.tell(bot_input2)
		self.assertEqual(response, expected_response)
def init_game():
    cards = [[pygame.image.load(path.join('cards', '{0:02d}'.format(value) + suit + ".gif"))
            for value in range(1, 14)]
            for suit in ['d', 'c', 'h', 's']]
    backside = pygame.image.load(path.join('cards', 'back192.gif'))
    bottom = pygame.image.load(path.join('cards', 'bottom01-n.gif'))
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))

    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((0, 130, 0))

    solitaire = Solitaire(background, cards, backside, bottom)
    solitaire.draw()
    bot = Bot()

    screen.blit(background, (0, 0))
    pygame.display.update()
    while 1:
        # event = pygame.event.wait()
        # if event.type == pygame.KEYDOWN:
            # if event.key == pygame.K_LEFT:
                # solitaire.move_left()
            # elif event.key == pygame.K_RIGHT:
                # solitaire.move_right()
            # elif event.key == pygame.K_UP:
                # solitaire.move_up()
            # elif event.key == pygame.K_DOWN:
                # solitaire.move_down()
            # elif event.key == pygame.K_SPACE:
                # solitaire.select()
        # background.fill((0, 130, 0))
        # solitaire.draw()
        # screen.blit(background, (0, 0))
        # pygame.display.update()


        event = pygame.event.get()
        bot.update_state(solitaire.deck.rows, solitaire.cursor)
        moves = bot.make_move()
        for move in moves:
            background.fill((0, 130, 0))
            if move == 'r':
                solitaire.move_right()
            elif move == 'l':
                solitaire.move_left()
            elif move == 'u':
                solitaire.move_up()
            elif move == 'd':
                solitaire.move_down()
            elif move == 's':
                solitaire.select()
            solitaire.draw()

            screen.blit(background, (0, 0))
            pygame.display.update()
            sleep(0.1)
Exemple #22
0
def file_recv_chunk(tox, friend_number, file_number, position, chunk, length, user_data):
    """
    Incoming chunk
    """
    Bot.get_instance().incoming_chunk(
                          friend_number,
                          file_number,
                          position,
                          chunk[:length] if length else None)
Exemple #23
0
def file_chunk_request(tox, friend_number, file_number, position, size, user_data):
    """
    Outgoing chunk
    """
    Bot.get_instance().outgoing_chunk(
                          friend_number,
                          file_number,
                          position,
                          size)
Exemple #24
0
 def update_state(state, move, outcome):
   """ Update (or create) outcome probabilities for a game state
   and move combo
   
   Arguments:
     state and move: standard notation game strings
     outcome: array of player scores [ player, bot ]
   """
   
   from bot import Bot
   game = BotMoves.find_state(state, move)
   outcome = BotMoves.outcome(outcome)
   if game:
     if game[0].count() > 1: # Dup!
       # Use the most played move
       dups = []
       for game in game[0]: dups.append(game)
       dups.sort(key=lambda g: g.played, reverse=True)
       for i in range(1,len(dups)): dups[i].delete()
       game = dups[0]
     else:
       game = game[0].one()
     game.played += 1
     if outcome == 1: game.wins += 1
     elif outcome == 0: game.draws += 1
     else: game.losses += 1
     game.winp = float(game.wins) / float(game.played);
     game.lossp = float(game.losses) / float(game.played);
     game.drawp = float(game.draws) / float(game.played);
     if game.played_in_sequence >= Bot.noise_factor():
       game.played_in_sequence = 0
     else:
       game.played_in_sequence += 1
     elixir.session.commit()
     # Add mapped flag if all valid moves have been played
     from botmovesmapped import BotMovesMapped
     if not BotMovesMapped.has(game.state):
       from state import State
       state = State(game.state)
       if not Bot.get_missing_move(state):
         BotMovesMapped(state=game.state)
         elixir.session.commit()
   else:
     # Create new record
     w = d = l = 0
     if outcome == 1: w = 1
     elif outcome == 0: d = 1
     else: l = 1
     BotMoves(state=state,
              move=move,
              wins=w,
              draws=d,
              losses=l,
              winp=float(w),
              drawp=float(d),
              lossp=float(l))
     elixir.session.commit()
Exemple #25
0
 def update_match_info(self, options):
     key, value = options
     if key=="round":
         self.has_raised_street = False
         if 'table' in self.match_settings:
             stderr.write('Removing runout from last hand\n')
             del self.match_settings['table']
     if key=="table":
         self.has_raised_street = False
     Bot.update_match_info(self,options)
	def test_adj_inquiry3(self):
		bot = Bot()
		bot_input1 = "David is cute"
		bot_input2 = "Brandon is cute"
		bot_input3 = "who is cute?"
		bot.tell(bot_input1)
		bot.tell(bot_input2)
		response = bot.tell(bot_input3)
		self.assertIn("David", response)
		self.assertIn("Brandon", response)
Exemple #27
0
def test_add_sentence():
    bot = Bot()
    sentence = "The cat in the hat"
    bot.add_sentence(sentence)
    expected_monte_carlo = {
        'The cat': ['in'],
        'cat in': ['the'],
        'in the': ['hat']
    }
    assert bot.monte_carlo == expected_monte_carlo
Exemple #28
0
    def __init__(self, canvas=None, namespace=None, vars=None):
        '''
        Nodebot grammar constructor

        :param canvas: Canvas implementation for output.
        :param namespace: Optionally specify a dict to inject as namespace
        :param vars: Optional dict containing initial values for variables
        '''
        Bot.__init__(self, canvas, namespace = namespace, vars = vars)
        canvas.mode = CORNER
        self._ns = self._namespace
Exemple #29
0
def callback(bot_id):
    req_bot = models.User.query.get(bot_id)
    tmp_bot = Bot(req_bot.bot_id, req_bot.acc_tok, req_bot.group_id)
    if request.method == 'POST':
        mreq = json.loads(request.get_data())
        msg = mreq['text']

        if msg.split()[0][0] == '!':  # Msg is a command
            tmp_bot.respond(msg)

    return flask.render_template('index.html')
def getRecommendedPicks(d):
    """
    datetime.date int -> listOfTuples
        today: datetime.date | today's date

    Produces a TupleOfTuples where each tuple is of format:
        (firstName, lastName, teamAbbrevations)
        for a player that is on given date's "recommended picks" dropdwown
        on the MLB beat the streak player selection page
    """
    bot = Bot(BTSUSERNAME, BTSPASSWORD, activeDate=d)
    return bot.get_recommended_players()
Exemple #31
0
 def __init__(self, slackconnection, botname):
     Bot.__init__(self, slackconnection, botname)
Exemple #32
0
from flask import Flask, request, jsonify
import time
from bot import Bot
from config import definindo_webhook
"""
Por ser o arquivo primário e de iniciação eu tentei deixar o mais limpo e claro possível.
Importei o Flask, uma das formas que eu achei pra criar um servidor no computador
Posso estar errado sobre ele pois não fiz muitas pesquisas, o request para requisições e 
Ter acesso ao que o Telegram envia para o meu link e o jsonify para transformar minhas 
Respostas para o servidor em Json.
"""
app = Flask(
    __name__
)  #Padrão para criação de um objeto do tipo Flask fazendo com que o programa tenha WSGI
Bot.init_webhook(definindo_webhook)


@app.route('/webhook', methods=[
    'POST'
])  #Programando para que o servidor recuse outros metodos no caminho /webhook
def index():
    req = request.get_json()  #Pega o que foi enviado pelo Telegram
    bot = Bot()  #Instacia o bot do arquivo bot.py importado no inicio
    bot.passando_dados(req)  #Passa os dados da requisição para ser trabalhado.
    time.sleep(
        5
    )  #Coloquei esse sleep pois a API do google estava dando erro e ele ajudou a cortar um pouco dos erros.
    success = bot.action(
    )  #Aqui ele trata o dado e retorna o código da operação, isso pode ser melhor entendido em HTML onde o código 200 indica que tudo foi certo.
    return jsonify(
        success=success
Exemple #33
0
def test_bot_game():
    g = Game()
    g.players = [Bot("X"), Bot("O")]
    g.main_loop()
    assert g.winner in ["X", "O", "Draw"]
Exemple #34
0
from bot import Bot

if __name__ == '__main__':

    b = Bot(input("Bot Name: "))
    while True:
        print(b.name, ": ", b.get_response(input("To Bot: ")))
        b.brain.print_my_knowledge()
    """
    b = Bot("Bororo")
    print(b.get_response("사과는 과일입니다."))
    b.brain.print_my_knowledge()
    """
    """
    ------------Brain Status------------
    Thing 사과 :
    >>> 사과's name is 사과
    >>> 사과's 과일 is True
    """
    """
    print(b.get_response("사과의 색깔은 빨간색 입니다."))
    b.brain.print_my_knowledge()
    print(b.get_response("아이유 콘서트 가고싶다."))
    b.brain.print_my_knowledge()
    print(b.get_response("나는 바보다"))
    b.brain.print_my_knowledge()
    print(b.get_response("나는 천재다"))
    b.brain.print_my_knowledge()
    print(b.get_response("손건은 남자다"))
    b.brain.print_my_knowledge()
    print(b.get_response("손건은 여자다."))
Exemple #35
0
# -*- coding: utf-8 -*-
from bot import Bot
from settings import tester_id, token, group_id

bot = Bot(token, group_id, tester_id)
bot.start()
Exemple #36
0
# These are the objects 
from bot import Bot

beep = Bot("Beep")

beep.display_name()
beep.display_age()
beep.display_energy()
beep.display_shield()
beep.display_summary()


Exemple #37
0
    #points_62 = []
    points_pr = []
    # display the processed image
    points_1 = vision_pilar1.find(screenshot, 0.45, 'rectangles')
    points_2 = vision_pilar2.find(screenshot, 0.6, 'rectangles')
    points_3 = vision_pilar3.find(screenshot, 0.6, 'rectangles')
    #points_4 = vision_pilar4.find(screenshot, 0.5)
    points_5 = vision_pilar5.find(screenshot, 0.6, 'rectangles')
    points_6 = vision_pilar6.find(screenshot, 0.6, 'rectangles')
    points_7 = vision_pilar7.find(screenshot, 0.6, 'rectangles')
    points_pr = vision_pilarPr.find(screenshot, 0.69, 'rectangles')
    #points_62 = vision_pilar62.find(screenshot,0.5, 'rectangles')
    if len(points_pr):
        print('pilar prohibido')
    elif len(points_1) or len(points_2) or len(points_3) or len(
            points_5) or len(points_6) or len(points_7):
        clicker = Bot()
        clicker.click()

    # debug the loop rate
    print('FPS {}'.format(1 / (time() - loop_time)))
    loop_time = time()

    # press 'q' with the output window focused to exit.
    # waits 1 ms every loop to process key presses
    if cv.waitKey(1) == ord('q'):
        cv.destroyAllWindows()
        break

print('Done.')
Exemple #38
0
 def _set_bots_randomly(self, bot_amount):
     for _ in range(bot_amount):
         self._map.add_member_in_rand(Bot(self._map),
                                      y=randrange(0, int(self._map._y / 2)))
Exemple #39
0
import requests
from flask import Flask, request

from credentials import ACCESS_TOKEN, VERIFY_TOKEN
from const import GRAPH_URL
from bot import Bot

app = Flask(__name__)
sensitive_bot = Bot()


@app.route('/', methods=['GET'])
def handle_verification():
    #  Verificate token related to callback URL set on fb
    token_sent = request.args.get('hub.verify_token')
    return verify_fb_token(token_sent)


@app.route('/', methods=['POST'])
def handle_messages():
    #  Get message sent from user
    output = request.get_json()
    for event in output['entry']:
        messaging = event['messaging']
        for message in messaging:
            if message.get('message'):
                sender_id = message['sender']['id']
                if message['message'].get('text'):
                    send_message(message['message']['text'], sender_id)
    return 'ok'
Exemple #40
0
	def cb_error(self, message):
		Bot.exit(self)
Exemple #41
0
class Jarvis:
    def __init__(self):
        self.bot = Bot()
        self.index = Index()

    # public method
    def add_top_10_questions(self):
        end_date = parser.parse('2016-12-19T21:25:13Z')
        start_date = end_date + timedelta(days=-7)
        results = self.index.search_date('date', start_date, end_date, 1000)
        newlist = sorted(results, key=lambda x: x.good_question_tally, reverse=True)
        newlist2 = [item for item in newlist if len(item.body) < 200 and item.is_question and item.has_i_answer]
        top10 = newlist2[:5]

        body = '<br>'
        for item in top10:
            question = '{0} - {1}'.format(clean_string(item.subject), clean_string(item.body))
            answer = clean_string(item.i_answer)
            #body += '<b>Question:</b>\n{0}\n<b>Answer:</b>{1}\n\n\n'.format(question, answer)
            body += '\n<b>{0}</b>\n- {1}\n\n\n'.format(question, answer)

        body += '<br>#pin'
        subject = 'FAQ for the Week'
        try:
            self.bot.create_post(subject, body)
        except:
            print('FAQ for this week already made')
        #print(body)

    # given a list of ids, it returns html equivalent for @first_item, @second_item..
    def get_at_response(self, id_list):
        response = ''
        for item in id_list:
            response += '&#64;{0} '.format(item)
        return response

    # private method that searches through piazza
    def get_search_results(self, query):
        # assume id_list has the list of ids of all the search results
        id_list = [6,7]
        response = get_at_response(id_list)
        return '<p>Here are some posts matching your queries {0}</p>'.format(response)

    # provide an additional way to search on piazza (custom search)
    # public method
    def answer_search_queries(self):
        search_posts = self.index.search_folder('search')
        for post in search_posts:
            if post.has_i_answer: # ignore posts with TA answer
                continue
            search_query = post.subject
            response = self.get_search_results(search_query)
            self.bot.create_answer(post.guid, response)

    def get_duplicates(self, post):
        # given post, find duplicates of this post
        # get all the posts with the same folder
        candidates = []
        for folder in post.folders.split(' '):
            # all posts in the same folder with answers are candidates
            all_posts = self.index.search_folder(folder)
            candidates.extend([pst for pst in all_posts if pst.has_answer])

        res, scores = find_top_N_similar_docs(post, candidates, 1)
        if len(res) == 0:
            print('no sufficiently similar post found')
            return ''
        else:
            if scores[0] > 0.3:
                print('found {0} potential matches'.format(len(res)))
                return self.get_at_response(res)

    # find duplicate questions and link them to similar old ones
    # public method
    def answer_unanswered_questions(self):

        unanswered_posts = self.index.search_other_unanswered()
        # the below code looks into same index and finds unanswered questions
        # unanswered_posts = self.index.search_unanswered()
        for u_post in unanswered_posts:
            if u_post.is_question and 'search' not in u_post.folders:
                response = self.get_duplicates(u_post)
                # if some response was obtained
                if response != '':
                    self.bot.create_answer(u_post.guid, response)
Exemple #42
0
 def process(self, state: State, bot):
     super().process(state, bot)
     print("CLONE!!!")
     state.bots.append(Bot(bot.pos))
     state.boosters[Booster.CLONE] -= 1
Exemple #43
0
 def __init__(self):
     self.bot = Bot()
     self.index = Index()
from bot import Bot

from traceback import format_exc

with open('token.txt') as fin:
    TOKEN = fin.read().strip()

bot = Bot(TOKEN, "./emias_buff.csv")

try:
    bot.loop()
except:
    traceback = format_exc()
    print(traceback)
    bot.send_error_alert(traceback)
Exemple #45
0
class Page():
    def __init__(self, channel, stream_data):
        self.channel = channel
        self.running = True
        self.messages = []

        self.bot = Bot(self.channel, self)
        self.paste_stream_start(stream_data)

        self.bot_thread = threading.Thread(target=self.run)
        self.bot_thread.start()

        self.save_thread = threading.Thread(target=self.save_messages)
        self.save_thread.start()
        self.viewers = ""
        self.game = ""

    def run(self):
        self.bot.read_chat()

    def close_tab(self):
        self.bot.running = False
        self.running = False
        self.bot_thread.join()
        print("{} bot stopped".format(self.channel))
        self.save_thread.join()

        dbx = dropbox.Dropbox(token)

        with open("channels/{}/{}_{}.txt".format(self.channel, self.channel, self.time), "rb") as f:
            dbx.files_upload(f.read(), '/channels/{}/{}_{}.txt'.format(self.channel, self.channel, self.time))

        os.remove("channels/{}/{}_{}.txt".format(self.channel, self.channel, self.time))

    def paste_stream_start(self, stream_data):
        d = datetime.datetime.strptime(stream_data[0]['started_at'], '%Y-%m-%dT%H:%M:%SZ')
        d = d.replace(tzinfo=datetime.timezone.utc).astimezone(tz=None)
        self.time = d.strftime("%Y-%m-%d %H-%M-%S")

        message = "{0}:{1}: {2}".format(self.time, "he305bot", "Stream started")

        try:
            os.mkdir('channels/' + self.channel)
        except FileExistsError:
            print('Folder {} already exists'.format(self.channel))

        if not os.path.isfile("channels/{}/{}_{}.txt".format(self.channel, self.channel, self.time)):
            with open("channels/{}/{}_{}.txt".format(self.channel, self.channel, self.time), 'w',
                      encoding='utf8') as fp:
                fp.write(message)

    def print_message(self, message):
        pass
        # try:
        #     print(message + '\n')
        # except Exception:
        #     print("Some exception while printing out")

    def save(self):
        with open("channels/{}/{}_{}.txt".format(self.channel, self.channel, self.time), 'a', encoding='utf8') as fp:
            for msg in self.messages:
                try:
                    fp.write('\n'+msg)
                except Exception as ex:
                    print(msg + " CAN'T BE WRITTEN")
                    print(ex)

            fp.write("\n{}:{}: {}".format(datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S"), "Viewer_counter", self.viewers))
            fp.write("\n{}:{}: {}".format(datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S"), "Game_name", self.game))
        print("{}: SAVED {} MESSAGES FROM {}".format(datetime.datetime.now().strftime('%H:%M:%S'), len(self.messages), self.channel))

    def save_messages(self):
        while self.running:
            if len(self.messages) != 0:
                self.save()
                self.messages = []

            sleep(60)
Exemple #46
0
from bot import Bot, randomword
from net import Net, State
from terminal import *

# TODO: Реализовать чистку папок от мусора после предыдущих прогонов
net = Net("https://another-todo-list.netlify.com/")
b = Bot(net.base_url, auth=False)
s = State(b.get_elements(), b.current_url(), b.get_screenshot())
net.base_url = s.url
net.add_node(s)
base_state = s
current_state = base_state
a = 0

while True:

    # Генерируем все возможные новые состояния
    log('Прокликиваем все элементы в текущем состоянии')
    for i, elm in enumerate(current_state.elements):
        a += 1
        if a > 10:
            break
        elm.highlight()
        # TODO: Если клик прошёл неудачно, то помечаем элемент как не живой и пропускаем итерацию
        log(f'({i}/{len(current_state.elements)}) Кликаем по элементу с текстом: {elm.get_text()}'
            )
        if 'input' in elm.xpath or 'input' in elm.get_innerHTML():
            # elm.input(f'{randomword(10)}\n')
            elm.input(f'Test!!!\n')
        else:
            elm.click()
Exemple #47
0
if settings["UserId"] == None:
    configurationMenu()

# Main menu
table = Table(show_header=True, header_style="Green")
table.add_column("Twitter Markov Bot")
table.add_row("1. Post a status")
table.add_row("2. Post a status with a keyword")
table.add_row("3. Reply to someone\'s last tweet")
table.add_row("4. update replied list")
table.add_row("5. update tweet stream")
table.add_row("6. refresh profile picture")
table.add_row("7. Quit")

bot = Bot(settings["UserId"], "data_tweets.json",
          "data_tweets_only_replies.json")


def menu1():
    entered = ''
    while entered != 'ok':
        clearConsole()
        tweet = bot.GenerateTweet()
        tweetTable = Table(show_header=True, header_style="Green")
        tweetTable.add_column("Post a status")
        tweetTable.add_row(tweet)
        console.print(tweetTable)
        entered = input('Enter "ok" if the message seems good\n')
        if entered == "quit":
            return None
    bot.PostTweet(tweet)
Exemple #48
0
class BotPlayer(object):
    nick = 'Bot'

    def __init__(self):
        self.key = make_key()
        self.thread = None

    def send(self, msg_type, msg):
        if msg_type == 'phase_one':
            self.on_phase_one(msg)
        elif msg_type == 'hand':
            self.on_hand(msg)
        elif msg_type == 'discarded':
            self.on_discarded(msg)
        elif msg_type == 'start_move':
            self.on_start_move(msg)
        elif msg_type in ['ron', 'draw', 'aborted']:
            self.room.remove_player(self.idx)
            self.shutdown()
        else:
            # ignore
            pass

    def set_room(self, room, idx):
        self.room = room
        self.idx = idx

    def on_phase_one(self, msg):
        tiles = msg['tiles']
        dora_ind = msg['dora_ind']
        if msg['east'] == msg['you']:
            fanpai_wind = 'X1'
        else:
            fanpai_wind = 'X2'
        self.bot = Bot(tiles=tiles,
                       options={
                           'dora_ind': dora_ind,
                           'fanpai_winds': [fanpai_wind]
                       })

    def on_hand(self, msg):
        self.bot.use_tenpai(msg['hand'])

    def choose_tenpai(self):
        def run():
            logger.info('Choosing tenpai...')
            hand = self.bot.choose_tenpai(cooperative=True)
            logger.info('Tenpai found')
            self.room.send_to_game(self.idx, 'hand', hand)

        self.thread = gevent.spawn(run)

    def on_discarded(self, msg):
        if msg['player'] == self.idx:
            self.bot.use_discard(msg['tile'])
        else:
            self.bot.opponent_discard(msg['tile'])

    def on_start_move(self, msg):
        if msg['type'] == 'discard':
            tile = self.bot.discard()
            self.room.send_to_game(self.idx, 'discard', tile)
        elif msg['type'] == 'hand':
            self.choose_tenpai()

    def shutdown(self):
        if self.thread:
            self.thread.join()
Exemple #49
0
from bot import Bot
import requests, os

bot = Bot()
bot.run(os.environ['DISCORD_TOKEN'])
Exemple #50
0
from yowsup.layers.protocol_iq.protocolentities import *
from yowsup.layers.protocol_media.mediauploader import MediaUploader
from yowsup.layers.protocol_media.protocolentities import *
from yowsup.layers.protocol_messages.protocolentities import *
from yowsup.layers.protocol_presence.protocolentities import *
from yowsup.layers.protocol_privacy.protocolentities import *
from yowsup.layers.protocol_profiles.protocolentities import *
from yowsup.layers.protocol_receipts.protocolentities import *

from yowsup.common.tools import Jid
from yowsup.common.optionalmodules import PILOptionalModule, AxolotlOptionalModule

from cli import Cli, clicmd
from bot import Bot

BOT = Bot()

logger = logging.getLogger(__name__)


class YowsupCliLayer(Cli, YowInterfaceLayer):
    PROP_RECEIPT_AUTO = "org.openwhatsapp.yowsup.prop.cli.autoreceipt"
    PROP_RECEIPT_KEEPALIVE = "org.openwhatsapp.yowsup.prop.cli.keepalive"
    PROP_CONTACT_JID = "org.openwhatsapp.yowsup.prop.cli.contact.jid"
    EVENT_LOGIN = "******"
    EVENT_START = "org.openwhatsapp.yowsup.event.cli.start"
    EVENT_SENDANDEXIT = "org.openwhatsapp.yowsup.event.cli.sendandexit"

    MESSAGE_FORMAT = "[{FROM}({TIME})]:[{MESSAGE_ID}]\t {MESSAGE}"

    DISCONNECT_ACTION_PROMPT = 0
Exemple #51
0
bots = []
print 'Setting up'
colors = [
    '#f00', '#0f0', '#00f', '#ff0', '#f0f', '#0ff', '#fff', '#000', '#800',
    '#080', '#008', '#880', '#808', '#088', '#888'
]


def delete_bot(bot):
    canvas.delete(bot.character)
    bots.remove(bot)


for i in xrange(15):
    bot = Bot(100 + i * 120, 120, 20, 0.5, screen, str(i))
    # bot.add_fx(10*i+10)
    # bot.add_fy(10*i+10)
    bot.setup_nn()
    bots.append(bot)

sess.run(tf.initialize_all_variables())
clock = pygame.time.Clock()
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
    screen.fill(black)
    animator(bots)
    clock.tick(30)
    pygame.display.flip()
    print 'FPS ', clock.get_fps()
Exemple #52
0
import asyncio
import async_timeout
from datetime import date, datetime
from dateutil import parser
import json
import random

import bs4
import feedparser
import requests

from bot import Bot
from registry import bot_command
from storage import store

bot = Bot()


async def _is_open():
    try:
        async with aiohttp.ClientSession(raise_for_status=True) as session:
            with async_timeout.timeout(5):
                async with session.get(
                        'http://api.shackspace.de/v1/space') as resp:
                    return json.loads(await resp.text())['doorState']['open']
    except:
        return None


@bot_command('open')
async def open(parsed, user, target, text):
Exemple #53
0
from bot import Bot

if __name__ == "__main__":
    bot = Bot("Saarbrücken", False)
    bot.startBot()
class Character:
    def __init__(self, typeC, clazz):
        if typeC == "P":
            self.charT = Player(clazz)
        if typeC == "B":
            self.charT = Bot()

    def help(self):
        return self.charT.help()

    def quit(self):
        return self.charT.quit()

    def health(self):
        return self.charT.health()

    def goN(self, pp):
        return self.charT.goN(pp)

    def goE(self, pp):
        return self.charT.goE(pp)

    def goW(self, pp):
        return self.charT.goW(pp)

    def goS(self, pp):
        return self.charT.goS(pp)

    def getStr(self):
        return self.charT.getStr()

    def getDef(self):
        return self.charT.getDef()

    def attack(self, charT, defense):
        return self.charT.attack(charT, defense)

    def botHit(self, dmg):
        self.charT.botHit(dmg)

    def hit(self, dmg):
        self.charT.hit(dmg)
c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)

# Add handlers to logger
logger.addHandler(c_handler)
logger.addHandler(f_handler)

logger.info('Starting up bot...')

# Setup config
if os.path.exists("config.txt"):
    conf = Config("config.txt")
else:
    conf = ConfigWizard("config.txt").conf

# Create and start the bot
bot = Bot(conf)

thread = BotThread(bot, 0)
thread.start()

# Enable cli
command = ""
logger.info("Command-line enabled:")

while not command == "quit":
    command = input()

# Close bot thread
thread.stop()
thread.join()
Exemple #56
0
from config import Config
from bot import Bot

#Get settings
properties = ['token', 'timeout', 'chats', 'active_chat', 'helper_modules']
config = Config(properties)

#Need for bot
settings = config.get_settings()
vk_data = config.get_vk_data()

#Extracting vk_data
vk_session = vk_data['vk_session']
api = vk_data['api']
longpoll = vk_data['longpoll']

#Start bot working
bot = Bot(vk_session, api, longpoll, settings)
bot.start()
 def __init__(self, typeC, clazz):
     if typeC == "P":
         self.charT = Player(clazz)
     if typeC == "B":
         self.charT = Bot()
Exemple #58
0
def gameplay():
    global high_score, mainBot
    game_speed = 4
    start_menu = False
    game_over = False
    game_quit = False
    runners = []
    bot = []
    for i in range(0, 10):
        runners.append(Runner(44, 47, random.randint(1, 80) * i))
        bot.append(Bot(str(i)))

    new_ground = Ground(-1 * game_speed)
    scb = Scoreboard()
    highsc = Scoreboard(width * 0.78)
    counter = 0

    cacti = pygame.sprite.Group()
    pteras = pygame.sprite.Group()
    last_obstacle = pygame.sprite.Group()

    Cactus.containers = cacti
    Ptera.containers = pteras

    retbutton_image, retbutton_rect = load_image('replay_button.png', 35, 31,
                                                 -1)
    gameover_image, gameover_rect = load_image('game_over.png', 190, 11, -1)

    temp_images, temp_rect = load_sprite_sheet('numbers.png', 12, 1, 11,
                                               int(11 * 6 / 5), -1)
    HI_image = pygame.Surface((22, int(11 * 6 / 5)))
    HI_rect = HI_image.get_rect()
    HI_image.fill(background_col)
    HI_image.blit(temp_images[10], temp_rect)
    temp_rect.left += temp_rect.width
    HI_image.blit(temp_images[11], temp_rect)
    HI_rect.top = height * 0.1
    HI_rect.left = width * 0.73

    while not game_quit:
        while not game_over:
            bot_event = []
            if pygame.display.get_surface() is None:
                print("Couldn't load display surface")
                game_quit = True
                game_over = True
            else:
                # TODO
                # make it list of events
                # type_obstacle, next_obstacle = get_first(cacti, pteras)

                x_diff = []
                y_diff = []
                type_obstacle = []
                next_obstacle = []

                for i in range(0, len(runners)):
                    runners[i].isDucking = False
                    x_diffTemp, y_diffTemp, type_obstacleTemp, next_obstacleTemp = get_game_param(
                        runners[i], cacti, pteras)
                    x_diff.append(x_diffTemp)
                    y_diff.append(y_diffTemp)
                    type_obstacle.append(type_obstacleTemp)
                    next_obstacle.append(next_obstacleTemp)

                    if next_obstacle[i] is not None:
                        bot_eventTemp = bot[i].act(x_diff[i],
                                                   y_diff[i],
                                                   game_speed,
                                                   obstacle=type_obstacle[i])
                        bot_event.append(bot_eventTemp)

                        if bot_event[i] == 1:
                            # print(">>> JUMP")
                            if runners[i].rect.bottom == int(0.98 * height):
                                runners[i].isJumping = True
                                if pygame.mixer.get_init() is not None:
                                    jump_sound.play()
                                runners[i].movement[
                                    1] = -1 * runners[i].jumpSpeed

                        if bot_event[i] == 2:
                            if not (runners[i].isJumping
                                    and runners[i].isDead):
                                runners[i].isDucking = True

                    for current_event in pygame.event.get():
                        if current_event.type == pygame.QUIT:
                            game_quit = True
                            game_over = True

            for c in cacti:
                c.movement[0] = -1 * game_speed
                for i in range(0, len(runners)):
                    if pygame.sprite.collide_mask(runners[i], c):
                        runners[i].isDead = True
                        if pygame.mixer.get_init() is not None:
                            die_sound.play()

            for p in pteras:
                p.movement[0] = -1 * game_speed
                for i in range(0, len(runners)):
                    if pygame.sprite.collide_mask(runners[i], p):
                        runners[i].isDead = True
                        if pygame.mixer.get_init() is not None:
                            die_sound.play()

            if len(cacti) < 2:
                if len(cacti) == 0:
                    last_obstacle.empty()
                    last_obstacle.add(Cactus(game_speed, 40, 40))
                else:
                    for l in last_obstacle:
                        if l.rect.right < width * 0.7 and random.randrange(
                                0, 50) == 10:
                            last_obstacle.empty()
                            last_obstacle.add(Cactus(game_speed, 40, 40))

            if len(pteras) == 0 and random.randrange(
                    0, 200) == 10 and counter > 10:
                for l in last_obstacle:
                    if l.rect.right < width * 0.8:
                        last_obstacle.empty()
                        last_obstacle.add(Ptera(game_speed, 46, 40))

            for i in range(0, len(runners)):
                runners[i].update()
            cacti.update()
            pteras.update()
            new_ground.update()
            sum = 0
            maxNum = float("-inf")
            for i in range(0, len(runners)):
                sum += runners[i].score
                maxNum = max(maxNum, runners[i].score)

            scb.update(sum / len(runners))
            maxNum = max(maxNum, highsc.getScore())
            high_score = max(high_score, maxNum)
            scb.update(maxNum)
            highsc.update(high_score)

            # print_matrix(game_image)
            # bot update

            # def update_scores(self, act, prev_state, state, isDead=False):
            for i in range(0, len(runners)):
                x_diff[i], y_diff[i], type_obstacle[i], _ = get_game_param(
                    runners[i], cacti, pteras)
                game_param = x_diff[i], y_diff[i], game_speed, type_obstacle[
                    i], runners[i].score
                bot[i].update_scores(game_param, runners[i].isDead)

            if pygame.display.get_surface() is not None:
                screen.fill(background_col)
                new_ground.draw()
                scb.draw()
                if high_score != 0:
                    highsc.draw()
                    screen.blit(HI_image, HI_rect)
                cacti.draw(screen)
                pteras.draw(screen)
                for i in range(0, len(runners)):
                    runners[i].draw()
                pygame.display.update()
            clock.tick(FPS)

            result = True
            for runner in runners:
                result = result & runner.isDead
                if runner.isDead:
                    runners.remove(runner)

            if result is True:
                game_over = True

            # if counter % 700 == 699:
            #     new_ground.speed -= 1
            #     game_speed += 1

            counter = (counter + 1)

            while game_over:

                if game_quit:
                    pygame.quit()
                    quit()

                for b in bot:
                    mainBot.set_max(b)

                for i in range(0, 3):
                    src = random.randint(0, 3)
                    dst = random.randint(0, 3)
                    bot[src].merge(bot[dst])
                    src = random.randint(0, 3)
                    dst = random.randint(0, 3)
                    bot[src].merge(bot[dst])
                    src = random.randint(0, 3)
                    dst = random.randint(0, 3)
                    bot[src].merge(bot[dst])

                for b in bot:
                    b.mutate()

                for b in bot:
                    mainBot.set_max(b)

                gameplay()

        pygame.quit()
        quit()
Exemple #59
0
def start_bot(artist):
	bot = Bot(artist)
	bot.start()
Exemple #60
0
 def __init__(self):
     self.db = DB()
     #self.logger = Logger()
     self.bot = Bot()