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*")
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")
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*")
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
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!")
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))
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)
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
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')
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 = []
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)
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)
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)
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])
if msg == 'PING :tmi.twitch.tv': irc.ping() # This is for Ceaser_Gamming he is good people don't delete this elif msg.startswith('!crashcode'): response = f'You may not crash me {user[0]}!!' elif msg.startswith('!poll'): response = vote_bot.reducer(user[0], msg.split(' ', 1)[1]) elif msg.startswith('!vote'): response = vote_bot.vote(user[0], msg.split(' ', 1)[1]) elif msg.startswith('!giveaway'): response = giveaway_bot.add_user(user[0]) elif msg.startswith('!pick_user'): response = giveaway_bot.pick_user(user[0]) if response is not None: irc.send(response) if __name__ == '__main__': irc_server = IRC(SERVER, PORT, NICK, CHANNEL, AUTH) irc_server.connect() try: main(irc_server) except KeyboardInterrupt: irc_server.disconnect()
from irc import IRC chatty = IRC("r4f1xd", "r4f1sBOTtom", "oauth:ckqni9uuiefzehgejl3lsy9nw79lnp") chatty.connect() chatty.send("AnotherTextmessage")
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"))
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")
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
from irc import IRC import time irc = IRC('#EpiKnet') irc.connect('irc.epiknet.org','Philippe') #irc.epiknet.org time.sleep(5) irc.send('Salut MEC') time.sleep(2) while True: time.sleep(1) m = irc.recv() id = m.split('!')[0] id = id.lstrip(':') messages = m.split(' :') message = messages[-1] message = message.strip('\r\n') if m.find('PING') != -1: irc.ping() message = '' if len(message) != 0: if message.find('JOIN') != -1: print(id, 'a rejoint le channel') elif message == ' Je suis pas ton pote MEC' and id == 'Terrance': irc.send('Je suis pas ton mec MON GARS') time.sleep(1) #print(id, '>', message)