Example #1
0
def main() -> None:
    """Main entrypoint of the ping 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()

    # Join a channel
    irc.join("#bot-test")

    # Loop through all messages - current and future
    for message in irc.messages:
        # If someone's sent a message "ping"
        if isinstance(message, IRCMessage) and message.message == "ping":
            # Get the target of the message. If the target is the bot directly,
            # send the message to the author - else send it to the channel the message
            # was directed to
            target = message.author if message.target == "test" else message.target
            # Send "pong"
            irc.send_message(target, "pong")
Example #2
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
Example #3
0
	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')
mo = config.get('Moduls', 'modul')
mo = strToArray(mo)

for m in mo:
	print m
	pr = config.get('Config', m)
	pr = strToArray(pr)
	t = __import__("Modul."+m, globals(), locals(), [m], -1)
	for p in pr:
		if(p!=False):
			f = getattr(t, m)(p, callBack) 
			modulList.append(f)

raw_input()
irc.join()


Example #4
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)
Example #5
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)
Example #6
0
def main() -> None:
    """Main entrypoint of the bot example."""
    # Parse the arguments and execute the chosen command
    options = parser.parse_args()

    logger = logging.getLogger(__name__)

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

    # Connect to the server
    irc.connect()

    # Join a channel
    irc.join("#bot-test")

    # Loop through all messages - current and future
    for message in irc.messages:
        # If someone's sent a message
        if isinstance(message, IRCMessage):
            # Get the target of the message. If the target is the bot directly,
            # send the message to the author - else send it to the channel the message
            # was directed to
            target = message.author if message.target == "test" else message.target

            # Match commands targeted to our bot
            match = re.match("bot: ([^ ]+)( (.*))?", message.message)
            if not match:
                continue

            # Extract command and optional parameters from the message
            command, _, parameter = match.groups()
            if command == "about":
                # Send about message
                irc.send_message(target, "I'm a simple example bot using irc-python version {}.".format(irc.version))
                irc.send_message(target, "Read more about me on https://github.com/AlexGustafsson/irc-python.")
            elif command == "help":
                # Send help message
                irc.send_message(target, "You invoke me by sending 'bot: <command> <parameters>'")
            elif command == "torvalds":
                quotes = [
                    "Talk is cheap. Show me the code.",
                    "Intelligence is the ability to avoid doing work, yet getting the work done.",
                    "Given enough eyeballs, all bugs are shallow."
                ]
                # Send a random Linus Torvalds quote
                irc.send_message(target, random.choice(quotes))  # nosec
            elif command == "time":
                # Send the local time
                irc.send_message(target, datetime.now().strftime("%H:%M:%S"))
            elif command == "sum":
                # Calculate the sum of the parameters
                try:
                    result = sum([int(number) for number in parameter.split(" ")])
                    irc.send_message(target, str(result))
                except ValueError:
                    logger.error("Got bad parameters for sum: %s", parameter)
                    irc.send_message(target, "Unable to sum the parameters")
            else:
                # Handle unknown commands
                irc.send_message(target, "Sorry, I'm not sure what you want me to do")
Example #7
0
def main() -> None:
    """Main entrypoint of the bot."""
    # Log at INFO level or higher
    logging.basicConfig(level=logging.INFO)

    # Create an argument parser for parsing CLI arguments
    parser = ArgumentParser(description="An IRC bot providing 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=1,
                        type=float,
                        help="Connection timeout in seconds")

    # Add optional parameters for authentication etc.
    parser.add_argument(
        "-u",
        "--user",
        default="emoji-bot",
        help="Username to use when connecting to the IRC server")
    parser.add_argument("-n",
                        "--nick",
                        default="emoji-bot",
                        help="Nick to use when connecting to the IRC server")
    parser.add_argument(
        "-g",
        "--gecos",
        default="Emoji Bot v1.0.0 (github.com/AlexGustafsson/irc-emoji-bot)",
        help="Gecos to use when connecting to the IRC server")
    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()

    # Read emojis from disk
    emojis = None
    with open(path.join(path.dirname(__file__), "./emojis.csv"), "r") as file:
        reader = csv.reader(file)
        emojis = {row[0]: row[1] for row in reader if row and row[0]}

    # 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)

    # 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):
            command = random.sample(list(emojis), 1)[0]
            irc.send_message(
                target,
                "I replace your emoji mentions with actual ASCII emojis. Example:"
            )
            irc.send_message(target, "{} -> {}".format(command,
                                                       emojis[command]))
            irc.send_message(target,
                             "You can also use the following commands:")
            irc.send_message(
                target,
                "{}: (bond) freeze, sucka!!! -> ┌( ͝° ͜ʖ͡°)=ε/̵͇̿̿/’̿’̿ ̿ freeze, sucka!!!"
                .format(options.nick))
            irc.send_message(target,
                             "{}: help -> this help text".format(options.nick))
        elif re.match(r"^{}:.*\([a-z0-9]+\).*".format(options.nick),
                      message.message) is not None:
            # Remove the nick prompt and trim whiteline
            body = message.message[len(options.nick) + 1:].strip()
            emoji_regex = re.compile(r"(\([a-z0-9]+\))")
            parts = emoji_regex.split(body)

            result = ""
            for part in parts:
                result += emojis[part] if part in emojis else part

            irc.send_message(target, result)
        else:
            possible_emojis = re.findall(r"(\([a-z0-9]+\))", message.message)
            for possible_emoji in possible_emojis:
                if possible_emoji in emojis:
                    irc.send_message(target, emojis[possible_emoji])
Example #8
0
def main() -> None:
    """Main entrypoint of the bot."""
    # Configure the default logging format
    logging.basicConfig(
        format="[%(asctime)s] [%(name)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 for reading news")

    # 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="news-bot",
        help="Username to use when connecting to the IRC server")
    parser.add_argument("-n",
                        "--nick",
                        default="news-bot",
                        help="Nick to use when connecting to the IRC server")
    parser.add_argument(
        "-g",
        "--gecos",
        default="News Bot v0.1.0 (github.com/AlexGustafsson/irc-news-bot)",
        help="Gecos to use when connecting to the IRC server")
    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)

    # 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 help you read news.")
            irc.send_message(target, "You can use the following commands:")
            irc.send_message(
                target,
                "{}: topic se sv business -> Swedish business news on Swedish".
                format(options.nick))
            irc.send_message(
                target,
                "{}: location se sv Karlskrona -> Swedish news on Swedish from Karlskrona"
                .format(options.nick))
            irc.send_message(
                target,
                "{}: search us en security -TikTok -> American news in English about security, not mentioning TikTok"
                .format(options.nick))
            irc.send_message(target,
                             "{}: help -> this help text".format(options.nick))
        elif message.message.startswith("{}:".format(options.nick)):
            handle_news_request(irc, options.nick, target, message)
Example #9
0
            print('{}: Sonarr could not process torrent {}'.format(time.asctime(), torrent_name))
        except IndexError:
            print('{}: Could not find torrent name / id in message: {}'.format(time.asctime(), message))
        except KeyboardInterrupt:
            print('{}: Exiting...'.format(time.asctime()))
            irc.quit("https://github.com/octine/irc2sonarr")
            exit(0)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--nick', default="pybot_"+str(uuid.uuid4()).split('-')[0])
    parser.add_argument('--sonarr-ip', default="localhost")
    parser.add_argument('--sonarr-port', default=8989)
    parser.add_argument('--sonarr-api-key', required=True)
    parser.add_argument('--auth', required=True)
    parser.add_argument('--tracker', required=True, choices=trackers.trackers.keys())
    args = parser.parse_args()

    conf = trackers.trackers[args.tracker]
    conf['rss_key'] = args.auth

    sonarr = SonarrApi(args.sonarr_api_key, args.sonarr_ip, args.sonarr_port)

    irc = IRC()
    irc.connect(conf['server'], conf['port'], args.nick)
    irc.join(conf['channel'])

    # Enter main loop
    main(sonarr, irc, conf)
Example #10
0
#!/usr/local/bin/python3
import time

from irc import IRC

host = "irc.rizon.net"
port = 6667
tls = False
nick = "TEST"
pwd = None
chan = "#pwnyan"
debug = True

irc = IRC(host, port)
print("irc.conn()")
irc.conn()
irc.join()