Example #1
0
    def __init__(self,
                 master,
                 worker_name,
                 bot_name,
                 server,
                 access_token,
                 port=6667,
                 proxy=None):
        self.master = master
        self.worker_name = worker_name
        self.command = "!" + self.master.bot_name
        self.started = False

        if proxy is not None:
            logging.info('[%s] Proxy set: %s:%s', self.worker_name,
                         proxy["address"], proxy["port"])
            socks.set_default_proxy(socks.HTTP, proxy["address"],
                                    proxy["port"])
            socket.socket = socks.socksocket

        SingleServerIRCBot.__init__(self, [(server, port, access_token)],
                                    bot_name, bot_name)

        # Channels set up
        self.channels = IRCDict()
        self.channel_join_queue = Queue.Queue()
        self.channel_list = []

        # Messages set up
        self.user_message_queue = Queue.Queue()

        logging.info('[%s] Chat worker bot initialized.', self.worker_name)
Example #2
0
    def __init__(self, channel, nick, server, port=6667, clen=9, db=None, nspw=None):
        """Arguments are straightforward. Exception: if 'db' is not None, it signifies
        desire to use an LMDB database as backing storage instead of memory; its
        value should be a string containing the name of the database directory.

        """
        SingleServerIRCBot.__init__(self, [(server, port)], nick, nick)
        if channel:
            self.clist = [channel]
        else:
            self.clist = []
        self.clen = clen
        self.nspw = nspw
        self.chains = {}
        self.mlen = 480
        if db is not None:
            self.env = lmdb.open(db, map_size=4294967296, max_dbs=4096)
            with self.env.begin() as txn:
                c = txn.cursor()
                for i in c.iternext(values=False):
                    db = self.env.open_db(name=i)
                    i = i.decode()
                    self.chains[i] = markov.MarkovGenerator(self.clen, (self.env, db))
        else:
            self.env = None
    def __init__(self, master, worker_name, bot_name, server, access_token, port=6667, proxy=None):
        self.master = master
        self.worker_name = worker_name
        self.command = "!"+self.master.bot_name
        self.started = False
        self.is_connected = False

        if proxy is not None:
            logging.info('[%s] Proxy set: %s:%s', self.worker_name, proxy["address"], proxy["port"])
            socks.set_default_proxy(socks.HTTP, proxy["address"], proxy["port"])
            socket.socket = socks.socksocket

        SingleServerIRCBot.__init__(self, [(server, port, access_token)], bot_name, bot_name)

        # keep ip for logging
        self.proxy_name = socket.gethostbyname(socket.getfqdn())

        # Channels set up
        self.channels = IRCDict()
        self.channel_join_queue = Queue.Queue()
        self.channel_list = []

        # Messages set up
        self.user_message_queue = Queue.Queue()

        self.log('Chat worker bot initialized.')
Example #4
0
    def __init__(self,
                 chans,
                 nickname,
                 nickname_pass,
                 server,
                 port=6667,
                 ssl=False,
                 ipv6=True,
                 ident_passwd=None):
        print('Connecting to IRC server %s...' % server)

        self.chans = chans
        self.nickname = nickname
        kwargs = {}
        if ssl:
            import ssl
            ssl_factory = irc.connection.Factory(ipv6=True,
                                                 wrapper=ssl.wrap_socket)
            kwargs['connect_factory'] = ssl_factory

        SingleServerIRCBot.__init__(self, [(server, port)], nickname_pass,
                                    'IRC echo bot', **kwargs)
        if ident_passwd is not None:
            ib3_auth.SASL.__init__(self, [(server, port)], nickname_pass,
                                   'IRC echo bot', ident_passwd, **kwargs)
Example #5
0
File: bot.py Project: j616/BeardBot
    def __init__(self, channel, server, port=6667, password=None, name="beardbot", noadmin=False):
        SingleServerIRCBot.__init__(self, [(server, port, password)], name, "The Beardy-Based Botulator")
        # The channel the bot is a member of
        self.channel = channel

        # The last place a message was recieved from (used by "reply")
        self.last_message_sender = self.channel

        # If bot should have no administrators
        self.noadmin = noadmin

        # The loaded modules
        self.modules = {}

        # list of nicks to ignore
        self.ignore = []

        # Try to load previously loaded modules
        try:
            old_modules = pickle.load(open(self.channel + "_modules.db", "r"))
            for module in old_modules:
                try:
                    self.load_module(module)
                except Exception, e:
                    traceback.print_exc(file=sys.stdout)
        except:
            # Otherwise just start the admin
            try:
                self.load_module("admin")
            except Exception, e:
                print e
Example #6
0
    def __init__(self, settings, connect_factory, debug):
        self.cfg = settings
        self.debug = debug
        self.start_time = time.time()
        self.channel_list = []
        if debug:
            self.nickname = 'testbot'
            self.realname = 'testbot'
            self.channel_list.append(Channel(self.cfg['channel_list'][0], self.nickname, self.cfg['quotes_dir']))
        else:
            self.nickname = self.cfg['nickname']
            self.realname = self.cfg['realname']
	    for channel in self.cfg['channel_list'][1:]:
                self.channel_list.append(Channel(channel, self.nickname, self.cfg['quotes_dir']))
        self.ignore_list = []
        self.faq_timeout = self.cfg['faq_timeout']
        self.last_faq = FAQ_Command.get_latest_faq()
        SingleServerIRCBot.__init__(
            self,
            server_list=[(self.cfg['server'], self.cfg['port'])],
            nickname=self.nickname,
            realname=self.realname,
            connect_factory=connect_factory
        )
        self.connection.privmsg = self.privmsg
Example #7
0
    def __init__(self, username, client_id, token, chan, settings):
        self.reset_color = attr("reset")
        print(
            fg("#00ff00") +
            "Thanks for using the chatbot! Use Ctrl+C to exit safely." +
            self.reset_color)
        self.init_logger()
        self.client_id = client_id
        self.token = token
        self.channel = '#' + chan
        self.dice_games = []
        self.settings = settings
        self.database = SQLiteConnector()

        self.commands = {
            "debug": DebugCommand,
            "join": JoinCommand,
            "slots": SlotsGame
        }

        # Initialize the thread cleaner
        t_cleaner = ThreadCleaner(self)
        t_cleaner.start()
        # Create IRC bot connection
        server = 'irc.chat.twitch.tv'
        port = self.settings["bot_settings"]["port"]
        self.logger.info(f'Connecting to {server} on port {port}')
        SingleServerIRCBot.__init__(self, [(server, port, token)], username,
                                    username)
Example #8
0
 def _dispatcher(self, c, e):
     et = e.type
     if et not in self._events_not_logged():
         s = e.source
         t = e.target
         log.debug(u'{}, {}, {} -- {}'.format(et, s, t, e.arguments))
     SingleServerIRCBot._dispatcher(self, c, e)
Example #9
0
    def run(self):
        spec = ServerSpec(self.server)
        SingleServerIRCBot.__init__(self, [spec], self.nick, self.realname)
        self._connect()
        self.lightCheck = 0 # Check only every N loops
        self.timestamp = datetime.datetime.now()
        self.updateStatus()
        feed_read_counter=99


        while(self.running):
            self.checkLights()
            feed_read_counter +=1
            if (self.vaasa and feed_read_counter==100): 
                feed_read_counter = 0
                self.read_feed()
                self.updateStatus()
            try:
                self.reactor.process_once(0.2)
            except UnicodeDecodeError:
                pass
#                print 'Somebody said something in non-utf8'
#                                traceback.print_exc(file=sys.stdout)
            except irc.client.ServerNotConnectedError:
                print 'Not connected. Can not do anything atm.'
            time.sleep(0.5)
Example #10
0
 def __init__(self, host, port, nickname, password, channel):
     logger.debug('TCIBot.__init__ (VERSION = %r)', self.VERSION)
     SingleServerIRCBot.__init__(self, [(host, port, password)], nickname,
                                 nickname)
     self.channel = channel
     self.viewers = []
     self.es = Elasticsearch("http://{}:{}".format(
         settings.ELK_HOST, settings.ELK_SEARCH_PORT))
Example #11
0
 def _dispatcher(self, c, e):
     eventtype = e.type
     source = e.source
     if source is not None:
         source = str(source)
     else:
         source = ''
     SingleServerIRCBot._dispatcher(self, c, e)
Example #12
0
 def __init__(self, config, port=6667):
     self.config = config
     self.nick = config['network']['nick']
     self.userpass=config['network']['nickserv']
     miscinfo = ServerSpec(config['network']['server'], 
                           port, 
                           config['network']['nickserv'])
     SingleServerIRCBot.__init__(self, [miscinfo], self.nick, self.nick)
Example #13
0
 def __init__(self):
     port = config_data['irc_port']
     nickname = config_data['irc_nickname']
     server = config_data['irc_server']
     print "connecting to %s as %s on port %s" % (server, nickname, port)
     server_list = [(server, port)]
     realname = config_data['irc_realname']
     SingleServerIRCBot.__init__(self, server_list, nickname, realname)
     self.chans = []
Example #14
0
    def __init__(self, server='localhost'):
        self.channel = CONFIG['irc']['default_channel']
        SingleServerIRCBot.__init__(
            self, [(CONFIG['irc']['host'], int(CONFIG['irc']['port']))],
            CONFIG['irc']['nick'], CONFIG['irc']['nick'])

        xmlrpc_host = CONFIG['skype']['xmlrpc_host']
        xmlrpc_port = CONFIG['skype']['xmlrpc_port']
        self.skype = xmlrpclib.ServerProxy('http://%s:%s' %
                                           (xmlrpc_host, xmlrpc_port))
Example #15
0
File: bot.py Project: j616/BeardBot
    def die(self, *args, **kwargs):
        # Store a list of loaded modules before going down
        pickle.dump(self.modules.keys(), open(self.channel + "_modules.db", "w"))

        # Kill all the modules
        for module in self.modules.values():
            module.die()

            # Disconnect and quit
        SingleServerIRCBot.die(self, *args, **kwargs)
Example #16
0
	def __init__(self):
		""" This initializes the bot with Config values. """
		server, channel = Config().UpdateServer.split("#")
		host, port = server.split(":")
		SingleServerIRCBot.__init__(self, [(host,int(port))], self.makeUserName(), "OlympusIRCUpdater" )
		self.channel = "#" + channel
		self.connection.buffer_class.errors = 'replace'
		self.ping_interval = 60
		print "Connecting to the update server. This might take some time..."
		print "-------------------------------------------------------------"
Example #17
0
    def __init__(self, nick, address, port, channels, task, download_dir=u"."):

        SingleServerIRCBot.__init__(self, [(address, port)], nick, nick)

        self.__recv_bytes = 0
        self.task = task
        self.filepath = u""
        self.download_dir = download_dir
        self.chans = channels
        self.file = None
        self.dcc = None
Example #18
0
	def __init__(self, channel, key, nickname, server, port=6667):
		SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
		WHGame.__init__(self)
		print "Initializing"
		self.channel = channel
		self.key = key
		self.load_assets()
		self.load_plugins("round")
		self.load_plugins("modifier")
		assert(self.rounds)
		print "Initialization complete"
Example #19
0
    def __init__(self, channels, nickname, server, port=6667):
        SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
        # self.connection.add_global_handler('pubmsg', self.on_pubmsg)
        self.connection.add_global_handler('join', self.on_join)
        self.connection.add_global_handler('welcome', self.on_welcome)

        self.mainchannel = channels[0]
        self.joined = dict()
        for channel in channels:
            self.joined[channel] = Event()
        self.weboob = None
Example #20
0
    def __init__(self,
                 nickname,
                 server,
                 port=6667,
                 allowed_nicks=[],
                 command=Command):
        self.allowed_nicks = allowed_nicks
        self.command = command

        logger.info(f"Connecting to {server}:{port} with nickname {nickname}")
        SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
Example #21
0
 def __init__(self, channel, key, nickname, server, port=6667):
     SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
     WHGame.__init__(self)
     print "Initializing"
     self.channel = channel
     self.key = key
     self.load_assets()
     self.load_plugins("round")
     self.load_plugins("modifier")
     assert (self.rounds)
     print "Initialization complete"
Example #22
0
    def __init__(self, channels, nickname, server, port=6667):
        SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
        # self.connection.add_global_handler('pubmsg', self.on_pubmsg)
        self.connection.add_global_handler('join', self.on_join)
        self.connection.add_global_handler('welcome', self.on_welcome)

        self.mainchannel = channels[0]
        self.joined = dict()
        for channel in channels:
            self.joined[channel] = Event()
        self.weboob = None
Example #23
0
    def __init__(self, chans, nickname, server, port=6667, ssl=False):
        print('Connecting to IRC server %s...' % server)

        if ssl:
            import ssl
            ssl_factory = irc.connection.Factory(wrapper=ssl.wrap_socket)
            SingleServerIRCBot.__init__(self, [(server, port)], nickname, 'IRC echo bot',
                                        connect_factory=ssl_factory)
        else:
            SingleServerIRCBot.__init__(self, [(server, port)], nickname, 'IRC echo bot')
        self.chans = chans
Example #24
0
 def __init__(self, channels, nickname, nickpass, server, port=6667):
     SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
     self.initial_channels = channels
     self.nickpass = nickpass
     # magic_key is used for admin commands. E.g., "magic_key say
     # test" in a query with the bot triggers the admin command
     # "say".
     self.magic_key = ''.join([random.choice(string.ascii_letters) for x in range(8)]) + ' '
     self.print_magic_key()
     self.current_topic = ''
     self._timers = []
     self._connect()
Example #25
0
    def __init__(self):
        '''
		Constructor
		'''
        self._channels = []
        self.username = Setting.get(Setting.key == 'TwitchUsername').value
        pw = Setting.get(Setting.key == 'TwitchAuth').value

        spec = ServerSpec(Constants.TWITCH_HOST, Constants.TWITCH_PORT, pw)
        SingleServerIRCBot.__init__(self, [spec], self.username, self.username)

        run_thread = Thread(target=self.start)
        run_thread.start()
Example #26
0
 def __init__(self, server_list, nickname, realname, bavard=True):
     '''Doc de SingleServerIRCBot
     - irc_list -- A list of ServerSpec objects or tuples of
                    parameters suitable for constructing ServerSpec
                    objects. Defines the list of servers the bot will
                    use (in order).
     - nickname -- The bot's nickname.
     - realname -- The bot's realname.
     '''
     SingleServerIRCBot.__init__(self, server_list, nickname, realname)
     self.wiki_out = ''
     self.bavard = bavard
     self.address = ""
Example #27
0
	def __init__(self):
		'''
		Constructor
		'''
		self._channels = []
		self.username = Setting.get(Setting.key=='TwitchUsername').value
		pw = Setting.get(Setting.key=='TwitchAuth').value
		
		spec = ServerSpec(Constants.TWITCH_HOST, Constants.TWITCH_PORT, pw)
		SingleServerIRCBot.__init__(self, [spec], self.username, self.username)
		
		run_thread = Thread(target=self.start)
		run_thread.start()
Example #28
0
    def __init__(self, server, channels, nick, nick_pass, port, topic, hist_path):
        log.debug("new bot started at %s:%d@#%s as %s", server, port, channels, nick)
        SingleServerIRCBot.__init__(self, server_list=[(server, port)], nickname=nick, realname="Mumford J. Hanabot")

        self.nick_pass = nick_pass
        self.nick_name = nick
        self.topic = topic
        # this should be in the config file so that different network
        # rate limiting polices can be specified. These defaults
        # are tuned to freenode.
        self.connection.set_rate_limit(2)

        game_history.hist_file = hist_path

        # force channels to start with #
        self.home_channels = [c if c[0] == "#" else "#%s" % c for c in channels]
        log.debug("Home channels: %s" % self.home_channels)

        # valid bot commands
        self.command_dict = {
            "Game Management": ["new", "delete", "join", "start", "stop", "leave", "part", "option", "watch"],
            "Hand Management": ["move", "swap", "sort"],
            "Game Action": ["play", "hint", "discard"],
            "Information": [
                "help",
                "rules",
                "turn",
                "turns",
                "game",
                "hints",
                "games",
                "hands",
                "table",
                "discardpile",
                "version",
                "last",
            ],
        }

        self.commands = list()
        for cmds in self.command_dict.values():
            self.commands += cmds

        self.commands_admin = ["die"]

        # these commands can execute without an active game.
        # otherwise the command handlers can assume an active game.
        self.no_game_commands = ["new", "join", "help", "rules", "game", "games", "part", "version", "last"]

        # games is a dict indexed by channel name, value is the Game object.
        self.games = dict()
Example #29
0
 def __init__(self, conf, tui, all_joined):
     SingleServerIRCBot.__init__(self, [(conf.server, conf.port)],
             conf.nickname, conf.realname)
     self.conf = conf
     self.tui = tui
     tui.bot = self
     self.handler = MessageHandler(conf, self)
     self.pollers = []
     self.all_joined = all_joined
     self.joined = []
     for (user, project) in self.conf.issues:
         p = IssuePoller(conf, self, user, project)
         self.pollers.append(p)
         self.tui.msg(u'Poller built for ' + user + '/' + project)
Example #30
0
    def __init__(self):
        config = ConfigParser.SafeConfigParser()
        config.read("./config.ini")

        self.interpreter = basinterp.BasicInterpreter({})
        self.user_list = []
        src_dir = os.path.join(os.path.dirname(__file__), unicode(config.get("basic", "src_dir")))
        self.interpreter.set_src_dir(src_dir) # default

        server = unicode(config.get("irc", "server"))
        port = int(config.get("irc", "port"))
        nick = unicode(config.get("irc", "nick"))
        SingleServerIRCBot.__init__(self, [(server, port)], nick, nick)
        self.channel = unicode(config.get("irc", "channel"))
Example #31
0
    def __init__(self, channels, nickname, server, port=6667):
        SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
        # self.connection.add_global_handler('pubmsg', self.on_pubmsg)
        self.connection.add_global_handler('join', self.on_join)
        self.connection.add_global_handler('welcome', self.on_welcome)
        self.connection.buffer_class.errors = 'replace'

        self.mainchannel = channels[0]
        self.joined = dict()
        for channel in channels:
            self.joined[channel] = Event()
        self.weboob = None
        self.storage = None

        self.tasks_queue = []
Example #32
0
    def __init__(self):
        config = ConfigParser.SafeConfigParser()
        config.read("./config.ini")

        self.interpreter = basinterp.BasicInterpreter({})
        self.user_list = []
        src_dir = os.path.join(os.path.dirname(__file__),
                               unicode(config.get("basic", "src_dir")))
        self.interpreter.set_src_dir(src_dir)  # default

        server = unicode(config.get("irc", "server"))
        port = int(config.get("irc", "port"))
        nick = unicode(config.get("irc", "nick"))
        SingleServerIRCBot.__init__(self, [(server, port)], nick, nick)
        self.channel = unicode(config.get("irc", "channel"))
Example #33
0
    def __init__(self, channels, nickname, server, port=6667):
        SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
        # self.connection.add_global_handler('pubmsg', self.on_pubmsg)
        self.connection.add_global_handler('join', self.on_join)
        self.connection.add_global_handler('welcome', self.on_welcome)
        self.connection.buffer_class.errors = 'replace'

        self.mainchannel = channels[0]
        self.joined = dict()
        for channel in channels:
            self.joined[channel] = Event()
        self.weboob = None
        self.storage = None

        self.tasks_queue = []
Example #34
0
    def __init__(self, server_spec, nickname, realname, channels, ssl=False,
                 shutdown_predicate=None):
        log('Connecting to IRC server {0.host}:{0.port:d} ...', server_spec)

        connect_params = {}
        if ssl:
            ssl_factory = Factory(wrapper=ssl_wrap_socket)
            connect_params['connect_factory'] = ssl_factory

        SingleServerIRCBot.__init__(self, [server_spec], nickname,
            realname, **connect_params)

        # Note: `self.channels` already exists in super class.
        self.channels_to_join = channels

        self.shutdown_predicate = shutdown_predicate
Example #35
0
    def __init__(self, server_list, channel, nickname, realname, bavard=True):
        """Doc de SingleServerIRCBot
        - irc_list -- A list of ServerSpec objects or tuples of
                       parameters suitable for constructing ServerSpec
                       objects. Defines the list of servers the bot will
                       use (in order).
        - channel  -- "#wikipedia-fr"
        - nickname -- The bot's nickname.
        - realname -- The bot's realname.
        """

        SingleServerIRCBot.__init__(self, server_list, nickname, realname)

        self.channel = channel
        self.wiki_out = ''
        self.bavard = bavard
        self.address = ""
Example #36
0
File: mrdo.py Project: velour/MrDO
 def __init__(self, config):
     SingleServerIRCBot.__init__(self,
                                 [serverOfConfig(config)],
                                 config.settings[Configuration.IRC_UNAME],
                                 config.settings[Configuration.IRC_UNAME])
     self.config = config
     self.channel = config.settings[Configuration.IRC_CHAN]
     self.droplet = None
     self.manager = None
     if self.config.settings[Configuration.DO_API_KEY]:
         try:
             key = self.config.settings[Configuration.DO_API_KEY]
             if key:
                 self.manager = digitalocean.Manager(token=key.strip())
         except:
             print "Couldn't setup a digital ocean manager. Key is bogus?"
     self._config_commands()
Example #37
0
    def __init__(self, botconfig):
        """Setup everything.

        | Setup the handler.
        | Setup the server.
        | Connect to the server.
        """
        atexit.register(self.do_shutdown)
        self.handler = handler.BotHandler(botconfig)
        self.config = botconfig
        serverinfo = ServerSpec(botconfig['core']['host'], int(botconfig['core']['ircport']), botconfig['auth']['nickpass'])
        nick = botconfig['core']['nick']
        SingleServerIRCBot.__init__(self, [serverinfo], nick, nick)
        # properly log quits.
        self.connection.add_global_handler("quit", self.handle_quit, -21)
        # fix unicode problems
        self.connection.buffer_class.errors = 'replace'
Example #38
0
 def __init__(self, site, channel, nickname, server, port=6667, **kwargs):
     """Initializer."""
     pywikibot.Bot.__init__(self, **kwargs)
     SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
     self.channel = channel
     self.site = site
     self.other_ns = re.compile(
         '\x0314\\[\\[\x0307(%s)'
         % '|'.join(item.custom_name for item in site.namespaces.values()
                    if item != 0))
     self.api_url = (
         self.site.apipath()
         + '?action=query&meta=siteinfo&siprop=statistics&format=xml')
     self.api_found = re.compile(r'articles="(.*?)"')
     self.re_edit = re.compile(
         r'^C14\[\[^C07(?P<page>.+?)^C14\]\]^C4 (?P<flags>.*?)^C10 ^C02'
         r'(?P<url>.+?)^C ^C5\*^C ^C03(?P<user>.+?)^C ^C5\*^C \(?^B?'
         r'(?P<bytes>[+-]?\d+?)^B?\) ^C10(?P<summary>.*)^C'
         .replace('^B', '\002').replace('^C', '\003').replace('^U', '\037'))
Example #39
0
 def __init__(self, site, channel, nickname, server, port=6667, **kwargs):
     """Initializer."""
     pywikibot.Bot.__init__(self, **kwargs)
     SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
     self.channel = channel
     self.site = site
     self.other_ns = re.compile(
         '\x0314\\[\\[\x0307(%s)' %
         '|'.join(item.custom_name
                  for item in site.namespaces.values() if item != 0))
     self.api_url = (
         self.site.apipath() +
         '?action=query&meta=siteinfo&siprop=statistics&format=xml')
     self.api_found = re.compile(r'articles="(.*?)"')
     self.re_edit = re.compile(
         r'^C14\[\[^C07(?P<page>.+?)^C14\]\]^C4 (?P<flags>.*?)^C10 ^C02'
         r'(?P<url>.+?)^C ^C5\*^C ^C03(?P<user>.+?)^C ^C5\*^C \(?^B?'
         r'(?P<bytes>[+-]?\d+?)^B?\) ^C10(?P<summary>.*)^C'.replace(
             '^B', '\002').replace('^C', '\003').replace('^U', '\037'))
Example #40
0
    def __init__(self, botconfig):
        """Setup everything.

        | Setup the handler.
        | Setup the server.
        | Connect to the server.
        """
        atexit.register(self.do_shutdown)
        self.handler = handler.BotHandler(botconfig)
        self.config = botconfig
        serverinfo = ServerSpec(botconfig['core']['host'], int(botconfig['core']['ircport']), botconfig['auth']['serverpass'])
        nick = botconfig['core']['nick']
        if botconfig['core'].getboolean('ssl'):
            SingleServerIRCBot.__init__(self, [serverinfo], nick, nick, connect_factory=Factory(wrapper=ssl.wrap_socket))
        else:
            SingleServerIRCBot.__init__(self, [serverinfo], nick, nick)
        # properly log quits.
        self.connection.add_global_handler("quit", self.handle_quit, -21)
        # fix unicode problems
        self.connection.buffer_class.errors = 'replace'
Example #41
0
        def onStart(self):
        # For handelig async stuff
        self.waitEvents = {}

        SingleServerIRCBot.__init__(self, [(server, port)], nickname, realname)
        self.allChannels = channels
        self.channel = channels[0] # first chan is default chan
        log.info('all configured channels: %s' % self.allChannels)
        log.info('configured main channel: %s' % self.channel)
        self.secrets = secrets
        self.help_hash = {'help':('This menu',{}),
                        }
        self.queue = OutputManager(self.connection, .9)
        self.queue.start()
        try:
            self.start()
        except KeyboardInterrupt:
            self.connection.quit("Ctrl-C at console")
            print "Quit IRC."
        except Exception, e:
            self.connection.quit("%s: %s" % (e.__class__.__name__, e.args))
Example #42
0
	def __init__(self, config): #, channel, nickname, password, server, port=6667, debug=False):
		self.log("Bot initialized.")
		self.config = config
		self.DEBUG = config.debug
		SingleServerIRCBot.__init__(self, [(config.server, config.port)], config.name, config.name)
		self.channel = config.channel
		self.nick = config.name
		self.nickpassword = config.password
		self.connection.add_global_handler("join", getattr(self, "inform_webusers"), 42)

		for i in ["kick", "join", "quit", "part", "topic", "endofnames", "notopic"]:
			self.connection.add_global_handler(i, getattr(self, "dump_users"), 42)

		# We need to distinguish between private and public messages
		self.connection.add_global_handler("pubmsg", getattr(self, "publicMessage"), 42)
		self.connection.add_global_handler("privmsg", getattr(self, "privateMessage"), 42)
		self.connection.add_global_handler("privnotice", getattr(self, "privateMessage"), 42)
		self.connection.add_global_handler("notice", getattr(self, "privateMessage"), 42)

		# List of active modules
		self.activeModules = []
Example #43
0
    def __init__(self, botconfig):
        """Setup everything.

        | Setup the handler.
        | Setup the server.
        | Connect to the server.
        """
        atexit.register(self.do_shutdown)
        self.handler = handler.BotHandler(botconfig)
        self.handler.workers = workers.Workers(self.handler)
        self.config = botconfig
        serverinfo = ServerSpec(botconfig['core']['host'], int(botconfig['core']['ircport']), botconfig['auth']['serverpass'])
        nick = botconfig['core']['nick']
        if botconfig['core'].getboolean('ssl'):
            SingleServerIRCBot.__init__(self, [serverinfo], nick, nick, connect_factory=Factory(wrapper=ssl.wrap_socket))
        else:
            SingleServerIRCBot.__init__(self, [serverinfo], nick, nick)
        # properly log quits.
        self.connection.add_global_handler("quit", self.handle_quit, -21)
        # fix unicode problems
        self.connection.buffer_class.errors = 'replace'
Example #44
0
    def on_ctcp(self, c, e):
        xbmc.log(e.arguments)
        args = parse_args(e,
                          (u"protocol", u"opt", u"filename", u"ip", u"port"))

        if not args or args[0:2] not in ([u"XDCC", u"SEND"], [u"DCC", u"SEND"
                                                              ]):

            return SingleServerIRCBot.on_ctcp(self, c, e)

        self.filepath = os.path.join(self.download_dir, args[2])
        self.file = open(self.filepath, u"ab")
        self.dcc = self.dcc_connect(*args[3:5] + [u"raw"])
        print u"\ndownload started"
Example #45
0
    def __init__(self, server, channel, nick='hanabot', nick_pass=None, port=6667, topic=None):
        log.debug('new bot started at %s:%d@#%s as %s', server, port,
                  channel, nick)
        SingleServerIRCBot.__init__(
            self,
            server_list=[(server, port)],
            nickname=nick,
            realname='Mumford J. Hanabot')

        self.nick_pass = nick_pass
        self.nick_name = nick  
        self.topic = topic

        # force channel to start with #
        self.initial_channel = channel if channel[0] == '#' else '#%s' % channel

        # valid bot commands
        self.command_dict = {
            'Game Management': ['new', 'delete', 'join', 'start', 'leave', 'part'],
            'Hand Management': ['move', 'swap', 'sort'],
            'Game Action': ['play', 'hint', 'discard'],
            'Information': ['help', 'rules', 'turn', 'turns', 'game',
                            'games', 'hands', 'table', 'discardpile']
        }
        
        self.commands = list()
        for cmds in self.command_dict.values():
            self.commands += cmds

        self.commands_admin = ['die']

        # these commands can execute without an active game.
        # otherwise the command handlers can assume an active game.
        self.no_game_commands = ['new', 'help', 'rules', 'game', 'games', 'part']

        # games is a dict indexed by channel name, value is the Game object.
        self.games = dict()
Example #46
0
    def run(self):
        spec = ServerSpec(self.server)
        SingleServerIRCBot.__init__(self, [spec], self.nick, self.realname)
        self._connect()
        self.lightCheck = 0 # Check only every N loops
        self.timestamp = datetime.datetime.now()
        self.updateStatus()
        feed_read_counter=99

        mqttclient = paho.Client()
        mqttclient.on_subscribe = on_subscribe
        mqttclient.on_message = on_message
        try:
            mqttclient.connect("tunkki9", 1883)
        except:
            print "mqtt not connected"

        mqttclient.loop_start()
        mqttclient.subscribe("door/#", qos=1)

        while(self.running):
            self.checkLights()
            self.mqtt_door()
#            feed_read_counter +=1
#            if (self.vaasa and feed_read_counter==100): 
#                feed_read_counter = 0
#                self.read_feed()
#                self.updateStatus()
            try:
                self.reactor.process_once(0.2)
            except UnicodeDecodeError:
                pass
#                print 'Somebody said something in non-utf8'
#                                traceback.print_exc(file=sys.stdout)
            except irc.client.ServerNotConnectedError:
                print 'Not connected. Can not do anything atm.'
            time.sleep(0.5)
Example #47
0
    def on_pubmsg(self, c, e):
        cmd = e.arguments[0].split()[0]

        if cmd[0] == "!":
            cmd = cmd[1:].upper()
            if commands.has_key(cmd):
                commands[cmd].index(self, c, e)
            else:
                cmd=e.arguments[0]

        if cmd=='!kuole':
            self.running = False
            SingleServerIRCBot.die(self, 'By your command')
        if (cmd=='!ovi') or (cmd=='!door'):
            self.sayDoorStatus()
        if (cmd=='!valot') or (cmd=='!lights'):
            self.say('lights are ' + ('on' if self.lightStatus else 'off'))
        if (cmd=='!checksum') or (cmd=='!checksum'):
            self.say('pixelvar: ' + str(self.camera.checkSum()))
        if (cmd=='!printer') or (cmd=='!tulostin'):
            ping_response = subprocess.Popen(["/bin/ping", "-c1", "-w2", self.printer_ip], stdout=subprocess.PIPE).stdout.read()
            if ('rtt' in ping_response):
                self.say('printer is online')
            else:
                self.say('printer is offline')
            print('p: ' + str(ping_response))

        if cmd=='!shot':
            self.camera.takeShotCommand()
            c.privmsg(self.channel, self.shoturl + ('' if self.lightStatus else ' (pretty dark, eh)'))
        if cmd=='!gitpull':
            os.system('/home/pi/pajabot/scripts/gitpull.sh')
            c.privmsg(self.channel, 'Pulled from git, restarting..')
            self.restart_program()
        if cmd=='!update':
            self.updateStatus()
            c.privmsg(self.channel, 'Done')
Example #48
0
    def __init__(self):
        self.path, self.file = os.path.split(_abspath)
        self.brain = Brain(u'{}/brain.sqlite'.format(self.path))

        config_json = u'{}/config.json'.format(self.path)
        rps_json = u'{}/rps.json'.format(self.path)
        keys_json = u'{}/keys.json'.format(self.path)
        self.config = dbaccess.Config(config_json, rps_json, keys_json)

        # Load plugins
        for plug_name in self.config.get(u'plugins', list())[:]:
            public, private = self.handle_load([u'!load', plug_name])
            for m in private:
                log.info(m)

        self.mb = util.CollectionOfNamedLists(u'{}/mb.json'.format(self.path))
        self.tf = util.TitleFetcher()

        args = sys.argv[1:]
        for arg in args:
            if arg.startswith(u'--set-'):
                key, value = arg[6:].split(u'=', 1)
                print u'Setting \'{}\' to \'{}\'.'.format(key, value)
                self.config.set(key, value)

        # Set up ignore if the ignore list is non-empty.
        ignore = self.config.get(u'msg:ignore', u'')
        self.reignore = None
        if ignore:
            self.reignore = re.compile(ignore, re.IGNORECASE)

        server = self.config.get(u'irc:server')
        nick = self.config.get(u'irc:nick')
        name = self.config.get(u'irc:name')
        SingleServerIRCBot.__init__(self, [(server, 6667)], nick, name)
        self.connection.buffer_class.errors = u'replace'
Example #49
0
    def __init__(self, auth, roles, service, channel=None, running=lambda:True):
        self.running = running
        self.service = None
        Interface.__init__(self, service)
        self.HOST = "irc.chat.twitch.tv"
        self.PORT = 6667

        if not channel.startswith("#"):
            channel = f"#{channel}"
        self.CHANNEL = channel

        self.CLIENT_ID = auth["client_id"]
        self.TOKEN = auth["token"]
        self.USERNAME = auth["username"]
        
        self.ROLES = roles

        url = f"https://api.twitch.tv/kraken/users?login={self.USERNAME}"
        headers = {"Client-ID": self.CLIENT_ID, "Accept": "application/vnd.twitchtv.v5+json"}
        resp = get(url, headers=headers).json()
        self.channel_id = resp["users"][0]["_id"]

        SingleServerIRCBot.__init__(self, [(self.HOST, self.PORT, f"oauth:{self.TOKEN}")],
            self.USERNAME, self.USERNAME, recon=No_Reconnect())
Example #50
0
    def on_pubmsg(self, c, e):
        cmd = e.arguments[0].split()[0]

        if cmd[0] == "!":
            cmd = cmd[1:].upper()
            if commands.has_key(cmd):
                commands[cmd].index(self, c, e)
            else:
                cmd=e.arguments[0]

        if cmd=='!kuole':
            self.running = False
            SingleServerIRCBot.die(self, 'By your command')
        if (cmd=='!ovi') or (cmd=='!door'):
            self.sayDoorStatus()
        if (cmd=='!valot') or (cmd=='!lights'):
            self.say('lights are ' + ('on' if self.lightStatus else 'off'))
        if (cmd=='!checksum') or (cmd=='!checksum'):
            self.say('pixelvar: ' + str(self.camera.checkSum()))
        if (cmd=='!printer') or (cmd=='!tulostin'):
            self.sayPrinterStatus()

#        if (cmd=='!printteri'):
#            commands['PRINTTERI'].index(self, c,e)


        if cmd=='!shot':
            self.camera.takeShotCommand()
            c.privmsg(self.channel, self.shoturl + ('' if self.lightStatus else ' (pretty dark, eh)'))
        if cmd=='!gitpull':
            os.system('/home/ovi/pajabot/scripts/gitpull.sh')
            c.privmsg(self.channel, 'Pulled from git, restarting..')
            self.restart_program()
        if cmd=='!update':
            self.updateStatus()
            c.privmsg(self.channel, 'Done')
Example #51
0
 def __init__(self, channel, nick, server, nspw=None, port=6667):
     SingleServerIRCBot.__init__(self, [(server, port)], nick, nick)
     self.channel = channel
     self.nspw = nspw
Example #52
0
    def __init__(self, mindfile, blfile, logfile, agefile, real_id, real,
                 ident, birthday, friend):
        SingleServerIRCBot.__init__(self, [(ident.server, ident.port)],
                                    ident.nickname, ident.realname)

        self.mindfile = mindfile
        self.blfile = blfile
        self.logfile = logfile
        self.agefile = agefile
        # load mind
        try:
            self.mind = pickle.load(open(mindfile, 'rb'))
        except IOError:
            print("No markov file (" + mindfile +
                  ") found; making a blank one")
            self.mind = Markov(2)

        # words that will highlight some nicks, in the form of a dictionary
        # from words to the nicks they hilight.
        try:
            self.blacklist = pickle.load(open(self.blfile, "rb"))
        except FileNotFoundError:
            self.blacklist = []

        class State(dict):
            def __getitem__(self, key):
                if key not in self:
                    super(State, self).__setitem__(key, random.getstate())

                return super(State, self).__getitem__(key)

        # the handle generator
        self.handlegen = Markov(2)
        for line in open("nicks", "r"):
            line = line[:-1]  # strip newl
            n = []
            for c in line:
                n.append(MarkovElem(c))

            #n = map(MarkovElem, line)

            n[0].tags["pos"] = "BEGIN"
            n[-1].tags["pos"] = "END"

            self.handlegen.learn(n)

        try:
            self.states = pickle.load(open("rstate", "rb"))
        except FileNotFoundError:
            self.states = State()

        self.waiting_for_friend = queue.Queue()  # channels to send lurkers to

        self.nick = ident.nickname
        self.password = ident.password
        self.channel = ident.channel  # active channels
        self.cafe = ident.cafe
        self.rstate = random.getstate()  # random state
        self.real_id = real_id  # whether self.real is a user or a nick
        self.real = real  # real user she imitates (i.e. avery)
        #self.save_counter = 0           # write to disk every 100 talks
        self.friend = friend
        self.birthday = birthday
 def __init__(self, channel, nickname, server, port=6667):
     SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
     self.channel = channel
Example #54
0
 def __init__(self, queue, server=IRC_SERVER, port=IRC_PORT, nick=IRC_NICK):
     SingleServerIRCBot.__init__(self, [(server, port)], nick, nick)
     self.queue = queue
Example #55
0
 def __init__(self, server, channel, nick, real, port=6667):
     SingleServerIRCBot.__init__(self, [(server, port)],
                                 nick, real)
     self.channel = channel
Example #56
0
 def _load_irc_connection(self):
     print(f'Connecting to {self.server} on port {str(self.port)}...')
     SingleServerIRCBot.__init__(
         self, [(self.server, self.port, 'oauth:' + self.token)],
         self.username, self.username)
Example #57
0
 def __init__(self, plugin, channels):
     IRCBot.__init__(self, [(plugin.server, plugin.port)], plugin.nick,
                     plugin.nick)
     self.initial_channels = channels
     self.plugin = plugin
     self.ratelimit = RateLimit()
Example #58
0
 def handle_connect(self, serverinfo, nick, botconfig):
     ipv6 = botconfig.getboolean('ipv6')
     if botconfig.getboolean('ssl'):
         SingleServerIRCBot.__init__(self, [serverinfo], nick, nick, connect_factory=Factory(wrapper=ssl.wrap_socket, ipv6=ipv6))
     else:
         SingleServerIRCBot.__init__(self, [serverinfo], nick, nick, connect_factory=Factory(ipv6=ipv6))