Пример #1
0
    def __init__(self,
                 host,
                 port,
                 channel,
                 nickname,
                 realname,
                 crate_host,
                 crate_port,
                 password=None):
        self.server = ServerSpec(host, port, password=password)
        super(CrateBot, self).__init__([self.server],
                                       nickname=nickname,
                                       realname=realname)
        engine = create_engine("crate://{0}:{1}".format(
            crate_host, crate_port))
        self.sessionmaker = sessionmaker(bind=engine)

        try:
            crate = connect(["{}:{}".format(crate_host, crate_port)])
            crate.cursor().execute(u"""
            create table messages (
              id string primary key,
              user string,
              created timestamp,
              message string index using fulltext with (analyzer='standard')
            ) clustered into 4 shards with (number_of_replicas=0)
            """)
        except Exception as e:
            print e

        self.channel = channel
        self.commands = {cmd.NAME: cmd() for cmd in self.supported_commands}
Пример #2
0
 def __init__(self, server, port, username, password, nick):
     self.nick = nick
     server_spec = ServerSpec(server, port, password)
     irc.bot.SingleServerIRCBot.__init__(self, [server_spec],
                                         nick,
                                         username,
                                         username=username)
Пример #3
0
 def test_with_host_and_port_and_password(self):
     server_spec = ServerSpec('irc.example.gov',
                              port=6668,
                              password='******')
     assert server_spec.host == 'irc.example.gov'
     assert server_spec.port == 6668
     assert server_spec.password == 'there-is-only-zuul'
Пример #4
0
 def __init__(self, password):
     """Create a VoidBot."""
     factory = Factory(wrapper=ssl.wrap_socket)  # SSL support
     super().__init__([ServerSpec('irc.libera.chat', 6697)],
                      'Void-bot',
                      'VoidBot',
                      connect_factory=factory)
     self.connection.buffer_class.errors = "replace"  # Encoded colors cause errors with utf-8
     self.account = 'Void-bot'
     self.dev = 'miraheze/Void'
     self.__password = password
     self.path = Path(os.path.dirname(os.path.abspath(sys.argv[0])))
     self.saves = {}
     self.trusted = {}
     self.banlist = {}
     self.channel_list = []
     self.load()
     self.apis = {
         'meta': Api('miraheze', 'meta.miraheze.org'),
         'cvt': Api('miraheze', 'cvt.miraheze.org'),
         'testadminwiki': Api('testadminwiki',
                              'testwiki.wiki',
                              script_path=''),
         'botwiki': Api('miraheze', 'wiki.fossbots.org')
     }
     self.probably_connected = True
     self.reactor.scheduler.execute_every(600, self.check_connection)
     self.reactor.scheduler.execute_every(1200, self.save)
     self.handlers = handlers.load_handlers(self)
     self.reactor.add_global_handler('all_events', self.run_handlers, 10)
Пример #5
0
    def __init__(self, channel, nickname, server, port=6667, **connect_params):
        super(IRCClient, self).__init__()
        if server is None:
            raise Exception("IRC Server not provided")
        if nickname is None or " " in nickname:
            raise Exception("Invalid nickname: must be one word")
        if channel is None or " " in channel or "#" not in channel:
            raise Exception("Invalid channel: must be a word starting with #")
        self.__connect_params = connect_params
        self.channels = IRCDict()
        self.channel = channel
        self.server = ServerSpec(server, port)
        self._nickname = nickname
        self.clientname = socket.gethostname().split(".")[0]
        if 0 <= self.min_reconnect_wait:
            raise Exception("Minimum reconnect wait must be positive number")
        if self.min_reconnect_wait <= self.max_reconnect_wait:
            raise Exception(
                "Maximum reconnect wait must be larger than minimum")
        self._check_scheduled = False

        # Global handlers to handle channel/nick associations
        # Mostly when a nick is already in use
        for i in [
                "disconnect",
                "join",
                "kick",
                "mode",
                "namreply",
                "nick",
                "part",
                "quit",
        ]:
            self.connection.add_global_handler(i, getattr(self, "_on_" + i),
                                               -20)
Пример #6
0
def main():
    nickname = os.getenv("BOT_NICKNAME")
    server = "irc.ppy.sh"
    port = 6667

    spec = ServerSpec(server, port, os.getenv("BOT_PASSWORD"))
    bot = BookmarksBot(nickname, spec)
    bot.start()
Пример #7
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()
Пример #8
0
def _create_bot(server: IrcServer, nickname: str, realname: str) -> Bot:
    """Create a bot."""
    server_spec = ServerSpec(server.host, server.port, server.password)
    factory = Factory(wrapper=ssl.wrap_socket) if server.ssl else Factory()

    bot = Bot([server_spec], nickname, realname, connect_factory=factory)

    _set_rate_limit(bot.connection, server.rate_limit)

    # Avoid `UnicodeDecodeError` on non-UTF-8 messages.
    bot.connection.buffer_class = LenientDecodingLineBuffer

    return bot
Пример #9
0
    def __init__(self, name, nick, realname, server, port, channels, account,
                 prefix):
        self.name = name
        self.prefix = prefix
        self.joinchans = channels
        self.account = account
        self.imported = False

        self.commands = {}
        self.cgroups = {}
        self.modules = {}
        self.docs = {}
        self.parsers = []
        self.reload("Initializing")

        super().__init__([ServerSpec(server, port)], nick, realname)
Пример #10
0
    def __init__(self,
                 server_list,
                 channel_list,
                 nickname,
                 reconnection_interval=5,
                 **connect_params):
        """Constructor for IRCChatBot objects.

        Arguments:

            server_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_list -- A list of channel names to join

            nickname -- The bot's nickname.

            reconnection_interval -- How long the bot should wait
                                     before trying to reconnect.

            **connect_params -- parameters to pass through to the connect
                                method.
        """

        super(IRCChatBot, self).__init__()
        self.connection.set_rate_limit(0.5)

        self.nickname = nickname
        self.__connect_params = connect_params

        self.channels = IRCDict()
        self.channel_list = channel_list

        self.server_list = [
            ServerSpec(*server) if isinstance(server,
                                              (tuple, list)) else server
            for server in server_list
        ]
        assert all(
            isinstance(server, ServerSpec) for server in self.server_list)

        if not reconnection_interval or reconnection_interval < 0:
            reconnection_interval = 2**31
        self.reconnection_interval = reconnection_interval
Пример #11
0
    def __init__(self, botconfig):
        """Setup everything.

        | Setup the handler.
        | Setup the server.
        | Connect to the server.
        """
        self.reload_event = threading.Event()
        self.reload_event.set()
        self.config = botconfig
        self.handler = handler.BotHandler(botconfig)
        if botconfig['feature'].getboolean('server'):
            self.server = server.init_server(self)
        serverinfo = ServerSpec(botconfig['core']['host'], int(botconfig['core']['ircport']), botconfig['auth']['serverpass'])
        nick = botconfig['core']['nick']
        self.handle_connect(serverinfo, nick, botconfig['core'])
        # properly log quits.
        self.connection.add_global_handler("quit", self.handle_quit, -21)
        # fix unicode problems
        self.connection.buffer_class.errors = 'replace'
Пример #12
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'
Пример #13
0
 def __init__(
     self, channel, nickname, server, port, password,
     limit_access_to, message_wait_seconds,
     paste_minimum_response_length,
     activation_timeout,
     paste_backend=None,
     **connect_params
 ):
     self.channel = channel
     self.queue = Queue()
     self.joined = False
     self.activated = False
     self.pre_join_queue = []
     self.message_wait_seconds = message_wait_seconds
     self.paste_minimum_response_length = paste_minimum_response_length
     self.paste_backend = paste_backend
     self.activation_timeout = activation_timeout
     self.limit_access_to = limit_access_to
     server = ServerSpec(server, port, password)
     super(IrcpdbBot, self).__init__(
         [server], nickname, nickname, **connect_params
     )
Пример #14
0
logging.basicConfig(format='%(levelname)s %(asctime)s: %(message)s',
                    filename='pikalaxbot_irc_client.log',
                    datefmt='%Y/%m/%d %H:%M:%S',
                    level=logging.DEBUG)
logging.getLogger().addHandler(logging.StreamHandler())
logger = logging.getLogger("PikalaxBOT")

with open('/home/pi/.oauth/discord') as F:
    token = F.read().rstrip()
    print('Loaded DISCORD token')

# Set up Twitch bot
with open("/home/pi/.oauth/twitch") as Token:
    servers = [
        ServerSpec("irc.chat.twitch.tv", password=Token.read().rstrip())
    ]
    Twitch = SingleServerIRCBot(servers, "pikalaxbot", "pikalaxbot")
    print('Loaded TWITCH token')
Twitch.connection.add_global_handler("whisper", twitch.on_whisper)
Twitch.connection.add_global_handler("pubmsg", twitch.on_pubmsg)
Twitch.connection.add_global_handler("action", twitch.on_pubmsg)
Twitch.connection.add_global_handler("ctcp", twitch.on_ctcp)
Twitch.connection.add_global_handler("endofmotd", twitch.on_endofmotd)
Twitch.connection.logs_dir = "/home/pi/irclogs/twitch/"
Twitch.connection._error = False
# Set up Freenode bot
with open("/home/pi/.oauth/freenode") as Token:
    servers = [ServerSpec("chat.freenode.net", password=Token.read().rstrip())]
    Freenode = SingleServerIRCBot(servers, "PikalaxBOT", "PikalaxBOT")
    print('Loaded FREENODE token')
Пример #15
0
 def test_with_host_and_password(self):
     server_spec = ServerSpec('irc.example.net', password='******')
     assert server_spec.host == 'irc.example.net'
     assert server_spec.port == 6667
     assert server_spec.password == 'heres johnny!'
Пример #16
0
 def test_with_host_and_port(self):
     server_spec = ServerSpec('irc.example.org', port=6669)
     assert server_spec.host == 'irc.example.org'
     assert server_spec.port == 6669
     assert server_spec.password is None
Пример #17
0
 def __init__(self, server, port, channels):
     super().__init__([ServerSpec(server, port)], "BLTBot",
                      "A simple BLT bot by Gustavo6046.")
     self.joinchans = channels
Пример #18
0
        self.do_whitelist(e.target)

    def on_pubmsg(self, c, e):
        message = e.arguments[0]

        if message.startswith("!whitelist "):
            self.do_whitelist(message[11:])
            return

        for word in get_words(message):
            if self.check_word(word):
                continue
            if self.rl(e.source):
                logging.info("Grace time allowed to {0}".format(e.source))
                break

            reply = choice(insult_messages).format(word,
                                                   NickMask(e.source).nick)
            c.privmsg(e.target, reply)
            break

    def on_nicknameinuse(self, c, e):
        c.nick(c.get_nickname() + "_")


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    servers = [ServerSpec('some.irc-server.example.com', 6667)]
    bot = OrthoNazi(servers)
    bot.start()
Пример #19
0
 def __init__(self, server, port, channels, chain=None):
     super().__init__([ServerSpec(server, port)], "Lonedude",
                      "A simple Markov bot by Gustavo6046")
     self.chain = chain or chat.MarkovChain()
     self.joinchans = channels
Пример #20
0
def serverOfConfig(config):
    return ServerSpec(config.settings[Configuration.IRC_SERVER],
                      port=config.settings[Configuration.IRC_PORT],
                      password=config.settings[Configuration.IRC_PASSWD])
Пример #21
0
 def __init__(self, name, desc, passwd, channels_list):
     sSpec = ServerSpec("irc_server", 6667)
     super().__init__([sSpec], name, desc)
     self.channels_list = channels_list
     self.passwd = passwd.split("\n")[0]
Пример #22
0
 def test_with_host(self):
     server_spec = ServerSpec('irc.example.com')
     assert server_spec.host == 'irc.example.com'
     assert server_spec.port == 6667
     assert server_spec.password is None
Пример #23
0
from irc.bot import ServerSpec

with open('.oauth_token') as f:
    token = f.readline()

DEFAULT_SERVER_SPEC = ServerSpec(host='irc.chat.twitch.tv', password=token)
Пример #24
0
 def add_servers(self, servers):
     for server_config in servers:
         self.servers.append(ServerSpec(*server_config))