示例#1
0
文件: quarid.py 项目: enmand/quarid
def main():
    """ Main callable for running Quarid """
    parser = argparse.ArgumentParser(
        description="qpirc (Quard Python IRC) bot: version %s" % (
            IRC.version()
        ),
        epilog="See http://github.com/enmand/quarid for information"
    )

    parser.add_argument("--version",
        action="version", version="%s" % IRC.version()
    )

    parser.add_argument("--config", "-c",
        default="bot.cfg",
        help="Configuration file to use (default bot.cfg"
    )

    parser.add_argument("action",
        choices=["start", "stop", "reload", "debug"]
    )
    args = parser.parse_args()

    if args.action == "start":
        start(args.config)
    elif args.action == "stop":
        stop()
    elif args.action == "reload":
        print("Not yet implemented")
    elif args.action == "debug":
        start(args.config, debug=True)
示例#2
0
def init():
  bot = IRC()
  bot.connect(config.hostname, config.port, config.nickname, config.username, config.realname, 
    config.channel, use_ssl=config.ssl, use_proxy=config.proxy, proxy_host=config.proxy_host, proxy_port=config.proxy_port)

  driver = pluginDriver()
  driver.load_plugins("plugins")

  return bot, driver
示例#3
0
 def __init__(self, info_filename):
     try:
         info = json.load(open(info_filename, "r"))
         self.share = Share(info)
         self.irc = IRC(self.share.HOST, self.share.PORT)
     except:
         print("\"info\" file not found or syntax error")
         traceback.print_exc()
         sys.exit(1)
示例#4
0
def main() -> None:
    """Main entrypoint of the minimal example."""
    # Parse the arguments and execute the chosen command
    options = parser.parse_args()

    # Create an IRC instance
    irc = IRC(options.server,
              options.port,
              options.user,
              options.nick,
              timeout=options.timeout,
              use_tls=options.use_tls)

    # Connect to the server
    irc.connect()

    # Read the first message
    print(next(irc.messages))
示例#5
0
    def __init__(self, address, oauth, username, channel):
        self.irc=IRC()
        self.oauth = oauth
        self.username = username
        self.channel = channel
        self.address = address
        self.events=Events()

        self.users = []
        self.commands=[]
        self.messages = []
        self.l = Lock()
        self.is_connected = False
        self.messages_sent = 0
        self.last_sent = datetime.datetime.now()

        self.protocol = Protocol(self.irc, self)
        self.client = TwitchIRCClient(self.protocol, self.address, self.on_socket_error)
        self.transport=None
    def connect(self):
        conn = sqlite3.connect(self.config['db'])
        cursor = conn.cursor()

        cursor.execute('CREATE TABLE IF NOT EXISTS channels (username text)')
        cursor.execute('SELECT username FROM channels')
        rows = cursor.fetchall()

        cursor.close()
        conn.close()

        channels = [row[0] for row in rows]
        channels = set(channels)
        channels.add('isabellesays')

        irc = IRC()
        irc.connect(self.config['server'], self.config['port'], channels,
                    self.config['nick'], self.config['oauth'])
        self.irc = irc
示例#7
0
    def __init__(self, config):
        self.config = config
        irc = IRC()
        irc.connect(config['server'], config['port'], [config['channel']], config['nick'], config['oauth'])
        self.irc = irc

        conn = sqlite3.connect('subs.db')
        cursor = conn.cursor()
        cursor.execute('CREATE TABLE IF NOT EXISTS subs (username text, count integer)')
        cursor.execute('CREATE TABLE IF NOT EXISTS points (username text, count integer)')
        cursor.execute('CREATE TABLE IF NOT EXISTS votes (username text, option text, points integer)')
        cursor.close()
        conn.close()

        for option in config['options']:
            filename = 'counters/' + option.lower() + '.txt'
            try:
                f = open(filename, 'r')
            except:
                f = open(filename, 'w')
                f.write('0')
示例#8
0
def handle_news_request(irc: IRC, nick: str, target: str,
                        message: IRCMessage) -> None:
    """Handle a news request."""
    words = message.message.replace("{}:".format(nick), "").strip().split()
    if len(words) < 3:
        irc.send_message(target, "Bad command. See help message")
        return
    command = words[0]
    country = words[1]
    language = words[2]
    parameter = " ".join(words[3:])

    logger.info("Handling news request. Command=%s, country=%s, language=%s",
                command, country, language)
    google_news = GoogleNews(country=country, lang=language)

    try:
        if command == "topic":
            handle_topic(irc, google_news, target, parameter)
        elif command == "location":
            handle_location(irc, google_news, target, parameter)
        elif command == "search":
            handle_search(irc, google_news, target, parameter)
        elif command == "top":
            handle_top(irc, google_news, target)
        else:
            irc.send_message(target, "I don't recognize that command")
    except Exception:  # pylint: disable=broad-except
        logger.error("Unable to fetch news", exc_info=True)
        irc.send_message(target, "I was unable to fetch news")
示例#9
0
    def __init__(self, nick, realname, channels, admin, trigger, plugins,
                  password = False, _ssl = False, reconnect = False,
                  oper_user = False, oper_pass = False):
        IRC.__init__(self, nick, realname, channels, admin, _ssl, reconnect, password,
                     oper_user, oper_pass)

        self.plugins = plugins
        self.send_lock = threading.Lock()
        self.trigger = trigger
        self._password = password
        
        # Stores the class instance of a plugin inside the key of any
        # event the plugin has chosen to listen for.
        # A plugin will not be able to listen to an event that is not
        # defined in the dictionary.
        self._plugin_callbacks = {
            'on_connect': [],
            'on_quit': [],
            'on_quit': [],
            'on_whois': [],
            'on_channel_message': [],
            'on_chat_command': [],
            'on_channel_join': [],
            'on_channel_part': [],
            'on_private_message': [],
            'on_ctcp': [],
            # Plugin specific events
            'on_exit': [],
            'on_load': [],
            }
        self._plugin_threads = {}
        self._plugin_objects = []
        
        # Constants for command types: CMD_CHANNEL is a channel command,
        # CMD_PRIVATE is a private message command, and CMD_ALL is both
        self.CMD_ALL = 0
        self.CMD_CHANNEL = 1
        self.CMD_PRIVATE = 2
        
        self.auto_rejoin = 1
示例#10
0
文件: jeeves.py 项目: Hauk/Jeeves
def main():

    #Create an instance of Jeeves and the TimeKeeper classes.
    jeeves = Jeeves(1, "Jeeves")

    time_keeper = TimeKeeper("TimeKeeper1")

    jeeves.start()

    print(jeeves.name)
    print(time_keeper.name)

   # jeeves.join()

    irc_handler = IRC("IRC_Handler", 'localhost', 6667, 'Jeeves', '#bots1', 'hauk', 'hauK', '')

    irc_handler.connect_to_channel()

    db_handler = Database("DB_Handler", dbconfig.user, dbconfig.dbpass, "localhost", "reminders")

    while(True):
        line = irc_handler.get_irc_message()

        print(line)

        if(line[3] == ":!lol"):
            irc_handler.send_message_to_channel("hullo good sire. *bows*")
        
        if(line[3] == ":!reminder"):
            jeeves.get_reminder_from_irc(line, irc_handler, db_handler, time_keeper)

        if(line[3] == ":!dailies"):
            jeeves.send_dailies(line, irc_handler, db_handler)
            print(jeeves.check_notifications(db_handler, "23/05/2013", "16:00"))
            print(jeeves.check_notifications(db_handler, "23/05/2013", "13:00"))
示例#11
0
文件: bot.py 项目: Toofifty/oracle3
    def __init__(self, config):
        IRC.__init__(self, config.ident, config.channels, config.host,
            config.port, config.nick, config.password or None)

        self.set_verbose(config.verbose)

        self.token_pattern = re.compile(r'\$([\w\.]*)\$')

        self.config = config
        self.db = Database(config.db)

        if not self.db.table_exists('users'):
            print '... Creating users table'
            self.db.execute('CREATE TABLE users(vhost TEXT, nick TEXT, '
                'rank INT, points INT, cmd_count INT, seen INT)', ())

        self.auth = False

        # Ranks are accessible anytime using the bot
        # instance object
        self.ranks = {
            'hidden': -1,
            'banned': 0,
            'user': 1,
            'moderator': 2,
            'administrator': 3,
            'developer': 4
        }

        # Load plugins last so they have access to the
        # above attributes
        self.plugins = PluginLoader(self)

        # List of users to avoid re-instantiation for every message
        self.users = []

        # Connect last, plugins may need to do something
        # before connecting to the IRC server
        self.connect()
示例#12
0
文件: bot.py 项目: citruspi/ReactIRC
    def __init__(self):

        self.config = conf

        self.__irc = IRC()
        self.on = self.__irc.add
        self.speak = self.__irc.speak
        self.join = self.__irc.join
        self.part = self.__irc.part
        self.quit = self.__irc.quit

        self.__web = Web(self.__irc)
        self.web = self.__web.add
示例#13
0
文件: quarid.py 项目: enmand/quarid
def qpirc(cfg_file):
    """
    Start the bot, register its modules and run the main loop
    """
    conf = config.Config(cfg_file)
    bot = IRC.factory()
    bot.also(conf) # also send conf with each Observer event
    core = conf.get('irc')

    for module in conf.get('modules.enabled'):
        Log('plugins.log').logger.debug('Registering plugin %s', module)

        plugin_module = importlib.import_module("plugins.%s" % module)
        plugin_module.register(bot, conf)

    print("Starting the bot...")
    connect_status = bot.connect(
        core['host'],
        core['port'],
        core['nick'],
        core['pass'],
        conf.get('ssl')['use']
    )
    # Sleep while we connect - we may be able to get rid of this at some point
    while True:
        time.sleep(5)
        if connect_status is True:
            break
    threads = []

    # Run the main loop listening for events
    threads.append(Thread(target=bot.run))
    for thread in threads:
        thread.setDaemon(True)
        thread.start()

    # Join some channels if they're configured
    if core['channels'] is not None:
        for chan_params in core['channels'].split(','):
            chan_params = chan_params.split(' ')
            chan = chan_params[0]
            if len(chan_params) > 1:
                # Assume that we have a key, otherwise set to empty
                chan_key = chan_params[1]
            else:
                chan_key = ''
            bot.join(chan, keys=chan_key)

    while True:
        pass
示例#14
0
def main():
    coordinator = Coordinator()
    coordinator.run_flag = True
    irc = IRC()
    bot = Bot(bot_account['usernm'],
              bot_account['pwd'],
              bot_account['channels'],
              bot_account['main_channel']
              )

    loop = asyncio.get_event_loop()
    loop.create_task(irc_bot_init_jobs(irc, bot, loop, coordinator))
    loop.create_task(run_irc_bot(irc, bot, loop, coordinator))
    loop.run_forever()
示例#15
0
    def add_new_channel(self):
        new_channel_dialog = IRCDialog()

        if new_channel_dialog.exec_():
            server = new_channel_dialog.server.text()
            channel = new_channel_dialog.channel.text()
            nickname = new_channel_dialog.nickname.text()

            if not server or not channel or not nickname:
                return

            new_irc = IRC(server, channel, nickname)
            self.irc_widget.new_channel(new_irc)
            self.update_actions()
示例#16
0
def bot_run():
    channel = get_channel()
    server = get_server()
    nickname = "test_bot"

    irc = IRC()
    irc.connect(server, channel, nickname)

    while True:
        text = filter_input(irc.get_text())
        print text

        if check_msg(text, channel) and "test" in text.lower():
            irc.send(channel, "Test successful!")
示例#17
0
    def start_bot(self, ip, port, oauth, username, channel):
        irc = IRC()
        Admin.bot = TwitchBot((ip, port), oauth, username, channel)

        test_cmd = TestCmd()
        Admin.bot.set_commands([test_cmd])

        Admin.bot.events.disconnected = self.bot_disconnected
        Admin.bot.events.connected = self.bot_connected
        Admin.bot.events.joined = lambda x: self.bot_user_joined(x)
        Admin.bot.events.parted = lambda x: self.bot_user_parted(x)
        Admin.bot.events.message_received = lambda x: self.bot_message_received(
            x.message, x.username)
        Admin.bot.events.socket_error = lambda exc, is_connected: self.bot_socket_error(
            exc, is_connected)

        Admin.bot.start()
示例#18
0
def qpirc(cfg_file):
	"""
	Start the bot, register it's modules and run the main loop
	"""
	conf = config.Config(cfg_file)
	bot = IRC.factory()
	bot.also(conf) # also send conf with each Observer event
	core = conf.get('irc')

	for module in conf.get('modules.enabled'):
		Log('plugins.log').logger.debug('Registering plugin %s', module)

		plugin_module = importlib.import_module("plugins.%s" % module)
		plugin_module.register(bot, conf)

	bot.connect(core['host'], core['port'], core['nick'], core['pass'],
				conf.get('ssl')['use'])
	bot.run()
示例#19
0
def handle_topic(irc: IRC, google_news: GoogleNews, target: str,
                 topic: str) -> None:
    """Handle a topic request."""
    irc.send_message(target, "Working on it")
    logger.info("Fetching news for topic %s", topic)
    try:
        news = google_news.topic_headlines(topic)
        for entry in news["entries"][:5]:
            irc.send_message(target, entry["title"])
    except Exception as exception:  # pylint: disable=broad-except
        if str(exception) == "unsupported topic":
            # See: https://github.com/kotartemiy/pygooglenews#stories-by-topic-1
            irc.send_message(
                target, "That topic is not supported. Supported topics are:")
            irc.send_message(
                target,
                "world, nation, business, technology, entertainment, science, sports, health"
            )
        else:
            raise exception
示例#20
0
def main(channelName, serverName):
    channel = channelName if channelName.startswith('#') else '#' + channelName
    server = serverName
    nickname = "guru_bot"

    irc = IRC()
    irc.connect(server, channel, nickname)

    while 1:
        messageObj = irc.get_text()
        print(messageObj.all)

        if messageObj.type == MessageTypes.MESSAGE and messageObj.message.startswith(
                nickname):
            message = messageObj.message
            answer = AskGuru(message[message.find(nickname) + len(nickname):])
            for line in answer.split('\n'):
                irc.send(channel, line)
示例#21
0
    def edit_current_channel(self):
        current_connection = self.irc_widget.current_connection()
        edit_channel_dialog = IRCDialog("Edit channel",
                                        current_connection.server,
                                        current_connection.channel,
                                        current_connection.botnick)

        if edit_channel_dialog.exec_():
            server = edit_channel_dialog.server.text()
            channel = edit_channel_dialog.channel.text()
            botnick = edit_channel_dialog.nickname.text()

            if not server or not channel or not botnick\
                    or server == current_connection.server\
                    and channel == current_connection.channel\
                    and botnick == current_connection.botnick:
                return

            self.irc_widget.remove_channel()
            edited_irc = IRC(server, channel, botnick)
            self.irc_widget.new_channel(edited_irc)
示例#22
0
def main():
    # Setup logging
    logging.basicConfig(level=logging.INFO)

    # Initialize the config.
    Config.Init()

    # Initialize agent
    agent = Agent()

    # Initialize IRC
    irc = IRC(nickname=Config.conf()['botNickName'])
    irc.SetChannel(Config.conf()['channel'])
    irc.ResetGame()
    irc.SetAgent(agent)
    irc.run(hostname=Config.conf()['ircServer'],
            port=Config.conf()['ircSSLPort'],
            tls=True,
            tls_verify=True)
示例#23
0
文件: main.py 项目: colons/pyfoot
    def start_common(self):
        """ Things that both daemonised and normal startup will do """
        if self.logfile_name:
            print(' @@ start of log')

        if self.pidfile_name:
            pidfile = open(args.pidfile, 'wt', encoding='us-ascii')
            pidfile.write(str(os.getpid()))
            pidfile.close()

        sys.stdout = Printer(args.logfile, args.logappend, args.daemonise)

        signal.signal(signal.SIGTERM, self.kill_handler)
        signal.signal(signal.SIGINT, self.kill_handler)

        self.conf = Config(self.network_name, args.config)
        self.irc = IRC(self.conf)
        self.network = Network(self.conf, self.irc)

        while True:
            data = self.irc.listen()
            self.network.dispatch(data)
示例#24
0
class TwitchBot:
    _delay=30
    _limit=100
    _sleep = 0.3

    def twitch_irc_cap_cmd(self):
        return 'CAP REQ :twitch.tv/tags\r\nCAP REQ :twitch.tv/membership\r\nCAP REQ :twitch.tv/commands\r\n'

    def __init__(self, address, oauth, username, channel):
        self.irc=IRC()
        self.oauth = oauth
        self.username = username
        self.channel = channel
        self.address = address
        self.events=Events()

        self.users = []
        self.commands=[]
        self.messages = []
        self.l = Lock()
        self.is_connected = False
        self.messages_sent = 0
        self.last_sent = datetime.datetime.now()

        self.protocol = Protocol(self.irc, self)
        self.client = TwitchIRCClient(self.protocol, self.address, self.on_socket_error)
        self.transport=None

    def process_messages(self):
        while True:
            if not self.is_connected:
                print("TwitchBot.process_messages: not connected, exit thread")
                return

            now = datetime.datetime.now()

            if (now - self.last_sent).seconds > self._delay:
                #print('TwitchBot.process_messages: reset check')
                self.messages_sent = 0
                self.last_sent = datetime.datetime.now()

            if self.messages_sent == self._limit:
                #print('TwitchBot.process_messages: limit reached')
                time.sleep(self._sleep)
                continue

            self.l.acquire()
            to_send = self.messages[0:self._limit - self.messages_sent]
            self.messages = self.messages[len(to_send):]
            self.l.release()

            if len(to_send) > 0:
                #print('TwitchBot.process_messages: send {} messages'.format(len(to_send)))

                data = ''
                for msg in to_send:
                    data+=msg

                print('TwitchBot.process_messages: to send={!r}'.format(data))

                self.transport.write(self.irc.encode(data))
                self.messages_sent += len(to_send)

            time.sleep(self._sleep)

    def set_commands(self, commands):
        self.commands=commands

    def start(self):
        self.client.connect()

    def stop(self):
        #force socket close if we have a open socket
        if not self.transport is None:
            try:
                self.transport._sock.close()
            except Exception as ex:
                print('TwitchBot.stop: {}'.format(ex))
        #force loop stop
        else:
            print('TwitchBot.stop: stop loop')
            self.protocol.loop.stop()

    # TODO Check is_connected flag so we know if we were attempting to connect and raise socket_error event
    def on_socket_error(self, exc):
        print('TwitchBot.on_socket_error: {}'.format(exc))
        self.events.socket_error(exc, self.is_connected)

    def disconnected(self):
        self.transport=None
        self.is_connected = False
        self.events.disconnected()
        print('TwitchBot.disconnected')

    def connected(self, transport):
        self.write_thread = Thread(target=self.process_messages)
        self.is_connected = True
        self.events.connected()

        self.transport = transport
        self.write_thread.start()

        cmd = self.irc.login_cmd(self.oauth, self.username)
        self.write(cmd)

    def write(self, message):
        self.l.acquire()
        self.messages.extend(message.splitlines(True))
        self.l.release()

    def joined(self, username):
        self.events.joined(username)
        print('TwitchBot.joined: {}'.format(username))
        self.users.append(username)

    def parted(self, username):
        self.events.parted(username)
        print('TwitchBot.parted: {}'.format(username))
        self.users.remove(username)

    def process(self, messages):
        for message in messages:
            try:
                parts = message.split(' ')
                #login successfull
                if parts[1]=='NOTICE' and ('Login authentication failed' in message):
                    print('TwitchBot.process: Failed to authenticate')
                    self.transport.close()
                    raise TwitchBotException('Failed to authenticate')
                if parts[1]=='376':
                    print('TwitchBot.process: received message with code 376. Proceed to join {} channel'.format(self.channel))
                    cmd = self.twitch_irc_cap_cmd()
                    self.write(cmd)
                    cmd = self.irc.join_cmd(self.channel)
                    self.write(cmd)
                elif parts[0]=='PING':
                    cmd = self.irc.pong_cmd(message)
                    self.write(cmd)
                elif parts[1]=='JOIN':
                    self.joined(extract_username(parts[0]))
                elif parts[1]=='PART':
                    self.parted(extract_username(parts[0]))
                elif 'PRIVMSG' in message:
                    username = extract_username(parts[1])
                    message = extract_message(parts)
                    self.events.message_received(TwitchMessage(username,message))

                    if message[0]=='!':
                        cmd, args = parse_command(message)

                        print('TwitchBot.process: find command {}'.format(cmd))
                        print('TwitchBot.process: args = {}'.format(args))

                        commands = list(filter(lambda x: x.cmd==cmd, self.commands))

                        if len(commands)>0:
                            command = commands[0]
                            print('TwitchBot.process: execute command {}'.format(cmd))
                            try:
                                output = command.execute(self, username, args)
                                print('TwitchBot.process: command output = {}'.format(output))
                                self.write(self.irc.sendmsg_cmd(self.channel, output))
                            except Exception as e:
                                print('TwitchBot.process: Error while executing command {}'.format(cmd))
                                print('TwitchBot.process: Exception: {}'.format(e))

                        else:
                            print('TwitchBot.process: command {} does not exist'.format(cmd))
            except IndexError as e:
                print('TwitchBot.process: IndexError: {}'.format(e))
            except ValueError as e:
                print('TwitchBot.process: ValueError: {}'.format(e))
示例#25
0
#!/usr/bin/env python

from irc import IRC
from xmlrpc.server import AsyncXMLRPCServer

if __name__ == '__main__':
    server = AsyncXMLRPCServer(('localhost', 8000),
                               allow_none=True,
                               logRequests=False)
    server.add_handler(IRC())

    print 'Running on %s:%s' % tuple(map(str, server.server_address))
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print 'Exiting'
示例#26
0
from irc import IRC
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from requests import Session
from threading import Thread
from time import sleep
from irc import IRC
import datetime
import random
import hashlib

username = "******"
oauth = "oauth:efhn2jfl093dyrdv94rd91vad3zdoy"
channel = "thiseguy"
chat1 = IRC(channel, username, oauth)
chat1.connect()
userlist = []
colorid = []

app = QApplication([])
text_area = QPlainTextEdit()
text_area.setFocusPolicy(Qt.NoFocus)
message = QLineEdit()
layout = QVBoxLayout()
layout.addWidget(text_area)
layout.addWidget(message)
window = QWidget()
window.setLayout(layout)
window.show()

new_messages = []
示例#27
0
	print ">>>'"+stop+"'"
	if(stop=="stop"):
		print "STOP"
		#for func in modulList:
		#	try:
		#		func.stop()
		#	except:
		#		print "No IRC Responst, maybe old Modul"
		#irc.stop()
		#sys.exit()
	for func in modulList:
		try:
			func.irc(msg)
		except:
			print "No IRC Responst, maybe old Modul"
irc = IRC("irc.freenode.net", 6697, "#ssptest", "kruemel|bot|test", ircCallBack)

def callBack(msg):
	print "["+str(time.strftime("%d.%m.%Y %H:%M:%S")) +"][CalBack] "+str(msg)
	irc.sendMSG(msg)
#t = __import__("Modul.TwitterUser").TwitterUser("mimimiKruemel", callBack)

def strToArray(str):
	try:
		regex = re.compile("\'([a-zA-Z0-9\-\_\.]*)\'")
		arr = regex.findall(str)
		return arr
	except:
		return False
config = ConfigParser.RawConfigParser()
config.read('bot.cfg')
示例#28
0
文件: bot.py 项目: citruspi/ReactIRC
class Bot(object):

    __web = None
    __irc = None

    def __init__(self):

        self.config = conf

        self.__irc = IRC()
        self.on = self.__irc.add
        self.speak = self.__irc.speak
        self.join = self.__irc.join
        self.part = self.__irc.part
        self.quit = self.__irc.quit

        self.__web = Web(self.__irc)
        self.web = self.__web.add

    def hook(self, source, rule, function):

        """Allow for the addition of existing functions without using the
        decorator pattern
        """

        if source == 'irc':

            self.__irc.hooks.append({
                'rule': re.compile(rule),
                'function': function
            })

        elif source == 'web':

            self.__web.hooks.append({
                'rule': re.compile(rule),
                'function': function
            })

    def monitor(self, **kwargs):

        """Determine the configuration, setup the connection, and then listen
        for data from the server. PONG when a PING is recieved. Otherwise
        iterate over the functions and check if the rule matches the message.
        If so, call the function with the context and the result of the
        matching.
        """

        for key in kwargs.keys():

                conf[key] = kwargs[key]

        conf['channels'] = conf['channels'].split(',')

        connection.connect()

        self.__irc.monitor()
        self.__web.monitor()

        while True:

            pass
示例#29
0
 def on_channel_part(self, user, channel, reason = None):
     IRC.on_channel_part(self, user, channel, reason)
     self.logger.info('[{0}] {1} has left the channel.'.format(channel.name, user.nick, reason))
     self._on_event('on_channel_part', [user, channel, reason])
示例#30
0
from irc import IRC
from auth import auth
import config
import time

def init(bot):
  bot.connect(config.hostname, config.port, config.nickname, config.username,
    config.realname, config.channel, use_ssl=config.ssl, use_proxy=config.proxy,
    proxy_host=config.proxy_host, proxy_port=config.proxy_port)

  driver = pluginDriver()
  driver.load_plugins()

  return driver

bot = IRC()
driver = init(bot)

while bot.socks != []:
  for sock, buffer in bot.receive():
    if not buffer:
      if not hasattr(sock, 'reconnect') or sock.reconnect:
        driver.unload_plugins()
        time.sleep(2)
        driver = init(bot)
      continue

    for buf in buffer:
      if not buf:
        continue
示例#31
0
文件: wvbot.py 项目: neanias/WVBot
volunteering_regexes = [
    r'^(I think )?(that )?We should (.*)$',
    r'^Why don\'t we (.*)$',
    r'^Tardis should (.*)$',
    r'^Someone (should|needs to) (.*)$',
    r'^(Please )?(Can|Could) someone (.*)$',
    r'^It would be good if (.*)$'
]

listing_regexes = [
    r'^ *what have i (volunteered for|agreed to|let myself in for)',
    r'^ *omgwtflol'
]

irc = IRC(  host=config['IRC']['host'],
            port=config['IRC']['port'],
            nick=config['IRC']['nick'],
            channel=config['IRC']['channel'])

def main():
    irc.channel_message_received_callback = channel_message
    irc.start_connection()

def channel_message(sender, channel, message):
    if config['System']['debug']:
        logger.debug("[{0}] {1}: {2}".format(channel, sender, message))
    
    for regex in volunteering_regexes:
        if re.match(regex, message, re.IGNORECASE):
            db.insert_message(nick=sender, message=message, channel=channel)
            num_recorded_messages = db.count_user_messages(nick=sender, channel=channel)
            pluralstring = 's'
示例#32
0
    def generate(self):
        """ 
        Creates the input for each reaction, runs them, and tests for success.
        If successful, it creates the barrier and product objects.
        It also then does the conformational search, and finally, the hindered rotor scans.
        To make the code the most efficient, all of these happen in parallel, in a sense that
        the jobs are not waiting for each other. E.g., one reaction can still be in the stage
        of TS search, while the other can be already at the hindered rotor scan. This way, 
        all cores are occupied efficiently.

        The switching between the various stages are done via the reac_ts_done variable.
        0: initiates the TS search
        1: checks barrier height and errors in TS, and initiates normal mode displacement test, start the irc calculations 
        2: submits product optimization
        3: submit the frequency calculation 
        4: do the optimization of the ts and the products
        5: follow up on the optimizations
        6: finalize calculations, check for wrong number of negative frequencies
        """
        if len(self.species.reac_inst) > 0:
            alldone = 1
        else:
            alldone = 0

        while alldone:
            for index, instance in enumerate(self.species.reac_inst):
                obj = self.species.reac_obj[index]
                instance_name = obj.instance_name

                # START REATION SEARCH
                if self.species.reac_ts_done[
                        index] == 0 and self.species.reac_step[index] == 0:
                    #verify after restart if search has failed in previous kinbot run
                    status = self.qc.check_qc(instance_name)
                    if status == 'error' or status == 'killed':
                        logging.info(
                            '\tRxn search failed (error or killed) for {}'.
                            format(instance_name))
                        self.species.reac_ts_done[index] = -999

                if self.species.reac_ts_done[
                        index] == 0:  # ts search is ongoing

                    if obj.scan == 0:  #don't do a scan of a bond
                        if self.species.reac_step[index] == obj.max_step + 1:
                            status = self.qc.get_qc_freq(
                                instance_name, self.species.natom)[0]
                            if status == 0:
                                self.species.reac_ts_done[index] = 1
                            elif status == -1:
                                logging.info(
                                    '\tRxn search failed for {}'.format(
                                        instance_name))
                                self.species.reac_ts_done[index] = -999
                        else:
                            self.species.reac_step[
                                index] = reac_family.carry_out_reaction(
                                    obj, self.species.reac_step[index])

                    else:  # do a bond scan
                        if self.species.reac_step[
                                index] == self.par.par['scan_step'] + 1:
                            status = self.qc.get_qc_freq(
                                instance_name, self.species.natom)[0]
                            if status == 0:
                                self.species.reac_ts_done[index] = 1
                            elif status == -1:
                                logging.info(
                                    '\tRxn search failed for {}'.format(
                                        instance_name))
                                self.species.reac_ts_done[index] = -999
                        else:
                            if self.species.reac_step[index] == 0:
                                self.species.reac_step[
                                    index] = reac_family.carry_out_reaction(
                                        obj, self.species.reac_step[index])
                            elif self.species.reac_step[index] > 0:
                                status = self.qc.check_qc(instance_name)
                                if status == 'error' or status == 'killed':
                                    logging.info(
                                        '\tRxn search failed for {}'.format(
                                            instance_name))
                                    self.species.reac_ts_done[index] = -999
                                else:
                                    err, energy = self.qc.get_qc_energy(
                                        instance_name)
                                    if err == 0:
                                        self.species.reac_scan_energy[
                                            index].append(energy)
                                        if len(self.species.
                                               reac_scan_energy[index]) > 1:
                                            if self.species.reac_scan_energy[
                                                    index][
                                                        -1] < self.species.reac_scan_energy[
                                                            index][-2]:
                                                self.species.reac_step[
                                                    index] = self.par.par[
                                                        'scan_step']
                                        self.species.reac_step[
                                            index] = reac_family.carry_out_reaction(
                                                obj,
                                                self.species.reac_step[index])

                elif self.species.reac_ts_done[index] == 1:
                    status = self.qc.check_qc(instance_name)
                    if status == 'running': continue
                    elif status == 'error':
                        logging.info(
                            '\tRxn search failed (gaussian error) for {}'.
                            format(instance_name))
                        self.species.reac_ts_done[index] = -999
                    else:
                        #check the barrier height:
                        if self.species.reac_type[
                                index] == 'R_Addition_MultipleBond':
                            sp_energy = self.qc.get_qc_energy(
                                str(self.species.chemid) + '_well_mp2')[1]
                            barrier = (self.qc.get_qc_energy(instance_name)[1]
                                       - sp_energy) * constants.AUtoKCAL
                        else:
                            sp_energy = self.qc.get_qc_energy(
                                str(self.species.chemid) + '_well')[1]
                            barrier = (self.qc.get_qc_energy(instance_name)[1]
                                       - sp_energy) * constants.AUtoKCAL
                        if barrier > self.par.par['barrier_threshold']:
                            logging.info(
                                '\tRxn barrier too high ({val}) for {name}'.
                                format(val=barrier, name=instance_name))
                            self.species.reac_ts_done[index] = -999
                        else:
                            obj.irc = IRC(
                                obj
                            )  #TODO: this doesn't seem like a good design
                            irc_status = obj.irc.check_irc()
                            if 0 in irc_status:
                                # No IRC started yet, start the IRC now
                                logging.info(
                                    '\tStarting IRC calculations for {}'.
                                    format(instance_name))
                                obj.irc.do_irc_calculations()
                            elif irc_status[0] == 'running' or irc_status[
                                    1] == 'running':
                                continue
                            else:
                                #IRC's have succesfully finished, have an error or were killed, in any case
                                #read the geometries and try to make products out of them
                                #verify which of the ircs leads back to the reactant, if any
                                prod = obj.irc.irc2stationary_pt()
                                if prod == 0:
                                    logging.info(
                                        '\t\tNo product found for {}'.format(
                                            instance_name))
                                    self.species.reac_ts_done[index] = -999
                                else:
                                    #IRC's are done
                                    obj.products = prod
                                    obj.product_bonds = prod.bond
                                    self.species.reac_ts_done[index] = 2
                elif self.species.reac_ts_done[index] == 2:
                    #identify bimolecular products and wells
                    fragments = obj.products.start_multi_molecular()
                    obj.products = []
                    for i, frag in enumerate(fragments):
                        obj.products.append(frag)
                        self.qc.qc_opt(frag, frag.geom)

                    self.species.reac_ts_done[index] = 3
                elif self.species.reac_ts_done[index] == 3:
                    #wait for the optimization to finish
                    err = 0
                    for st_pt in obj.products:
                        chemid = st_pt.chemid
                        orig_geom = copy.deepcopy(st_pt.geom)
                        e, st_pt.geom = self.qc.get_qc_geom(
                            str(st_pt.chemid) + '_well', st_pt.natom)
                        if e < 0:
                            logging.info(
                                '\tProduct optimization failed for {}, product {}'
                                .format(instance_name, st_pt.chemid))
                            self.species.reac_ts_done[index] = -999
                            err = -1
                        elif e != 0:
                            err = -1
                        else:
                            e2, st_pt.energy = self.qc.get_qc_energy(
                                str(st_pt.chemid) + '_well')
                            e2, st_pt.zpe = self.qc.get_qc_zpe(
                                str(st_pt.chemid) + '_well')
                            st_pt.bond_mx()
                            st_pt.characterize()
                            st_pt.calc_chemid()
                            if chemid != st_pt.chemid:
                                #product was optimized to another structure, give warning and remove this reaction
                                logging.info(
                                    '\tProduct optimizatied to other structure for {}, product {} to {}'
                                    .format(instance_name, chemid,
                                            st_pt.chemid))
                                self.species.reac_ts_done[index] = -999
                                err = -1
                    if err == 0:
                        self.species.reac_ts_done[index] = 4
                elif self.species.reac_ts_done[index] == 4:
                    # Do the TS and product optimization

                    #make a stationary point object of the ts
                    bond_mx = np.zeros(
                        (self.species.natom, self.species.natom), dtype=int)
                    for i in range(self.species.natom):
                        for j in range(self.species.natom):
                            bond_mx[i][j] = max(self.species.bond[i][j],
                                                obj.product_bonds[i][j])
                    err, geom = self.qc.get_qc_geom(instance_name,
                                                    self.species.natom)
                    ts = StationaryPoint(instance_name,
                                         self.species.charge,
                                         self.species.mult,
                                         atom=self.species.atom,
                                         geom=geom,
                                         wellorts=1)
                    err, ts.energy = self.qc.get_qc_energy(instance_name)
                    err, ts.zpe = self.qc.get_qc_zpe(instance_name)
                    ts.bond = bond_mx
                    ts.find_cycle()
                    ts.find_conf_dihedral()
                    obj.ts = ts
                    #do the ts optimization
                    obj.ts_opt = Optimize(obj.ts, self.par, self.qc)
                    obj.ts_opt.do_optimization()
                    #do the products optimizations
                    for st_pt in obj.products:
                        #check for products of other reactions that are the same as this product
                        #in the case such products are found, use the same Optimize object for both
                        new = 1
                        for i, inst_i in enumerate(self.species.reac_inst):
                            if not i == index:
                                obj_i = self.species.reac_obj[i]
                                if self.species.reac_ts_done[i] > 3:
                                    for j, st_pt_i in enumerate(
                                            obj_i.products):
                                        if st_pt_i.chemid == st_pt.chemid:
                                            if len(obj_i.prod_opt) > j:
                                                prod_opt = obj_i.prod_opt[j]
                                                new = 0
                                                break
                        if new:
                            prod_opt = Optimize(st_pt, self.par, self.qc)
                            prod_opt.do_optimization()
                        obj.prod_opt.append(prod_opt)
                    self.species.reac_ts_done[index] = 5
                elif self.species.reac_ts_done[index] == 5:
                    #check up on the TS and product optimizations
                    opts_done = 1
                    fails = 0
                    #check if ts is done
                    if not obj.ts_opt.shir == 1:
                        opts_done = 0
                        obj.ts_opt.do_optimization()
                    if obj.ts_opt.shigh == -999:
                        fails = 1
                    for pr_opt in obj.prod_opt:
                        if not pr_opt.shir == 1:
                            opts_done = 0
                            pr_opt.do_optimization()
                        if pr_opt.shigh == -999:
                            fails = 1
                    if fails:
                        self.species.reac_ts_done[index] = -999
                    elif opts_done:
                        self.species.reac_ts_done[index] = 6
                elif self.species.reac_ts_done[index] == 6:
                    #Finilize the calculations

                    #continue to PES search in case a new well was found
                    if self.par.par['pes']:
                        #verify if product is monomolecular, and if it is new
                        if len(obj.products) == 1:
                            st_pt = obj.prod_opt[0].species
                            chemid = st_pt.chemid
                            energy = st_pt.energy
                            well_energy = self.species.energy
                            new_barrier_threshold = self.par.par[
                                'barrier_threshold'] - (
                                    energy - well_energy) * constants.AUtoKCAL
                            dir = os.path.dirname(os.getcwd())
                            jobs = open(dir + '/chemids',
                                        'r').read().split('\n')
                            jobs = [ji for ji in jobs]
                            if not str(chemid) in jobs:
                                #this well is new, add it to the jobs
                                while 1:
                                    try:
                                        #try to open the file and write to it
                                        pes.write_input(
                                            self.par, obj.products[0],
                                            new_barrier_threshold, dir)
                                        f = open(dir + '/chemids', 'a')
                                        f.write('{}\n'.format(chemid))
                                        f.close()
                                        break
                                    except IOError:
                                        #wait a second and try again
                                        time.sleep(1)
                                        pass

                    #check for wrong number of negative frequencies
                    neg_freq = 0
                    for st_pt in obj.products:
                        if any([fi < 0. for fi in st_pt.reduced_freqs]):
                            neg_freq = 1
                    if any([fi < 0. for fi in obj.ts.reduced_freqs[1:]]):
                        neg_freq = 1

                    if neg_freq:
                        logging.info('\tFound negative frequency for ' +
                                     instance_name)
                        self.species.reac_ts_done[index] = -999
                    else:
                        #the reaction search is finished
                        self.species.reac_ts_done[
                            index] = -1  # this is the success code

                        # write a temporary pes input file
                        # remove old xval and im_extent files
                        if os.path.exists('{}_xval.txt'.format(
                                self.species.chemid)):
                            os.remove('{}_xval.txt'.format(
                                self.species.chemid))
                        if os.path.exists('{}_im_extent.txt'.format(
                                self.species.chemid)):
                            os.remove('{}_im_extent.txt'.format(
                                self.species.chemid))
                        postprocess.createPESViewerInput(
                            self.species, self.qc, self.par)

            alldone = 1
            for index, instance in enumerate(self.species.reac_inst):
                if any(self.species.reac_ts_done[i] >= 0
                       for i in range(len(self.species.reac_inst))):
                    alldone = 1
                    break
                else:
                    alldone = 0

            # write a small summary while running
            wr = 1
            if wr:
                f_out = open('kinbot_monitor.out', 'w')
                for index, instance in enumerate(self.species.reac_inst):
                    f_out.write('{}\t{}\t{}\n'.format(
                        self.species.reac_ts_done[index],
                        self.species.reac_step[index],
                        self.species.reac_obj[index].instance_name))
                f_out.close()
            time.sleep(1)

        s = []
        for index, instance in enumerate(self.species.reac_inst):
            obj = self.species.reac_obj[index]
            instance_name = obj.instance_name
            # Write a summary on the combinatorial exploration
            if 'combinatorial' in instance_name:
                s.append('NAME\t' + instance_name)

                # Write the bonds that were broken and formed
                s.append('BROKEN_BONDS\t' +
                         '\t'.join('[{}, {}]'.format(re[0], re[1])
                                   for re in obj.reac))
                s.append('FORMED_BONDS\t' +
                         '\t'.join('[{}, {}]'.format(pr[0], pr[1])
                                   for pr in obj.prod))

                # Populate the ts_bond_lengths dict with the values
                # of this reaction
                if self.species.reac_ts_done[index] == -1:
                    for i in range(self.species.natom - 1):
                        for j in range(i + 1, self.species.natom):
                            if self.species.bond[i][j] != obj.product_bonds[i][
                                    j]:
                                if (self.species.bond[i][j] == 0
                                        or obj.product_bonds[i][j] == 0):
                                    syms = []
                                    syms.append(self.species.atom[i])
                                    syms.append(self.species.atom[j])
                                    syms = ''.join(sorted(syms))
                                    dist = np.linalg.norm(obj.ts.geom[i] -
                                                          obj.ts.geom[j])
                                    s.append('TS_BOND_LENGTHS\t{}\t{}'.format(
                                        syms, dist))
                # write the expected inchis
                s.append('EXPECTED_INCHIS\t' +
                         '\t'.join(inchi for inchi in obj.prod_inchi))
                # get the inchis the reaction found
                if self.species.reac_ts_done[index] == -1:
                    inchis = obj.get_final_inchis()
                    s.append('FOUND_INCHIS\t' + '\t'.join(inchis))
                s.append('\n')
            with open('combinatorial.txt', 'w') as f:
                f.write('\n'.join(s) + '\n')

        logging.info("Reaction generation done!")
示例#33
0
 def send(self, msg, silent = False):
     """Sends a message to the IRC server."""
     self.send_lock.acquire()
     IRC.send(self, msg, silent)
     self.send_lock.release()
示例#34
0
 def on_connect(self):
     IRC.on_connect(self)
     self._on_event('on_connect', [])
示例#35
0
文件: main.py 项目: colons/pyfoot
class Robot(Process):
    def __init__(self, network, configfile, logfile, pidfile):
        Process.__init__(self)

        self.network_name = network
        self.configfile_name = configfile
        self.logfile_name = logfile
        self.pidfile_name = pidfile

    def kill_handler(self, signum, frame):
        if signum == signal.SIGINT:
            sig = 'SIGINT'
        elif signum == signal.SIGTERM:
            sig = 'SIGTERM'
        print('\n !! ' + sig + ' caught : warning plugins')

        # Disconnect from the IRC server
        self.network.warn_plugins()
        sleep(2)
        self.irc.quit()

        # Delete the pid file and close the log file for a clean exit
        if args.pidfile:
            os.remove(args.pidfile)
        if args.logfile:
            print(' @@ end of log\n')
        sys.exit()

    def start_common(self):
        """ Things that both daemonised and normal startup will do """
        if self.logfile_name:
            print(' @@ start of log')

        if self.pidfile_name:
            pidfile = open(args.pidfile, 'wt', encoding='us-ascii')
            pidfile.write(str(os.getpid()))
            pidfile.close()

        sys.stdout = Printer(args.logfile, args.logappend, args.daemonise)

        signal.signal(signal.SIGTERM, self.kill_handler)
        signal.signal(signal.SIGINT, self.kill_handler)

        self.conf = Config(self.network_name, args.config)
        self.irc = IRC(self.conf)
        self.network = Network(self.conf, self.irc)

        while True:
            data = self.irc.listen()
            self.network.dispatch(data)

    def start_normal(self):
        """ Start pyfoot normally. """
        sys.stderr.write(' -- my process id is ' + str(os.getpid()) + '\n')

        self.start_common()

    def run(self):
        self.start_common()

    def start_threaded(self):
        self.start()

    def start_daemon(self):
        """ Start pyfoot in daemon mode. """
        pid = os.fork()  # First child
        if pid == 0:
            os.setsid()
            pid = os.fork()  # Second child
            if pid != 0:
                sys.stderr.write('now running in the background : '
                                 'my process id is ' + str(pid) + '\n')
                os._exit(0)
        else:
            os._exit(0)

        self.start_common()
示例#36
0
 def on_channel_mode(self, user, channel, modes, args = None):
     IRC.on_channel_mode(self, user, channel, modes, args)
     self.logger.info('[{0}] {1} sets mode: {2} {3}'.format(channel.name, user.nick, 
                                                            modes, (args if args else '')))
示例#37
0
class Bot:
    
    def __init__(self, info_filename):
        try:
            info = json.load(open(info_filename, "r"))
            self.share = Share(info)
            self.irc = IRC(self.share.HOST, self.share.PORT)
        except:
            print("\"info\" file not found or syntax error")
            traceback.print_exc()
            sys.exit(1)

    """ Connect to the server by sending to IRC the required messages to initialize a connection
    """
    def connect(self):
        self.sendcmd(("NICK", self.share.NICK))
        self.sendcmd(("USER", self.share.IDENT, "0", "*"), self.share.REALNAME)
        
    def run(self):
        while True:
            # Sleep so we don't eat the CPU alive
            time.sleep(0.05)
            # Handle module commands
            server_msg = self.irc.getmsg()
            if server_msg:
                try: self.handle(server_msg)
                except: traceback.print_exc()
            # Process responses from modules
            while not self.share.empty_queue():
                response = self.share.get_queue()
                self.sendcmd(response[0], response[1])

    def send(self, string):
        self.irc.write(string + "\r\n")

    def sendcmd(self, cmd, text=None):
        temp = ' '.join(cmd)
        if text: temp = "{} :{}".format(temp, text)[:510]
        self.send(temp)

    def sendmsg(self, msg, string):
        if self.share.NICK == msg.TO[1]: msg.TO[1] = msg.FROM[1]
        sendcmd(("PRIVMSG", msg.TO[1]), string)        

    # Try to run our modules
    def runmodules(self, msg):
        for mod in self.share.get_modulelist():
            moduleClass = getattr(mod, "Module")
            modcmd = None
            modregex = None
            
            try: modcmd = moduleClass.cmd 
            except: pass 
            try: modregex = moduleClass.regex 
            except: pass
            
            if modcmd:
                if modcmd == msg.MSG[:len(moduleClass.cmd)]:
                    try:
                        n_msg = copy.deepcopy(msg)
                        n_msg.MSG = msg.MSG[len(modcmd):]
                        thread = moduleClass(n_msg, self.share)
                        thread.start()
                    except:
                        self.sendcmd(("PRIVMSG", msg.TO[1]), "MODULE {} FAILED".format(moduleClass))
                        traceback.print_exc()
            elif modregex:
                if re.search(modregex, msg.MSG):
                    try:
                        n_msg = copy.deepcopy(msg)
                        thread = moduleClass(n_msg, self.share)
                        thread.start()
                    except:
                        self.sendmsg(("PRIVMSG", msg.TO[1]), "MODULE {} FAILED".format(moduleClass))
                        traceback.print_exc()

    def handle(self, server_msg):
        try:
            getattr(self, "handle_{}".format(server_msg[1]))(server_msg)
        except:
            print("CMD {} - NOT IMPLEMENTED".format(server_msg[1]))
            # print("prefix: {}\nparams: {}\ntrailing: {}".format(server_msg[0], server_msg[2], server_msg[3]))
            # traceback.print_exc()

    # PING - Play PING PONG with the server
    def handle_PING(self, server_msg):
        self.sendcmd(("PONG",), server_msg[3])

    # RPL_ENDOFMOTD / ERR_NOMOTD - Finish joining server here
    def handle_376(self, server_msg):
        self.handle_422(server_msg)
    def handle_422(self, server_msg):
        extras = self.share.EXTRAS
        for e in extras: self.send(e)
        channels = self.share.CHANNELS.split(",")
        for c in channels: self.sendcmd(("JOIN",), c)
    
    # INVITE - Accept all channel invites automatically
    def handle_INVITE(self, server_msg):
        print(server_msg)
        self.sendcmd(("JOIN",), server_msg[3])

    # PRIVMSG - Any sort of message
    def handle_PRIVMSG(self, server_msg):
        print(server_msg)
        try:
            msg = Message(server_msg)
            self.runmodules(msg)
        except:
            traceback.print_exc()
示例#38
0
def bot_run():
    channel = get_channel()
    server = get_server()
    nickname = "spider_bot"

    irc = IRC()
    irc.connect(server, channel, nickname)

    # Infinite loop until disconnected
    while True:
        text = filter_input(irc.get_text())
        print text

        if check_msg(text, channel) and "*snap*" in text.lower():
            irc.send(channel, "Alexis...I don't feel so good...")
            irc.quit("disintegrated")

            if nickname == "spider_bot":
                nickname = "CAPTAIN_MARVEL"
            elif nickname == "CAPTAIN_MARVEL":
                nickname = "spider_bot"

            sleep(5)

            # Because quitting closes the connection with the server
            irc = IRC()
            irc.connect(server, channel, nickname)

        if check_msg(text, channel) and "goat" in text.lower():
            with open("./static/battle_goat.txt", "r") as goat:
                lines = goat.readlines()
                for line in lines:
                    irc.send(channel, line.strip("""\n"""))

        if check_msg(text, channel) and "pineapple" in text.lower():
            with open("./static/pineapple.txt", "r") as pineapple:
                lines = pineapple.readlines()
                for line in lines:
                    irc.send(channel, line.strip("""\n"""))

        if check_msg(text, channel)\
           and ("tom brady" in text.lower()
                or "tb12" in text.lower()
                or "touchdown tommy" in
                text.lower()):
            irc.send(channel, "the GOAT")

        if check_msg(text, channel) and "spider_bot" in text.lower():
            irc.send(channel, ":D")

        if check_msg(text, channel) and "the herd" in text.lower():
            irc.send(channel, "ALL THE GOATS")

        if check_msg(text, channel) and "idea" in text.lower():
            irc.send(channel, "it's gonna be YUUUGGEEE")

        if "QUIT" in text:
            irc.send(channel, "*mic drop*")
from irc import IRC

server = ""  #Provide a valid IP address
port = 6667
channel = "#"  #Provide a valid channel name
myNick = "myNickname"

irc = IRC()

irc.simpleConnect(server, port, channel, myNick, myNick)
irc.getResponse()
示例#40
0
def bot_run():
    channel = get_channel()
    server = get_server()
    nickname = "THANOS"

    irc = IRC()
    irc.connect(server, channel, nickname)

    # Infinite loop until disconnected
    while True:
        text = filter_input(irc.get_text(), nums=True)
        print text

        if check_msg(text, channel) and "imperfectly balanced" in text.lower():
            irc.send(channel, "Let's fix that shall we... *snap*")
        elif check_msg(text, channel) and "perfectly balanced" in text.lower():
            irc.send(channel, "As all things should be")

        if check_msg(text, channel) and "imperfectly balanced"[::-1]\
                                        in text.lower():
            irc.send(channel, "Let's fix that shall we... *snap*")
        elif check_msg(text, channel) and "perfectly balanced"[::-1]\
                                        in text.lower():
            irc.send(channel, "As all things should be"[::-1])

        if check_msg(text, channel) and "fun" in text.lower():
            irc.send(
                channel,
                "Fun isn't something one considers when balancing the universe"
            )

        if check_msg(text, channel) and "you should have gone for the head"\
                                        in text.lower():
            irc.send(channel, "*snap*")
示例#41
0
from irc import IRC
from commands.test_cmd import TestCmd
import time

if __name__=='__main__':
    parser = argparse.ArgumentParser('Twitch IRC client')
    parser.add_argument('oauth', help='Oauth token')
    parser.add_argument('username', help='twitch username')
    parser.add_argument('channel', help='twitch channel')
    parser.add_argument('-ip', type=str, default='irc.chat.twitch.tv', help='IP of twitch IRC server')
    parser.add_argument('-port', type=int, default=6667, help='Port of twitch IRC server (default 1060)')
    args = parser.parse_args()

    address = (args.ip, args.port)

    irc = IRC()
    bot = TwitchBot(address, args.oauth, args.username, args.channel)

    test_cmd = TestCmd()
    bot.set_commands([test_cmd])

    bot.events.disconnected=lambda: print('Event: disconnected')
    bot.events.connected = lambda: print('Event: connected')
    bot.events.joined = lambda x: print('Event: {} joined'.format(x))
    bot.events.parted = lambda x: print('Event: {} parted'.format(x))
    bot.events.message_received = lambda x: print('Event: message {} received from {}'.format(x.message, x.username))
    bot.events.socket_error = lambda x: print('Event: exc={}'.format(x))

    try:
        bot.start()
    except OSError as e:
示例#42
0
import math
from irc import IRC

# Inicializa a conexão
irc = IRC()
ep = '!ep1'

# Faz contato com o bot
irc.send_private_message(ep)
question = irc.listen()
print(question)

# Calcula resultado
question = question.split(':')[2]
a, b = question.split('/')
a, b = int(a), int(b)
result = math.sqrt(a) * b
result = round(result, 2)

# Envia resposta
irc.send_private_message(f"{ep} -rep {result}")

# Recebe a flag
print(irc.listen())
示例#43
0
文件: bot.py 项目: jtneal/hochibot
#!/usr/bin/env python

from irc import IRC
import os
import re
import socket
import sys

irc = IRC()
chat = irc.getConnection()


def send(command):
    chat.send(irc.make_command(command))


def join(room):
    send('JOIN #%s' % room)
    send('PRIVMSG #%s :Kappa /' % room)


def watch():
    buffer = ''
    while True:
        buffer = buffer + chat.recv(1024).decode('UTF-8')
        temp = str.split(buffer, '\n')
        buffer = temp.pop()

        for line in temp:
            line = str.rstrip(line)
            line = str.split(line)
示例#44
0
文件: bot.py 项目: slice/drc
from ruamel.yaml import YAML

from irc import IRC, User

with open('config.yml', 'r') as fp:
    config = YAML().load(fp)

logging.basicConfig(level=logging.DEBUG)
logging.getLogger('lomond').setLevel(logging.WARNING)
logging.getLogger('curious').setLevel(logging.WARNING)
multio.init('trio')

bot = Client(config['discord']['token'])
bot.irc = IRC(config['irc']['host'],
              config['irc']['port'],
              autojoin=config['irc']['autojoin'],
              nick=config['irc'].get('nick'),
              bot=bot,
              config=config)


@bot.irc.on('privmsg')
async def privmsg_handler(channel: str, author: User, message: str):
    dest = bot.find_channel(config['discord']['broadcast_channel'])
    clean_message = message.replace('@', '@\u200b').replace(
        '`', '\N{MODIFIER LETTER GRAVE ACCENT}')[:1500]
    timestamp = datetime.datetime.utcnow().strftime('%H:%M:%S')
    forward = f'`[{timestamp}]` `[{channel}]` {author.nick} » {clean_message}'
    await dest.messages.send(forward)


async def run():
示例#45
0
 def on_ctcp(self, user, cmd, args):
     IRC.on_ctcp(self, user, cmd, args)
     self._on_event('on_ctcp', [user, cmd, args])
示例#46
0
def emoji_bot():

    channel = get_channel()
    server = get_server()
    nickname = "emoji_bot"

    irc = IRC()
    irc.connect(server, channel, nickname)

    # Implicitly render Emojibot help on every successful connection attempt
    emoji_bot_help(irc, channel)

    # Infinite loop until disconnected
    while True:
        text = filter_input(irc.get_text())
        print text

        # Retrieve Emojibot help  whenever "emoji_bot --help" is called
        if check_msg(text, channel) and "emoji_bot --help" in text.lower():
            emoji_bot_help(irc, channel)

        # -------------------- Various emojis implemented ---------------------

        if check_msg(text, channel) and "*smiles*" in text.lower():
            irc.send(
                channel,
                emoji.emojize(':smiley:',
                              use_aliases=True).encode("utf-8", "replace"))

        if check_msg(text, channel) and "*winks*" in text.lower():
            irc.send(
                channel,
                emoji.emojize(':wink:',
                              use_aliases=True).encode("utf-8", "replace"))

        if check_msg(text, channel) and "*laughs*" in text.lower():
            irc.send(
                channel,
                emoji.emojize(':joy:',
                              use_aliases=True).encode("utf-8", "replace"))

        if check_msg(text, channel) and "*fistbombs*" in text.lower():
            irc.send(
                channel,
                emoji.emojize(':punch:',
                              use_aliases=True).encode("utf-8", "replace"))

        if check_msg(text, channel) and "*heart*" in text.lower():
            irc.send(
                channel,
                emoji.emojize(':hearts:',
                              use_aliases=True).encode("utf-8", "replace"))

        if check_msg(text, channel) and "*smirks*" in text.lower():
            irc.send(
                channel,
                emoji.emojize(':smirk:',
                              use_aliases=True).encode("utf-8", "replace"))

        if check_msg(text, channel) and "*sleeps*" in text.lower():
            irc.send(
                channel,
                emoji.emojize(':zzz:',
                              use_aliases=True).encode("utf-8", "replace"))

        if check_msg(text, channel) and "*cool*" in text.lower():
            irc.send(
                channel,
                emoji.emojize(':sunglasses:',
                              use_aliases=True).encode("utf-8", "replace"))

        if check_msg(text, channel) and "*cries*" in text.lower():
            irc.send(
                channel,
                emoji.emojize(':cry:',
                              use_aliases=True).encode("utf-8", "replace"))

        if check_msg(text, channel) and "*tongue*" in text.lower():
            irc.send(
                channel,
                emoji.emojize(':stuck_out_tongue:',
                              use_aliases=True).encode("utf-8", "replace"))

        # Secret mic_drop emoji not included in the emoji_bot_help
        if check_msg(text, channel) and "*mic drop*" in text.lower():
            irc.send(
                channel,
                emoji.emojize(':microphone:',
                              use_aliases=True).encode("utf-8", "replace"))
示例#47
0
 def on_channel_join(self, user, channel):
     IRC.on_channel_join(self, user, channel)
     self.logger.info('[{0}] {1} has joined the channel.'.format(channel.name, user.nick))
     # Temporarily pass channel.name until we finish the whole Channel/User object transition
     self._on_event('on_channel_join', [user, channel])
示例#48
0
class Bot(object):
    def __init__(self):
        self.IRC = IRC()
        cmd.loadCusCommands()
        _thread.start_new_thread(twitch.threadFillOpList, ())
        smugs.initSmugs()
        _thread.start_new_thread(twitch.threadOfflineMSG, (self.IRC, ))
        _thread.start_new_thread(twitch.threadGlobalMSG, (self.IRC, ))
        _thread.start_new_thread(smugs.threadCalcPoints, ())
        print(config.userList)
        self.run()

    def handleMsg(self, username, channel, message):
        if message[0] == "!":
            message = message.lower()
            tempCommand = message.split()[0][1:]
            print(tempCommand)
            if tempCommand in config.cusCommands:
                response = cmd.findCusCommand(tempCommand)
                self.IRC.sendMessage(channel, response)
            elif cmd.is_valid_command(tempCommand):
                if cmd.check_has_correct_args(message, tempCommand):
                    if cmd.get_return(tempCommand) == "command":

                        args = message.split()
                        del args[0]
                        print("args" + str(args))
                        self.IRC.sendMessage(
                            channel,
                            cmd.pass_to_function(tempCommand,
                                                 args,
                                                 username=username,
                                                 channel=channel,
                                                 bot=self))
                    else:
                        self.IRC.sendMessage(channel,
                                             commands[tempCommand]["return"])
            else:
                self.IRC.sendMessage(channel, "Command does not exist.")

    def run(self):
        def receive_data():
            while True:
                try:
                    data = self.IRC.nextMessage()
                    print(data)

                    message = self.IRC.check_for_message(data)

                    if not message:
                        continue
                    if message:
                        message_dict = self.IRC.get_message(data)

                        channel = message_dict.get("channel")
                        message = message_dict.get("message")
                        username = message_dict.get("username")
                        Thread(target=self.handleMsg,
                               args=(username, channel, message)).start()

                except Exception as error:
                    print(error)

        Thread(target=receive_data(), args=("chat", )).start()
示例#49
0
def main():
    irc = IRC()
    irc.connect(config.HOST, config.PORT, config.CHANNEL, config.NICK)

    skyline = Skyline(config.BRIDGE_IP)
    skyline.start()

    stream_room = Group('Stream Room',
                        lights=[
                            'Roo side table',
                            'Lunar side table',
                            'Desk Portrait Left',
                            'Desk Portrait Right'
                        ])

    _thread.start_new_thread(irc.fill_user_list, ())

    while True:
        response = irc.receive()

        # If Twitch pings the bot, respond.
        irc.respond_to_ping(response)

        username, message = irc.parse_message(response)

        # Custom commands
        insta_com = Command('insta', response='Follow r00 on Instagram at www.instagram.com/user_r00')
        twitter_com = Command('twitter', response='Follow r00 on Twitter at www.twitter.com/user_r00')
        ping_com = Command('ping', response='Pong')
        lights_com = Command('lights', response='Control r00\'s lighting with !lights and a color. For example, "!lights purple" will set the room lights to purple! For a full list of colors use !lightcolors.')

        # irc.process_command(response)
        if message.strip() == '!ping':
            irc.chat(ping_com.response)

        # Socials
        if message.strip() == "!insta":
            irc.chat(insta_com.response)

        elif message.strip() == '!twitter':
            irc.chat(twitter_com.response)

        # Shoutouts
        elif message.strip().split(' ')[0] == "!so":
            streamer_long = message.strip().split(' ')[1]
            streamer_short = streamer_long.replace('@', '')
            irc.chat(f'If you\'re looking for more interesting content, '
                     f'go check out {streamer_long} at '
                     f'https://twitch.tv/{streamer_short} ! Drop them a '
                     f'follow to be notified when they go live.')

        elif message.strip() == '!crash':
            # Get a light and collect its current colors for later.
            light = skyline.lights['Roo side table']
            hue, sat, bri = light.hue, light.saturation, light.brightness

            # Create temporary light to hold current settings.
            temp_color = Color('temp', hue=hue, sat=sat, bri=bri)
            skyline.set_color(stream_room.lights, 'red')
            sleep(3)
            skyline.set_color(stream_room.lights, temp_color)

        # Skyline
        elif message.strip() == '!lights':
            irc.chat(lights_com.response)

        elif message.strip() == '!lightcolors':
            message = 'Lights can be set to '
            counter = 0
            for color in skyline.colors:
                if counter < len(skyline.colors.keys()) - 1:
                    message = f'{message}{skyline.colors[color].name}, '
                    counter += 1
                else:
                    message = f'{message} or {skyline.colors[color].name}.'
            irc.chat(message)

        elif message.strip().split(' ')[0] == "!lights":
            color = message.strip().split(' ')[1]
            if color in skyline.colors:
                skyline.set_color(stream_room.lights, color)
            else:
                irc.chat('Honestly, I have no idea what you want.')

        elif message.strip() == '!rainbow':
            skyline.rainbow(stream_room.lights)

        sleep(1)
示例#50
0
def main() -> None:
    """Main entrypoint of the bot."""
    # Configure the default logging format
    logging.basicConfig(format="[%(asctime)s] [%(levelname)-5s] %(message)s",
                        level=logging.INFO,
                        datefmt="%Y-%m-%d %H:%M:%S")

    # Create an argument parser for parsing CLI arguments
    parser = ArgumentParser(
        description=
        "An IRC bot providing sentiment analysis and reactions using ASCII emojis"
    )

    # Add parameters for the server connection
    parser.add_argument("-s",
                        "--server",
                        required=True,
                        type=str,
                        help="The server to connect to")
    # Add optional parameters for the server connection
    parser.add_argument("-p",
                        "--port",
                        default=6697,
                        type=int,
                        help="The port to connect to")
    parser.add_argument("--use-tls",
                        default=True,
                        type=bool,
                        help="Whether or not to use TLS")
    parser.add_argument("-t",
                        "--timeout",
                        default=300,
                        type=float,
                        help="Connection timeout in seconds")

    # Add optional parameters for authentication etc.
    parser.add_argument(
        "-u",
        "--user",
        default="sentiment-bot",
        help="Username to use when connecting to the IRC server")
    parser.add_argument("-n",
                        "--nick",
                        default="sentiment-bot",
                        help="Nick to use when connecting to the IRC server")
    parser.add_argument(
        "-g",
        "--gecos",
        default=
        "Sentiment Bot v1.0.2 (github.com/AlexGustafsson/irc-sentiment-bot)")
    parser.add_argument("-c",
                        "--channel",
                        required=True,
                        action='append',
                        help="Channel to join. May be used more than once")

    # Parse the arguments
    options = parser.parse_args()

    # Create an IRC connection
    irc = IRC(options.server,
              options.port,
              options.user,
              options.nick,
              timeout=options.timeout,
              use_tls=options.use_tls)

    irc.connect()

    # Connect to specified channels
    for channel in options.channel:
        irc.join(channel)

    # The last analyzed result
    lastMessageValence = None

    # Handle all messages
    for message in irc.messages:
        if not isinstance(message, IRCMessage):
            continue

        target = message.author if message.target == options.nick else message.target

        if message.message == "{}: help".format(options.nick):
            irc.send_message(
                target,
                "I perform a simple sentiment analysis on your messages and respond with emojis"
            )
            irc.send_message(
                target,
                "You can debug the sentiment analysis of the last message like so:"
            )
            irc.send_message(target, "{}: debug".format(options.nick))
        elif message.message == "{}: debug".format(options.nick):
            if lastMessageValence is not None:
                compound = "compound: {}".format(
                    lastMessageValence["compound"])
                debug = ", ".join([
                    "'{}': {}".format(text, valence)
                    for text, valence in lastMessageValence["debug"]
                ])
                irc.send_message(target, "{}. {}".format(compound, debug))
        else:
            analyzer = SentimentIntensityAnalyzer()
            scores = analyzer.polarity_scores(message.message)
            if scores["compound"] >= 0.6:
                irc.send_message(target, random.choice(positives))
                lastMessageValence = scores
            elif scores["compound"] <= -0.6:
                irc.send_message(target, random.choice(negatives))
                lastMessageValence = scores
示例#51
0
#!/usr/bin/python
# coding: utf-8

import os
import sys
import traceback
sys.path += ("irc", )
from pluginDriver import pluginDriver
from irc import IRC
from auth import auth

bot = IRC("irc.freenode.net", 6697, "phukbot", "phukj00", "phuk3r", use_ssl=1)
bot.raw("MODE phukbot +B")
bot.join("#nopezor")

driver = pluginDriver()
driver.load_plugins("plugins", bot)

authentication = auth(bot)
authentication.auth_levels['phukd'] = 10

while bot.connected == 1:
  buffer = bot.receive()
  if not buffer:
    continue

  for buf in buffer:
    if not buf:
      continue

    (tmp, auth_level) = authentication.check(bot, buf)