Ejemplo n.º 1
0
def handle_top(irc: IRC, google_news: GoogleNews, target: str) -> None:
    """Handle a search request."""
    irc.send_message(target, "Working on it")
    logger.info("Fetching top news")
    news = google_news.top_news()
    for entry in news["entries"][:5]:
        irc.send_message(target, entry["title"])
Ejemplo n.º 2
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")
Ejemplo n.º 3
0
def handle_search(irc: IRC, google_news: GoogleNews, target: str,
                  query: str) -> None:
    """Handle a search request."""
    irc.send_message(target, "Working on it")
    logger.info("Fetching news for query %s", query)
    news = google_news.search(query)
    for entry in news["entries"][:5]:
        irc.send_message(target, entry["title"])
Ejemplo n.º 4
0
def handle_location(irc: IRC, google_news: GoogleNews, target: str,
                    location: str) -> None:
    """Handle a location request."""
    irc.send_message(target, "Working on it")
    logger.info("Fetching news for location %s", location)
    news = google_news.geo_headlines(location)
    for entry in news["entries"][:5]:
        irc.send_message(target, entry["title"])
Ejemplo n.º 5
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")
Ejemplo n.º 6
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
Ejemplo n.º 7
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
Ejemplo n.º 8
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")
Ejemplo n.º 9
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])
Ejemplo n.º 10
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)