From f14f14890181ec19df25cb24f5fe4618611f2c8d Mon Sep 17 00:00:00 2001 From: g1n Date: Sat, 27 Nov 2021 18:32:59 +0000 Subject: [PATCH] Initial commit --- .gitignore | 4 +++ LICENSE | 12 +++++++ README.org | 15 +++++++++ TODO.org | 18 ++++++++++ commands.py | 78 +++++++++++++++++++++++++++++++++++++++++++ config.json.sample | 1 + config.py | 28 ++++++++++++++++ irc.py | 82 ++++++++++++++++++++++++++++++++++++++++++++++ pygbot.py | 43 ++++++++++++++++++++++++ requirements.txt | 2 ++ web.py | 17 ++++++++++ youtube.py | 17 ++++++++++ 12 files changed, 317 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.org create mode 100644 TODO.org create mode 100644 commands.py create mode 100644 config.json.sample create mode 100644 config.py create mode 100644 irc.py create mode 100755 pygbot.py create mode 100644 requirements.txt create mode 100644 web.py create mode 100644 youtube.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4ad91ca --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*~ +__pycache__ +config.json +venv diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..36939a7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,12 @@ + +MIT License + +Copyright (c) 2021 g1n + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + diff --git a/README.org b/README.org new file mode 100644 index 0000000..495236d --- /dev/null +++ b/README.org @@ -0,0 +1,15 @@ +#+TITLE: pygbot - simple irc bot in python + +** Setup + +*** Requirements + + ~pip3 install --user -r requirements.txt~ + +*** Config + + Rename/copy ~config.json.sample~ to ~config.json~ and change it values + +*** How to start + + Just run ~./pygbot.py~ after you downloaded requirements and changed your config diff --git a/TODO.org b/TODO.org new file mode 100644 index 0000000..ff8f694 --- /dev/null +++ b/TODO.org @@ -0,0 +1,18 @@ +#+TITLE: TODOs + +* TODO Password (identify) + +* DONE SSL/TLS + +* DONE config.py +** DONE JSON! +** TODO Fixing config without restarting bot (via file access) +** TODO more config options in chat + +* DONE admins +** TODO admin commands + +* TODO commands +** DONE prefix parsing +** TODO add other commands +* TODO respond in query diff --git a/commands.py b/commands.py new file mode 100644 index 0000000..ddee949 --- /dev/null +++ b/commands.py @@ -0,0 +1,78 @@ +import irc +from config import pygbot as c +from config import changeobj +import youtube as yt +import web + +def bothelp(bot, channel): + helpmsg = """Hi I am pygbot. Created by g1n. My commands: help, ping, echo, yt (youtube), t (title) but more features are planing""" + bot.send(channel, helpmsg) + +def isadmin(user): + if user in c.admins: + return True + else: + return False + +def bot_command_parser(config, bot, user, channel, message): + if channel == "pygbot": + channel = user.split('!')[0] + if message[0] == c.prefix: + if message.split()[0] == (c.prefix + "echo"): + bot.send(channel, ' '.join(message.split()[1:])) + elif message.split()[0] == (c.prefix + "admin"): + if isadmin(user): + bot.send(channel, "You are admin") + else: + bot.send(channel, "You are not admin") + elif message.split()[0] == (c.prefix + 'c') or message.split()[0] == (c.prefix + 'config'): + configure(config, bot, channel, message) if isadmin(user) else bot.send(channel, "Permissions Denied") + elif message.split()[0] == (c.prefix + "ping"): + bot.send(channel, "pong") + elif message.split()[0] == (c.prefix + "help"): + bothelp(bot, channel) + elif message.split()[0] == (c.prefix + "join"): + bot.join(message.split()[1]) if isadmin(user) else bot.send(channel, "Permissions Denied") + elif message.split()[0] == (c.prefix + "kick"): + bot.kick(channel, message.split()[1]) if isadmin(user) else bot.send(channel, "Permissions Denied") + elif message.split()[0] == (c.prefix + "eval"): + boteval(config, bot, channel, message) if isadmin(user) else bot.send(channel, "Permissions Denied") + elif message.split()[0] == (c.prefix + "exec"): + botexec(config, bot, channel, message) if isadmin(user) else bot.send(channel, "Permissions Denied") + elif message.split()[0] == (c.prefix + "quit"): + bot.shutdown(None, None, "bye") if isadmin(user) else bot.send(channel, "Permissions Denied") + + elif message.split()[0] == (c.prefix + "yt") or message.split()[0] == (c.prefix + "youtube"): + yt.gettitle(bot, channel, message) + elif message.split()[0] == (c.prefix + "t") or message.split()[0] == (c.prefix + "title"): + web.gettitle(bot, channel, message) + +def configure(config, bot, channel, message): + try: + message = message.split() + if message[1] == "bot": + if message[2] == "prefix": + changeobj(config, "prefix", message[3]) + c.prefix = message[3] + elif message[2] == "nick": + bot.setnick(message[3]) + changeobj(config, "nick", message[3]) + c.nick = message[3] + else: + bot.send(channel, "No such config category") + return 1 + bot.send(channel, "Changed successfully") + except: + bot.send(channel, "Something went wrong") + +def boteval(config, bot, channel, message): + try: + eval(str(''.join(message.split()[1:]))) + except: + bot.send(channel, "Failed to eval") + +def botexec(config, bot, channel, message): + try: + exec(str(' '.join(message.split()[1:]))) + except: + bot.send(channel, "Failed to exec") diff --git a/config.json.sample b/config.json.sample new file mode 100644 index 0000000..bd59ee5 --- /dev/null +++ b/config.json.sample @@ -0,0 +1 @@ +{"nick": "pygbot", "host": "serveraddress", "port": 6697, "tls": true, "prefix": ".", "channels": ["#channel"], "admins": ["yournickname"]} diff --git a/config.py b/config.py new file mode 100644 index 0000000..ddaa73f --- /dev/null +++ b/config.py @@ -0,0 +1,28 @@ +import json + +def changeobj(config, obj, value): + config[obj] = value + writeconfig("config.json", config) + return config + +def readobj(config, obj): + return config[obj] + +def writeconfig(configfile, data): + with open(configfile, 'w') as f: + json.dump(data, f) + +def readconfig(configfile): + with open(configfile, 'r') as f: + config = json.load(f) + return config + +class pygbot: + nick = "" + host = "" + port = 0 + tls = False + prefix = "" + channels = [] + admins = [] + diff --git a/irc.py b/irc.py new file mode 100644 index 0000000..4a618bd --- /dev/null +++ b/irc.py @@ -0,0 +1,82 @@ +import ssl +import sys +import time +import socket + +class IRC: + def __init__(self, sock=None): + if sock is None: + self.sock = socket.socket( + socket.AF_INET, socket.SOCK_STREAM) + else: + self.sock = sock + + def connect(self, host, port, nick, realname, username, password=None, tls=False): + ctx = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) + if tls == True: + self.sock = ctx.wrap_socket(self.sock) + time.sleep(1) + self.sock.connect((host, port)) + time.sleep(5) + self.sock.send(bytes(f"NICK {nick}\n", "UTF-8")) + time.sleep(1) + self.sock.send(bytes(("USER "+ nick + " " + username + " " + nick + " :" + realname +"\n"), "UTF-8")) + time.sleep(1) + + def rawsend(self, msg): + totalsent = 0 + while totalsent < len(msg): + sent = self.sock.send(msg[totalsent:]) + if sent <= 0: + raise RuntimeError("socket connection broken") + totalsent = totalsent + sent + + def send(self, receiver, msg): + self.rawsend(bytes(f"PRIVMSG {receiver} :{msg}\n", "UTF-8")) + + def recv(self, msglen=2048): + chunks = [] + bytes_recd = 0 + while bytes_recd < msglen: + chunk = self.sock.recv(msglen - bytes_recd) + if chunk == b'': + raise RuntimeError("socket connection broken") + chunks.append(chunk) + bytes_recd = bytes_recd + len(chunk) + return b''.join(chunks) + + def join(self, channel): + self.rawsend(bytes(f"JOIN {channel}\n", "UTF-8")) + def kick(self, channel, nick): + self.rawsend(bytes(f"KICK {channel} {nick}\n", "UTF-8")) + def setnick(self, nick): + self.rawsend(bytes(f"NICK {nick}\n", "UTF-8")) + + def command_parser(self, line): + args = line.split() + if len(args) > 1 and args[0] == "PING": + self.rawsend(bytes('PONG ' + args[1] + '\r\n', "UTF-8")) + return '' + if len(args) > 2 and args[1] == "INVITE": + self.join(args[3][1:]) + return '' + if len(args) > 2 and args[1] == "PRIVMSG": + return args + else: + return '' + + def get_response(self, msglen=1): + resp = self.recv(msglen) + try: + resp = resp.decode("UTF-8") + except: + return '' + + return resp + + def shutdown(self, sig=None, frame=None, msg=None): + self.rawsend(b"QUIT Catched SIGINT\n") if msg == None else self.rawsend(bytes(f"QUIT bye\n", "UTF-8")) + self.sock.shutdown(2) #SHUT_RDWR + self.sock.close() + sys.exit(0) + diff --git a/pygbot.py b/pygbot.py new file mode 100755 index 0000000..6eabd03 --- /dev/null +++ b/pygbot.py @@ -0,0 +1,43 @@ +#!/usr/bin/python3 + +import time +import signal +import irc +import commands +import config as c + +config = c.readconfig("config.json") + +nick = c.pygbot.nick = c.readobj(config, "nick") +host = c.pygbot.host = c.readobj(config, "host") +port = c.pygbot.port = c.readobj(config, "port") +tls = c.pygbot.tls = c.readobj(config, "tls") +channels = c.pygbot.channels = c.readobj(config, "channels") +admins = c.pygbot.admins = c.readobj(config, "admins") +prefix = c.pygbot.prefix = c.readobj(config, "prefix") + +bot = irc.IRC() + +signal.signal(signal.SIGINT, bot.shutdown) + +bot.connect(host, port, nick, nick, nick, None, tls) +time.sleep(1) +for channel in channels: + bot.join(channel) + +line = '' + +while True: + resp=bot.get_response() + if resp != '\n' and resp != '\r': + line += resp + print(resp, end='') + else: + print('\r\n', end='') + parsedline = bot.command_parser(line) + if len(parsedline) > 1: + user, server_command, channel, message = parsedline[0][1:], parsedline[1], parsedline[2], ' '.join(parsedline[3:])[1:] + commands.bot_command_parser(config, bot, user, channel, message) + line = '' + + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..dc1536f --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +requests +bs4 diff --git a/web.py b/web.py new file mode 100644 index 0000000..c279187 --- /dev/null +++ b/web.py @@ -0,0 +1,17 @@ +import re +import requests +from bs4 import BeautifulSoup + +def gettitle(bot, channel, message): + try: + link = ' '.join(message.split()[1:]) + iflinkok = re.search("^http", link) + if iflinkok != None: + page = requests.get(link) + soup = BeautifulSoup(page.text, 'html.parser') + title = soup.title.string + bot.send(channel, title) + else: + bot.send(channel, "Failed to get title") + except: + bot.send(channel, "Failed to get title") diff --git a/youtube.py b/youtube.py new file mode 100644 index 0000000..ba2cd06 --- /dev/null +++ b/youtube.py @@ -0,0 +1,17 @@ +import re +import requests +from bs4 import BeautifulSoup + +def gettitle(bot, channel, message): + try: + link = ' '.join(message.split()[1:]) + iflinkok = re.search("^http", link) + if iflinkok != None: + page = requests.get(link) + soup = BeautifulSoup(page.text, 'html.parser') + title = soup.find("meta", itemprop="name")["content"] + bot.send(channel, title) + else: + bot.send(channel, "Failed to get title") + except: + bot.send(channel, "Failed to get title")