def initialize():
    # Creates twitter_bot that connects to twitter account
    bot = Bot(consumer_key=Login_Settings.twitter['CONSUMER_KEY'],
              consumer_secret=Login_Settings.twitter['CONSUMER_SECRET'],
              access_key=Login_Settings.twitter['ACCESS_TOKEN'],
              access_secret=Login_Settings.twitter['ACCESS_SECRET'])

    latest_mention = "0"
    mentions = bot.get_mentions(latest_mention)
    for mention in mentions:
        tweet_id = mention["tweet_id"]

        if int(tweet_id) > int(latest_mention):
            latest_mention = tweet_id

    with open("last_mention_id.txt", "w+") as f:
        f.write(latest_mention)
        f.close()

    time = datetime.datetime.now()
    post_list = General_Posts.function_names.keys()

    with open("latest_post.txt", "w+") as f:
        f.write(str(time) + "\n")
        for post in post_list:
            f.write(post + "\n")
def config():
    sql = SQL(host=Login_Settings.database['HOST'],
              port=Login_Settings.database['PORT'],
              username=Login_Settings.database['DB_USERNAME'],
              password=Login_Settings.database['DB_PASSWORD'],
              database=Login_Settings.database['DATABASE'])

    # Creates twitter_bot that connects to twitter account
    bot = Bot(consumer_key=Login_Settings.twitter['CONSUMER_KEY'],
              consumer_secret=Login_Settings.twitter['CONSUMER_SECRET'],
              access_key=Login_Settings.twitter['ACCESS_TOKEN'],
              access_secret=Login_Settings.twitter['ACCESS_SECRET'])

    sql.table_setup()

    # Inserts initial dataset into database (500 per twitter account)
    inspire_list = bot.get_user_tweets("inspire_us",
                                       "inspired") + bot.get_user_tweets(
                                           "InspowerMinds", "inspired")
    weather_list = bot.get_user_tweets("NWS", "weather") + bot.get_user_tweets(
        "weatherchannel", "weather")
    horoscope_list = bot.get_user_tweets("ZodiacFacts", "horoscope")
    romance_list = bot.get_user_tweets("romntic_quotes", "flirt") + bot.get_user_tweets("LikeLoveInLove", "flirt") + \
                   bot.get_user_tweets("RomanticcQuotes", "flirt")
    sql.insertion_tweet(inspire_list + horoscope_list + weather_list +
                        romance_list)
    sql.close()

    Scheduler_Initializer.initialize()
示例#3
0
  def __init__(self,cards, level="advanced",name="j1",allyName="j3",ennemyNames=["j2","j4"]):

    Bot.__init__(self,cards=cards,level=level,name=name,allyName=allyName,ennemyNames=ennemyNames)
    self.previouscounter={} #keep track of the last round
    self.announcetracker={}
    for color in const.liste_couleur :
      self.announcetracker[color]=False
示例#4
0
 def __init__(self, posX, posY):
     width = 40
     height = 40
     Bot.__init__(self, posX, posY, "spider", width, height)
     self.setStep(2)
     hp = 3
     self.health = HealthBot(hp)
示例#5
0
 def reinitialize(self):
   """
   reinitialize for a new round
   """
   for color in self.counter:
     self.previouscounter[color]=self.counter[color]
   Bot.reinitialize(self)
示例#6
0
    def connect(self):
        """
        function coordinates bot spawning process
        """
        bot_ammount_current = len(self.bots)
        if bot_ammount_current==0:
            self.wave_counter+=1
            self.bot_ammount_wave = ((self.wave_counter // 2) + 1) * 5
            bot_ammount_create = self.bot_ammount_wave if self.bot_ammount_wave<=50 else 50
            for _ in range(bot_ammount_create):
                pos_cofig = self.pos_dict_bot[random.randint(1,2)]
                start_pos = pos_cofig[0], random.sample(pos_cofig[1], 1)[0]
                self.bots.append(Bot(self.game, start_pos[0], start_pos[1]))
                self.bot_ammount_wave -= 1
        elif bot_ammount_current < 50 and self.bot_ammount_wave>0:
            bot_ammount_create = 50 - bot_ammount_current
            if self.bot_ammount_wave < bot_ammount_create:
                bot_ammount_create = self.bot_ammount_wave
            for _ in range(bot_ammount_create):
                pos_cofig = self.pos_dict_bot[random.randint(1,2)]
                start_pos = pos_cofig[0], random.sample(pos_cofig[1], 1)[0]
                self.bots.append(Bot(self.game, start_pos[0], start_pos[1]))
                self.bot_ammount_wave -= 1

        current_time = time.perf_counter()
        if current_time-self.time_last_gunpack > self.gunpck_frequency:
            self.game.arena.create_gunpack()
            self.time_last_gunpack = current_time
示例#7
0
def main(args):
    time.sleep(2)  # Give user a moment to tab into site

    valid_modes = ["generic", "bestbuy", "psdirect", "all_vendors"]

    mode = None
    if len(args) == 1:
        mode = args[0]
    else:
        mode = "all_vendors"

    if mode not in valid_modes:
        print(f'Error, {mode} is not a valid mode.')
        return

    vendorhub = VendorHub()
    parser = Parser(vendorhub, mode)
    bot = Bot(vendorhub)

    flag = True
    while flag:
        actions_required = parser.parse()
        print(f'Actions required -> {actions_required}')

        for vendor in actions_required:
            result = bot.run(vendor, actions_required[vendor])
            print(result)

        time.sleep(30)  # Ping sites every 30 seconds
示例#8
0
    def __init__(self, configParser):
        super(CommandEngine, self).__init__()
        self.initialize_logger()
        self.config_parser = configParser
        self.config = dict(self.config_parser.items('command-engine'))

        self.client = plivo.RestClient(
            auth_id=self.config['client_auth_id'],
            auth_token=self.config['client_auth_token'])

        self.conference = {}
        self.polling_thread = Thread(target=self.find_conference)
        self.polling_thread.daemon = True

        self.raw_text_queue = Queue()

        self.bot = Bot(dict(self.config_parser.items('bot')))

        # thread for recognition
        self.recognition_thread = Thread(target=self.speech_recognition)
        self.recognition_thread.daemon = True
        self.recognition_thread_started = False

        self.polling = True
        self.polling_thread.start()
        # self.find_conference()
        # join the polling thread in the end

        self.commander()
示例#9
0
 def __init__(self, posX = None, posY = None):
     width = 25
     height = 32
     Bot.__init__(self, posX, posY, "zombie", width, height)
     self.setStep(2)
     hp = 3
     self.health = HealthBot(hp)
示例#10
0
 def __init__(self, bot_id, waitingTime=0, download_folder=tempfile.gettempdir()+os.sep):
     self.bot = Bot(bot_id, download_folder)
     self.textHandler     = doNothing;
     self.photoHandler    = doNothing;
     self.voiceHandler    = doNothing;
     self.documentHandler = doNothing;
     self.waitingTime     = waitingTime;
示例#11
0
    def __init__(self, slackconnection, botname):
        Bot.__init__(self, slackconnection, botname)

        self.icon_emoji = ':bread:'
        self.destinations = dict() # string => Destination
        self.luncher_index = 0
        self.load()
示例#12
0
    def main(self, screen,bot_mode):
        clock = pygame.time.Clock()
        if bot_mode == "Neural": 
            self.bot = Neural_Bot()
        else:
            self.bot = Bot()
        menu = kezmenu.KezMenu(
            ['Play!', lambda: self.game_create(menu) ],
            ['Quit', lambda: setattr(self, 'running', False)],event_gameover = GAMEOVER
            )       
        menu.position = (50, 50)
        menu.enableEffect('enlarge-font-on-focus', font=None, size=60, enlarge_factor=1.2, enlarge_time=0.3)
        menu.color = (255,255,255)
        menu.focus_color = (40, 200, 40)
        nightmare = construct_nightmare(screen.get_size())
        highscoresurf = self.construct_highscoresurf()
        timepassed = clock.tick(30) / 1000.
        print("New Game")
        while self.running:
    
            events = pygame.event.get()

            for event in events:
                if event.type == pygame.QUIT:
                    exit()

            menu.update(self.gameover,events, timepassed)
            timepassed = clock.tick(30) / 1000. #30 original           
            if timepassed > 1: # A game has most likely been played 2e
                highscoresurf = self.construct_highscoresurf()

            screen.blit(nightmare, (0,0))
            screen.blit(highscoresurf, highscoresurf.get_rect(right=WIDTH-50, bottom=HEIGHT-50))
            menu.draw(screen) 
            pygame.display.flip()
示例#13
0
    def check_triggers(self, comment):
        pattern = self.triggers['@review_bot']
        matches = pattern.findall(comment.body)

        # Matches contains tuples in the format:
        # (@review_bot, ' network:sub', subreddit, ' keyword', keyword)
        reply = ''
        for _, _, sub, _, keyword in matches:
            if not keyword:
                keyword = ''
            keywords = keyword.split()
            if not sub:
                sub = self.review_subs
            else:
                sub = [sub.lower()]

            reviews = self.get_last_reviews(comment.author, keywords, sub)

            # list reply functions here to add a single reply
            if len(sub) == 1:
                sub = sub[0]
            reply += self.reply_header.format(comment.author, keyword, sub)
            reply += self.list_reviews(reviews)
        if matches:    
            reply += self.reply_footer
            Bot.handle_ratelimit(comment.reply, reply)
            self.idle_count = 0
示例#14
0
    def tick(self, world, tick):
        local_cells = world.surroundingCells(self.cell)
        local_actors = []
        for cell in local_cells:
            local_actors = local_actors + world.cells[cell]

        # If we are female, not pregnant and a male is nearby, become pregnant (because thats totally how this works IRL)
        if self.gender == "F" and not self.pregnant:
            for actor in local_actors:
                if hasattr(actor, "gender") and actor.gender is "M":
                    self.pregnant = True
                    self.doIn(9, "birth")
                    print "%s is pregnant! %s is the father." % (self, actor)
                    break

        # Die if we are too hungry
        if self.hunger == 30:
            print "%s died of hunger :(" % self
            return self.kill()

        # Increase hunger every 5 ticks
        if tick % 5 == 0:
            self.hunger += 1
            if self.hunger == 10:
                print "%s is hungry!" % self

        Bot.tick(self, world, tick)
示例#15
0
 def mutateMultiple(self, bot, times):
     genom = bot.getGenom()
     for i in range(0, times):
         genom = self.singleMutation(genom)
     b = Bot(0, 0, 1)
     b.setGenom(genom)
     return b
示例#16
0
def start_bots(args):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    Entry = namedtuple('Entry', 'client event')
    for b_ct in range(len(args.bot_tokens)):
        b = Bot(name=args.bot_name[b_ct],
                premium_role=args.premium_role,
                standard_role=args.standard_role,
                stripe_channels=args.stripe_channels,
                user_info_channels=args.user_info_channels,
                token=args.bot_tokens[b_ct],
                loop=loop)
        if b.get_name() not in bots:
            bots[b.get_name()] = b
            queues.append(b.get_queue())
        else:
            log.critical("Names of Bot processes must be unique (not case " +
                         "sensitive)! Process will exit.")
            sys.exit(1)
    log.info("Starting up the Bots")
    for b_name in bots:
        bot = bots[b_name]
        entries.append(Entry(client=bot, event=asyncio.Event()))
        loop.run_until_complete(bot.login(bot.get_token()))
        loop.create_task(bot.connect())
        loop.create_task(bot.webhook())
    try:
        loop.run_until_complete(check_close(entries))
    except KeyboardInterrupt:
        loop.close()
    except Exception:
        raise Exception
示例#17
0
class Mediator(ChatMediator):

    _users = None
    _bot = None

    def __init__(self):
        self._users = []

    def add_user(self, user):
        self._users.append(user)

    def send_message(self, message, user):

        if message == "addBot":
            self._bot = Bot(user.get_chat_mediator(), "Bot")

            self._users.append(self._bot)

        for usr in self._users:
            if (usr != user):
                usr.receive(message)

        if re.compile(r'\bcat\b').findall(
                message) and self._bot is not None and user != self._bot:
            self._bot.send("cat is a forbidden word!")
            self._bot.remove_user(user)

    def get_users(self):
        return self._users
示例#18
0
    def __init__(self, portNo):
        self.host = socket.gethostname()
        print("host ", self.host)
        self.port = portNo
        print("port ", self.port)
        self.size = 4096
        self.sock = socket.socket()
        print("sock 1", self.sock)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        print("sock 2", self.sock)
        self.sock.bind((self.host, self.port))
        print("sock 3", self.sock)
        self.sock.listen(1)
        print("sock 4", self.sock)
        self.conn, self.addr = self.sock.accept()
        print("sock 5", self.sock)
        print("Client connected")

        self.billReader = BillReader()
        self.currencyRecognizer = CurrencyRecognizer()
        # self.currencyRecognizer.configure("D:\\TP_PROGS\\Projects\\TeProjSahara\\progs\\Sahara-System-For-Aiding-Visually-Impaired-master\\Sahara-System-For-Aiding-Visually-Impaired-master\\Server_side\\DataFiles\\yolov3.weights",\
        #      "D:\\TP_PROGS\\Projects\\TeProjSahara\\progs\\Sahara-System-For-Aiding-Visually-Impaired-master\\Sahara-System-For-Aiding-Visually-Impaired-master\\Server_side\\DataFiles\\yolov3-tiny.cfg", \
        #          ('10','20','50','100','200','500','2000'))
        self.summarizer = Summarizer()
        self.textRecognizer = TextRecognizer()
        self.bot = Bot()
        self.objectDet = DetectObject()
        self.maskDet = DetectMask()
示例#19
0
def index():
    param = request.args.get("pergunta")
    bot = Bot(lista, respostas)

    return jsonify({
        "resposta": bot.find_word(param)
    })
示例#20
0
    def check_triggers(self, comment):
        pattern = self.triggers['@review_bot']
        matches = pattern.findall(comment.body)

        # Matches contains tuples in the format:
        # (@review_bot, ' network:sub', subreddit, ' keyword', keyword)
        reply = ''
        for _, _, sub, _, keyword in matches:
            if not keyword:
                keyword = ''
            keywords = keyword.split()
            if not sub:
                sub = self.review_subs
            else:
                sub = [sub.lower()]

            reviews = self.get_last_reviews(comment.author, keywords, sub)

            # list reply functions here to add a single reply
            if len(sub) == 1:
                sub = sub[0]
            reply += self.reply_header.format(comment.author, keyword, sub)
            reply += self.list_reviews(reviews)
        if matches:
            reply += self.reply_footer
            Bot.handle_ratelimit(comment.reply, reply)
            self.idle_count = 0
示例#21
0
 def __init__(self, posX=None, posY=None):
     width = 25
     height = 32
     Bot.__init__(self, posX, posY, "zombie", width, height)
     self.setStep(2)
     hp = 3
     self.health = HealthBot(hp)
示例#22
0
文件: Human.py 项目: SkylarKelty/AI
	def tick(self, world, tick):
		local_cells = world.surroundingCells(self.cell)
		local_actors = []
		for cell in local_cells:
			local_actors = local_actors + world.cells[cell]

		# If we are female, not pregnant and a male is nearby, become pregnant (because thats totally how this works IRL)
		if self.gender == "F" and not self.pregnant:
			for actor in local_actors:
				if hasattr(actor, "gender") and actor.gender is "M":
					self.pregnant = True
					self.doIn(9, "birth")
					print "%s is pregnant! %s is the father." % (self, actor)
					break

		# Die if we are too hungry
		if self.hunger == 30:
			print "%s died of hunger :(" % self
			return self.kill()

		# Increase hunger every 5 ticks
		if tick % 5 == 0:
			self.hunger += 1
			if self.hunger == 10:
				print "%s is hungry!" % self
		
		Bot.tick(self, world, tick)
示例#23
0
 def test_botTakesThreeChips(self):
     bot = Bot()
     bot.recieveChip(9)
     self.assertEqual(bot.getChips(), [9])
     bot.recieveChip(3)
     self.assertEqual(bot.getChips(), [9, 3])
     with self.assertRaises(Exception):
         bot.recieveChip(0)
示例#24
0
    def __init__(self, locale='pt-br', creatorName='', chatBotName='Jarvis', coeficient_confidence= 0.5):

        self.__init__(locale)
        self.creatorName = creatorName
        self.botName = chatBotName
        self.jarvisBot = Bot(chatBotName)
        self.jarvisBot.load_for_trainer()
        self.coeficient_confidence = float(coeficient_confidence)
示例#25
0
class Updater:
    def __init__(self,
                 bot_id,
                 waitingTime=0,
                 download_folder=tempfile.gettempdir() + os.sep):
        self.bot = Bot(bot_id, download_folder)
        self.textHandler = doNothing
        self.photoHandler = doNothing
        self.voiceHandler = doNothing
        self.documentHandler = doNothing
        self.waitingTime = waitingTime

    def setTextHandler(self, f):
        self.textHandler = f

    def setPhotoHandler(self, f):
        self.photoHandler = f

    def setVoiceHandler(self, f):
        self.voiceHandler = f

    def start(self):
        while True:
            for u in self.bot.getUpdates():
                # get info about the message
                messageType = self.bot.getMessageType(u['message'])
                message = u['message']
                chat_id = message['chat']['id']

                try:
                    name = message['chat']['first_name']
                except:
                    name = message['from']['username']
                pass

                message_id = message['message_id']
                # call right functors
                if messageType == 'text':
                    # TODO: distinguish between command and plain text
                    text = message['text']
                    self.textHandler(self.bot, message, chat_id, text)
                if messageType == 'photo':
                    local_filename = self.bot.getFile(
                        u['message']['photo'][-1]['file_id'])
                    self.photoHandler(self.bot, message, chat_id,
                                      local_filename, name)
                if messageType == 'voice':
                    local_filename = self.bot.getFile(
                        u['message']['voice']['file_id'])
                    self.voiceHandler(self.bot, message, chat_id,
                                      local_filename)
                if messageType == 'document':
                    local_filename = self.bot.getFile(
                        u['message']['document']['file_id'])
                    self.documentHandler(self.bot, message, chat_id,
                                         local_filename)
            if self.waitingTime > 0:
                time.sleep(self.waitingTime)
示例#26
0
 def move(self, bot: Bot, x: int, y: int):
     range_of_move = abs(bot.get_position_x()) - abs(x) + abs(
         bot.get_position_y()) - abs(y)
     if self.game_field[x, y] != 0 & range_of_move < bot.get_speed() | len(
             self.game_field) < x | len(self.game_field[x]) < y:
         return -1
     else:
         bot.set_position_xy(x, y)
         return 1
示例#27
0
class ConnectFourClient(WebSocketClient):

    def __init__(self, *args, **kwargs):
        super(ConnectFourClient, self).__init__(*args, **kwargs)
        if len(sys.argv) > 1 and sys.argv[1] == "human":
            self.player = Human()
        else:
            self.player = Bot()

    def opened(self):
        print("[*] Connected to server")
        payload = {"command": "init"}
        self.send(json.dumps(payload))

    def closed(self, code, reason=None):
        print("[!] Lost connection to server\n{}: {}".format(code, reason))

    def received_message(self, msg):
        try:
            payload = json.loads(str(msg))
            command = payload.get("command")
            if "token" == command:
                self.handle_joined(payload)
            if "waiting" == command:
                player = payload.get("player")
                if self.player.token == player:
                    self.handle_turn(payload)
            if "winner" == command:
                self.handle_winner(payload)
        except TypeError:
            print("[!] Unexpected message from server: {}".format(msg))
            sys.exit()

    def handle_joined(self, payload):
        if payload.get("token"):
            print("[+] Joined")
            print("[*] Player Token: {}".format(payload.get("token")))
            self.player.token = payload.get("token")
        else:
            print("[!] Max players joined. Closing...")
            sys.exit()

    def handle_turn(self, payload):
        print("[+] Player's turn")
        self.player.board = payload.get("board")
        self.player.print_board()
        column = self.player.make_move()
        self.send(json.dumps(
            {"command": "move", "player": self.player.token, "column": column}))

    def handle_winner(self, payload):
        player = payload.get("player")
        if self.player.token == player:
            print("[+] Player won")
        else:
            print("[+] Player lost")
        sys.exit()
示例#28
0
 def __init__(self, title="Default", parent=None):
     super(Chat, self).__init__(parent)
     """Construteur de la classe"""
     self.main = QtWidgets.QMainWindow.__init__(self)
     self.ui = Ui_MainWindow()
     self.utilisateur = Utilisateur("Thierry", "CE1")
     self.bot = Bot()
     self.ui.setupUi(self)
     self._initSlotButton()
示例#29
0
 def __init__(self, user):
     self.bot = Bot().getBot()
     self.url = "https://www.tiktok.com/upload?lang=en"
     self.cookies = Cookies()
     self.userRequest = {"dir": "", "cap": "", "vidTxt": ""}
     self.video = None
     self.IO = IO("hashtags.txt")
     self.videoFormats = ["mov", "flv", "avi"]
     self.userPreference = user
示例#30
0
文件: Human.py 项目: SkylarKelty/AI
	def __init__(self):
		self.hunger = 0
		self.tiredness = 0
		self.gender = random.choice(["F", "M"])
		self.pregnant = False
		self.movingToFood = False

		Bot.__init__(self, namegen.human(self.gender), 0xBA6C49)

		self.doIn(random.randint(100, 250), "die")
示例#31
0
    def __init__(self):
        self.hunger = 0
        self.tiredness = 0
        self.gender = random.choice(["F", "M"])
        self.pregnant = False
        self.movingToFood = False

        Bot.__init__(self, namegen.human(self.gender), 0xBA6C49)

        self.doIn(random.randint(100, 250), "die")
示例#32
0
    def __init__(self, slackconnection, botname):
        Bot.__init__(self, slackconnection, botname)

        self.icon_emoji = ":video_game:"
        self.games = []
        self.user_options = defaultdict(set)  # name => set([flag1, flag2...])
        self.history = PS4History(negative_stats=set([Stats.scrub]))
        self.latest_stats_table = defaultdict(
            LatestStats)  # channel => LatestStats
        self.load()
示例#33
0
文件: import.py 项目: itsheox3/ttdash
def main():
   auth = sys.argv[1]
   ttuid = sys.argv[2]

   bot = Bot('Bot Import', auth, ttuid, None)
   bot.playlist_all()
   data = bot.ws.recv()
   data = json.loads(data[data.index('{'):])

   print json.dumps(data)
示例#34
0
 def __init__(self, size):
     #initialize everything the world needs to do its thing
     self.grid = np.empty((size, size), dtype=object)
     self.size = size
     #get the agent set up
     self.place_agent()
     print("{} {}".format(self.agentx, self.agenty))
     self.offsetx = self.get_agentx  #offsets are used to calculate relative positions
     self.offsety = self.get_agenty
     self.agent = Bot(self.agentx, self.agenty, self.size, self)
示例#35
0
 def set_configurables(self):
     Bot.set_configurables(self)
     self.reply_header = '\n\n/u/{0}\'s {1} reviews in /r/{2}:\n\n'
     self.reply_footer = '\n\n___\n\n[^Info](http://github.com/Chronophobe/ReviewBot)^( | Please address any remarks to /u/FlockOnFire)'
     self.list_limit = 10
     self.triggers = {
         '@review_bot': re.compile(r'(@review_bot)( (scotch|bourbon|worldwhisky))?( [\'|\"]([a-z0-9_\ -]+)[\'\"])?', re.I),
     }
     self.sub_from_subscriptions = True 
     self.review_subs = ['scotch', 'bourbon', 'worldwhisky']
     print("""
         List limit:          {0}
     """.format(self.list_limit))
示例#36
0
 def set_configurables(self):
     Bot.set_configurables(self)
     self.reply_header = '\n\n/u/{0}\'s {1} reviews in /r/{2}:\n\n'
     self.reply_footer = '\n\n___\n\n^(Please report any issues to /u/FlockOnFire)'
     self.list_limit = 10
     self.triggers = {
         '@review_bot': re.compile(r'(@review_bot)( (scotch|bourbon|worldwhisky))?( [\'|\"]([a-z0-9_\ -]+)[\'\"])?', re.I),
     }
     self.sub_from_subscriptions = True 
     self.review_subs = ['scotch', 'bourbon', 'worldwhisky']
     print("""
         List limit:          {0}
     """.format(self.list_limit))
示例#37
0
	def __init__(self, num_players=1, num_decks=6):
		self.num_decks = num_decks
		self.dealer = Dealer()
		self.bot = Bot('Bot')
		self.players = []
		self.busted = []
		self.stand = []
		self.move = 0
		self.dealer_done = False
		self.bot_moves = []
		for i in xrange(0,num_players):
			self.players.append(Player('Player'+str(i+1)))

		self.players.append(self.bot)
		self.deck = Deck(num_decks)
		self.bot_deck = self.deck.deck * 1
		for player in self.players:
			player.make_bet()
			if player.name == 'Bot':
				player.add(self.bot_deck.pop())
				player.add(self.bot_deck.pop())
				self.bot_deck.pop()
				self.bot_deck.pop()
			else:
				player.add(self.deck.draw())
				player.add(self.deck.draw())
				self.dealer.add(self.deck.draw())
				self.dealer.add(self.deck.draw())

		self.rules = RulesEngine(self.dealer, self.players)
示例#38
0
    def set_configurables(self):
        Bot.set_configurables(self)

        self.refresh_rate = 0
        self.refresh_cap  = 0
        self.sub_from_subscriptions = True

        self.owner = self.reddit.get_redditor('Malz_')
        self.currency = 'Ɍ'
        self.reply_footer = """ 
[^([help])](http://www.reddit.com/r/RedditPointTrade/wiki/about)
\n___\n
^(\'Spend\' your Reddits at /r/RedditPointTrade)
        """
        self.gift_amount = 1
        self.karma_minimum = 100
        self.triggers = {
            '+accept'   : re.compile(r'\+accept', re.I), 
            '[request]' : re.compile(r'\[R\] ?\[[^\d]?([\d,]+)\]', re.I),
            '[offer]'   : re.compile(r'\[O\] ?\[[^\d]?([\d,]+)\]', re.I),
            '+reddittip': re.compile(r'\+redditpointtrade (\d+)', re.I),
            'pm_tip'    : re.compile(r'\+redditpointtrade ([a-z0-9_-]{3,}) [^\d]?(\d+)', re.I),
            'pm_join'   : re.compile(r'\+join (/r/)?([a-z0-9_-]{3,})', re.I),
            'pm_leave'  : re.compile(r'\+leave (/r/)?([a-z0-9_-]{3,})', re.I),
            'pm_balance': re.compile(r'(\+balance)', re.I)
        }
        self.home = self.reddit.get_subreddit('RedditPointTrade')
        # self.subreddits = [sub.display_name for sub in self.reddit.get_my_subreddits()]
        
        self.messages = {
            'verified'    : '\n\n^(**[Verified]** /u/{0} -> /u/{1} {2}{3}.00)',
            'accepted'    : '\n\n^(**[Verified]** /u/{0} -> /u/{1} {2}{3}.00)',
            'failed'      : '\n\n^(**[Failed]** /u/{0} -/-> /u/{1} {2}{3}.00)',
            'pm_tip'      : '[RPT] Private Transaction',
            'pm_join'     : 'RedditPointTrade Bot joined your subreddit. For more info check /r/{0} or contact /u/{1}'.format(str(self.home), str(self.owner)),
            'pm_leave'    : 'RedditPointTrade Bot has left your subreddit.',
            'pm_balance'  : '^(Current balance: {}{:,}) ^[[help]](/r/redditpointtrade/wiki/about)',
            'join_not_authorized' : 'You are not allowed to subscribe me to this subreddit.',
            'leave_not_authorized': 'You are not allowed to unsubscribe me to this subreddit.'
        }
        self.messages['welcome_gift'] =  '\n\nWelcome to /r/RedditPointTrade. You have been given a complementary Reddit ({1}{2}.00).'
        self.messages['welcome_gift'] += '\n\nLearn more at /r/RedditPointTrade/wiki/about.'
        self.messages['welcome_gift'] += '\n\n___\n\n'
        self.messages['welcome_gift'] += '\n\n^(**[Verified]** /u/RPTtipbot -> /u/{0} {1}{2}.00)'
        self.flair_css = 'balance'
示例#39
0
class MUCBot(MUCClient):
    """
    I join a room and respond to greetings.
    """

    def __init__(self, roomJID, nick):
        MUCClient.__init__(self)
        self.roomJID = roomJID
        self.nick = nick
        self._bot = Bot(roomJID, nick, self.groupChat)

    def connectionInitialized(self):
        """
        Once authorized, join the room.
        
        If the join action causes a new room to be created, the room will be
        locked until configured. Here we will just accept the default
        configuration by submitting an empty form using L{configure}, which
        usually results in a public non-persistent room.
        
        Alternatively, you would use L{getConfiguration} to retrieve the
        configuration form, and then submit the filled in form with the
        required settings using L{configure}, possibly after presenting it to
        an end-user.
        """
        
        def joinedRoom(room):
            if room.locked:
                # Just accept the default configuration. 
                return self.configure(room.roomJID, {})
        
        MUCClient.connectionInitialized(self)
        
        d = self.join(self.roomJID, self.nick)
        d.addCallback(joinedRoom)
        d.addCallback(lambda _: log.msg("Joined room"))
        d.addErrback(log.err, "Join failed")

    def receivedGroupChat(self, room, user, message):
        # uncomment this to prevent nasty things
        # it's a global loop failsafe
        # if user.nick != self.nick:
        self._bot.listen(user.nick, message.body)
示例#40
0
 def get_last_reviews(self, redditor, keywords, sub):
     keywords.append('review')
     logging.info(Bot.get_time() + '    Listing Reviews: {0}'.format(str(redditor)))
     counter = 0
     author_posts = redditor.get_submitted(limit=None)
     last_reviews = []
     for post in author_posts:
         if counter < self.list_limit and self.submission_is_review(post, keywords, sub):
             last_reviews.append((post.title, post.permalink))
             counter += 1
     return last_reviews
示例#41
0
    def check_triggers(self, comment, subreddit):
        if subreddit.lower() == self.home.display_name.lower():
            is_new  = self.new_user(comment.author)
        else:
            is_new = False
        accept  = self.triggers['+accept'].search(comment.body) 
        tip     = self.triggers['+reddittip'].search(comment.body)

        reply = ''
        if is_new:
            reply += is_new
        if accept and comment.submission.subreddit == self.home:
                reply += self.accept(comment)
        if tip:
            reply += self.tip_user(tip.group(1), comment)

        if reply != '':    
            reply += self.reply_footer
            Bot.handle_ratelimit(comment.reply, reply)
            self.idle_count = 0
示例#42
0
    def set_configurables(self):
        Bot.set_configurables(self)

        self.refresh_rate = 0
        self.refresh_cap  = 0
        self.sub_from_subscriptions = True

        self.owner = self.reddit.get_redditor('Malz_')
        self.currency = 'Ɍ'
        self.reply_footer = """ 
[^([help])](http://www.reddit.com/r/RedditPointTrade/wiki/about)
\n___\n
^(\'Spend\' your Reddits at /r/RedditPointTrade)
        """
        self.gift_amount = 1
        self.karma_minimum = 100
        self.triggers = {
            '+accept'   : re.compile(r'\+accept', re.I), 
            '[request]' : re.compile(r'\[R\] ?\[[^\d]?([\d,]+)\]', re.I),
            '[offer]'   : re.compile(r'\[O\] ?\[[^\d]?(\d+)\]', re.I),
            '+reddittip': re.compile(r'\+redditpointtrade (\d+)', re.I),
            'pm_tip'    : re.compile(r'\+redditpointtrade ([a-z0-9_-]{3,}) [^\d]?(\d+)', re.I),
            'pm_join'   : re.compile(r'\+join (/r/)?([a-z0-9_-]{3,})', re.I),
            'pm_leave'  : re.compile(r'\+leave (/r/)?([a-z0-9_-]{3,})', re.I),
            'pm_balance': re.compile(r'(\+balance)', re.I)
        }
        self.home = self.reddit.get_subreddit('RedditPointTrade')
        # self.subreddits = [sub.display_name for sub in self.reddit.get_my_subreddits()]
        
        self.messages = {
            'verified'    : '\n\n^(**[Verified]** /u/{0} -> /u/{1} {2}{3}.00)',
            'accepted'    : '\n\n^(**[Verified]** /u/{0} -> /u/{1} {2}{3}.00)',
            'failed'      : '\n\n^(**[Failed]** /u/{0} -/-> /u/{1} {2}{3}.00)',
            'welcome_gift': '\n\n^(**Welcome /u/{0},**\n\n To get you started you have received {1}{2}.00! [[help]](http://www.reddit.com/r/RedditPointTrade/wiki/about))',
            'pm_tip'      : '[RPT] Private Transaction',
            'pm_join'     : 'RedditPointTrade Bot joined your subreddit. For more info check /r/{0} or contact /u/{1}'.format(str(self.home), str(self.owner)),
            'pm_leave'    : 'RedditPointTrade Bot has left your subreddit.',
            'pm_balance'  : 'Your /r/RedditPointTrade balance is: {0}'
        }
        self.flair_css = 'balance'
示例#43
0
 def submission_is_review(self, submission, keywords, sub):
     title = not submission.is_self \
     and submission.subreddit.display_name.lower() in sub \
     and all(keyword.lower() in submission.title.lower() for keyword in keywords)
     if title:
         submission.replace_more_comments(limit=None, threshold=0)
         comments = praw.helpers.flatten_tree(submission.comments)
         for comment in comments:
             try:
                 if self.comment_is_review(comment, submission.author):
                     return True
             except requests.exceptions.HTTPError as e:
                 logging.warning(Bot.get_time() + '    {0}'.format(e))
                 continue
     return False
示例#44
0
 def submission_is_review(self, submission):
     logging.debug('Checking Submission({})'.format(submission.id))
     title = not submission.is_self \
     and submission.subreddit.display_name.lower() in self.review_subs
     if title:
         logging.debug('    properties check out')
         submission.replace_more_comments(limit=None, threshold=0)
         comments = praw.helpers.flatten_tree(submission.comments)
         for comment in comments:
             try:
                 logging.debug('    {}'.format(comment.permalink))
                 if self.get_comment_class(comment = comment) == 1 and comment.author == submission.author:
                     logging.debug('        contains a review')
                     return comment
             except requests.exceptions.HTTPError as e:
                 logging.warning(Bot.get_time() + '    {0}'.format(e))
                 continue
     logging.debug('    not a review')
     return None
示例#45
0
def main():
   auth = sys.argv[1]
   ttuid = sys.argv[2]

   bot = Bot('Bot Export', auth, ttuid, None)
   bot.playlist_all()
   data = bot.ws.recv()
   data = json.loads(data[data.index('{'):])

   # Remove all songs in my current playlist.
   playlist = data['list']
   for s in playlist:
      bot.playlist_remove('default', 0)
      bot.ws.recv()

   for song in sys.argv[3:]:
      bot.playlist_add('default', song)
      bot.ws.recv()

   print 'true'
示例#46
0
    def __init__(self, servidor, canal, nombre, puerto, patron, ID_Bot):
        # Esto hay que hacerlo siempre: 
        threading.Thread.__init__(self)    

        # Copiamos como atributos los parametros:
        self.servidor     = servidor
        self.canal        = canal
        self.nombre       = nombre
        self.puerto       = puerto
        self.patron       = patron
        self.ID_Bot       = ID_Bot
        #Conexion BD
        print "Abriendo BD..."
        self.con        = sqlite3.connect('C:/DjangoProyectos/irc.db')  #con_bd.close()
        self.cursor     = self.con.cursor()  #cursor.close()

        #Generamos un ID para el BOT y registramos el BOT:
        print "Registrar BOT"
        self.registro_Bot(self.servidor, self.canal)

        # Creamos el objeto "bot":
        self.bot    = Bot(self.servidor, self.canal, self.nombre, self.puerto, self.patron, self.ID_Bot, self.ID_convers);
示例#47
0
#!/usr/local/bin/python
# -*- coding: UTF-8 -*-
import logging
import General
from time import sleep
from GameField import GameField
from Blank import Blank
from Bot import Bot
from ActualGame import Combatant

LOG_FILE_NAME = 'Minesweeper.log'
logging.basicConfig(filename='Minesweeper.log', filemode='w', format='%(message)s', level=logging.DEBUG)
logging.info('Начало новой игры.')
try:
    comb = Combatant()
    field = GameField(comb)
    bot = Bot(field)
    bot.solve()
except General.MineOpened:
    print('Oops, a mine was opened =(')
    logging.info('Проигрыш.')
except General.Victory:
    print('Victory!')
    logging.info('Победа.')
except Exception as ex:
    logging.exception(ex)
    raise ex
finally:
    logging.debug(str(field))
    logging.info('Завершение.\n')
示例#48
0
文件: run.py 项目: NotLeet/n0tb0t
import logging
import socket
import time
from TwitchSocket import TwitchSocket
from Bot import Bot
from config import SOCKET_ARGS

logging.basicConfig(filename='error-log.txt', level=logging.WARNING)
ts = TwitchSocket(**SOCKET_ARGS)
bot = Bot(ts)

messages = ""

while True:
    try:
        read_buffer = ts.sock.recv(1024)
    except Exception as e:
        print('{}: Attempting to reconnecting to the socket.'.format(str(e)))
        ts.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ts.join_room()
        read_buffer = ts.sock.recv(1024)

    if len(read_buffer) == 0:
        print('Disconnected: Attempting to reconnecting to the socket.')
        ts.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ts.join_room()
        read_buffer = ts.sock.recv(1024)

    messages = messages + read_buffer.decode('utf-8')
    messages_list = messages.split('\r\n')
    # print(messages)
示例#49
0
文件: tetris.py 项目: DrDrei/Tetris
					menu.update_menu(screen)
					pygame.display.flip()
				
				if event.key == pygame.K_UP:
					menu.move_cursor(1)
					menu.update_menu(screen)
					pygame.display.flip()
		
				if event.key == pygame.K_RETURN:
					menu.gameStart=1	


################### MAIN ####################
# some initialization procedures
pygame.init()
bot = Bot()

# initializes the screen, window name and the key repeater
# if the key is held the key is repeated
size = width, height = 300, 440
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('TETRIS')
pygame.key.set_repeat(75)

while 1:
	# build a matrix for from the width and height
	area = Area(width - 100, height)

	# initializes the shape queue (first number is current shape, second is upcoming)
	# randomizes the shape color
	shape_queue = []	
示例#50
0
from logging.handlers import RotatingFileHandler

from Bot import Bot

# setup logging

log_file_handler = RotatingFileHandler('alter-me.log',
                                       mode='a',
                                       maxBytes=5*1024*1024,
                                       backupCount=2,
                                       encoding=None,
                                       delay=0)

logging.basicConfig(format='%(asctime)s | %(name)s | %(levelname)s | %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    level=logging.INFO,
                    handlers=[log_file_handler])

# setup bot

bot = Bot()


def exit_handler():
    bot.stop()


atexit.register(exit_handler)

bot.start()
示例#51
0
 def reply(self, comment, text):
     Bot.handle_ratelimit(comment.reply, text)
示例#52
0
class HebraBot(threading.Thread):
    def __init__(self, servidor, canal, nombre, puerto, patron, ID_Bot):
        # Esto hay que hacerlo siempre: 
        threading.Thread.__init__(self)    

        # Copiamos como atributos los parametros:
        self.servidor     = servidor
        self.canal        = canal
        self.nombre       = nombre
        self.puerto       = puerto
        self.patron       = patron
        self.ID_Bot       = ID_Bot
        #Conexion BD
        print "Abriendo BD..."
        self.con        = sqlite3.connect('C:/DjangoProyectos/irc.db')  #con_bd.close()
        self.cursor     = self.con.cursor()  #cursor.close()

        #Generamos un ID para el BOT y registramos el BOT:
        print "Registrar BOT"
        self.registro_Bot(self.servidor, self.canal)

        # Creamos el objeto "bot":
        self.bot    = Bot(self.servidor, self.canal, self.nombre, self.puerto, self.patron, self.ID_Bot, self.ID_convers);

    # Lo que tiene que hacer en concurrencia:
    def run(self):
        print ">> lanzando bot... " 
        return self.bot.conexion()

    def existe_ID(self, ID_Bot):
        # print "  >>>> Probando si ID '" + self.ID_Bot + "' existe..."
        self.cursor.execute("SELECT ID_Bot FROM BOT_INFO WHERE ID_Bot == '" + str(self.ID_Bot) + "'")            
        if (self.cursor.fetchone()) != None:
              return True
        else:
              return False

    def generar_ID_Bot(self):
        probarDeNuevo   = True
        numerito        = 0
        while probarDeNuevo:   
            numerito = numerito + 1         
            # numerito          = random.choice(range(100))
            self.ID_Bot       = 'BOT' + str(numerito)
            # print "\n  >> Probando ID: " + self.ID
            if self.existe_ID(self.ID_Bot) == False:
                probarDeNuevo = False
                print "  >> ID... OK"
                print "  >> El ID del BOT es: " + self.ID_Bot + "\n  >> Anota el ID para futuras modificaciones.\n"
            else: 
                probarDeNuevo = True 
                # print "  >> El ID ya existe, probando otro..."        

        threading.Thread(name = self.ID_Bot)   
        return self.ID_Bot

    def registro_Bot(self, servidor, canal):
        tiempo_ini      = time.strftime('%d %b %y / %H:%M:%S')
        t1              = time.strftime('%H %M %S')
        self.ID_convers = t1.replace(" ", "")
        tiempo_fin      = 0
        eventos         = 0
        estado          = "ON"
        num_msg         = 0
        print " Generando ID..."
        self.ID_Bot  = self.generar_ID_Bot()  
        print " Registrando " + self.ID_Bot
        self.cursor.execute(
            "INSERT INTO BOT_INFO (ID_CONVERS, ID_BOT, INICIO, ULTIMA, SERVIDOR, CANAL, EVENTOS, NUM_MSG, ESTADO) VALUES ('"
            + str(self.ID_convers) +"','"+ str(self.ID_Bot)+"','"+ str(tiempo_ini) +"', '"+ str(tiempo_fin) +"',' "
            + str(self.servidor) +"', '"+ str(self.canal) +"', '"+ str(eventos) + "', '"
            + str(num_msg) + "', '"+ str(estado) +"')"
            )
        self.con.commit() 
        self.cursor.fetchone()
        print " Ok!  Registrado correctamente.";
        self.con.close()
        reintentar = False

    def desconexion(ID_Bot):
        # Bot.desconexion(self.ID_Bot)
        thread._stop(self.ID_BOT)

    def estado(ID_BOT):
        threading.isAlive(name = ID_BOT)
        threading.enumerate()
示例#53
0
def main() :
	backend = SimpleBackend()
	bot = Bot("mpetyx@gic", "emp", backend, "147.102.6.34")
	bot.start()
	httpFrontend = HTTPFrontend(8080, backend)
	httpFrontend.start()
示例#54
0
class Game:
	
	def __init__(self, num_players=1, num_decks=6):
		self.num_decks = num_decks
		self.dealer = Dealer()
		self.bot = Bot('Bot')
		self.players = []
		self.busted = []
		self.stand = []
		self.move = 0
		self.dealer_done = False
		self.bot_moves = []
		for i in xrange(0,num_players):
			self.players.append(Player('Player'+str(i+1)))

		self.players.append(self.bot)
		self.deck = Deck(num_decks)
		self.bot_deck = self.deck.deck * 1
		for player in self.players:
			player.make_bet()
			if player.name == 'Bot':
				player.add(self.bot_deck.pop())
				player.add(self.bot_deck.pop())
				self.bot_deck.pop()
				self.bot_deck.pop()
			else:
				player.add(self.deck.draw())
				player.add(self.deck.draw())
				self.dealer.add(self.deck.draw())
				self.dealer.add(self.deck.draw())

		self.rules = RulesEngine(self.dealer, self.players)

	def ongoing(self):
		return not len(self.players) == 0 or not self.dealer_done

	def winner(self):
		self.stand.sort(key=lambda x: x.val)
		self.stand.reverse()
		winner = self.dealer if self.dealer.val <= 21 else Player("Default")
		for player in self.stand:
			if player.val > winner.val:
				winner = player
		return winner

	def payout(self):
		self.rules.update(self.stand)

	def reset(self):
		self.players = self.rules.players
		self.stand = []
		self.busted = []
		self.dealer_done = False
		self.bot.update(self.players+[self.dealer])
		if len(self.deck.deck) <= self.deck.num_decks*52*0.25: # re-shuffle if < 75% of deck left
			self.deck.deck = self.deck.generate(self.deck.num_decks)
			self.deck.shuffle()
			self.reset_count()

		self.dealer.clear_hand()
		for player in self.players:
			player.clear_hand()
		self.bot_deck = self.deck.deck * 1
		for player in self.players:
			player.make_bet()
			if player.name == 'Bot':
				player.add(self.bot_deck.pop())
				player.add(self.bot_deck.pop())
				self.bot_deck.pop()
				self.bot_deck.pop()
			else:
				player.add(self.deck.draw())
				player.add(self.deck.draw())
				self.dealer.add(self.deck.draw())
				self.dealer.add(self.deck.draw())
		
		self.bot_moves = []

	def move_player(self, player, hand):
		newplayers = []
		
		if self.players[0].name == "Bot":
			move = player.play(self.dealer,hand)
		else:
			move = self.move

		if move == 1:
			player.add(self.deck.draw(),hand)
			if hand == len(player.hands)-1:
				newplayers.append(player)

		elif move == -1:
			if hand == len(player.hands)-1:
				self.busted.append(player)

		elif move == 2:
			player.add(self.deck.draw(),hand)
			player.doubled_down = True
			player.cash -= player.bet
			player.bet *= 2
			if hand == len(player.hands)-1:
				newplayers.append(player)

		elif move == 3:
			player.aces.append(0)
			player.tmp.append(0)

			player.hands.append([])
			card2 = player.hands[0].pop()
			player.val[0] = 0
			player.add(player.hands[0].pop(),0)
			player.cash -= player.bet
			player.val.append(0)
			player.add(card2,1)
			player.add(self.deck.draw(),0)
			player.add(self.deck.draw(),1)
			newplayers.append(player)

	def run(self):
		newplayers = []

		move = self.dealer.play()
		if move == 1:
			self.dealer.add(self.deck.draw())
			self.bot_deck.pop()
		else:
			self.dealer_done = True

		for i in xrange(0,len(self.players)):
			for j in xrange(0,len(self.players[i].hands)):
				if self.players[i].name == "Bot":
					move = self.players[i].play(self.dealer,j)
					if move == 2 and len(self.bot.hands[j]) > 2:
						move = 1
					if not (move == 0 and (j,move) in self.bot_moves):
						self.bot_moves.append((j,move))
				else:
					move = self.move

				if move == 1:
					if self.players[i].name == 'Bot':
						self.players[i].add(self.bot_deck.pop(),j)
					else:
						self.players[i].add(self.deck.draw(),j)
					if j == len(self.players[i].hands)-1:
						newplayers.append(self.players[i])

				elif move == -1:
					if j == len(self.players[i].hands)-1:
						self.busted.append(self.players[i])

				elif move == 2:
					if self.players[i].name == 'Bot':
						self.players[i].add(self.bot_deck.pop(),j)
					else:
						self.players[i].add(self.deck.draw(),j)
					self.players[i].doubled_down = True
					self.players[i].cash -= self.players[i].bet
					self.players[i].bet *= 2
					if j == len(self.players[i].hands)-1:
						newplayers.append(self.players[i]) # STAND?

				elif move == 3:
					self.players[i].aces.append(0)
					self.players[i].tmp.append(0)

					self.players[i].hands.append([])
					card2 = self.players[i].hands[0].pop()
					self.players[i].val[0] = 0
					self.players[i].add(self.players[i].hands[0].pop(),0)
					self.players[i].cash -= self.players[i].bet
					self.players[i].val.append(0)
					self.players[i].add(card2,1)
					
					if self.players[i].name == 'Bot':
						self.players[i].add(self.bot_deck.pop(),0)
						self.players[i].add(self.bot_deck.pop(),1)						
					else:
						self.players[i].add(self.deck.draw(),0)
						self.players[i].add(self.deck.draw(),1)
					newplayers.append(self.players[i])
					
				else:
					if j == len(self.players[i].hands)-1:
						self.stand.append(self.players[i])

		self.players = newplayers

	def reset_count(self):
		self.bot.rcount = 0
		self.bot.tcount = 0
		self.bot.dead_cards = 0

	def __repr__(self):
		repr = ['\n']
		repr.append('Dealer: ' + str(self.dealer))
		for player in self.players:
			repr.append('Active Player --> ' + str(player))
		for player in self.stand:
			repr.append('Standing Player --> ' + str(player))
		for player in self.busted:
			repr.append('Busted Player --> ' + str(player))
		repr.append('\n')
		return '\n'.join(repr)
示例#55
0
 def __init__(self, roomJID, nick):
     MUCClient.__init__(self)
     self.roomJID = roomJID
     self.nick = nick
     self._bot = Bot(roomJID, nick, self.groupChat)
示例#56
0
 def set_properties(self):
     Bot.set_properties(self)
     self.refresh_cap = 30
示例#57
0
def main():
    bot = Bot('irc.freenode.net', 6667, 'idbot')
    bot.start()
示例#58
0
import json
import socket
from Bot import Bot

run_loop = 1

with open('config.json', 'r') as f:
    config = json.load(f)

print(config['host'])

irc_bot = Bot(config['host'], config['port'], config['nick'], config['ident'], config['realname'], config["testchannel"])
s = irc_bot.connect_to_server
irc_bot.set_nick()
irc_bot.join_channel()

# Run loop.
while run_loop == 1:
    irc_bot.readbuffer = irc_bot.readbuffer + s.recv(1024).decode('utf-8')
    temp = irc_bot.readbuffer.split("\n")
    irc_bot.readbuffer = temp.pop()

    for line in temp:
        run_loop = irc_bot.parse_irc_line(line, run_loop)

s.shutdown(socket.SHUT_RDWR)
s.close()
print("Bye bye!")