Example #1
0
def follow_cb(word, word_eol, userdata):
    if len(word) >= 2 and word[1] not in userlist:
        userlist.append(word[1])
        hexchat.prnt(
            "-\002Follow\002-\tYou are now following \002\003{0}{1}\017".
            format(nick_color(word[1]), word[1]))
        return hexchat.EAT_ALL
Example #2
0
def unfollow_cb(word, word_eol, userdata):
    if len(word) >= 2 and word[1] in userlist:
        userlist.remove(word[1])
        hexchat.prnt(
            "-\002Follow\002-\tYou have unfollowed \002\003{0}{1}\017".format(
                nick_color(word[1]), word[1]))
        return hexchat.EAT_ALL
Example #3
0
def main():
    if MODULE_DEBUG:
        hexchat.prnt("daychanged.py: DEBUG MODE")
        schedule.every(5).seconds.do(print_day_changed)
    schedule.every().day.at("00:00").do(print_day_changed)

    hexchat.hook_timer(1000, schedule_callback)
Example #4
0
File: icu.py Project: lf94/ICU
def icu(word, word_eol, userdata):
    if len(word) < 4:
        hexchat.prnt(__module_help_message__)
        return hexchat.EAT_ALL
    
    contexts = userdata
    this_context = hexchat.get_context()
    operation = word[1]
    direction = word[2]
    destination = word[3]
    
    potential_context = hexchat.find_context(channel=destination)
    if potential_context == None:
        hexchat.prnt("Could not find {}.".format(destination))
        return hexchat.EAT_ALL

    if operation == "add":
        if direction == "to":
            contexts["to"].append(potential_context)
        elif direction == "from":
            contexts["from"].append(potential_context)
        this_context.prnt("Added relay {} {}".format(direction, destination))

    if operation == "del":
        if direction == "to":
            contexts["to"].remove(potential_context)
        elif direction == "from":
            contexts["from"].remove(potential_context)
        this_context.prnt("Deleted relay {} {}".format(direction, destination))

    return hexchat.EAT_ALL
Example #5
0
File: qc.py Project: SoniEx2/Stuff
 def setter(self, value):
     self.value = value
     hexchat.set_pluginpref("queercraft_{}".format(self.name), str(value))
     if value and self.statusmsg.get("true", None):
         hexchat.prnt(self.statusmsg["true"])
     elif (not value) and self.statusmsg.get("false", None):
         hexchat.prnt(self.statusmsg["false"])
Example #6
0
def shorten(word, word_eol, userdata):
    params = {
        'version': '2.0.1',
        'login': USERNAME,
        'apiKey': API_KEY,
        'longUrl': word[1],
        'format': 'json',
    }
    urlparts = ('https', 'api-ssl.bit.ly', '/shorten',
                urllib.parse.urlencode(params), '')
    url = urllib.parse.urlunsplit(urlparts)
    request = urllib.request.Request(url)
    response = urllib.request.urlopen(request)
    data = json.loads(response.read().decode('utf-8'))
    if data['errorCode'] != 0 or data['errorMessage']:
        hexchat.emit_print('Generic Message', '*', '\x0304An error occured:')
        hexchat.emit_print(
            'Generic Message', '*',
            '\x0304({}) {}'.format(data['errorCode'], data['errorMessage']))
        return hexchat.EAT_HEXCHAT

    short_url = None
    for url in data['results']:
        short_url = data['results'][url].get('shortUrl', None)

    if short_url is not None:
        hexchat.prnt('Shortened URL: {}'.format(short_url))
        return hexchat.EAT_HEXCHAT

    hexchat.prnt('Shortening failed!')
    return hexchat.EAT_HEXCHAT
def ud(word, word_eol, userdata):
	try:
		r = requests.get('http://api.urbandictionary.com/v0/define', params={'term': word_eol[1]})
		data = r.json()['list'][0]
		hexchat.prnt('Urban Dictionary -> ' + data['word'] + ': ' + data['definition'])
	except:
		hexchat.prnt('Urban Dictionary: ENGLISH, M**********R DO YOU SPEAK IT???')	
Example #8
0
def onMessage(word, word_eol, userdata):
	try:
	  gameDirector.parse(word[0], word[1])
	  return hexchat.EAT_NONE
	except:
		hexchat.prnt('Fout bij het parsen van ' + word[0] + ': ' + word[1] + '.')
		return hexchat.EAT_NONE
Example #9
0
def viewdb():
	if os.path.isfile(addonsfolder1.replace('s\\"','s\\') + db):
		"""hexchat.prnt("there is a database, will be used...")"""
	else:
		hexchat.prnt("there is not a db, will be created...")
		makedb();
	return;
Example #10
0
def toggle(words, word_eols, userdata):
    global enabled
    enabled = not enabled
    if enabled:
        hexchat.prnt("Rainbow text is now enabled")
    else:
        hexchat.prnt("Rainbow text is now disabled")
Example #11
0
  def play_sound(self):
    sound = random.choice(self.file_list)
    active = hexchat.get_pluginpref("soundalert_active")

    if self.debug == True:
      hexchat.prnt("Playing: {}".format(os.path.abspath(sound)))

    else:
      if not active:
        return

    if sound == False:
      hexchat.prnt("Could not find default share/sounds directory, and no sounds directory is specified. See /help soundalert.")

    if os.name == "nt":
      winsound.PlaySound(sound, winsound.SND_FILENAME ^ winsound.SND_ASYNC)

    elif os.name == "posix":
      xine = pyxine.Xine()
      stream = xine.stream_new()
      stream.open(sound)
      stream.Play()

    self.debug = False
    return True
Example #12
0
    def commands(self, word, word_eol, userdata):
        if len(word) < 2:
            hexchat.prnt("Not enough arguments given. See /help soundalert")

        else:
            if word[1] == "set":
                if len(word) < 3:
                    hexchat.prnt("No directory specified.")

                if os.path.isdir(word_eol[2]):
                    hexchat.set_pluginpref("soundalert_dir", word_eol[2])
                    self.sound_directory = self.find_sound_directory()
                    self.file_list = self.find_sounds()

                else:
                    hexchat.prnt("Not a valid directory.")

            elif word[1] == "on":
                self.enable()

            elif word[1] == "off":
                self.disable()

            elif word[1] == "get":
                hexchat.prnt("Currently set sound directory: {}".format(
                    hexchat.get_pluginpref("soundalert_dir")))

            elif word[1] == "test":
                self.debug = True
                self.spawn(None, None, None)

            else:
                hexchat.prnt("No such command exists.")

        return hexchat.EAT_ALL
Example #13
0
    def play_sound(self):
        sound = random.choice(self.file_list)
        active = hexchat.get_pluginpref("soundalert_active")

        if self.debug == True:
            hexchat.prnt("Playing: {}".format(os.path.abspath(sound)))

        else:
            if not active:
                return

        if sound == False:
            hexchat.prnt(
                "Could not find default share/sounds directory, and no sounds directory is specified. See /help soundalert."
            )

        if os.name == "nt":
            winsound.PlaySound(sound,
                               winsound.SND_FILENAME ^ winsound.SND_ASYNC)

        elif os.name == "posix":
            xine = pyxine.Xine()
            stream = xine.stream_new()
            stream.open(sound)
            stream.Play()

        self.debug = False
        return True
Example #14
0
def reply(a, b, c):
    hexchat.command("msg " + (a[0].split("!")[0][1:]) + " " + str(count))
    #hexchat.command("msg "+(a[0].split("!")[0][1:])+" the time is 11:30")
    count += 1
    hexchat.prnt((a[0].split("@"))[-1])
    #hexchat.prnt(str(a)+str(b)+str(c))
    return hexchat.EAT_NONE
Example #15
0
  def commands(self, word, word_eol, userdata):
    if len(word) < 2:
      hexchat.prnt("Not enough arguments given. See /help soundalert")
    
    else:      
      if word[1] == "set":
        if len(word) < 3:
          hexchat.prnt("No directory specified.")
        
        if os.path.isdir(word_eol[2]):
          hexchat.set_pluginpref("soundalert_dir", word_eol[2])
          self.sound_directory = self.find_sound_directory()
          self.file_list = self.find_sounds()

        else:
          hexchat.prnt("Not a valid directory.")

      elif word[1] == "on":
        self.enable()

      elif word[1] == "off":
        self.disable()

      elif word[1] == "get":
        hexchat.prnt("Currently set sound directory: {}".format(hexchat.get_pluginpref("soundalert_dir")))

      elif word[1] == "test":
        self.debug = True
        self.spawn(None, None, None)

      else:
        hexchat.prnt("No such command exists.")

    return hexchat.EAT_ALL
Example #16
0
def greplog(channel, pattern):

    logmask = hexchat.get_prefs("irc_logmask")
    logfile = logmask.replace("%n", hexchat.get_info("network")).replace("%s",hexchat.get_info("server")).replace("%c",channel)
    logfile = os.path.join(hexchat.get_info("configdir"), "logs", logfile)

    if not os.path.isfile(logfile):
        error("log-file %s does not exist" % logfile)
        return hexchat.EAT_ALL

    if is_linux:
        # on linux
        hexchat.command("exec grep '" + pattern + "' " + logfile)

    else:
        with open(logfile, "r") as f:
            for line in f:
                try:
                    if re.search(pattern, line):
                        hexchat.prnt(line)
                except:
                    if line.find(pattern) > -1:
                        hexchat.prnt(line)

    return hexchat.EAT_ALL
Example #17
0
def toggle(words, word_eols, userdata):
    global enabled
    enabled = not enabled
    if enabled:
    	hexchat.prnt("\"Typing...\" is now enabled")
    else:
    	hexchat.prnt("\"Typing...\" is now disabled")
def now_playing(word, word_eol, userdata):
	try:
	# URL for MPC web interface. Check under Options -> Web Interface, listen on port and allow localhost only.
		url = 'http://127.0.0.1:13579/info.html'
	
	# Request the URL
		r = requests.get(url)

	# Get the body of the page
		content = r.text

	# Convert text to CP1252 encoding since that's what the MPC Web interface reports
		convert = content.encode('cp1252').decode('utf-8')
		
	# Convert the html content into a beautiful soup object
		soup = BeautifulSoup(convert, "html5lib")

	# If no web interface then MPC isn't running
	except:
		hexchat.prnt('Nothing open in MPC')
		return
		
	# Get the info from the page to parse with regex
	nowplaying = soup.p.string
	
	# Take the text found on the page and run it through regex to grab the info	
	line = re.search('(MPC.*?)\s(.*?)\s•\s(.*?)\s•\s(.*?)\s•\s(.*?(GB|MB))', nowplaying, flags=re.UNICODE)
	if len(word) > 1 and (word[1] == 'v' or word[1] == 'full'):
		hexchat.command('SAY Now Playing in {1} : {3} @ {4} [{5}]'.format(line.group(0), line.group(1), line.group(2), line.group(3), line.group(4), line.group(5)))
	else:
		hexchat.command('SAY Now Playing in {1} : {3} '.format(line.group(0), line.group(1), line.group(2), line.group(3), line.group(4), line.group(5)))
	return hexchat.EAT_ALL
Example #19
0
 def main_menu(self, word, word_eol, userdata):
     if '@test ' == word[1][0:6]:
         hexchat.prnt('Success')
         return hexchat.EAT_ALL
     elif word[1].startswith('$anime '):
         if len(word[1]) == 7:
             return hexchat.EAT_ALL
         self.function = AnimeTiming(word[1][7:])
         self.function = None
         return hexchat.EAT_ALL
     elif word[1].startswith('$poll '):
         self.state = 'poll'
         self.function = Poll(word[1][6:])
         self.t = threading.Timer(15, self.poll_complete)
         self.t.start()
         return hexchat.EAT_ALL
     elif word[1][0:13] == '$settimezone ' or word[1].startswith('$time'):
         self.function = TimeZoneCheck(word[1], word[0].lower())
         self.function = None
         return hexchat.EAT_ALL
     elif word[1].startswith('$money'):
         self.function = Money()
         hexchat.command('say %s has %d NanoDollars.' %(word[0], self.function.check(word[0].lower())))
         self.function = None
         return hexchat.EAT_ALL
     elif word[1].startswith('$blackjack'):
         self.state = 'preblackjack'
         hexchat.command('me puts on a tuxedo and sets up the table.')
         hexchat.command('say %s has started a game of blackjack! Everyone is free to $join in! (Once ready, press $start)' %(word[0]))
         self.function = blackjack.Game()
         self.add_blackjack_player(word[0].lower())
     else:
         self.setactiveuser(word[0])
         return hexchat.EAT_ALL
Example #20
0
def shorten(word, word_eol, userdata):
    params = {
        'version': '2.0.1',
        'login': USERNAME,
        'apiKey': API_KEY,
        'longUrl': word[1],
        'format': 'json',
    }
    urlparts = ('https', 'api-ssl.bit.ly', '/shorten',
                urllib.parse.urlencode(params), '')
    url = urllib.parse.urlunsplit(urlparts)
    request = urllib.request.Request(url)
    response = urllib.request.urlopen(request)
    data = json.loads(response.read().decode('utf-8'))
    if data['errorCode'] != 0 or data['errorMessage']:
        hexchat.emit_print('Generic Message', '*', '\x0304An error occured:')
        hexchat.emit_print('Generic Message', '*', '\x0304({}) {}'.format(
            data['errorCode'], data['errorMessage']))
        return hexchat.EAT_HEXCHAT

    short_url = None
    for url in data['results']:
        short_url = data['results'][url].get('shortUrl', None)

    if short_url is not None:
        hexchat.prnt('Shortened URL: {}'.format(short_url))
        return hexchat.EAT_HEXCHAT

    hexchat.prnt('Shortening failed!')
    return hexchat.EAT_HEXCHAT
Example #21
0
def slap_func(word, word_eol, userdata):
    if len(word) >= 2:
        for nick in word[1:]:
            hexchat.command("me slaps \002{}\002 around a bit with a large trout.".format(nick))
    else:
        hexchat.prnt(str_prefix + "Could not slap. " + help)
    return hexchat.EAT_ALL
Example #22
0
def autoback_cb(word, word_eol, userdata):

    with AutobackConfig() as autoback:
        enabled = autoback.enabled

    if enabled:
        current_network = hexchat.get_info("network")
        with NetworkList() as networks:
            away_networks = list(networks._get_away())

        if current_network in away_networks:
            # "AutobackConfig(1)", 1 to increment .talk_count
            with AutobackConfig(1) as autoback:
                hexchat.prnt(str_prefix + \
                    "\002warning:\002 you've talked " + \
                        "\002{}\002/\002{}\002 times while away.".format(
                            autoback.talk_count, autoback.threshold))
                if autoback.talk_count >= autoback.threshold:
                    hexchat.prnt(str_prefix + \
                        "You will be set back on network \002{}\002".format(
                            current_network))
                    autoback.talk_count = 0
                    suffix = hexchat.get_pluginpref("hcaway_suffix")
                    context = hexchat.find_context(server=current_network)
                    context.command("nick {}".format(
                        context.get_info("nick").replace(suffix, "")))
                    context.command("back")

    return hexchat.EAT_NONE
Example #23
0
def get_song(word, word_eol, userdata):
    # Check if the user is logged in
    if (not os.path.exists(SESSION_KEY_FILE)) or (
            not os.path.exists(USERNAME_FILE)):
        hexchat.prnt(
            ">> You need to log into your lastfm account: /fmlogin <username>")
        return hexchat.EAT_ALL

    # The user is logged in, so proceed
    try:
        # Get the username from the file
        fp = open(USERNAME_FILE, "r")
        username = fp.read()
        fp.close()

        # And find out what he's listening to
        user = network.get_user(username)
        track = user.get_now_playing()
        hexchat.command('me is listening to ' + str(track.title) + ' by ' +
                        str(track.artist) + '.')
    except:
        hexchat.prnt(
            ">> Something's gone wrong! Are you sure you're scrobbling to lastfm?"
        )
    return hexchat.EAT_ALL
Example #24
0
 def addToQuizz(self, question, nick, channel):
     try:
         qmatch = re.compile('((?:#[A-Z#]+)?)(.*?)\\\\(.+)$')
         if qmatch.match(question):
             questionfile = codecs.open(self.quizzfile.str(), 'a', 'utf-8')
             questionfile.write(question + '\n')
             questionfile.close()
             if channel == self.channel.str():
                 self.SendMessage(BOLD + COLORDEFAULT + nick +
                                  ' a ajouté une question !')
             else:
                 self.SendMessage(
                     BOLD + COLORDEFAULT + 'La question a été ajoutée !',
                     nick)
                 self.SendMessage(BOLD + COLORDEFAULT + nick +
                                  ' a ajouté une question !')
             if self.mode > 0:
                 self.writeCooldownFile('cooldowns')
                 if self.currentQuestion:
                     currentQuestionId = self.questions.index(
                         self.currentQuestion)
                 self.loadQuizz()
                 if currentQuestionId:
                     self.currentQuestion = self.questions[
                         currentQuestionId]
             return True
     except Exception as e:
         hexchat.prnt(BOLD + 'Le fichier ' + self.quizzfile.str() +
                      ' n\'a pas pu être ouvert en écriture.')
         if questionfile:
             questionfile.close()
         return False
Example #25
0
def toggle(words, word_eols, userdata):
    global enabled
    enabled = not enabled
    if enabled:
        hexchat.prnt("Rainbow text is now enabled")
    else:
        hexchat.prnt("Rainbow text is now disabled")
def key_press(word, word_eol, userdata):
    global confirm
    key = int(word[0])
    modifier = int(word[1])

    if key == 65293 or key == 65421:
        message = hexchat.get_info('inputbox')

        if not re.search('[\r\n]', message):
            return hexchat.EAT_NONE

        if modifier == 0:
            if confirm:
                confirm = False
                return hexchat.EAT_NONE

            hexchat.prnt('The input field contains a multiline message. Press \002enter\002 again to send or \002shift+enter\002 to replace newlines with " | ".')
            confirm = True
            return hexchat.EAT_ALL

        elif modifier == 1:
            message = re.sub('(^\s+|\s+$)', '', message)
            message = re.sub('\s*[\r\n]+\s*', ' | ', message)
            hexchat.command('SETTEXT %s' % message)
            return hexchat.EAT_ALL

    else:
        confirm = False

    return hexchat.EAT_NONE
Example #27
0
 def loadQFile(self):
     self.questions = []
     try:
         questionfile = codecs.open(self.quizzfile.str(), 'r', 'utf-8')
         qmatch = re.compile('((?:#[A-Z#]+)?)(.*?)\\\\(.+)$')
         for line in questionfile:
             result = qmatch.match(line)
             if result:
                 type = result.group(1)[1:]
                 enunciated = result.group(2)
                 if type == 'S':
                     answers = [result.group(3)]
                 else:
                     answers = result.group(3).split(
                         '\\')  # Last character is a line ending
                 self.questions.append(Question(type, enunciated, answers))
         questionfile.close()
         hexchat.prnt('Fichier ' + questionfile.name + ' lu. ' +
                      str(len(self.questions)) + ' questions chargées !')
         return True
     except Exception as e:
         hexchat.prnt('Le fichier \'' + self.quizzfile.str() +
                      '\' n\'a pas pu être ouvert en lecture.' + str(e))
         if questionfile:
             questionfile.close()
         return False
Example #28
0
	def addToQuizz(self, question, nick, channel):
		try:
			qmatch = re.compile('((?:#[A-Z#]+)?)(.*?)\\\\(.+)$')
			if qmatch.match(question):
				questionfile = codecs.open(self.quizzfile.str(), 'a', 'utf-8')
				questionfile.write(question + '\n')
				questionfile.close()
				if channel == self.channel.str():
					self.SendMessage(BOLD + COLORDEFAULT + nick + ' a ajouté une question !')
				else:
					self.SendMessage(BOLD + COLORDEFAULT + 'La question a été ajoutée !', nick)
					self.SendMessage(BOLD + COLORDEFAULT + nick + ' a ajouté une question !')
				if self.mode > 0:
					self.writeCooldownFile('cooldowns')
					if self.currentQuestion:
						currentQuestionId = self.questions.index(self.currentQuestion)
					self.loadQuizz()
					if currentQuestionId:
						self.currentQuestion = self.questions[currentQuestionId]
				return True
		except Exception as e:
			hexchat.prnt(BOLD + 'Le fichier ' + self.quizzfile.str() + ' n\'a pas pu être ouvert en écriture.')
			if questionfile:
				questionfile.close()
			return False
Example #29
0
def icu(word, word_eol, userdata):
    if len(word) < 4:
        hexchat.prnt(__module_help_message__)
        return hexchat.EAT_ALL

    contexts = userdata
    this_context = hexchat.get_context()
    operation = word[1]
    direction = word[2]
    destination = word[3]

    potential_context = hexchat.find_context(channel=destination)
    if potential_context == None:
        hexchat.prnt("Could not find {}.".format(destination))
        return hexchat.EAT_ALL

    if operation == "add":
        if direction == "to":
            contexts["to"].append(potential_context)
        elif direction == "from":
            contexts["from"].append(potential_context)
        this_context.prnt("Added relay {} {}".format(direction, destination))

    if operation == "del":
        if direction == "to":
            contexts["to"].remove(potential_context)
        elif direction == "from":
            contexts["from"].remove(potential_context)
        this_context.prnt("Deleted relay {} {}".format(direction, destination))

    return hexchat.EAT_ALL
Example #30
0
def unload_callback(userdata):
    # find the join/part tab and close it
    for chan in hexchat.get_list("channels"):
        if chan.type == 1 and chan.channel == tab_name:
            jp_context = hexchat.find_context(channel=tab_name)
            jp_context.command("CLOSE")
    hexchat.prnt(__module_name__ + " version " + __module_version__ + " unloaded")
Example #31
0
def unload_cb(userdata):
    for chan in hexchat.get_list("channels"):
        if chan.type == 1 and chan.channel == tab_name:
            ad_context = hexchat.find_context(channel=tab_name)
            ad_context.command("CLOSE")
    hexchat.prnt(__module_name__ + " version " + __module_version__ +
                 " unloaded")
Example #32
0
def nowplaying_callback(word, word_eol, user_data):
    try:
        data = ET.parse(xml_file).getroot()

        message = ''

        audio = data.find('audio')
        if audio is not None:
            name = get_child_value(data, 'name')
            if name is not None:
                message = 'listening to'

                disc_number = get_child_int_value(audio, 'disc_number')
                total_discs = get_child_int_value(audio, 'total_discs')
                track_number = get_child_int_value(audio, 'track_number')

                if disc_number is not None and total_discs is not None and total_discs > 1:
                    if track_number is not None:
                        message += ' {0:01d}-{1:02d}'.format(
                            disc_number, track_number)
                    else:
                        message += ' {0:01d}-?'.format(disc_number)

                elif track_number is not None:
                    message += ' {0:02d}'.format(track_number)

                message += ' {0}'.format(name)

                album_title = get_child_value(audio, 'album_title')
                if album_title is not None:
                    message += ' ({0})'.format(album_title)

                artist = get_child_value(audio, 'artist')
                if artist is not None:
                    message += ' by {0}'.format(artist)
                else:
                    album_artist = get_child_value(audio, 'album_artist')
                    if album_artist is not None:
                        message += ' by {0}'.format(album_artist)

        else:
            for source_url in (other.findall('source_url')
                               for other in data.findall('other')):
                message = 'playing {0}'.format(source_url)
                break

    except (FileNotFoundErrorType, ET.ParseError):
        pass

    if message:
        command = 'me is {0}'.format(message)

        if sys.version_info[0] < 3:
            command = command.encode('utf-8')

        hexchat.command(command)
    else:
        hexchat.prnt('Error in {0}'.format(xml_file))

    return hexchat.EAT_ALL
Example #33
0
def setup_channels(word, word_eol, user_data):
    # Callback for: server motd-received event
    # Unhook and /join channels
    hexchat.unhook(setup_channels)
    hexchat.prnt('FOOOOOOOOOOOOOOOOOO')
    x = hexchat.list_pluginpref()
    hexchat.prnt(x)
Example #34
0
File: qc.py Project: SoniEx2/Stuff
 def setter(self, value):
     self.value = value
     hexchat.set_pluginpref("queercraft_{}".format(self.name), str(value))
     if value and self.statusmsg.get("true", None):
         hexchat.prnt(self.statusmsg["true"])
     elif (not value) and self.statusmsg.get("false", None):
         hexchat.prnt(self.statusmsg["false"])
Example #35
0
def hcaway_cb(word, word_eol, userdata):
    away_time, reason = time.strftime("%H:%M (%b %d %Y) %z"), ""
    suffix = hexchat.get_pluginpref("hcaway_suffix")

    away_string = "'{}' at {}".format(__module_fullname__, away_time)
    if len(word) > 1:
        away_string = "'{}' at {}".format(word_eol[1], away_time)
        reason = " reason: \"{}\"".format(word_eol[1])

    with NetworkList() as networks:
        # networks that the user is not away on
        whitelist = list(networks._get_back())
        for network in whitelist:
            context = hexchat.find_context(server=network)
            context.command("nick {}{}".format(
                context.get_info("nick"), suffix))
            context.command("away " + away_string)

    if len(whitelist) >= 1:
        hexchat.prnt(str_prefix + "you're now away on \002{}\002.{}".format(
            ("\002, \002".join(whitelist[0:-1]) + "\002 and \002" + \
                whitelist[-1]) if len(whitelist) > 1 else (whitelist[0]), 
                    reason))
    else:
        error("either you've no networks added to your whitelist, "
            "or you're already away on one or more of them.")

    return hexchat.EAT_ALL
def loadJSON(url):
	try:
		r = requests.get(url, timeout=3)
		return r.json()
	except Exception as e:
		hexchat.prnt('Exception: ' + e.message)
		return None
Example #37
0
def enchode(word, word_eol, userdata):
    # Usage
    #  /enchode [-flags] [/me]
    # Flags
    #  sN: strokes, where N is the number of strokes to apply
    #  lN: length, where N is the maximum length message to output
    # The following three flags are mutually exclusive:
    #  m: mixed chodes
    #  t: thin chodes
    #  w: wide chodes
    cmds = {
        b'say ': {
            b'event': b'Channel Message',
            b'fmt': b'QUOTE PRIVMSG {} :{}'
        },
        b'me ': {
            b'event': b'Channel Action',
            b'fmt': b'QUOTE PRIVMSG {} :\x01ACTION {}\x01'
        }
    }
    cmd = b'say '
    flags = {b'strokes': 2, 'mode': b't', b'length': 340}
    modes = {
        b'm': cpi.CyphallicMethod.MIXED_CHODE,
        b't': cpi.CyphallicMethod.THIN_CHODE,
        b'w': cpi.CyphallicMethod.WIDE_CHODE
    }
    args = word_eol[1]
    if args[0:2] == b'--':
        args = args[1:]
    else:
        matches = RE_CMD.match(args)
        if matches:
            groups = matches.groupdict()
            for key in set(groups).intersection(flags):
                val = groups[key]
                if val is not None:
                    flags[key] = int(val) if val.isdigit() else val
            args = args[matches.end(0):]
    if args[0:2] == b'//':
        args = args[1:]
    elif args[0] == b'/':
        if args[0:4] == b'/me ':
            args = args[4:]
            cmd = b'me '
        else:
            hexchat.prnt(
                b'"{0}" not allowed here. Did you mean "/{0}"?'.format(
                    args[:args.find(b' ')]))
            return None
    text = api.enchode(bytearray(args), flags[b'strokes'],
                       modes[flags[b'mode']], flags[b'length'])
    target = hexchat.get_info('channel')
    for line in text.splitlines():
        hexchat.command(cmds[cmd][b'fmt'].format(target, line))
    hexchat.emit_print(cmds[cmd][b'event'],
                       sformat(hexchat.get_info(b'nick'), flags[b'strokes']),
                       args)
    return hexchat.EAT_HEXCHAT
Example #38
0
def setignorer(word, word_eol, userdata):
    global ignores
    if len(word) != 2:
        hexchat.command('HELP ' + word[0])
        return
    ignores.append(word[1])
    hexchat.prnt('user {0} successfully added to ignore list'.format(word[1]))
    saveconf()
Example #39
0
def loadlist():
    global ignorelist
    global botlist
    try:
        ignorelist = eval(hexchat.get_pluginpref('ignorelist'))
        botlist = eval(hexchat.get_pluginpref('botlist'))
    except Exception as e:
        hexchat.prnt(str(e))
Example #40
0
	def command(self, word, word_eol, userdata):
		if (len(word)>1):
			newValue = word_eol[1]
			self.value = newValue
			if self.pluginpref:
				hexchat.set_pluginpref(self.pluginpref, newValue)
		hexchat.prnt( word[0].upper() + ': ' + str(self.value))
		return hexchat.EAT_ALL
Example #41
0
 def command(self, word, word_eol, userdata):
     if (len(word) > 1):
         newValue = word_eol[1]
         self.value = newValue
         if self.pluginpref:
             hexchat.set_pluginpref(self.pluginpref, newValue)
     hexchat.prnt(word[0].upper() + ': ' + str(self.value))
     return hexchat.EAT_ALL
Example #42
0
def setignorer(word, word_eol, userdata):
    global ignores
    if len(word) !=  2:
        hexchat.command('HELP '+ word[0])
        return 
    ignores.append(word[1])
    hexchat.prnt('user {0} successfully added to ignore list'.format(word[1]))
    saveconf()
Example #43
0
    def remove_target(self, context):
        """ Messages call this to notice us when they are done pasting. """

        if not context in self.targets:
            raise HexPasteError('HexPaste: internal error, removing unknown context?!')

        del self.targets[context]
        hexchat.prnt('HexPaste: finished pasting to: {}.'.format(context))
def cmd_slap(word, word_eol, userdata):
    slapstring = "with a %s %s" %(random.choice(size), random.choice(items))
    if len(word) < 2:
        hexchat.prnt("Choose a nick please")
        return hexchat.EAT_ALL
    if len(word) == 2:
        hexchat.command("me slaps %s around a bit %s " %(word[1], slapstring))
        return hexchat.EAT_ALL
Example #45
0
def commandStatus(w, we, u):
    for p in ChanServPromise.promises:
        hexchat.prnt("[" + str(netId(p.ctx)) + "] Waiting for ChanServ in " +
                     p.channel)
    for p in WhoisPromise.promises:
        hexchat.prnt("[" + str(netId(p.ctx)) +
                     "] Waiting for WHOIS reply for " + p.nick)
    return hexchat.EAT_ALL
Example #46
0
def unload(userdata):
    try:
        with open(STATE_FILE_PATH, 'wb') as f:
            dump(PREFS, f)
    except Exception as e:
        hexchat.prnt(str(e))

    hexchat.prnt('{} unloaded'.format(__module_name__))
Example #47
0
def reset_mask_color(word, word_eol, userdata):
    combo = get_combo()

    if combo in PREFS.color_overrides:
        del PREFS.color_overrides[combo]
        hexchat.prnt('Color for {} has been reset'.format(combo))

    return hexchat.EAT_ALL
Example #48
0
def remove_mask(word, word_eol, userdata):
    combo = get_combo()

    if combo in PREFS.masks:
        del PREFS.masks[combo]
        hexchat.prnt('Removed mask for {}'.format(combo))

    return hexchat.EAT_ALL
Example #49
0
def onMessage(word, word_eol, userdata):
    try:
        gameDirector.parse(word[0], word[1])
        return hexchat.EAT_NONE
    except Exception as e:
        dict = {"nick": word[0], "line": word[1], "exception": str(e)}
        hexchat.prnt("Fout bij het parsen van %(nick)s: %(line)s op %(exception)s." % dict)
        return hexchat.EAT_NONE
Example #50
0
    def add(self, network_name = None):
        network_name = network_name or hexchat.get_info("network")

        if network_name not in self.networks:
            self.networks += [network_name]
            hexchat.prnt(str_prefix + "added \002{}\002.".format(network_name))
        else:
            error("\002{}\002 already in network list.".format(network_name))
Example #51
0
File: urc.py Project: suqdiq/urc.py
def prnt(*args):
    if hexchat:
        s = ''
        for arg in args:
            s += '{}'.format(arg)
        hexchat.prnt(s)
    else:
        print (args)
Example #52
0
def delignore(word, word_eol, userdata):
    global ignorelist
    try:
        ignorelist.remove(word[1])
        hexchat.prnt("Removed " + word[1] + " from your ignore list.")
        savelist()
    except: pass
    return hexchat.EAT_ALL
Example #53
0
def enfab_callback(word, word_eol, user_data):
    global fab_hook

    if fab_hook is None:
        fab_hook = hexchat.hook_command('', fab_passthru_callback)
        hexchat.prnt('Fabulous mode on')

    return hexchat.EAT_ALL
Example #54
0
def enfab_callback(word, word_eol, user_data):
	global fab_hook
	
	if fab_hook is None:
		fab_hook = hexchat.hook_command('', fab_passthru_callback)
		hexchat.prnt('Fabulous mode on')
	
	return hexchat.EAT_ALL
def unload_callback(userdata):
    # find the join/part tab and close it
    for chan in hexchat.get_list("channels"):
        if chan.type == 1 and chan.channel == tab_name:
            jp_context = hexchat.find_context(channel=tab_name)
            jp_context.command("CLOSE")
    hexchat.prnt(__module_name__ + " version " + __module_version__ +
                 " unloaded")
Example #56
0
def unalias_cb(word, word_eol, userdata):
    if len(word) > 1:
        if remove_alias(word[1]):
            print('Alias: {} removed'.format(word[1]))
        else:
            print('Alias: {} not found'.format(word[1]))
    else:
        hexchat.prnt('Alias: Not enough arguements')
    return hexchat.EAT_ALL
def whisper_cb(word, word_eol, userdata):
	hexchat.command('PRIVMSG %s :. /w %s' % (hexchat.get_info('channel'), word_eol[1].encode('utf-8')))
	
	whisper = hexchat.get_info('nick') + ' >> ' + word[1] + ': ' + word_eol[2]
	hexchat.prnt('\002\00326' + whisper.encode('utf-8') + '\002\00326')

	return hexchat.EAT_ALL