<commit_before>"""
The Python parts of the Jedi library for VIM. It is mostly about communicating
with VIM.
"""

import traceback  # for exception output
import re
import os

import vim
import jedi
import jedi.keywords
from jedi._compatibility import unicode

class PythonToVimStr(unicode):
    """ Vim has a different string implementation of single quotes """
    __slots__ = []

    def __repr__(self):
        # this is totally stupid and makes no sense but vim/python unicode
        # support is pretty bad. don't ask how I came up with this... It just
        # works...
        # It seems to be related to that bug: http://bugs.python.org/issue5876
        s = self.encode('UTF-8')
        return '"%s"' % s.replace('\\', '\\\\').replace('"', r'\"')

def echo_highlight(msg):
    vim.command('echohl WarningMsg | echo "%s" | echohl None' % msg)

def get_script(source=None, column=None):
    jedi.settings.additional_dynamic_modules = [b.name for b in vim.buffers
                            if b.name is not None and b.name.endswith('.py')]
    if source is None:
        source = '\n'.join(vim.current.buffer)
    row = vim.current.window.cursor[0]
    if column is None:
        column = vim.current.window.cursor[1]
    buf_path = vim.current.buffer.name
    encoding = vim.eval('&encoding')
    return jedi.Script(source, row, column, buf_path, encoding)

def complete():
    row, column = vim.current.window.cursor
    clear_func_def()
    if vim.eval('a:findstart') == '1':
        count = 0
        for char in reversed(vim.current.line[:column]):
            if not re.match('[\w\d]', char):
                break
            count += 1
        vim.command('return %i' % (column - count))
    else:
        base = vim.eval('a:base')
        source = ''
        for i, line in enumerate(vim.current.buffer):
            # enter this path again, otherwise source would be incomplete
            if i == row - 1:
                source += line[:column] + base + line[column:]
            else:
                source += line
            source += '\n'
        # here again hacks, because jedi has a different interface than vim
        column += len(base)
        try:
            script = get_script(source=source, column=column)
            completions = script.complete()
            call_def = script.get_in_function_call()

            out = []
            for c in completions:
                d = dict(word=PythonToVimStr(c.word[:len(base)] + c.complete),
                         abbr=PythonToVimStr(c.word),
                         # stuff directly behind the completion
                         menu=PythonToVimStr(c.description),
                         info=PythonToVimStr(c.doc),  # docstr
                         icase=1,  # case insensitive
                         dup=1  # allow duplicates (maybe later remove this)
                )
                out.append(d)

            strout = str(out)
        except Exception:
            # print to stdout, will be in :messages
            print(traceback.format_exc())
            strout = ''
            completions = []
            call_def = None

        #print 'end', strout
        show_func_def(call_def, len(completions))
        vim.command('return ' + strout)

def goto(is_definition=False, is_related_name=False, no_output=False):
    definitions = []
    script = get_script()
    try:
        if is_related_name:
            definitions = script.related_names()
        elif is_definition:
            definitions = script.get_definition()
        else:
            definitions = script.goto()
    except jedi.NotFoundError:
        echo_highlight(
                    "Cannot follow nothing. Put your cursor on a valid name.")
    except Exception:
        # print to stdout, will be in :messages
        echo_highlight("Some different eror, this shouldn't happen.")
        print(traceback.format_exc())
    else:
        if no_output:
            return definitions
        if not definitions:
            echo_highlight("Couldn't find any definitions for this.")
        elif len(definitions) == 1 and not is_related_name:
            # just add some mark to add the current position to the jumplist.
            # this is ugly, because it overrides the mark for '`', so if anyone
            # has a better idea, let me know.
            vim.command('normal! m`')

            d = list(definitions)[0]
            if d.in_builtin_module():
                if isinstance(d.definition, jedi.keywords.Keyword):
                    echo_highlight(
                            "Cannot get the definition of Python keywords.")
                else:
                    echo_highlight("Builtin modules cannot be displayed.")
            else:
                if d.module_path != vim.current.buffer.name:
                    vim.eval('jedi#new_buffer(%s)' % \
                                        repr(PythonToVimStr(d.module_path)))
                vim.current.window.cursor = d.line_nr, d.column
                vim.command('normal! zt')  # cursor at top of screen
        else:
            # multiple solutions
            lst = []
            for d in definitions:
                if d.in_builtin_module():
                    lst.append(dict(text=
                                PythonToVimStr('Builtin ' + d.description)))
                else:
                    lst.append(dict(filename=PythonToVimStr(d.module_path),
                                    lnum=d.line_nr, col=d.column + 1,
                                    text=PythonToVimStr(d.description)))
            vim.eval('setqflist(%s)' % repr(lst))
            vim.eval('<sid>add_goto_window()')
    return definitions

def show_pydoc():
    script = get_script()
    try:
        definitions = script.get_definition()
    except jedi.NotFoundError:
        definitions = []
    except Exception:
        # print to stdout, will be in :messages
        definitions = []
        print("Exception, this shouldn't happen.")
        print(traceback.format_exc())

    if not definitions:
        vim.command('return')
    else:
        docs = ['Docstring for %s\n%s\n%s' % (d.desc_with_module, '='*40, d.doc) if d.doc
                    else '|No Docstring for %s|' % d for d in definitions]
        text = ('\n' + '-' * 79 + '\n').join(docs)
        vim.command('let l:doc = %s' % repr(PythonToVimStr(text)))
        vim.command('let l:doc_lines = %s' % len(text.split('\n')))

def clear_func_def():
    cursor = vim.current.window.cursor
    e = vim.eval('g:jedi#function_definition_escape')
    regex = r'%sjedi=([0-9]+), ([^%s]*)%s.*%sjedi%s'.replace('%s', e)
    for i, line in enumerate(vim.current.buffer):
        match = re.search(r'%s' % regex, line)
        if match is not None:
            vim_regex = r'\v' + regex.replace('=', r'\=') + '.{%s}' % \
                                                        int(match.group(1))
            vim.command(r'try | %s,%ss/%s/\2/g | catch | endtry' \
                                                % (i + 1, i + 1, vim_regex))
            vim.eval('histdel("search", -1)')
            vim.command('let @/ = histget("search", -1)')
    vim.current.window.cursor = cursor

def show_func_def(call_def=None, completion_lines=0):
    if vim.eval("has('conceal') && g:jedi#show_function_definition") == '0':
        return
    try:
        if call_def == None:
            call_def = get_script().get_in_function_call()
        clear_func_def()

        if call_def is None:
            return

        row, column = call_def.bracket_start
        if column < 2 or row == 0:
            return  # edge cases, just ignore

        # TODO check if completion menu is above or below
        row_to_replace = row - 1
        line = vim.eval("getline(%s)" % row_to_replace)

        insert_column = column - 2  # because it has stuff at the beginning

        params = [p.get_code().replace('\n', '') for p in call_def.params]
        try:
            params[call_def.index] = '*%s*' % params[call_def.index]
        except (IndexError, TypeError):
            pass

        # This stuff is reaaaaally a hack! I cannot stress enough, that this is
        # a stupid solution. But there is really no other yet. There is no
        # possibility in VIM to draw on the screen, but there will be one (see
        # :help todo Patch to access screen under Python. (Marko Mahni, 2010
        # Jul 18))
        text = " (%s) " % ', '.join(params)
        text = ' ' * (insert_column - len(line)) + text
        end_column = insert_column + len(text) - 2  # -2 due to bold symbols

        # Need to decode it with utf8, because vim returns always a python 2
        # string even if it is unicode.
        e = vim.eval('g:jedi#function_definition_escape').decode('UTF-8')
        # replace line before with cursor
        regex = "xjedi=%sx%sxjedix".replace('x', e)

        prefix, replace = line[:insert_column], line[insert_column:end_column]

        # Check the replace stuff for strings, to append them
        # (don't want to break the syntax)
        regex_quotes = r'''\\*["']+'''
        # `add` are all the quotation marks.
        # join them with a space to avoid producing '''
        add = ' '.join(re.findall(regex_quotes, replace))
        # search backwards
        if add and replace[0] in ['"', "'"]:
            a = re.search(regex_quotes + '$', prefix)
            add = ('' if a is None else a.group(0)) + add

        tup = '%s, %s' % (len(add), replace)
        repl = prefix + (regex % (tup, text)) + add + line[end_column:]

        vim.eval('setline(%s, %s)' % \
                            (row_to_replace, repr(PythonToVimStr(repl))))
    except Exception:
        print(traceback.format_exc())

def rename():
    if not int(vim.eval('a:0')):
        _rename_cursor = vim.current.window.cursor

        vim.command('normal A ')  # otherwise startinsert doesn't work well
        vim.current.window.cursor = _rename_cursor

        vim.command('augroup jedi_rename')
        vim.command('autocmd InsertLeave <buffer> call jedi#rename(1)')
        vim.command('augroup END')

        vim.command('normal! diw')
        vim.command(':startinsert')
    else:
        cursor = vim.current.window.cursor
        window_path = vim.current.buffer.name
        # reset autocommand
        vim.command('autocmd! jedi_rename InsertLeave')

        replace = vim.eval("expand('<cword>')")
        vim.command('normal! u')  # undo new word
        vim.command('normal! u')  # 2u didn't work...

        if replace is None:
            echo_highlight('No rename possible, if no name is given.')
        else:
            temp_rename = goto(is_related_name=True, no_output=True)
            # sort the whole thing reverse (positions at the end of the line
            # must be first, because they move the stuff before the position).
            temp_rename = sorted(temp_rename, reverse=True,
                                key=lambda x: (x.module_path, x.start_pos))
            for r in temp_rename:
                if r.in_builtin_module():
                    continue

                if vim.current.buffer.name != r.module_path:
                    vim.eval("jedi#new_buffer('%s')" % r.module_path)

                vim.current.window.cursor = r.start_pos
                vim.command('normal! cw%s' % replace)

            vim.eval("jedi#new_buffer('%s')" % window_path)
            vim.current.window.cursor = cursor
            echo_highlight('Jedi did %s renames!' % len(temp_rename))

def tabnew(path):
    path = os.path.abspath(path)
    for tab_nr in range(int(vim.eval("tabpagenr('$')"))):
        for buf_nr in vim.eval("tabpagebuflist(%i + 1)" % tab_nr):
            buf_nr = int(buf_nr) - 1
            try:
                buf_path = vim.buffers[buf_nr].name
            except IndexError:
                # Just do good old asking for forgiveness.
                # don't know why this happens :-)
                pass
            else:
                if buf_path == path:
                    # tab exists, just switch to that tab
                    vim.command('tabfirst | tabnext %i' % (tab_nr + 1))
                    break
        else:
            continue
        break
    else:
        # tab doesn't exist, add a new one.
        vim.command('tabnew %s' % path)

def escape_file_path(path):
    return path.replace(' ', r'\ ')

def print_to_stdout(level, str_out):
    print(str_out)
<commit_msg>set the cursor to the right position, messed that up in the previous commit, #65<commit_after>"""
The Python parts of the Jedi library for VIM. It is mostly about communicating
with VIM.
"""

import traceback  # for exception output
import re
import os

import vim
import jedi
import jedi.keywords
from jedi._compatibility import unicode

class PythonToVimStr(unicode):
    """ Vim has a different string implementation of single quotes """
    __slots__ = []

    def __repr__(self):
        # this is totally stupid and makes no sense but vim/python unicode
        # support is pretty bad. don't ask how I came up with this... It just
        # works...
        # It seems to be related to that bug: http://bugs.python.org/issue5876
        s = self.encode('UTF-8')
        return '"%s"' % s.replace('\\', '\\\\').replace('"', r'\"')

def echo_highlight(msg):
    vim.command('echohl WarningMsg | echo "%s" | echohl None' % msg)

def get_script(source=None, column=None):
    jedi.settings.additional_dynamic_modules = [b.name for b in vim.buffers
                            if b.name is not None and b.name.endswith('.py')]
    if source is None:
        source = '\n'.join(vim.current.buffer)
    row = vim.current.window.cursor[0]
    if column is None:
        column = vim.current.window.cursor[1]
    buf_path = vim.current.buffer.name
    encoding = vim.eval('&encoding')
    return jedi.Script(source, row, column, buf_path, encoding)

def complete():
    row, column = vim.current.window.cursor
    clear_func_def()
    if vim.eval('a:findstart') == '1':
        count = 0
        for char in reversed(vim.current.line[:column]):
            if not re.match('[\w\d]', char):
                break
            count += 1
        vim.command('return %i' % (column - count))
    else:
        base = vim.eval('a:base')
        source = ''
        for i, line in enumerate(vim.current.buffer):
            # enter this path again, otherwise source would be incomplete
            if i == row - 1:
                source += line[:column] + base + line[column:]
            else:
                source += line
            source += '\n'
        # here again hacks, because jedi has a different interface than vim
        column += len(base)
        try:
            script = get_script(source=source, column=column)
            completions = script.complete()
            call_def = script.get_in_function_call()

            out = []
            for c in completions:
                d = dict(word=PythonToVimStr(c.word[:len(base)] + c.complete),
                         abbr=PythonToVimStr(c.word),
                         # stuff directly behind the completion
                         menu=PythonToVimStr(c.description),
                         info=PythonToVimStr(c.doc),  # docstr
                         icase=1,  # case insensitive
                         dup=1  # allow duplicates (maybe later remove this)
                )
                out.append(d)

            strout = str(out)
        except Exception:
            # print to stdout, will be in :messages
            print(traceback.format_exc())
            strout = ''
            completions = []
            call_def = None

        #print 'end', strout
        show_func_def(call_def, len(completions))
        vim.command('return ' + strout)

def goto(is_definition=False, is_related_name=False, no_output=False):
    definitions = []
    script = get_script()
    try:
        if is_related_name:
            definitions = script.related_names()
        elif is_definition:
            definitions = script.get_definition()
        else:
            definitions = script.goto()
    except jedi.NotFoundError:
        echo_highlight(
                    "Cannot follow nothing. Put your cursor on a valid name.")
    except Exception:
        # print to stdout, will be in :messages
        echo_highlight("Some different eror, this shouldn't happen.")
        print(traceback.format_exc())
    else:
        if no_output:
            return definitions
        if not definitions:
            echo_highlight("Couldn't find any definitions for this.")
        elif len(definitions) == 1 and not is_related_name:
            # just add some mark to add the current position to the jumplist.
            # this is ugly, because it overrides the mark for '`', so if anyone
            # has a better idea, let me know.
            vim.command('normal! m`')

            d = list(definitions)[0]
            if d.in_builtin_module():
                if isinstance(d.definition, jedi.keywords.Keyword):
                    echo_highlight(
                            "Cannot get the definition of Python keywords.")
                else:
                    echo_highlight("Builtin modules cannot be displayed.")
            else:
                if d.module_path != vim.current.buffer.name:
                    vim.eval('jedi#new_buffer(%s)' % \
                                        repr(PythonToVimStr(d.module_path)))
                vim.current.window.cursor = d.line_nr, d.column
                vim.command('normal! zt')  # cursor at top of screen
        else:
            # multiple solutions
            lst = []
            for d in definitions:
                if d.in_builtin_module():
                    lst.append(dict(text=
                                PythonToVimStr('Builtin ' + d.description)))
                else:
                    lst.append(dict(filename=PythonToVimStr(d.module_path),
                                    lnum=d.line_nr, col=d.column + 1,
                                    text=PythonToVimStr(d.description)))
            vim.eval('setqflist(%s)' % repr(lst))
            vim.eval('<sid>add_goto_window()')
    return definitions

def show_pydoc():
    script = get_script()
    try:
        definitions = script.get_definition()
    except jedi.NotFoundError:
        definitions = []
    except Exception:
        # print to stdout, will be in :messages
        definitions = []
        print("Exception, this shouldn't happen.")
        print(traceback.format_exc())

    if not definitions:
        vim.command('return')
    else:
        docs = ['Docstring for %s\n%s\n%s' % (d.desc_with_module, '='*40, d.doc) if d.doc
                    else '|No Docstring for %s|' % d for d in definitions]
        text = ('\n' + '-' * 79 + '\n').join(docs)
        vim.command('let l:doc = %s' % repr(PythonToVimStr(text)))
        vim.command('let l:doc_lines = %s' % len(text.split('\n')))

def clear_func_def():
    cursor = vim.current.window.cursor
    e = vim.eval('g:jedi#function_definition_escape')
    regex = r'%sjedi=([0-9]+), ([^%s]*)%s.*%sjedi%s'.replace('%s', e)
    for i, line in enumerate(vim.current.buffer):
        match = re.search(r'%s' % regex, line)
        if match is not None:
            vim_regex = r'\v' + regex.replace('=', r'\=') + '.{%s}' % \
                                                        int(match.group(1))
            vim.command(r'try | %s,%ss/%s/\2/g | catch | endtry' \
                                                % (i + 1, i + 1, vim_regex))
            vim.eval('histdel("search", -1)')
            vim.command('let @/ = histget("search", -1)')
    vim.current.window.cursor = cursor

def show_func_def(call_def=None, completion_lines=0):
    if vim.eval("has('conceal') && g:jedi#show_function_definition") == '0':
        return
    try:
        if call_def == None:
            call_def = get_script().get_in_function_call()
        clear_func_def()

        if call_def is None:
            return

        row, column = call_def.bracket_start
        if column < 2 or row == 0:
            return  # edge cases, just ignore

        # TODO check if completion menu is above or below
        row_to_replace = row - 1
        line = vim.eval("getline(%s)" % row_to_replace)

        insert_column = column - 2  # because it has stuff at the beginning

        params = [p.get_code().replace('\n', '') for p in call_def.params]
        try:
            params[call_def.index] = '*%s*' % params[call_def.index]
        except (IndexError, TypeError):
            pass

        # This stuff is reaaaaally a hack! I cannot stress enough, that this is
        # a stupid solution. But there is really no other yet. There is no
        # possibility in VIM to draw on the screen, but there will be one (see
        # :help todo Patch to access screen under Python. (Marko Mahni, 2010
        # Jul 18))
        text = " (%s) " % ', '.join(params)
        text = ' ' * (insert_column - len(line)) + text
        end_column = insert_column + len(text) - 2  # -2 due to bold symbols

        # Need to decode it with utf8, because vim returns always a python 2
        # string even if it is unicode.
        e = vim.eval('g:jedi#function_definition_escape').decode('UTF-8')
        # replace line before with cursor
        regex = "xjedi=%sx%sxjedix".replace('x', e)

        prefix, replace = line[:insert_column], line[insert_column:end_column]

        # Check the replace stuff for strings, to append them
        # (don't want to break the syntax)
        regex_quotes = r'''\\*["']+'''
        # `add` are all the quotation marks.
        # join them with a space to avoid producing '''
        add = ' '.join(re.findall(regex_quotes, replace))
        # search backwards
        if add and replace[0] in ['"', "'"]:
            a = re.search(regex_quotes + '$', prefix)
            add = ('' if a is None else a.group(0)) + add

        tup = '%s, %s' % (len(add), replace)
        repl = prefix + (regex % (tup, text)) + add + line[end_column:]

        vim.eval('setline(%s, %s)' % \
                            (row_to_replace, repr(PythonToVimStr(repl))))
    except Exception:
        print(traceback.format_exc())

def rename():
    if not int(vim.eval('a:0')):
        _rename_cursor = vim.current.window.cursor

        vim.command('normal A ')  # otherwise startinsert doesn't work well
        vim.current.window.cursor = _rename_cursor

        vim.command('augroup jedi_rename')
        vim.command('autocmd InsertLeave <buffer> call jedi#rename(1)')
        vim.command('augroup END')

        vim.command('normal! diw')
        vim.command(':startinsert')
    else:
        window_path = vim.current.buffer.name
        # reset autocommand
        vim.command('autocmd! jedi_rename InsertLeave')

        replace = vim.eval("expand('<cword>')")
        vim.command('normal! u')  # undo new word
        cursor = vim.current.window.cursor
        vim.command('normal! u')  # undo the space at the end
        vim.current.window.cursor = cursor

        if replace is None:
            echo_highlight('No rename possible, if no name is given.')
        else:
            temp_rename = goto(is_related_name=True, no_output=True)
            # sort the whole thing reverse (positions at the end of the line
            # must be first, because they move the stuff before the position).
            temp_rename = sorted(temp_rename, reverse=True,
                                key=lambda x: (x.module_path, x.start_pos))
            for r in temp_rename:
                if r.in_builtin_module():
                    continue

                if vim.current.buffer.name != r.module_path:
                    vim.eval("jedi#new_buffer('%s')" % r.module_path)

                vim.current.window.cursor = r.start_pos
                vim.command('normal! cw%s' % replace)

            vim.eval("jedi#new_buffer('%s')" % window_path)
            vim.current.window.cursor = cursor
            echo_highlight('Jedi did %s renames!' % len(temp_rename))

def tabnew(path):
    path = os.path.abspath(path)
    for tab_nr in range(int(vim.eval("tabpagenr('$')"))):
        for buf_nr in vim.eval("tabpagebuflist(%i + 1)" % tab_nr):
            buf_nr = int(buf_nr) - 1
            try:
                buf_path = vim.buffers[buf_nr].name
            except IndexError:
                # Just do good old asking for forgiveness.
                # don't know why this happens :-)
                pass
            else:
                if buf_path == path:
                    # tab exists, just switch to that tab
                    vim.command('tabfirst | tabnext %i' % (tab_nr + 1))
                    break
        else:
            continue
        break
    else:
        # tab doesn't exist, add a new one.
        vim.command('tabnew %s' % path)

def escape_file_path(path):
    return path.replace(' ', r'\ ')

def print_to_stdout(level, str_out):
    print(str_out)
<|endoftext|>


<commit_before>###
# Copyright (c) 2002-2004, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

"""
Includes commands for connecting, disconnecting, and reconnecting to multiple
networks, as well as several other utility functions related to IRC networks.
"""

import supybot

__revision__ = "$Id$"
__author__ = supybot.authors.jemfinch

import supybot.plugins as plugins

import time

import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
from supybot.commands import *
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.privmsgs as privmsgs
import supybot.registry as registry
import supybot.callbacks as callbacks

class Network(callbacks.Privmsg):
    _whois = {}
    _latency = {}
    def _getIrc(self, network):
        irc = world.getIrc(network)
        if irc:
            return irc
        else:
            raise callbacks.Error, \
                  'I\'m not currently connected to %s.' % network

    def connect(self, irc, msg, args, network, server, password):
        """<network> [<host[:port]>] [<password>]

        Connects to another network (which will be represented by the name
        provided in <network>) at <host:port>.  If port is not provided, it
        defaults to 6667, the default port for IRC.  If password is
        provided, it will be sent to the server in a PASS command.
        """
        try:
            otherIrc = self._getIrc(network)
            irc.error('I\'m already connected to %s.' % network, Raise=True)
        except callbacks.Error:
            pass
        if server:
            if ':' in server:
                (server, port) = server.split(':')
                port = int(port)
            else:
                port = 6667
            serverPort = (server, port)
        else:
            try:
                serverPort = conf.supybot.networks.get(network).servers()[0]
            except (registry.NonExistentRegistryEntry, IndexError):
                irc.error('A server must be provided if the network is not '
                          'already registered.')
                return
        Owner = irc.getCallback('Owner')
        newIrc = Owner._connect(network, serverPort=serverPort)
        conf.supybot.networks().add(network)
        assert newIrc.callbacks is irc.callbacks, 'callbacks list is different'
        irc.replySuccess('Connection to %s initiated.' % network)
    connect = wrap(connect, ['owner', 'something', additional('something'),
                             additional('something', '')])

    def disconnect(self, irc, msg, args, otherIrc, quitMsg):
        """[<network>] [<quit message>]

        Disconnects from the network represented by the network <network>.
        If <quit message> is given, quits the network with the given quit
        message.  <network> is only necessary if the network is different
        from the network the command is sent on.
        """
        quitMsg = quitMsg or conf.supybot.plugins.Owner.quitMsg() or msg.nick
        otherIrc.queueMsg(ircmsgs.quit(quitMsg))
        otherIrc.die()
        conf.supybot.networks().discard(otherIrc.network)
        if otherIrc != irc:
            irc.replySuccess('Disconnection to %s initiated.' %
                             otherIrc.network)
    disconnect = wrap(disconnect, ['owner', 'networkIrc', additional('text')])

    def reconnect(self, irc, msg, args, otherIrc, quitMsg):
        """[<network>] [<quit message>]

        Disconnects and then reconnects to <network>.  If no network is given,
        disconnects and then reconnects to the network the command was given
        on.  If no quit message is given, uses the configured one
        (supybot.plugins.Owner.quitMsg) or the nick of the person giving the
        command.
        """
        quitMsg = quitMsg or conf.supybot.plugins.Owner.quitMsg() or msg.nick
        otherIrc.queueMsg(ircmsgs.quit(quitMsg))
        if otherIrc != irc:
            # No need to reply if we're reconnecting ourselves.
            irc.replySuccess()
    reconnect = wrap(reconnect, ['owner', 'networkIrc', additional('text')])

    def command(self, irc, msg, args, otherIrc, commandAndArgs):
        """<network> <command> [<arg> ...]

        Gives the bot <command> (with its associated <arg>s) on <network>.
        """
        self.Proxy(otherIrc, msg, commandAndArgs)
    command = wrap(command, ['admin', ('networkIrc', True), many('something')])

    ###
    # whois command-related stuff.
    ###
    def do311(self, irc, msg):
        nick = ircutils.toLower(msg.args[1])
        if (irc, nick) not in self._whois:
            return
        else:
            self._whois[(irc, nick)][-1][msg.command] = msg

    # These are all sent by a WHOIS response.
    do301 = do311
    do312 = do311
    do317 = do311
    do319 = do311
    do320 = do311

    def do318(self, irc, msg):
        nick = msg.args[1]
        loweredNick = ircutils.toLower(nick)
        if (irc, loweredNick) not in self._whois:
            return
        (replyIrc, replyMsg, d) = self._whois[(irc, loweredNick)]
        hostmask = '@'.join(d['311'].args[2:4])
        user = d['311'].args[-1]
        if '319' in d:
            channels = d['319'].args[-1].split()
            ops = []
            voices = []
            normal = []
            halfops = []
            for channel in channels:
                if channel.startswith('@'):
                    ops.append(channel[1:])
                elif channel.startswith('%'):
                    halfops.append(channel[1:])
                elif channel.startswith('+'):
                    voices.append(channel[1:])
                else:
                    normal.append(channel)
            L = []
            if ops:
                L.append('is an op on %s' % utils.commaAndify(ops))
            if halfops:
                L.append('is a halfop on %s' % utils.commaAndify(halfops))
            if voices:
                L.append('is voiced on %s' % utils.commaAndify(voices))
            if normal:
                if L:
                    L.append('is also on %s' % utils.commaAndify(normal))
                else:
                    L.append('is on %s' % utils.commaAndify(normal))
        else:
            L = ['isn\'t on any non-secret channels']
        channels = utils.commaAndify(L)
        if '317' in d:
            idle = utils.timeElapsed(d['317'].args[2])
            signon = time.strftime(conf.supybot.reply.format.time(),
                                   time.localtime(float(d['317'].args[3])))
        else:
            idle = '<unknown>'
            signon = '<unknown>'
        if '312' in d:
            server = d['312'].args[2]
        else:
            server = '<unknown>'
        if '301' in d:
            away = '  %s is away: %s.' % (nick, d['301'].args[2])
        else:
            away = ''
        if '320' in d:
            if d['320'].args[2]:
                identify = ' identified'
            else:
                identify = ''
        else:
            identify = ''
        s = '%s (%s) has been%s on server %s since %s (idle for %s) and ' \
            '%s.%s' % (user, hostmask, identify, server, signon, idle,
                       channels, away)
        replyIrc.reply(s)
        del self._whois[(irc, loweredNick)]

    def do402(self, irc, msg):
        nick = msg.args[1]
        loweredNick = ircutils.toLower(nick)
        if (irc, loweredNick) not in self._whois:
            return
        (replyIrc, replyMsg, d) = self._whois[(irc, loweredNick)]
        del self._whois[(irc, loweredNick)]
        s = 'There is no %s on %s.' % (nick, irc.network)
        replyIrc.reply(s)
    do401 = do402

    def whois(self, irc, msg, args, otherIrc, nick):
        """[<network>] <nick>

        Returns the WHOIS response <network> gives for <nick>.  <network> is
        only necessary if the network is different than the network the command
        is sent on.
        """
        # The double nick here is necessary because single-nick WHOIS only works
        # if the nick is on the same server (*not* the same network) as the user
        # giving the command.  Yeah, it made me say wtf too.
        nick = ircutils.toLower(nick)
        otherIrc.queueMsg(ircmsgs.whois(nick, nick))
        self._whois[(otherIrc, nick)] = (irc, msg, {})
    whois = wrap(whois, ['networkIrc', 'nick'])

    def networks(self, irc, msg, args):
        """takes no arguments

        Returns the networks to which the bot is currently connected.
        """
        L = ['%s: %s' % (ircd.network, ircd.server) for ircd in world.ircs]
        utils.sortBy(str.lower, L)
        irc.reply(utils.commaAndify(L))
    networks = wrap(networks)

    def doPong(self, irc, msg):
        now = time.time()
        if irc in self._latency:
            (replyIrc, when) = self._latency.pop(irc)
            replyIrc.reply('%.2f seconds.' % (now-when))

    def latency(self, irc, msg, args, otherIrc):
        """[<network>]

        Returns the current latency to <network>.  <network> is only necessary
        if the message isn't sent on the network to which this command is to
        apply.
        """
        otherIrc.queueMsg(ircmsgs.ping('Latency check (from %s).' % msg.nick))
        self._latency[otherIrc] = (irc, time.time())
        irc.noReply()
    latency = wrap(latency, ['networkIrc'])

Class = Network

# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:
<commit_msg>Added a driver command.<commit_after>###
# Copyright (c) 2002-2004, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

"""
Includes commands for connecting, disconnecting, and reconnecting to multiple
networks, as well as several other utility functions related to IRC networks.
"""

import supybot

__revision__ = "$Id$"
__author__ = supybot.authors.jemfinch

import supybot.plugins as plugins

import time

import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
from supybot.commands import *
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.privmsgs as privmsgs
import supybot.registry as registry
import supybot.callbacks as callbacks

class Network(callbacks.Privmsg):
    _whois = {}
    _latency = {}
    def _getIrc(self, network):
        irc = world.getIrc(network)
        if irc:
            return irc
        else:
            raise callbacks.Error, \
                  'I\'m not currently connected to %s.' % network

    def connect(self, irc, msg, args, network, server, password):
        """<network> [<host[:port]>] [<password>]

        Connects to another network (which will be represented by the name
        provided in <network>) at <host:port>.  If port is not provided, it
        defaults to 6667, the default port for IRC.  If password is
        provided, it will be sent to the server in a PASS command.
        """
        try:
            otherIrc = self._getIrc(network)
            irc.error('I\'m already connected to %s.' % network, Raise=True)
        except callbacks.Error:
            pass
        if server:
            if ':' in server:
                (server, port) = server.split(':')
                port = int(port)
            else:
                port = 6667
            serverPort = (server, port)
        else:
            try:
                serverPort = conf.supybot.networks.get(network).servers()[0]
            except (registry.NonExistentRegistryEntry, IndexError):
                irc.error('A server must be provided if the network is not '
                          'already registered.')
                return
        Owner = irc.getCallback('Owner')
        newIrc = Owner._connect(network, serverPort=serverPort)
        conf.supybot.networks().add(network)
        assert newIrc.callbacks is irc.callbacks, 'callbacks list is different'
        irc.replySuccess('Connection to %s initiated.' % network)
    connect = wrap(connect, ['owner', 'something', additional('something'),
                             additional('something', '')])

    def disconnect(self, irc, msg, args, otherIrc, quitMsg):
        """[<network>] [<quit message>]

        Disconnects from the network represented by the network <network>.
        If <quit message> is given, quits the network with the given quit
        message.  <network> is only necessary if the network is different
        from the network the command is sent on.
        """
        quitMsg = quitMsg or conf.supybot.plugins.Owner.quitMsg() or msg.nick
        otherIrc.queueMsg(ircmsgs.quit(quitMsg))
        otherIrc.die()
        conf.supybot.networks().discard(otherIrc.network)
        if otherIrc != irc:
            irc.replySuccess('Disconnection to %s initiated.' %
                             otherIrc.network)
    disconnect = wrap(disconnect, ['owner', 'networkIrc', additional('text')])

    def reconnect(self, irc, msg, args, otherIrc, quitMsg):
        """[<network>] [<quit message>]

        Disconnects and then reconnects to <network>.  If no network is given,
        disconnects and then reconnects to the network the command was given
        on.  If no quit message is given, uses the configured one
        (supybot.plugins.Owner.quitMsg) or the nick of the person giving the
        command.
        """
        quitMsg = quitMsg or conf.supybot.plugins.Owner.quitMsg() or msg.nick
        otherIrc.queueMsg(ircmsgs.quit(quitMsg))
        if otherIrc != irc:
            # No need to reply if we're reconnecting ourselves.
            irc.replySuccess()
    reconnect = wrap(reconnect, ['owner', 'networkIrc', additional('text')])

    def command(self, irc, msg, args, otherIrc, commandAndArgs):
        """<network> <command> [<arg> ...]

        Gives the bot <command> (with its associated <arg>s) on <network>.
        """
        self.Proxy(otherIrc, msg, commandAndArgs)
    command = wrap(command, ['admin', ('networkIrc', True), many('something')])

    ###
    # whois command-related stuff.
    ###
    def do311(self, irc, msg):
        nick = ircutils.toLower(msg.args[1])
        if (irc, nick) not in self._whois:
            return
        else:
            self._whois[(irc, nick)][-1][msg.command] = msg

    # These are all sent by a WHOIS response.
    do301 = do311
    do312 = do311
    do317 = do311
    do319 = do311
    do320 = do311

    def do318(self, irc, msg):
        nick = msg.args[1]
        loweredNick = ircutils.toLower(nick)
        if (irc, loweredNick) not in self._whois:
            return
        (replyIrc, replyMsg, d) = self._whois[(irc, loweredNick)]
        hostmask = '@'.join(d['311'].args[2:4])
        user = d['311'].args[-1]
        if '319' in d:
            channels = d['319'].args[-1].split()
            ops = []
            voices = []
            normal = []
            halfops = []
            for channel in channels:
                if channel.startswith('@'):
                    ops.append(channel[1:])
                elif channel.startswith('%'):
                    halfops.append(channel[1:])
                elif channel.startswith('+'):
                    voices.append(channel[1:])
                else:
                    normal.append(channel)
            L = []
            if ops:
                L.append('is an op on %s' % utils.commaAndify(ops))
            if halfops:
                L.append('is a halfop on %s' % utils.commaAndify(halfops))
            if voices:
                L.append('is voiced on %s' % utils.commaAndify(voices))
            if normal:
                if L:
                    L.append('is also on %s' % utils.commaAndify(normal))
                else:
                    L.append('is on %s' % utils.commaAndify(normal))
        else:
            L = ['isn\'t on any non-secret channels']
        channels = utils.commaAndify(L)
        if '317' in d:
            idle = utils.timeElapsed(d['317'].args[2])
            signon = time.strftime(conf.supybot.reply.format.time(),
                                   time.localtime(float(d['317'].args[3])))
        else:
            idle = '<unknown>'
            signon = '<unknown>'
        if '312' in d:
            server = d['312'].args[2]
        else:
            server = '<unknown>'
        if '301' in d:
            away = '  %s is away: %s.' % (nick, d['301'].args[2])
        else:
            away = ''
        if '320' in d:
            if d['320'].args[2]:
                identify = ' identified'
            else:
                identify = ''
        else:
            identify = ''
        s = '%s (%s) has been%s on server %s since %s (idle for %s) and ' \
            '%s.%s' % (user, hostmask, identify, server, signon, idle,
                       channels, away)
        replyIrc.reply(s)
        del self._whois[(irc, loweredNick)]

    def do402(self, irc, msg):
        nick = msg.args[1]
        loweredNick = ircutils.toLower(nick)
        if (irc, loweredNick) not in self._whois:
            return
        (replyIrc, replyMsg, d) = self._whois[(irc, loweredNick)]
        del self._whois[(irc, loweredNick)]
        s = 'There is no %s on %s.' % (nick, irc.network)
        replyIrc.reply(s)
    do401 = do402

    def whois(self, irc, msg, args, otherIrc, nick):
        """[<network>] <nick>

        Returns the WHOIS response <network> gives for <nick>.  <network> is
        only necessary if the network is different than the network the command
        is sent on.
        """
        # The double nick here is necessary because single-nick WHOIS only works
        # if the nick is on the same server (*not* the same network) as the user
        # giving the command.  Yeah, it made me say wtf too.
        nick = ircutils.toLower(nick)
        otherIrc.queueMsg(ircmsgs.whois(nick, nick))
        self._whois[(otherIrc, nick)] = (irc, msg, {})
    whois = wrap(whois, ['networkIrc', 'nick'])

    def networks(self, irc, msg, args):
        """takes no arguments

        Returns the networks to which the bot is currently connected.
        """
        L = ['%s: %s' % (ircd.network, ircd.server) for ircd in world.ircs]
        utils.sortBy(str.lower, L)
        irc.reply(utils.commaAndify(L))
    networks = wrap(networks)

    def doPong(self, irc, msg):
        now = time.time()
        if irc in self._latency:
            (replyIrc, when) = self._latency.pop(irc)
            replyIrc.reply('%.2f seconds.' % (now-when))

    def latency(self, irc, msg, args, otherIrc):
        """[<network>]

        Returns the current latency to <network>.  <network> is only necessary
        if the message isn't sent on the network to which this command is to
        apply.
        """
        otherIrc.queueMsg(ircmsgs.ping('Latency check (from %s).' % msg.nick))
        self._latency[otherIrc] = (irc, time.time())
        irc.noReply()
    latency = wrap(latency, ['networkIrc'])

    def driver(self, irc, msg, args, otherIrc):
        """[<network>]

        Returns the current network driver for <network>.  <network> is only
        necessary if the message isn't sent on the network to which this
        command is to apply.
        """
        irc.reply(otherIrc.driver.__class__.__module__[8:])

Class = Network

# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:
<|endoftext|>


<commit_before>import math
import config
import utils
from utils.util import add_cmd

@add_cmd("shrug", min_args=0)
def shrug(bot, event, irc, args):
    """Sends a shrug to the channel"""
    irc.reply(event, "\u00AF\\_(\u30C4)_/\u00AF")

@add_cmd("calc", alias=["math"], min_args=1)
def calc(bot, event, irc, args):
    """Command to do some math calculation using the math.js web API"""
    arguments = "".join(args)
    payload = {
        'expr': arguments,
        'precision': 10
    }
    r = utils.util.post("http://api.mathjs.org/v1/", json=payload)
    if not r.json()['error']:
        result = r.json()['result']
        if not result.find('.') != -1 or result.find("e") != -1:
            output = format(int(float(result)), ",d")
        else:
            output = result
        message = f"The answer is: {output}"
    else:
        message = r.json()['error']
    irc.reply(event, message)

@add_cmd("echo", min_args=1)
def echo(bot, event, irc, args):
    """Responds with given text"""
    irc.reply(event, f'\u200b{' '.join(args)}')

@add_cmd("rainbow", min_args=1)
def rainbow(bot, event, irc, args):
    """Responds with given text colored in rainbow"""
    irc.reply(event, ' '.join(args), rainbow=True)

@add_cmd("ping", min_args=0)
def ping(bot, event, irc, args):
    """Responds with pong"""
    irc.reply(event, "PONG!")

@add_cmd("help", min_args=0)
def help_cmd(bot, event, irc, args):
    """<command>
    Returns help text for the specified command"""
    if len(args):
        try:
            doc = utils.util.commands[args[0]]['func'].__doc__
            irc.reply(event, utils.commands.format_cmd_docs(doc, args[0]))
        except KeyError:
            irc.reply(event, "Invalid command {0}".format(args[0]))
    else:
        doc = utils.util.commands["help"]['func'].__doc__
        irc.reply(event, utils.commands.format_cmd_docs(doc, 'help'))

@add_cmd("list", min_args=0, alias=["ls"])
def list_cmds(bot, event, irc, args):
    """Help text"""
    if len(args) and args[0] == "alias":
        irc.reply(event, ", ".join(utils.util.alias_list))
    else:
        host = event.source.host
        channel = event.target
        owner, admin, trusted, users = [], [], [], []
        text = "Commands({0!s}): {1!s}"
        for i in utils.util.cmd_list:
            if utils.util.commands[i]['perms'][2]:
                owner.append(i)
            elif utils.util.commands[i]['perms'][1]:
                admin.append(i)
            elif utils.util.commands[i]['perms'][0]:
                trusted.append(i)
            else:
                users.append(i)
        cmd_list = users
        if utils.util.check_perms(event, channel, owner=True):
            cmd_list += owner + admin + trusted
            msg = text.format('Owner', ", ".join(sorted(cmd_list)))
        elif utils.util.check_perms(event, channel, admin=True):
            cmd_list += admin + trusted
            msg = text.format('Admin', ", ".join(sorted(cmd_list)))
        elif utils.util.check_perms(event, channel, trusted=True):
            cmd_list += trusted
            msg = text.format('Trusted', ", ".join(sorted(cmd_list)))
        else:
            msg = text.format('User', ", ".join(sorted(cmd_list)))
        irc.reply(event, msg)

@add_cmd("perms", min_args=0)
def permissions(bot, event, irc, args):
    """Replies with your permission level"""
    channel = event.target
    host = event.source.host

    is_bot = host.find("/bot/") != -1
    is_bot_chan = channel in config.bots['channels']
    if utils.util.check_perms(event, channel, owner=True):
        perms = 'Owner'
    elif utils.util.check_perms(event, channel, admin=True):
        perms = 'Admin'
    elif utils.util.check_perms(event, channel, trusted=True):
        perms = 'Trusted'
    elif host in config.bots['hosts'] or (is_bot_chan and is_bot):
        perms = 'Bot'
    else:
        perms = 'User'

    irc.reply(event, perms)

@add_cmd("version", min_args=0)
def version(bot, event, irc, args):
    irc.reply(event, utils.version)

@add_cmd("host", min_args=0)
def hostmask(bot, event, irc, args):
    """Replies with your host"""
    irc.reply(event, event.source.host)

@add_cmd("seen", min_args=1)
def seen(bot, event, irc, args):
    """[<channel>] <nick>
    Returns the last time <nick> was seen and what <nick> was last seen saying.
    <channel> is only necessary if the message isn't sent on the channel itself.
    """
    import datetime
    if args[0].startswith("#"):
        channel = args[0]
        nick = args[1]
    else:
        channel = event.target
        nick = args[0]
    try:
        db = sorted(bot.userdb[channel][nick]["seen"], key=lambda x: x['time'], reverse=True)
        ago = datetime.datetime.now() - datetime.datetime.fromtimestamp(db[0]["time"])
        hour = math.floor(ago.seconds / 3600)
        minute = math.floor((ago.seconds / 60) % 60)
        seconds = ago.seconds - ((ago.days * 8600) + (hour * 3600) + (minute * 60))
        last_msg = db[0]["message"]
        msg = " ".join(["I have last seen {0} {2} days, {3} hours, {4} minutes and",
                        "{5} seconds ago: {1}"])
        irc.reply(event, msg.format(nick, last_msg, ago.days, hour, minute, seconds))
    except (KeyError, TypeError):
        irc.reply(event, f"I have not seen {nick}")
<commit_msg>fix: change from single quote to double quote in order to fix f-string<commit_after>import math
import config
import utils
from utils.util import add_cmd

@add_cmd("shrug", min_args=0)
def shrug(bot, event, irc, args):
    """Sends a shrug to the channel"""
    irc.reply(event, "\u00AF\\_(\u30C4)_/\u00AF")

@add_cmd("calc", alias=["math"], min_args=1)
def calc(bot, event, irc, args):
    """Command to do some math calculation using the math.js web API"""
    arguments = "".join(args)
    payload = {
        'expr': arguments,
        'precision': 10
    }
    r = utils.util.post("http://api.mathjs.org/v1/", json=payload)
    if not r.json()['error']:
        result = r.json()['result']
        if not result.find('.') != -1 or result.find("e") != -1:
            output = format(int(float(result)), ",d")
        else:
            output = result
        message = f"The answer is: {output}"
    else:
        message = r.json()['error']
    irc.reply(event, message)

@add_cmd("echo", min_args=1)
def echo(bot, event, irc, args):
    """Responds with given text"""
    irc.reply(event, f"\u200b{' '.join(args)}")

@add_cmd("rainbow", min_args=1)
def rainbow(bot, event, irc, args):
    """Responds with given text colored in rainbow"""
    irc.reply(event, ' '.join(args), rainbow=True)

@add_cmd("ping", min_args=0)
def ping(bot, event, irc, args):
    """Responds with pong"""
    irc.reply(event, "PONG!")

@add_cmd("help", min_args=0)
def help_cmd(bot, event, irc, args):
    """<command>
    Returns help text for the specified command"""
    if len(args):
        try:
            doc = utils.util.commands[args[0]]['func'].__doc__
            irc.reply(event, utils.commands.format_cmd_docs(doc, args[0]))
        except KeyError:
            irc.reply(event, "Invalid command {0}".format(args[0]))
    else:
        doc = utils.util.commands["help"]['func'].__doc__
        irc.reply(event, utils.commands.format_cmd_docs(doc, 'help'))

@add_cmd("list", min_args=0, alias=["ls"])
def list_cmds(bot, event, irc, args):
    """Help text"""
    if len(args) and args[0] == "alias":
        irc.reply(event, ", ".join(utils.util.alias_list))
    else:
        host = event.source.host
        channel = event.target
        owner, admin, trusted, users = [], [], [], []
        text = "Commands({0!s}): {1!s}"
        for i in utils.util.cmd_list:
            if utils.util.commands[i]['perms'][2]:
                owner.append(i)
            elif utils.util.commands[i]['perms'][1]:
                admin.append(i)
            elif utils.util.commands[i]['perms'][0]:
                trusted.append(i)
            else:
                users.append(i)
        cmd_list = users
        if utils.util.check_perms(event, channel, owner=True):
            cmd_list += owner + admin + trusted
            msg = text.format('Owner', ", ".join(sorted(cmd_list)))
        elif utils.util.check_perms(event, channel, admin=True):
            cmd_list += admin + trusted
            msg = text.format('Admin', ", ".join(sorted(cmd_list)))
        elif utils.util.check_perms(event, channel, trusted=True):
            cmd_list += trusted
            msg = text.format('Trusted', ", ".join(sorted(cmd_list)))
        else:
            msg = text.format('User', ", ".join(sorted(cmd_list)))
        irc.reply(event, msg)

@add_cmd("perms", min_args=0)
def permissions(bot, event, irc, args):
    """Replies with your permission level"""
    channel = event.target
    host = event.source.host

    is_bot = host.find("/bot/") != -1
    is_bot_chan = channel in config.bots['channels']
    if utils.util.check_perms(event, channel, owner=True):
        perms = 'Owner'
    elif utils.util.check_perms(event, channel, admin=True):
        perms = 'Admin'
    elif utils.util.check_perms(event, channel, trusted=True):
        perms = 'Trusted'
    elif host in config.bots['hosts'] or (is_bot_chan and is_bot):
        perms = 'Bot'
    else:
        perms = 'User'

    irc.reply(event, perms)

@add_cmd("version", min_args=0)
def version(bot, event, irc, args):
    irc.reply(event, utils.version)

@add_cmd("host", min_args=0)
def hostmask(bot, event, irc, args):
    """Replies with your host"""
    irc.reply(event, event.source.host)

@add_cmd("seen", min_args=1)
def seen(bot, event, irc, args):
    """[<channel>] <nick>
    Returns the last time <nick> was seen and what <nick> was last seen saying.
    <channel> is only necessary if the message isn't sent on the channel itself.
    """
    import datetime
    if args[0].startswith("#"):
        channel = args[0]
        nick = args[1]
    else:
        channel = event.target
        nick = args[0]
    try:
        db = sorted(bot.userdb[channel][nick]["seen"], key=lambda x: x['time'], reverse=True)
        ago = datetime.datetime.now() - datetime.datetime.fromtimestamp(db[0]["time"])
        hour = math.floor(ago.seconds / 3600)
        minute = math.floor((ago.seconds / 60) % 60)
        seconds = ago.seconds - ((ago.days * 8600) + (hour * 3600) + (minute * 60))
        last_msg = db[0]["message"]
        msg = " ".join(["I have last seen {0} {2} days, {3} hours, {4} minutes and",
                        "{5} seconds ago: {1}"])
        irc.reply(event, msg.format(nick, last_msg, ago.days, hour, minute, seconds))
    except (KeyError, TypeError):
        irc.reply(event, f"I have not seen {nick}")
<|endoftext|>


<commit_before># Copyright (c) 2013-2014 Molly White
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import json
from plugins.util import command, get_url
from urllib.parse import quote

@command()
def weather(m):
    """Get the weather for a specified location."""

    #-     !weather [--now|--week] location
    #-
    #- ```irc
    #- < GorillaWarfare> !weather boston
    #- < GorillaBot> Weather in Boston, MA, USA: Rain until tomorrow evening and breezy until
    #-               tomorrow morning. 51˚F (10˚C). Feels like 51˚F (10˚C). Humidity: 95%. Wind
    #-               speed: 23mph (38kph).
    #- < GorillaWarfare> !weather --now boston
    #- < GorillaBot> Weather in Boston, MA, USA: Light Rain and Breezy. 51˚F (10˚C). Feels like
    #-               51˚F (10˚C). Humidity: 96%. Wind speed: 25mph (40kph).
    #- ```
    #-
    #- Provide weather information for the given location. Defaults to giving weather information
    #  about today, but will give more specific information if passed the `--now` parameter.
    #-
    #- In order to provide weather information, you must provide a Forecast.io API key when
    #-  configuring the bot. You can get an API key by registering an email address at
    #-  http://developer.forecast.io/.

    api_key = m.bot.get_config('forecast')
    if api_key:
        if len(m.line) <= 1:
            m.bot.private_message(m.location, "Please format this command as !weather ["
                                              "args] location")
        else:
            if m.line[1] in ["--now", "-now", "-n"]:
                loc = get_location(m, args=True)
                blob = get_weather(m, loc, api_key)
                msg = format_weather_now(blob, loc)
            elif m.line[1] in ["--week", "-week", "-w"]:
                loc = get_location(m, args=True)
                blob = get_weather(m, loc, api_key)
                msg = format_weather_weekly(blob, loc)
            else:
                loc = get_location(m)
                blob = get_weather(m, loc, api_key)
                msg = format_weather(blob, loc)
            m.bot.private_message(m.location, msg)
    else:
        m.bot.logger.info("No Forecast.io API key recorded.")

def get_location(m, args=False):
    """Get the latitude, longitude, and well-formatted name of the given location."""
    google_api = "http://maps.googleapis.com/maps/api/geocode/json?address={}"
    loc = {}
    if args:
        loc["name"] = " ".join(m.line[2:])
        resp = get_url(m, google_api.format("+".join(m.line[2:])))
    else:
        loc["name"] = " ".join(m.line[1:])
        resp = get_url(m, google_api.format("+".join(m.line[1:])))
    blob = json.loads(resp)
    if not blob["results"]:
        m.bot.private_message(m.location, "Could not find weather information for {}."
                              .format(" ".join(m.line[1:])))
    else:
        loc["lat"] = blob['results'][0]['geometry']['location']['lat']
        loc["long"] = blob['results'][0]['geometry']['location']['lng']
        loc["addr"] = blob['results'][0]['formatted_address']
        return loc

def get_weather(m, loc, api_key):
    """Make the API call to get the weather."""
    if loc:
        m.bot.logger.info("Finding weather for {}.".format(loc["name"]))
        forecast_api = "https://api.forecast.io/forecast/{0}/{1},{2}?exclude=flags"
        resp = get_url(m, forecast_api.format(api_key, loc["lat"], loc["long"]))
        return json.loads(resp)

def format_weather(blob, loc):
    """Format the weather nicely."""
    w = {"loc": loc["addr"]}
    w["summary"] = blob["hourly"]['summary']
    temp = blob["hourly"]['data'][0]['temperature']
    app_temp = blob["hourly"]['data'][0]["apparentTemperature"]
    w["humidity"] = round(blob["hourly"]['data'][0]['humidity'] * 100)
    wind = blob["hourly"]['data'][0]["windSpeed"]

    w["temp_f"] = round(temp)
    w["temp_c"] = round(to_celsius(temp))
    w["app_temp_f"] = round(app_temp)
    w["app_temp_c"] = round(to_celsius(app_temp))
    w["wind_mph"] = round(wind)
    w["wind_kph"] = round(wind*1.609)

    return "Weather in {loc}: {summary} {temp_f}˚F ({temp_c}˚C). Feels like {app_temp_f}˚F " \
           "({app_temp_c}˚C). Humidity: {humidity}%. Wind speed: {wind_mph}mph " \
           "({wind_kph}kph).".format(**w)

def format_weather_now(blob, loc):
    """Format the weather nicely."""
    w = {"loc": loc["addr"]}
    summary = blob["currently"]["summary"]
    summary = summary[0] + summary[1:].lower()
    temp = blob["currently"]["temperature"]
    app_temp = blob["currently"]["apparentTemperature"]
    w["humidity"] = round(blob["currently"]["humidity"] * 100)
    wind = blob["currently"]["windSpeed"]

    w["summary"] = summary + "." if summary[-1] != "." else summary
    w["temp_f"] = round(temp)
    w["temp_c"] = round(to_celsius(temp))
    w["app_temp_f"] = round(app_temp)
    w["app_temp_c"] = round(to_celsius(app_temp))
    w["wind_mph"] = round(wind)
    w["wind_kph"] = round(wind*1.609)

    return "Weather in {loc}: {summary} {temp_f}˚F ({temp_c}˚C). Feels like {app_temp_f}˚F " \
           "({app_temp_c}˚C). Humidity: {humidity}%. Wind speed: {wind_mph}mph " \
           "({wind_kph}kph).".format(**w)

def format_weather_weekly(blob, loc):
    """Format the weekly weather nicely."""
    w = {"loc": loc["addr"]}
    w["summary"] = blob["daily"]["summary"]
    min_temp = blob["daily"]["data"][0]["temperatureMin"]
    max_temp = blob["daily"]["data"][0]["temperatureMax"]

    w["min_temp_f"] = round(min_temp)
    w["min_temp_c"] = round(to_celsius(min_temp))
    w["max_temp_f"] = round(max_temp)
    w["max_temp_c"] = round(to_celsius(max_temp))

    return "Weather in {loc}: {summary} {min_temp_f}–{max_temp_f}˚F ({min_temp_c}–" \
           "{max_temp_c}˚C).".format(**w)

def to_celsius(temp):
    """Convert Fahrenheit to Celsius."""
    return (temp-32)*5/9<commit_msg>Give --weekly example<commit_after># Copyright (c) 2013-2014 Molly White
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import json
from plugins.util import command, get_url
from urllib.parse import quote

@command()
def weather(m):
    """Get the weather for a specified location."""

    #-     !weather [--now|--week] location
    #-
    #- ```irc
    #- < GorillaWarfare> !weather boston
    #- < GorillaBot> Weather in Boston, MA, USA: Rain until tomorrow evening and breezy until
    #-               tomorrow morning. 51˚F (10˚C). Feels like 51˚F (10˚C). Humidity: 95%. Wind
    #-               speed: 23mph (38kph).
    #- < GorillaWarfare> !weather --now boston
    #- < GorillaBot> Weather in Boston, MA, USA: Light Rain and Breezy. 51˚F (10˚C). Feels like
    #-               51˚F (10˚C). Humidity: 96%. Wind speed: 25mph (40kph).
    #- < GorillaWarfare> !weather --week boston
    #- < GorillaBot> Weather in Boston, MA, USA: Light rain throughout the week, with temperatures
    #-               bottoming out at 53°F on Friday. 51–55˚F (11–13˚C).
    #- ```
    #-
    #- Provide weather information for the given location. Defaults to giving weather information
    #- about today. Given the `--now` parameter, this will give the current weather. Given the
    #- `--weekly` parameter, this will give the forecast for the week.
    #-
    #- In order to provide weather information, you must provide a Forecast.io API key when
    #-  configuring the bot. You can get an API key by registering an email address at
    #-  http://developer.forecast.io/.

    api_key = m.bot.get_config('forecast')
    if api_key:
        if len(m.line) <= 1:
            m.bot.private_message(m.location, "Please format this command as !weather ["
                                              "args] location")
        else:
            if m.line[1] in ["--now", "-now", "-n"]:
                loc = get_location(m, args=True)
                blob = get_weather(m, loc, api_key)
                msg = format_weather_now(blob, loc)
            elif m.line[1] in ["--week", "-week", "-w"]:
                loc = get_location(m, args=True)
                blob = get_weather(m, loc, api_key)
                msg = format_weather_weekly(blob, loc)
            else:
                loc = get_location(m)
                blob = get_weather(m, loc, api_key)
                msg = format_weather(blob, loc)
            m.bot.private_message(m.location, msg)
    else:
        m.bot.logger.info("No Forecast.io API key recorded.")

def get_location(m, args=False):
    """Get the latitude, longitude, and well-formatted name of the given location."""
    google_api = "http://maps.googleapis.com/maps/api/geocode/json?address={}"
    loc = {}
    if args:
        loc["name"] = " ".join(m.line[2:])
        resp = get_url(m, google_api.format("+".join(m.line[2:])))
    else:
        loc["name"] = " ".join(m.line[1:])
        resp = get_url(m, google_api.format("+".join(m.line[1:])))
    blob = json.loads(resp)
    if not blob["results"]:
        m.bot.private_message(m.location, "Could not find weather information for {}."
                              .format(" ".join(m.line[1:])))
    else:
        loc["lat"] = blob['results'][0]['geometry']['location']['lat']
        loc["long"] = blob['results'][0]['geometry']['location']['lng']
        loc["addr"] = blob['results'][0]['formatted_address']
        return loc

def get_weather(m, loc, api_key):
    """Make the API call to get the weather."""
    if loc:
        m.bot.logger.info("Finding weather for {}.".format(loc["name"]))
        forecast_api = "https://api.forecast.io/forecast/{0}/{1},{2}?exclude=flags"
        resp = get_url(m, forecast_api.format(api_key, loc["lat"], loc["long"]))
        return json.loads(resp)

def format_weather(blob, loc):
    """Format the weather nicely."""
    w = {"loc": loc["addr"]}
    w["summary"] = blob["hourly"]['summary']
    temp = blob["hourly"]['data'][0]['temperature']
    app_temp = blob["hourly"]['data'][0]["apparentTemperature"]
    w["humidity"] = round(blob["hourly"]['data'][0]['humidity'] * 100)
    wind = blob["hourly"]['data'][0]["windSpeed"]

    w["temp_f"] = round(temp)
    w["temp_c"] = round(to_celsius(temp))
    w["app_temp_f"] = round(app_temp)
    w["app_temp_c"] = round(to_celsius(app_temp))
    w["wind_mph"] = round(wind)
    w["wind_kph"] = round(wind*1.609)

    return "Weather in {loc}: {summary} {temp_f}˚F ({temp_c}˚C). Feels like {app_temp_f}˚F " \
           "({app_temp_c}˚C). Humidity: {humidity}%. Wind speed: {wind_mph}mph " \
           "({wind_kph}kph).".format(**w)

def format_weather_now(blob, loc):
    """Format the current weather nicely."""
    w = {"loc": loc["addr"]}
    summary = blob["currently"]["summary"]
    summary = summary[0] + summary[1:].lower()
    temp = blob["currently"]["temperature"]
    app_temp = blob["currently"]["apparentTemperature"]
    w["humidity"] = round(blob["currently"]["humidity"] * 100)
    wind = blob["currently"]["windSpeed"]

    w["summary"] = summary + "." if summary[-1] != "." else summary
    w["temp_f"] = round(temp)
    w["temp_c"] = round(to_celsius(temp))
    w["app_temp_f"] = round(app_temp)
    w["app_temp_c"] = round(to_celsius(app_temp))
    w["wind_mph"] = round(wind)
    w["wind_kph"] = round(wind*1.609)

    return "Weather in {loc}: {summary} {temp_f}˚F ({temp_c}˚C). Feels like {app_temp_f}˚F " \
           "({app_temp_c}˚C). Humidity: {humidity}%. Wind speed: {wind_mph}mph " \
           "({wind_kph}kph).".format(**w)

def format_weather_weekly(blob, loc):
    """Format the weekly weather nicely."""
    w = {"loc": loc["addr"]}
    w["summary"] = blob["daily"]["summary"]
    min_temp = blob["daily"]["data"][0]["temperatureMin"]
    max_temp = blob["daily"]["data"][0]["temperatureMax"]

    w["min_temp_f"] = round(min_temp)
    w["min_temp_c"] = round(to_celsius(min_temp))
    w["max_temp_f"] = round(max_temp)
    w["max_temp_c"] = round(to_celsius(max_temp))

    return "Weather in {loc}: {summary} {min_temp_f}–{max_temp_f}˚F ({min_temp_c}–" \
           "{max_temp_c}˚C).".format(**w)

def to_celsius(temp):
    """Convert Fahrenheit to Celsius."""
    return (temp-32)*5/9<|endoftext|>