depot/packages/servers/ircbot/main.py

85 lines
2 KiB
Python
Raw Normal View History

import os
import sys
2022-09-24 17:51:13 +03:00
import justirc
import importlib
class EventHandler(object):
def on_message(bot, event):
...
def on_reload(bot):
...
2022-09-24 17:51:13 +03:00
def main():
config = dict(
debug=False,
nick='smith',
channel='#general',
server='irc.privatevoid.net',
port=6697,
tls=True,
)
2022-09-24 17:56:08 +03:00
run_bot(config)
2022-09-24 17:51:13 +03:00
def shutdown_bot_hooks(bot):
for name, hook in bot.hooks:
try:
hook.EventHandler.on_reload(bot)
except Exception as e:
print(f'exception running hook {name}: {e}')
2022-09-24 17:56:08 +03:00
def run_bot(c):
bot = justirc.IRCConnection()
2022-09-24 17:51:13 +03:00
bot.db = () # TODO: store a database handle here
bot.hooks = [] # storage for all bot hooks
2022-09-24 17:56:08 +03:00
if c['debug']:
@bot.on('packet')
def new_packet(e):
print(e.packet)
2022-09-24 17:51:13 +03:00
@bot.on('reload-hooks')
def reload_hooks(e):
shutdown_bot_hooks(bot)
bot.hooks.clear()
for path in filter(lambda h: h[-3:] == '.py', os.listdir('hooks')):
name = '.'.join(['hooks', path.split('.py')[0]])
if name in sys.modules.keys():
del sys.modules[name]
try:
mod = importlib.import_module(name, package=name)
bot.hooks.append((name, mod))
except Exception as e:
print(f'failed to load hook {name}: {e}')
@bot.on('quit')
def quit(e):
shutdown_bot_hooks(bot)
exit(0)
2022-09-24 17:51:13 +03:00
@bot.on('connect')
def connect(e):
2022-09-24 17:56:08 +03:00
bot.send_line(f'NICK {c["nick"]}')
bot.send_line(f'USER {c["nick"]} 8 * {c["nick"]}')
bot.emit('reload-hooks')
2022-09-24 17:51:13 +03:00
@bot.on('welcome')
def welcome(e):
bot.join_channel(c['channel'])
2022-09-24 17:51:13 +03:00
@bot.on('message')
def message(e):
for name, hook in bot.hooks:
try:
hook.EventHandler.on_message(bot, e)
except Exception as e:
print(f'exception running hook {name}: {e}')
2022-09-24 17:51:13 +03:00
bot.connect(c['server'], port=c['port'], tls=c['tls'])
2022-09-24 17:51:13 +03:00
bot.run_loop()
if __name__ == '__main__':
main()