Exemplo n.º 1
0
    def __init__(self, args, datastore):
        self.args = args
        self.datastore = datastore
        self.responder = Responder(args, datastore, self)

        if args.use_irc:
            self.ircbot = IRCBot(args)
Exemplo n.º 2
0
class IOHandler():
    def __init__(self, args, datastore):
        self.args = args
        self.datastore = datastore
        self.responder = Responder(args, datastore, self)

        if args.use_irc:
            self.ircbot = IRCBot(args)

    def get_message(self) -> str:
        '''Returns the next message from the user'''
        if self.args.use_irc:
            return self.ircbot.get_message()

        return input("> ")

    def send_message(self, message: str) -> None:
        '''Sends a message to the user'''
        if self.args.use_irc:
            return self.ircbot.send_message(message)

        print(f"{self.args.bot_name}: {message}\n")

    def ask_question(self, question: str) -> str:
        '''Prompts the user with question, returns their response'''
        self.send_message(question)
        return self.get_message()

    def listen(self) -> None:
        '''Main loop of the chatbot. Gets messages, prints response. Returns when program is over'''

        while True:
            try:
                message = self.get_message()

                #Exit condition
                if self.responder.is_signaling_exit(message):
                    self.send_message(self.responder.get_exit_phrase())
                    return

                self.send_message(self.responder.get_response(message))

            except KeyboardInterrupt:
                self.send_message(self.responder.get_exit_phrase())
                break
Exemplo n.º 3
0
    def __init__(self):
        ' Load up some configs '
        conf = ConfigParser.ConfigParser()
        conf.readfp(open('CONFIG'))
        config = dict(conf.items('Main'))

        # initialise the parent object
        IRCBot.__init__(self, config['ip'], int(config['port']),
                        config['nick'], config['chan'], config['pass'])

        # Some additional parameters
        self.pingcounter = 0
        self.prepends = []
        for x in [a[1] for a in conf.items('Prepends')]:
            self.prepends.append(x + ' ')
            self.prepends.append('')
            self.prepends.append('')
        self.PING = int(config['pings'])
Exemplo n.º 4
0
def main():
    server = settings.SERVER
    port = settings.PORT
    channel = settings.CHANNEL
    nickname = settings.NICKNAME

    lichessmate = lichess.LichessBot()

    # LenientDecodingBuffer attempts UTF-8 but falls back to latin-1 to avoid UnicodeDecoreError in all cases.
    irc.client.ServerConnection.buffer_class = buffer.LenientDecodingLineBuffer
    ircbot = IRCBot(channel, nickname, server, port, lichessmate, settings)

    try:
        # Start a new thread for running Lichess, send the ircbot instance to it.
        _thread.start_new_thread(run_lichess, (lichessmate, ircbot))
    except _thread.error:
        print_error('Error: Unable to start thread.')

    ircbot.start()
Exemplo n.º 5
0
def background():
    '''
    load and maintain cache

    communicate with other kybyz servers
    '''
    delay = int(os.getenv('KB_DELAY') or 600)  # seconds
    CACHED['ircbot'] = IRCBot(nickname=CACHED.get('username', None))
    while True:
        logging.info('kybyz active %s seconds', CACHED['uptime'], **TO_PAGE)
        time.sleep(delay)  # releases the GIL for `serve`
        CACHED['uptime'] += delay
        logging.debug('CACHED: %s, threads: %s',
                      CACHED, threading.enumerate())
Exemplo n.º 6
0
def run():
    args = parse_args()
    verbosity_levels = {
        'error': logging.WARNING,
        'bot': logging.INFO,
        'debug': logging.DEBUG,
        'dump': logging.NOTSET,
    }
    logging.basicConfig(
        level=verbosity_levels[args.verbosity],
        format='%(levelname)-8s %(message)s',
    )

    bot = IRCBot(args.channel, args.nick)
    reactor.connectTCP(args.server, args.port, bot)
    reactor.run()
Exemplo n.º 7
0
# coding: latin-1

from ircbot import IRCBot
from httpsrv import http_server
import time
import settings
import datetime
import sys

if settings.nick == "CHANGEME":
    print "---> Please customize settings.py and try again. <---"
    sys.exit(0)

bot = IRCBot(settings.server_address, settings.server_port, settings.nick,
             settings.username, settings.realname)

#web_server = http_server.HTTPServer(8000)

botnik_picture_data = None


def handle_request(request):
    if request.request_path == "/botnik.png":
        global botnik_picture_data

        if not botnik_picture_data:
            try:
                file = open("botnik.png")
                botnik_picture_data = file.read()
                file.close()
            except:
Exemplo n.º 8
0
parser = argparse.ArgumentParser(description='Python IRC bot.')
parser.add_argument('--verbose', action='store_true',
                    help='Become more verbose.')
parser.add_argument('config', type=str,
                    help='A py file with the bot\'s config.')
arguments = parser.parse_args()

# Load the config from the given file
if not os.path.exists(arguments.config):
    raise ValueError('Config file {}'
            'does not exist.'.format(arguments.config,))
config = imp.load_source('config', arguments.config)

# Set verbose mode if needed
VERBOSE = config.VERBOSE or arguments.verbose

# Create the bot
ircbot = IRCBot()
ircbot.setup(config)

# Load the actions from the specified modules
for path in config.MODULES:
    if not os.path.exists(path):
        raise ValueError('Module %s does not exist.' % (path, ))
    name = os.path.basename(path)[:-3]
    module = imp.load_source(name, path)

# Start the bot
asyncore.loop()
Exemplo n.º 9
0
for x in sys.argv:
    if x[0] == '-':
        if x[1] == 'd':
            is_daemon = True
        else:
            print """[+] Minicar Operating Program by jyp
            -d: Daemonize this app.
            """
if __name__ == '__main__':
    if is_daemon:
        pid = os.fork()  # Demonize itself
    else:
        pid = 0
    if pid == 0:
        # Initialize
        b = IRCBot(config['irc']['channels'])

        def __init():
            b.connect(config['irc']['host'][0], config['irc']['host'][1],
                      config['irc']['nickname'])
            return b

        def __notifier(m):
            b.connection.privmsg(config['irc']['channels'][0], m)

        # Threads
        threads = []

        # Add services
        threads.append(
            threading.Thread(target=wifi.start, args=(__init, __notifier)))
Exemplo n.º 10
0
def main():
    bot = IRCBot()
    bot.run()
Exemplo n.º 11
0
      return f**e    
    if split[0]=="fibonacci":
      a = [0, 1]
      tgt = int(split[1])
      v = 0
      while tgt >= 2:
        v = a[0] + a[1]
        a[0] = a[1]
        a[1] = v
        tgt -= 1
      return v


if __name__ == '__main__':
  import sys
  c = IRCBot(sys.argv[1], verbosity=True)
  def exampleexitcallback(user, host, dest, mesg):
    if (user == 'ChloeD'):
      print("Oh, hello ChloeD")
      c.send_chat("#bottest", "I'm leaving now")
      c.disconnect()
      sys.exit(0)
  c.add_privmsg_callback(re.compile("!exit"), exampleexitcallback)
  bot = Botsync(c, "#bottest")
  bot.add_work_executor(StupidMathsWorker())
  t1 = Thread(target=lambda:c.connect("irc.freenode.net", 6667, "#bottest"))
  t2 = Thread(target=bot.schedule_start)
  t1.start()
  t2.start()
  [ x.join() for x in [ t1, t2 ] ]
Exemplo n.º 12
0
# -*- coding: utf-8 -*-

import ConfigParser
from straight.plugin import load
from ircbot import IRCBot

if __name__ == '__main__':
    from modules.module import Module
    
    config = ConfigParser.ConfigParser()
    config.readfp(open('config.ini'))
    
    bot = IRCBot()
    bot.set_config(config)
    
    plugins = [plugin_class() for plugin_class in load("modules", Module)]
    for plugin in plugins:
        bot.load_module(plugin)
    bot.end_load_modules()
    
    bot.connect(config.get('core', 'server'), int(config.get('core', 'port')))
Exemplo n.º 13
0
# coding: latin-1

from ircbot import IRCBot
from httpsrv import http_server
import time
import settings
import datetime
import sys

if settings.nick == "CHANGEME":
	print "---> Please customize settings.py and try again. <---"
	sys.exit(0);

bot = IRCBot(settings.server_address, settings.server_port, settings.nick, settings.username, settings.realname)

#web_server = http_server.HTTPServer(8000)

botnik_picture_data = None


def handle_request(request):
	if request.request_path == "/botnik.png":
		global botnik_picture_data

		if not botnik_picture_data:
			try:
				file = open("botnik.png")
				botnik_picture_data = file.read()
				file.close()
			except:
				web_server.respond_200(request, "Couldn't send image...")
Exemplo n.º 14
0
import yaml
from ircbot import IRCBot
from channelmodule import ChannelModule
from permissionmodule import PermissionModule
from autoopmodule import AutoOPModule
from titlemodule import TitleModule
from calcmodule import CalcModule
from codeforcesmodule import CodeForcesModule
from adminmodule import AdminModule
from dynamicmoduleloadermodule import DynamicModuleLoaderModule

if __name__ == '__main__':
    settings = yaml.load(open('settings.yaml'))

    bot = IRCBot(settings['nick'], settings['user'], settings['realname'])
    for network, server in settings['servers'].items():
        bot.connect(network, **server)

    bot.install_module(ChannelModule, channels=settings['channels'])
    bot.install_module(PermissionModule)
    bot.install_module(AutoOPModule)
    bot.install_module(TitleModule)
    bot.install_module(CalcModule)
    bot.install_module(CodeForcesModule)
    bot.install_module(AdminModule)
    bot.install_module(DynamicModuleLoaderModule)

    bot.run()