Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • weechat/scripts
1 result
Show changes
Commits on Source (8)
Loading
Loading
@@ -15,6 +15,8 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# 2017-11-03: fix script/issue #236
# v0.2: add "%h" variable in option 'file'
 
import os
import re
Loading
Loading
@@ -31,7 +33,7 @@ except Exception:
 
NAME = "autoconf"
AUTHOR = "Manu Koell <manu@koell.li>"
VERSION = "0.1"
VERSION = "0.2"
LICENSE = "GPL3"
DESCRIPTION = "auto save/load changed options in a ~/.weerc file, useful to share dotfiles with"
 
Loading
Loading
@@ -49,14 +51,9 @@ SETTINGS = {
'ignore': (
','.join(EXCLUDES),
'comma separated list of patterns to exclude'),
'file': ('~/.weerc', 'config file location')
'file': ('%h/.weerc', 'config file location ("%h" will be replaced by WeeChat home, "~/.weechat" by default)')
}
 
RE = {
'option': re.compile('\s*(.*) = (.*) \(default')
}
def cstrip(text):
"""strip color codes"""
 
Loading
Loading
@@ -68,8 +65,7 @@ def get_config(args):
try:
conf = args[1]
except Exception:
conf = w.config_get_plugin('file')
conf = w.config_get_plugin('file').replace("%h",w.info_get("weechat_dir", ""))
return os.path.expanduser(conf)
 
def load_conf(args):
Loading
Loading
@@ -151,6 +147,10 @@ def quit_cb(data, signal, signal_data):
if __name__ == '__main__':
if w.register(NAME, AUTHOR, VERSION, LICENSE, DESCRIPTION, "", ""):
w.hook_command(NAME, DESCRIPTION, 'save [path] || load [path]', '', 'save || load', 'autoconf_cb', '')
default_txt = w.gettext("default: ") # check if string is translated
RE = {
'option': re.compile('\s*(.*) = (.*) \(%s' % default_txt)
}
 
# set default config
for option, value in SETTINGS.items():
Loading
Loading
@@ -163,5 +163,3 @@ if __name__ == '__main__':
 
if 'on' in w.config_get_plugin('autosave'):
w.hook_signal('quit', 'quit_cb', '')
Loading
Loading
@@ -25,6 +25,13 @@
 
#
# Changelog:
# 3.3:
# * Fix the /autosort debug command for unicode.
# * Update the default rules to work better with Slack.
# 3.2:
# * Fix python3 compatiblity.
# 3.1:
# * Use colors to format the help text.
# 3.0:
# * Switch to evaluated expressions for sorting.
# * Add `/autosort debug` command.
Loading
Loading
@@ -58,12 +65,13 @@
import json
import math
import re
import sys
import time
import weechat
 
SCRIPT_NAME = 'autosort'
SCRIPT_AUTHOR = 'Maarten de Vries <maarten@de-vri.es>'
SCRIPT_VERSION = '3.0'
SCRIPT_VERSION = '3.3'
SCRIPT_LICENSE = 'GPL3'
SCRIPT_DESC = 'Flexible automatic (or manual) buffer sorting based on eval expressions.'
 
Loading
Loading
@@ -72,6 +80,25 @@ config = None
hooks = []
timer = None
 
# Make sure that unicode, bytes and str are always available in python2 and 3.
# For python 2, str == bytes
# For python 3, str == unicode
if sys.version_info[0] >= 3:
unicode = str
def ensure_str(input):
'''
Make sure the given type if the correct string type for the current python version.
That means bytes for python2 and unicode for python3.
'''
if not isinstance(input, str):
if isinstance(input, bytes):
return input.encode('utf-8')
if isinstance(input, unicode):
return input.decode('utf-8')
return input
if hasattr(time, 'perf_counter'):
perf_counter = time.perf_counter
else:
Loading
Loading
@@ -137,9 +164,9 @@ class Config:
'${irc_last}',
'${buffer.plugin.name}',
'${irc_raw_first}',
'${server}',
'${info:autosort_order,${type},server,*,channel,private}',
'${hashless_name}',
'${if:${plugin}==irc?${server}}',
'${if:${plugin}==irc?${info:autosort_order,${type},server,*,channel,private}}',
'${if:${plugin}==irc?${hashless_name}}',
'${buffer.full_name}',
])
 
Loading
Loading
@@ -395,12 +422,13 @@ def command_debug(buffer, command, args):
for merged in buffers:
for buffer in merged:
fullname = weechat.hdata_string(hdata, buffer, 'full_name')
if isinstance(fullname, bytes): fullname = fullname.decode('utf-8')
results.append((fullname, key(buffer)))
elapsed = perf_counter() - start
 
for fullname, result in results:
log('{0}: {1}'.format(fullname, result))
fullname = ensure_str(fullname)
result = [ensure_str(x) for x in result]
log('{0}: {1}'.format(fullname, result))
log('Computing evalutaion results took {0:.4f} seconds.'.format(elapsed))
 
return weechat.WEECHAT_RC_OK
Loading
Loading
@@ -734,95 +762,116 @@ def on_autosort_complete(data, name, buffer, completion):
return autosort_complete_helpers(words[1:], completion)
return weechat.WEECHAT_RC_OK
 
command_description = r'''
NOTE: For the best effect, you may want to consider setting the option irc.look.server_buffer to independent and buffers.look.indenting to on.
# Commands
command_description = r'''{*white}# General commands{reset}
 
## Miscellaneous
/autosort sort
{*white}/autosort {brown}sort{reset}
Manually trigger the buffer sorting.
 
/autosort debug
{*white}/autosort {brown}debug{reset}
Show the evaluation results of the sort rules for each buffer.
 
 
## Sorting rules
{*white}# Sorting rule commands{reset}
 
/autosort rules list
{*white}/autosort{brown} rules list{reset}
Print the list of sort rules.
 
/autosort rules add <expression>
{*white}/autosort {brown}rules add {cyan}<expression>{reset}
Add a new rule at the end of the list.
 
/autosort rules insert <index> <expression>
{*white}/autosort {brown}rules insert {cyan}<index> <expression>{reset}
Insert a new rule at the given index in the list.
 
/autosort rules update <index> <expression>
{*white}/autosort {brown}rules update {cyan}<index> <expression>{reset}
Update a rule in the list with a new expression.
 
/autosort rules delete <index>
{*white}/autosort {brown}rules delete {cyan}<index>
Delete a rule from the list.
 
/autosort rules move <index_from> <index_to>
{*white}/autosort {brown}rules move {cyan}<index_from> <index_to>{reset}
Move a rule from one position in the list to another.
 
/autosort rules swap <index_a> <index_b>
{*white}/autosort {brown}rules swap {cyan}<index_a> <index_b>{reset}
Swap two rules in the list
 
 
## Helper variables
{*white}# Helper variable commands{reset}
 
/autosort helpers list
{*white}/autosort {brown}helpers list
Print the list of helper variables.
 
/autosort helpers set <name> <expression>
{*white}/autosort {brown}helpers set {cyan}<name> <expression>
Add or update a helper variable with the given name.
 
/autosort helpers delete <named>
{*white}/autosort {brown}helpers delete {cyan}<name>
Delete a helper variable.
 
/autosort helpers rename <old_name> <new_name>
{*white}/autosort {brown}helpers rename {cyan}<old_name> <new_name>
Rename a helper variable.
 
/autosort helpers swap <name_a> <name_b>
{*white}/autosort {brown}helpers swap {cyan}<name_a> <name_b>
Swap the expressions of two helper variables in the list.
 
 
# Introduction
Autosort is a weechat script to automatically keep your buffers sorted.
The sort order can be customized by defining your own sort rules,
but the default should be sane enough for most people.
It can also group IRC channel/private buffers under their server buffer if you like.
## Sort rules
Autosort evaluates a list of eval expressions (see /help eval) and sorts the buffers based on evaluated result.
Earlier rules will be considered first.
Only if earlier rules produced identical results is the result of the next rule considered for sorting purposes.
You can debug your sort rules with the `/autosort debug` command, which will print the evaluation results of each rule for each buffer.
NOTE: The sort rules for version 3 are not compatible with version 2 or vice versa.
You will have to manually port your old rules to version 3 if you have any.
## Helper variables
You may define helper variables for the main sort rules to keep your rules readable.
They can be used in the main sort rules as variables.
For example, a helper variable named `foo` can be accessed in a main rule with the string `${foo}`.
## Replacing substrings
There is no default method for replacing text inside eval expressions.
However, autosort adds a `replace` info hook that can be used inside eval expressions: `${info:autosort_replace,from,to,text}`.
For example, `${info:autosort_replace,#,,${buffer.name}}` will evaluate to the buffer name with all hash signs stripped.
You can escape commas and backslashes inside the arguments by prefixing them with a backslash.
## Automatic or manual sorting
By default, autosort will automatically sort your buffer list whenever a buffer is opened, merged, unmerged or renamed.
This should keep your buffers sorted in almost all situations.
However, you may wish to change the list of signals that cause your buffer list to be sorted.
Simply edit the "autosort.sorting.signals" option to add or remove any signal you like.
If you remove all signals you can still sort your buffers manually with the "/autosort sort" command.
To prevent all automatic sorting, "autosort.sorting.sort_on_config_change" should also be set to off.
{*white}# Description
Autosort is a weechat script to automatically keep your buffers sorted. The sort
order can be customized by defining your own sort rules, but the default should
be sane enough for most people. It can also group IRC channel/private buffers
under their server buffer if you like.
{*white}# Sort rules{reset}
Autosort evaluates a list of eval expressions (see {*default}/help eval{reset}) and sorts the
buffers based on evaluated result. Earlier rules will be considered first. Only
if earlier rules produced identical results is the result of the next rule
considered for sorting purposes.
You can debug your sort rules with the `{*default}/autosort debug{reset}` command, which will
print the evaluation results of each rule for each buffer.
{*brown}NOTE:{reset} The sort rules for version 3 are not compatible with version 2 or vice
versa. You will have to manually port your old rules to version 3 if you have any.
{*white}# Helper variables{reset}
You may define helper variables for the main sort rules to keep your rules
readable. They can be used in the main sort rules as variables. For example,
a helper variable named `{cyan}foo{reset}` can be accessed in a main rule with the
string `{cyan}${{foo}}{reset}`.
{*white}# Replacing substrings{reset}
There is no default method for replacing text inside eval expressions. However,
autosort adds a `replace` info hook that can be used inside eval expressions:
{cyan}${{info:autosort_replace,from,to,text}}{reset}
For example, to strip all hashes from a buffer name, you could write:
{cyan}${{info:autosort_replace,#,,${{buffer.name}}}}{reset}
You can escape commas and backslashes inside the arguments by prefixing them with
a backslash.
{*white}# Automatic or manual sorting{reset}
By default, autosort will automatically sort your buffer list whenever a buffer
is opened, merged, unmerged or renamed. This should keep your buffers sorted in
almost all situations. However, you may wish to change the list of signals that
cause your buffer list to be sorted. Simply edit the `{cyan}autosort.sorting.signals{reset}`
option to add or remove any signal you like.
If you remove all signals you can still sort your buffers manually with the
`{*default}/autosort sort{reset}` command. To prevent all automatic sorting, the option
`{cyan}autosort.sorting.sort_on_config_change{reset}` should also be disabled.
{*white}# Recommended settings
For the best visual effect, consider setting the following options:
{*white}/set {cyan}irc.look.server_buffer{reset} {brown}independent{reset}
{*white}/set {cyan}buffers.look.indenting{reset} {brown}on{reset}
The first setting allows server buffers to be sorted independently, which is
needed to create a hierarchical tree view of the server and channel buffers.
The second one indents channel and private buffers in the buffer list of the
`{*default}buffers.pl{reset}` script.
If you are using the {*default}buflist{reset} plugin you can (ab)use Unicode to draw a tree
structure with the following setting (modify to suit your need):
{*white}/set {cyan}buflist.format.indent {brown}"${{color:237}}${{if:${{buffer.next_buffer.local_variables.type}}=~^(channel|private)$?├─:└─}}"{reset}
'''
 
command_completion = '%(plugin_autosort) %(plugin_autosort) %(plugin_autosort) %(plugin_autosort) %(plugin_autosort)'
Loading
Loading
@@ -841,9 +890,33 @@ info_order_arguments = 'value,first,second,third,...'
if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", ""):
config = Config('autosort')
 
colors = {
'default': weechat.color('default'),
'reset': weechat.color('reset'),
'black': weechat.color('black'),
'red': weechat.color('red'),
'green': weechat.color('green'),
'brown': weechat.color('brown'),
'yellow': weechat.color('yellow'),
'blue': weechat.color('blue'),
'magenta': weechat.color('magenta'),
'cyan': weechat.color('cyan'),
'white': weechat.color('white'),
'*default': weechat.color('*default'),
'*black': weechat.color('*black'),
'*red': weechat.color('*red'),
'*green': weechat.color('*green'),
'*brown': weechat.color('*brown'),
'*yellow': weechat.color('*yellow'),
'*blue': weechat.color('*blue'),
'*magenta': weechat.color('*magenta'),
'*cyan': weechat.color('*cyan'),
'*white': weechat.color('*white'),
}
weechat.hook_config('autosort.*', 'on_config_changed', '')
weechat.hook_completion('plugin_autosort', '', 'on_autosort_complete', '')
weechat.hook_command('autosort', command_description, '', '', command_completion, 'on_autosort_command', '')
weechat.hook_command('autosort', command_description.format(**colors), '', '', command_completion, 'on_autosort_command', '')
weechat.hook_info('autosort_replace', info_replace_description, info_replace_arguments, 'on_info_replace', '')
weechat.hook_info('autosort_order', info_order_description, info_order_arguments, 'on_info_order', '')
 
Loading
Loading
Loading
Loading
@@ -26,9 +26,12 @@
# settings:
# plugins.var.python.twitch.servers (default: twitch)
# plugins.var.python.twitch.prefix_nicks (default: 1)
# plugins.var.python.twitch.debug (default: 0)
#
# # History:
#
# 2017-11-02, mumixam
# v0.4: added debug mode for API calls, minor bugfixes
# 2017-06-10, mumixam
# v0.3: fixed whois output of utf8 display names
# 2016-11-03, mumixam
Loading
Loading
@@ -40,12 +43,13 @@
 
SCRIPT_NAME = "twitch"
SCRIPT_AUTHOR = "mumixam"
SCRIPT_VERSION = "0.3"
SCRIPT_VERSION = "0.4"
SCRIPT_LICENSE = "GPL3"
SCRIPT_DESC = "twitch.tv Chat Integration"
OPTIONS={
'servers': ('twitch','Name of server(s) which script will be active on, space seperated'),
'prefix_nicks': ('1','Prefix nicks based on ircv3 tags for mods/subs, This can be cpu intensive on very active chats [1 for enabled, 0 for disabled]')
'prefix_nicks': ('1','Prefix nicks based on ircv3 tags for mods/subs, This can be cpu intensive on very active chats [1 for enabled, 0 for disabled]'),
'debug': ('0','Debug mode')
}
 
 
Loading
Loading
@@ -59,7 +63,7 @@ import ast
 
clientid='awtv6n371jb7uayyc4jaljochyjbfxs'
params = '?client_id='+clientid
curlopt = {"timeout": "5"}
def days_hours_minutes(td):
age = ''
hours = td.seconds // 3600
Loading
Loading
@@ -82,8 +86,8 @@ def twitch_main(data, buffer, args):
if not (server in OPTIONS['servers'].split() and type == 'channel'):
return weechat.WEECHAT_RC_OK
url = 'https://api.twitch.tv/kraken/streams/' + username
url_hook_process = weechat.hook_process(
"url:" + url+params, 7 * 1000, "stream_api", buffer)
weechat.hook_process_hashtable(
"url:" + url+params, curlopt, 7 * 1000, "stream_api", buffer)
return weechat.WEECHAT_RC_OK
 
 
Loading
Loading
@@ -114,7 +118,12 @@ def channel_api(data, command, rc, stdout, stderr):
try:
jsonDict = json.loads(stdout.strip())
except Exception as e:
weechat.prnt(data['buffer'], 'TWITCH: Error with twitch API')
weechat.prnt(data['buffer'], '%stwitch.py: error communicating with twitch api' % weechat.prefix('error'))
if OPTIONS['debug']:
weechat.prnt(data['buffer'],'%stwitch.py: return code: %s' % (weechat.prefix('error'),rc))
weechat.prnt(data['buffer'],'%stwitch.py: stdout: %s' % (weechat.prefix('error'),stdout))
weechat.prnt(data['buffer'],'%stwitch.py: stderr: %s' % (weechat.prefix('error'),stderr))
weechat.prnt(data['buffer'],'%stwitch.py: exception: %s' % (weechat.prefix('error'),e))
return weechat.WEECHAT_RC_OK
currentbuf = weechat.current_buffer()
name = data['name']
Loading
Loading
@@ -144,8 +153,8 @@ def channel_api(data, command, rc, stdout, stderr):
weechat.prnt(data['buffer'], makeutf8(output))
url = 'https://api.twitch.tv/kraken/users/' + \
name.lower() + '/follows/channels'
urlh = weechat.hook_process(
"url:" + url+params, 7 * 1000, "channel_api", str({'buffer': currentbuf, 'name': name, 'dname': dname}))
weechat.hook_process_hashtable(
"url:" + url+params, curlopt, 7 * 1000, "channel_api", str({'buffer': currentbuf, 'name': name, 'dname': dname}))
 
if len(jsonDict) == 18:
dname = jsonDict['display_name']
Loading
Loading
@@ -168,8 +177,8 @@ def channel_api(data, command, rc, stdout, stderr):
pcolor, pformat, dcolor, ncolor, user, dcolor, ccolor))
else:
url = 'https://api.twitch.tv/api/channels/' + data['name'].lower()
urlh = weechat.hook_process(
"url:" + url+params, 7 * 1000, "channel_api", str({'buffer': currentbuf, 'name': name, 'dname': data['name']}))
weechat.hook_process_hashtable(
"url:" + url+params, curlopt, 7 * 1000, "channel_api", str({'buffer': currentbuf, 'name': name, 'dname': data['name']}))
count = jsonDict['_total']
if count:
output = '%s%s %s[%s%s%s]%s %sFollowing%s: %s' % (
Loading
Loading
@@ -182,7 +191,12 @@ def stream_api(data, command, rc, stdout, stderr):
try:
jsonDict = json.loads(stdout.strip())
except Exception as e:
weechat.prnt(data, 'TWITCH: Error with twitch API')
weechat.prnt(data, '%stwitch.py: error communicating with twitch api' % weechat.prefix('error'))
if OPTIONS['debug']:
weechat.prnt(data,'%stwitch.py: return code: %s' % (weechat.prefix('error'),rc))
weechat.prnt(data,'%stwitch.py: stdout: %s' % (weechat.prefix('error'),stdout))
weechat.prnt(data,'%stwitch.py: stderr: %s' % (weechat.prefix('error'),stderr))
weechat.prnt(data,'%stwitch.py: exception: %s' % (weechat.prefix('error'),e))
return weechat.WEECHAT_RC_OK
currentbuf = weechat.current_buffer()
title_fg = weechat.color(
Loading
Loading
@@ -206,7 +220,7 @@ def stream_api(data, command, rc, stdout, stderr):
weechat.prnt(data, 'ERROR: The page could not be found, or has been deleted by its owner.')
return weechat.WEECHAT_RC_OK
if not 'stream' in jsonDict.keys():
weechat.prnt(data, 'TWITCH: Error with twitch API')
weechat.prnt(data, 'twitch.py: Error with twitch API (stream key missing from json)')
return weechat.WEECHAT_RC_OK
if not jsonDict['stream']:
line = "STREAM: %sOFFLINE%s %sCHECKED AT: %s" % (
Loading
Loading
@@ -291,7 +305,7 @@ def twitch_clearchat(data, modifier, modifier_data, string):
rul = weechat.color("-underline")
if user:
if 'ban-duration' in tags:
if tags['ban-reason']:
if 'ban-reason' in tags and tags['ban-reason']:
bn=tags['ban-reason'].replace('\s',' ')
weechat.prnt(buffer,"%s--%s %s has been timed out for %s seconds %sReason%s: %s" %
(pcolor, ccolor, user, tags['ban-duration'], ul, rul, bn))
Loading
Loading
@@ -402,7 +416,7 @@ def twitch_privmsg(data, modifier, server_name, string):
'irc_message_parse', {"message": string})
if message['channel'].startswith('#'):
return string
newmsg = 'PRIVMSG jtv :.w ' + message['nick'] + ' ' + message['text']
newmsg = 'PRIVMSG #%s :/w %s %s' % (message['nick'],message['nick'],message['text'])
return newmsg
 
 
Loading
Loading
@@ -438,8 +452,8 @@ def twitch_whois(data, modifier, server_name, string):
username = msg['nick'].lower()
currentbuf = weechat.current_buffer()
url = 'https://api.twitch.tv/kraken/channels/' + username
url_hook = weechat.hook_process(
"url:" + url+params, 7 * 1000, "channel_api", str({'buffer': currentbuf, 'name': username}))
url_hook = weechat.hook_process_hashtable(
"url:" + url+params, curlopt, 7 * 1000, "channel_api", str({'buffer': currentbuf, 'name': username}))
return ""
 
def config_setup():
Loading
Loading
@@ -449,7 +463,7 @@ def config_setup():
weechat.config_set_plugin(option, value[0])
OPTIONS[option] = value[0]
else:
if option == 'prefix_nicks':
if option == 'prefix_nicks' or option == 'debug':
OPTIONS[option] = weechat.config_string_to_boolean(
weechat.config_get_plugin(option))
else:
Loading
Loading
@@ -457,7 +471,7 @@ def config_setup():
 
def config_change(pointer, name, value):
option = name.replace('plugins.var.python.'+SCRIPT_NAME+'.','')
if option == 'prefix_nicks':
if option == 'prefix_nicks' or option == 'debug':
value=weechat.config_string_to_boolean(value)
OPTIONS[option] = value
return weechat.WEECHAT_RC_OK
Loading
Loading
@@ -469,6 +483,7 @@ if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE,
" settings:\n"
" plugins.var.python.twitch.servers (default: twitch)\n"
" plugins.var.python.twitch.prefix_nicks (default: 1)\n"
" plugins.var.python.twitch.debug (default: 0)\n"
"\n\n"
" This script checks stream status of any channel on any servers listed\n"
" in the \"plugins.var.python.twitch.servers\" setting. When you switch\n"
Loading
Loading
@@ -482,12 +497,15 @@ if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE,
"\n\n"
" This script also will prefix users nicks (@ for mod, % for sub,\n"
" and ~ for broadcaster). This will break the traditional function\n"
" of /ignore add nightbot and will require you to prefix nicks if you\n"
" want to ignore someone /ignore add re:[~@%]{0,3}nightbot should ignore\n"
" of `/ignore add nightbot` and will require you to prefix nicks if you\n"
" want to ignore someone `/ignore add re:[~@%]{0,3}nightbot` should ignore\n"
" a nick with all or none of the prefixes used by this script.\n"
" NOTE: This may cause high cpu usage in very active chat and/or on slower cpus.\n"
" This can also be disabled by setting\n /set plugins.var.python.twitch.prefix_nicks off\n"
"\n\n"
" If you are experiencing errors you can enable debug mode by setting\n"
" /set plugins.var.python.twitch.debug on\n"
"\n\n"
" Required server settings:\n"
" /server add twitch irc.twitch.tv\n"
" /set irc.server.twitch.capabilities \"twitch.tv/membership,twitch.tv/commands,twitch.tv/tags\"\n"
Loading
Loading