Initial commit

This commit is contained in:
g1n 2021-11-27 18:32:59 +00:00
commit f14f148901
12 changed files with 317 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*~
__pycache__
config.json
venv

12
LICENSE Normal file
View File

@ -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.

15
README.org Normal file
View File

@ -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

18
TODO.org Normal file
View File

@ -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

78
commands.py Normal file
View File

@ -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")

1
config.json.sample Normal file
View File

@ -0,0 +1 @@
{"nick": "pygbot", "host": "serveraddress", "port": 6697, "tls": true, "prefix": ".", "channels": ["#channel"], "admins": ["yournickname"]}

28
config.py Normal file
View File

@ -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 = []

82
irc.py Normal file
View File

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

43
pygbot.py Executable file
View File

@ -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 = ''

2
requirements.txt Normal file
View File

@ -0,0 +1,2 @@
requests
bs4

17
web.py Normal file
View File

@ -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")

17
youtube.py Normal file
View File

@ -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")