Beispiel #1
0
    def __init__(self, *,
                 hostname="localhost", port=6667, ssl=False,
                 nickname=None, username=None, realname=None, password=None,
                 channels=[]):
        """
        Initialize the actual IRC client and register callback methods.
        """
        self.logger.info("Creating Protocol instance.")

        self.nickname = nickname
        self.password = password
        self.username = username
        self.realname = realname
        self.channels = channels

        self.logger.debug("Registering callback methods.")
        self.irc = bottom.Client(hostname, port, ssl=ssl)

        self.event_handler("PING")(self.keepalive)
        self.event_handler("CLIENT_CONNECT")(self.register)
        self.event_handler("CLIENT_DISCONNECT")(self.reconnect)
        self.event_handler("RPL_WELCOME")(self.join)

        self.fake_ping = functools.partial(
                self.irc.trigger, "PING", message="keepalive")
Beispiel #2
0
    def __init__(self, parent, config):
        self.config = config
        self.irc = bottom.Client(host=config['host'].get(),
                                 port=config['port'].get(),
                                 ssl=config['ssl'].get())

        @self.irc.on('CLIENT_CONNECT')
        async def connect(**kwargs):
            self.irc.send('NICK', nick=config['nick'].get())
            self.irc.send('USER',
                          user=config['username'].get(),
                          realname='https://devse.wiki/')

            done, pending = await asyncio.wait(
                [self.irc.wait('RPL_ENDOFMOTD'),
                 self.irc.wait('ERR_NOMOTD')],
                return_when=asyncio.FIRST_COMPLETED)
            for future in pending:
                future.cancel()

            # FIXME: maybe a cleaner way to do this with confuse (maybe I'll just drop confuse)
            try:
                self.irc.send('PRIVMSG',
                              target="nickserv",
                              message=f"IDENTIFY {config['nickserv'].get()}")
            except BaseException:
                pass
            self.irc.send('JOIN', channel=config['channel'].get())

        @self.irc.on('privmsg')
        async def irc_message(nick, target, message, **kwargs):
            if nick == config['nick'].get():
                return
            if target == config['nick'].get():
                if message == '\001VERSION\001':

                    def gnuify(x):
                        return 'GNU/Linux' if x == 'Linux' else x

                    self.irc.send(
                        'NOTICE',
                        target=nick,
                        message=
                        f"\001VERSION devse-chan on {gnuify(platform.system())}\001"
                    )
                elif message == '\001SOURCE\001':
                    self.irc.send(
                        'NOTICE',
                        target=nick,
                        message=
                        '\001SOURCE https://github.com/d0p1s4m4/devse-chan\001'
                    )
            elif target != config['channel'].get():
                return
            await parent.to_discord(nick, message)

        @self.irc.on('PING')
        async def irc_ping(message, **kwargs):
            self.irc.send('PONG', message=message)
Beispiel #3
0
    def __init__(self, nick, channels, noiselevel=5):
        self.nick = nick
        self.channels = channels
        self.noiselevel = noiselevel
        self.client = bottom.Client(host=host, port=port, ssl=ssl)

        self.client.on('CLIENT_CONNECT', self.handle_connect)
        self.client.on('PING', self.keepalive)
        self.client.on('PRIVMSG', self.message)
        self.client.on('RPL_WELCOME', self.loop)
        self.silence = False
Beispiel #4
0
 def __init__(self, xanmel, config):
     self.connected = False
     self.joined = False
     self.reconnect_interval = 0
     super(IRCModule, self).__init__(xanmel, config)
     self.client = bottom.Client(host=config['host'],
                                 port=config['port'],
                                 ssl=config['ssl'],
                                 loop=self.loop)
     self.message_queue = asyncio.Queue(maxsize=config.get('flood_max_queue_size', 1024))
     self.msg_lock = asyncio.Lock()
     self.challenge_reply = None
 def __init__(self, discordChannel, host, port, ircChannel, nickname,
              discordBot):
     self.discordChannel = discordChannel
     self.host = host
     self.port = port
     self.ircChannel = ircChannel
     self.nickname = nickname
     self.discordBot = discordBot
     self.ircclient = bottom.Client(host=host, port=port, ssl=False)
     self.ircclient.on('CLIENT_CONNECT', self.connect)
     self.ircclient.on('PING', self.keepalive)
     self.ircclient.on('PRIVMSG', self.on_message)
     self.loop = asyncio.get_event_loop()
     self.task = self.loop.create_task(self.ircclient.connect())
async def connect_irc(apps, serviceid, auth_token):
    print("Connecting to IRC...")

    conn = bottom.Client("localhost", 6667, ssl=False, loop=loop)
    await conn.connect()

    conn.send("NICK", nick="matrix")
    conn.send("USER", user="******", realname="apps")

    # Temp join for testing
    conn.send('JOIN', channel=room)

    # Tempt send for testing
    conn.send('PRIVMSG', target=room, message="Hello")

    return conn, serviceid
Beispiel #7
0
    async def run(self):
        self.client = bottom.Client(host=self.ircserver,
                                    port=self.ircport,
                                    ssl=self.ssl)

        self.client.on('CLIENT_CONNECT', self.handle_connect)
        self.client.on('CLIENT_DISCONNECT', self.handle_disconnect)
        self.client.on('RPL_WELCOME', self.handle_welcome)
        self.client.on('RPL_MYINFO', self.handle_myinfo)
        self.client.on('PING', self.handle_ping)
        self.client.on('PRIVMSG', self.handle_privmsg)
        self.client.on('JOIN', self.handle_join)
        self.client.on('PART', self.handle_part)
        self.client.on('KICK', self.handle_kick)
        self.client.on('QUIT', self.handle_quit)
        self.client.on('NICK', self.handle_nick)
        self.client.on('RPL_NAMREPLY', self.handle_namreply)
        await self.client.connect()
Beispiel #8
0
import bottom, asyncio, logging, random
from tbot.twitch_bot.unpack import rfc2812_handler
from tbot import config
'''
Used for sending messages to channels so we can log 
the bots own messages on the main connection.
'''

bot_sender = bottom.Client('a', 0)
bot_sender.pong_check_callback = None
bot_sender.ping_callback = None
bot_sender.raw_handlers = [rfc2812_handler(bot_sender)]


def setup(bot):

    bot_sender.host = config['twitch']['irc_host']
    bot_sender.port = config['twitch']['irc_port']
    bot_sender.ssl = config['twitch']['irc_use_ssl']

    @bot_sender.on('CLIENT_CONNECT')
    async def connect(**kwargs):
        if bot_sender.pong_check_callback:
            bot_sender.pong_check_callback.cancel()
        if bot_sender.ping_callback:
            bot_sender.ping_callback.cancel()
        bot_sender.ping_callback = asyncio.ensure_future(send_ping(10))
        if config['twitch']['chat_token']:
            bot_sender.send('PASS',
                            password='******'.format(
                                config['twitch']['chat_token']))
Beispiel #9
0
import spoilerbot.srl as srl
import spoilerbot.sg as sg

# our special asyncio version of pyz3r
import pyz3r_asyncio

config = cfg.get_config()

# discord bot using discord.py rewrite
discordbot = commands.Bot(command_prefix=config['cmd_prefix'], )
discordbot.load_extension("spoilerbot.verifiers")
discordbot.load_extension("spoilerbot.eggs")
discordbot.load_extension("spoilerbot.admin")

# irc bot using bottom, an very, very low level async irc client
ircbot = bottom.Client(host='irc.speedrunslive.com', port=6667, ssl=False)

#setup logging configuration
logger = logging.getLogger('discord')
logger.setLevel(logging.INFO)
handler = handlers.TimedRotatingFileHandler(filename='logs/discord.log',
                                            encoding='utf-8',
                                            when='D',
                                            interval=1,
                                            backupCount=30)
handler.setFormatter(
    logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)


#do some stuff when we connect to discord
Beispiel #10
0
import asyncio
from time import gmtime, strftime, time

import bottom
from utils import log_msg, get_settings

host, port, nick, password, channel = get_settings()

bot = bottom.Client(host=host, port=port, ssl=False)
loop = asyncio.get_event_loop()
loop.set_debug(True)


@bot.on('CLIENT_CONNECT')
async def connect(**kwargs):
    print("Connected.")

    bot.send('PASS', password=password)
    bot.send('NICK', nick=nick)
    bot.send('USER', user=nick, realname=nick)

    # wait till server motd
    done, pending = await asyncio.wait(
        [bot.wait("RPL_ENDOFMOTD"),
         bot.wait("ERR_NOMOTD")],
        return_when=asyncio.FIRST_COMPLETED)

    for future in pending:
        future.cancel()

    print("joining %s" % channel)
Beispiel #11
0
import asyncio
import bottom
import json
import re
import websockets
from helpers import config, ripple_api, convertmods, naoapi, generate
from irc import Dispatcher, connector, cooldown

bot_ripple = bottom.Client(host=config.ripple()["irc_ip"],
                           port=config.ripple()["irc_port"],
                           ssl=False)
bot_twitch = bottom.Client(host=config.twitch()["irc_ip"],
                           port=config.twitch()["irc_port"],
                           ssl=False)


def load_memes():
    arr = []
    players = naoapi.get_list()["data"]
    for player in players:
        arr.append(player["user_id"])
    return arr


async def ripple_websocket():
    await bot_ripple.wait("client_connect")

    async with websockets.connect("wss://api.ripple.moe/api/v1/ws",
                                  timeout=1) as websocket:

        await websocket.send('{"type": "subscribe_scores", "data": []}')
Beispiel #12
0
import asyncio
from time import gmtime, strftime, time

import bottom

from handlers import command, action
from singletons.config import Config

config = Config()

bot = bottom.Client(host=config['irc']['host'],
                    port=int(config['irc']['port']),
                    ssl=False)
loop = asyncio.get_event_loop()
loop.set_debug(True)  # TODO: remove this?

NICK = config['irc']['nick']
CHANNELS = [
    "#%s" % x for x in config['irc']['channels'].replace(" ", "").split(",")
]

message_send_lock = asyncio.Lock()

bot.last_message = 0


async def keepalive():
    """
    Every five seconds, checks if it's been two minutes since the last time we got a message.
    If it has, the bot will reconnect.
Beispiel #13
0
            b.get_api()
            break
        except phue.PhueRegistrationException:
            if not press_message_displayed:
                print('Press the button on the Hue Bridge to allow access')
                press_message_displayed = True
            time.sleep(1)
        except:
            raise
    print('Connected to the Hue Bridge')
    return b


bot = bottom.Client(
    host='irc.chat.twitch.tv', 
    port=6697, 
    ssl=True,
)
bot.raw_handlers = [rfc2812_handler(bot)]

@bot.on('CLIENT_CONNECT')
async def connect(**kwargs):
    bot.send('PASS', password='******')
    bot.send('NICK', nick='justinfan32429')

    done, pending = await asyncio.wait(
        [bot.wait("RPL_ENDOFMOTD"),
         bot.wait("ERR_NOMOTD")],
        loop=bot.loop,
        return_when=asyncio.FIRST_COMPLETED
    )
Beispiel #14
0
import bottom
from dispatcher import Dispatcher, connector, cooldown

host = 'chat.freenode.net'
port = 6697
ssl = True

NICK = "russel-test"
CHANNEL = ["#pigbenis", "#fuccboi"]
PASSWORD = None

loop = asyncio.get_event_loop()
loop.set_debug(True)

# create the irc client
bot = bottom.Client(host=host, port=port, ssl=ssl, loop=loop)


async def autoupdate_or_some_shit():
    await bot.wait("client_connect")
    while not bot.protocol.closed:
        # bot.send("privmsg", target=CHANNEL, message="sent this test message")
        await asyncio.sleep(3, loop=bot.loop)


# this is the command dispatcher
class IrcBot(Dispatcher):
    # nick, message and channel are always supplied
    # command and args come from the regex named capture groups
    # (in this case: r'^!(?P<command>.*?)\s(?P<args>.*)')
    @cooldown(5)
Beispiel #15
0
import bottom, asyncio, logging, random, aiohttp
from datetime import datetime
from logitch.unpack import rfc2812_handler
from logitch import config, db

bot = bottom.Client('a', 0)


@bot.on('CLIENT_CONNECT')
async def connect(**kwargs):
    if not bot.http_session:
        bot.http_session = aiohttp.ClientSession()
    if not bot.db:
        bot.db = await db.Db().connect(bot.loop)

    if bot.pong_check_callback:
        bot.pong_check_callback.cancel()
    logging.info('IRC Connecting to {}:{}'.format(config['irc']['host'],
                                                  config['irc']['port']))
    if config['token']:
        bot.send('PASS', password='******'.format(config['token']))
    bot.send('NICK', nick=config['user'])
    bot.send('USER', user=config['user'], realname=config['user'])

    # Don't try to join channels until the server has
    # sent the MOTD, or signaled that there's no MOTD.
    done, pending = await asyncio.wait(
        [bot.wait("RPL_ENDOFMOTD"),
         bot.wait("ERR_NOMOTD")],
        loop=bot.loop,
        return_when=asyncio.FIRST_COMPLETED)
Beispiel #16
0
def irc_transform(func):
    irc_transforms.append(func)
    return func

# Functions that do message modification before sending to Discord
# Take message, author, irc client, discord server
discord_transforms = []


def discord_transform(func):
    discord_transforms.append(func)
    return func

irc_client = irc_client = bottom.Client(
    host=get_config("mainserver.irc.irc.address"),
    port=get_config("mainserver.irc.irc.port"),
    loop=asyncio.get_event_loop(),
    ssl=True
)
logger = logging.getLogger(__name__)
messagelogger = logging.getLogger("IRC")
MENTION_RE = re.compile(r"<@!?(\d+)>")
IRC_MENTION_RE = re.compile(r"@([^@]+?)@")
IGNORED_NAMES = {"travis-ci", "vg-bot", "py-ctcp"}


async def unload(loop=None):
    logger.info("Dropping IRC connection.")
    await irc_client.disconnect()


@irc_client.on("client_connect")
Beispiel #17
0
import bottom
import win32com
import win32com.client


speaker = win32com.client.Dispatch('SAPI.SpVoice')


host = '192.168.137.3'
port = 6667
ssl = False

NICK = "talkbot"
CHANNEL = "#system"

bot = bottom.Client(host=host, port=port, ssl=ssl)
@bot.on('CLIENT_CONNECT')
def connect(**kwargs):
    print("Connected")
    bot.send('NICK', nick=NICK)
    bot.send('USER', user=NICK,
             realname='iamthetalkingrobot')
    bot.send('JOIN', channel=CHANNEL)

@bot.on("client_disconnect")
async def reconnect(**kwargs):
  # Trigger an event that may cascade to a client_connect.
  # Don't continue until a client_connect occurs, which may be never.
  print("lost connection")  

@bot.on('PING')
Beispiel #18
0
    async def start_wrapper(self):
        print("Attempting to connect to IRC...")

        # Create bottom IRC client
        self._bottom = bottom.Client(host=self._config["irc_server"],
                                     port=self._config["irc_port"],
                                     ssl=False)

        # Basic IRC handlers
        @self._bottom.on('NOTICE')
        def irc_notice(message, **kwargs):
            print(message)

        @self._bottom.on('PING')
        def keepalive(message, **kwargs):
            self._bottom.send('PONG', message=message)

        # Connect and then send username
        await self._bottom.connect()
        self._bottom.send('PASS', password=self._config["irc_password"])
        self._bottom.send('NICK', nick=self._config["irc_nick"])
        self._bottom.send('USER', user=self._config["irc_nick"],
                          realname=self._config["irc_nick"])

        print("Waiting for IRC MOTD...")

        # Wait on MOTD
        done, pending = await asyncio.wait(
            [self._bottom.wait("RPL_ENDOFMOTD"),
             self._bottom.wait("ERR_NOMOTD")],
            loop=self._loop,
            return_when=asyncio.FIRST_COMPLETED
        )

        # Cancel whichever waiter's event didn't come in.
        for future in pending:
            future.cancel()

        print("Joining channel...")

        self._bottom.send('JOIN', channel=self._config["irc_channel"])

        # Register message handler
        @self._bottom.on('PRIVMSG')
        async def privmsg(nick, target, message, **kwargs):
            # User must be authorized
            if nick not in self._config["users"]:
                # Not a command, send to MC
                self.mc_send(nick, message)
                return

            fragments = message.strip().split(maxsplit=2)
            if len(fragments) != 3:
                # Not a command, send to MC
                self.mc_send(nick, message)
                return

            # Command must start with "!<nick>" or "!!<nick>"
            if ((fragments[0] != ("!" + self._config["irc_nick"])) and
                    (fragments[0] != ("!!" + self._config["irc_nick"]))):
                # Forward to minecraft, not a command
                self.mc_send(nick, message)
                return

            is_special_cmd = fragments[0][:2] == "!!"

            # Actual command
            real_command = fragments[2]

            if real_command == "nonce":
                nonce_text = binascii.hexlify(self._nonce).decode('ascii')
                self._bottom.send('PRIVMSG', message=nonce_text, target=nick)
                return

            # Sigcheck command
            if self._config["enable_sig_verify"]:
                # Signature must be this length
                if len(fragments[1]) != 86:
                    print("Signature invalid!")
                    return

                vk_enc = self._config["users"][nick]
                vk = ed25519.VerifyingKey(vk_enc, encoding='base64')

                bytes_to_sign = b'\x00' if not is_special_cmd else b'\x01'
                bytes_to_sign += self._nonce
                bytes_to_sign += real_command.encode('utf-8')

                try:
                    vk.verify(fragments[1], bytes_to_sign, encoding='base64')
                except ed25519.BadSignatureError:
                    print("Signature invalid!")
                    return

            self.new_nonce()

            if not is_special_cmd:
                # Command to forward to server
                if self._subprocess:
                    real_command = (real_command + "\n").encode('utf-8')
                    self._subprocess.stdin.write(real_command)
            else:
                # Command for us
                if real_command == "kill":
                    self.subprocess_kill()
                elif real_command == "launch":
                    if self._subprocess:
                        return
                    self._loop.create_task(self.subprocess_create())
                elif real_command == "status":
                    if not self._subprocess:
                        message = "Server not running"
                    else:
                        message = "Server running, PID {}".format(
                            self._subprocess.pid)

                    self.irc_send(message)
                elif real_command == "all-shutdown":
                    print("Shutting down!")

                    if self._backup_task:
                        self._backup_task.cancel()
                        self._backup_task = None

                    if self._subprocess:
                        self._subprocess.stdin.write(b"stop\n")
                        await self._subprocess.wait()
                    self._bottom.send('QUIT', message=":( :( :( ")
                    self._loop.stop()
                    return
                elif real_command[:7] == "taillog":
                    lines = 10
                    try:
                        lines = int(real_command[8:])
                    except ValueError:
                        pass

                    with open("logs/latest.log", "r") as f:
                        # FIXME: Ugly
                        lines = f.readlines()[-lines:]

                        for line in lines:
                            self.irc_send(line)
                else:
                    # Bad command
                    message = "Unrecognized command: " + real_command
                    self.irc_send(message)

        @self._bottom.on('JOIN')
        def irc_join(nick, user, host, **kwargs):
            if not self._config["enable_irc_bridge"]:
                return
            if not self._subprocess:
                return

            if nick == self._config["irc_nick"]:
                # Ourselves
                return

            message = "{} has joined IRC ({}!{}@{})".format(
                nick, nick, user, host)

            if self._config["use_tellraw"]:
                json_msg = json.dumps(["* " + message])
                formatted_message = "/tellraw @a " + json_msg
            else:
                formatted_message = "/say " + message

            formatted_message = (formatted_message + "\n").encode('utf-8')
            self._subprocess.stdin.write(formatted_message)

        @self._bottom.on('PART')
        def irc_part(nick, user, host, message, **kwargs):
            if not self._config["enable_irc_bridge"]:
                return
            if not self._subprocess:
                return

            if nick == self._config["irc_nick"]:
                # Ourselves
                return

            part_message = message
            message = "{} has left IRC".format(nick, nick, user)
            if part_message:
                message += " (" + part_message + ")"
            print(message)

            if self._config["use_tellraw"]:
                json_msg = json.dumps(["* " + message])
                formatted_message = "/tellraw @a " + json_msg
            else:
                formatted_message = "/say " + message

            formatted_message = (formatted_message + "\n").encode('utf-8')
            self._subprocess.stdin.write(formatted_message)
            print(formatted_message)

        print("IRC ready!")

        # Launch subprocess
        self._loop.create_task(self.subprocess_create())