This commit is contained in:
.[d]. 2023-03-15 12:24:49 -05:00
parent 1133bd61e5
commit 845128801b
53 changed files with 3400 additions and 878 deletions

@ -184,6 +184,8 @@ export HYDRA_HOME=#b0tsh0p
- openai plugin is written and functions, the setup automation has omitted it's incorporation until baselined
- convert escaped irc color codes back to terminal codes for ansi_plugin.py
# [ `CHANGELOG`/`VERSION HISTORY` ]
# **v2.9**
- overhaul - too much to name
# **v2.8**
- boombox - youtube bug listing spotify.
- boombox - open.spotify.com url was not pulling page title correctlyl

@ -1,13 +1,40 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
import irc3,re,os,sys,asyncio
from datetime import datetime
from irc3.plugins.command import command
from irc3.plugins.cron import cron
from datetime import datetime
import irc3,re,os,asyncio
from plugins.tool_colors_plugin import colorform as print
from plugins.tool_log_plugin import FOG
###########################################################################################
dr1p_home=os.environ['ANSI_HOME']
###########################################################################################
def getenv(s):
try:
s = os.environ[s]
return s
except:
fog=FOG().fog
error_type="environmental variable error"
error_reason=f"exported {s} not found"
fog(f"{error_type}: {error_reason}")
sys.exit(1)
###########################################################################################
###########################################################################################
dr1p_home=getenv('ANSI_HOME')
###########################################################################################
###########################################################################################
class EIO():
#######################################################################################
#######################################################################################
def __init__(self):
self.regex=re.compile("\x03(?:\d{1,2}(?:,\d{1,2})?)?",re.UNICODE)
self.buffering=False
@ -16,13 +43,14 @@ class EIO():
self.cycle=0
self.sorted=[]
self.sorting=[]
#######################################################################################
#######################################################################################
def push(self,nick,channel,dataline,hexdataline):
###################################################################################
if self.buffering==False:
self.sorting.append([nick,True,channel,[datetime.now().timestamp()],[dataline],[hexdataline]])
self.buffering=True
###################################################################################
try:
for x in self.sorting:
if x[0]==nick:
@ -30,17 +58,25 @@ class EIO():
x[3].append(datetime.now().timestamp())
x[4].append(dataline)
x[5].append(hexdataline)
###################################################################################
except Exception as e:
pass
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot=bot
self.bot.eio=EIO()
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg(self,mask=None,event=None,target=None,data=None,**kw):
if mask.nick==self.bot.nick: return
@ -50,7 +86,10 @@ class Plugin:
for c in data:
hexdataline+=hex(ord(c))[2:].upper()
self.bot.eio.push(mask.nick,target,data,hexdataline)
####################################################################################### EOF
###########################################################################################
###########################################################################################
@cron('* * * * * */1')
def eio_cron(bot):
eio=bot.eio
@ -80,21 +119,27 @@ def eio_cron(bot):
eio_sorted=eio.sorted[-1]
for dataline in eio_sorted[2]:
bot.privmsg(dr1p_home,dataline)
###################################################################################
###################################################################################
SELF_DISABLE_FLAG=True
try:
for eio_sorting in eio.sorting:
for isnotdisabled in eio_sorting[1]:
if isnotdisabled: SELF_DISABLE_FLAG=False
###################################################################################
except:
pass
###################################################################################
###################################################################################
if SELF_DISABLE_FLAG:
msg=f'<<< ________ansi_plugin >>> [ event: control code buffer ]'
msg+=' - '
msg+='finished, disabling cleanup cronjob'
print(msg)
bot.eio.buffering=False
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,31 +1,58 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.cron import cron
import irc3, os
import irc3, os, sys
from plugins.tool_log_plugin import FOG
###########################################################################################
###########################################################################################
NICKSERV_USERNAME=os.environ['NICKSERV_USERNAME']
NICKSERV_PASSWORD=os.environ['NICKSERV_PASSWORD']
def getenv(s):
try:
s = os.environ[s]
return s
except:
fog=FOG().fog
error_type="environmental variable error"
error_reason=f"exported {s} not found"
fog(f"{error_type}: {error_reason}")
sys.exit(1)
###########################################################################################
###########################################################################################
NICKSERV_USERNAME=getenv('NICKSERV_USERNAME')
NICKSERV_PASSWORD=getenv('NICKSERV_PASSWORD')
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self,bot):
self.bot=bot
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.CONNECTED)
def connected(self, **kw):
MSG=f"identify {NICKSERV_USERNAME} {NICKSERV_PASSWORD}"
self.bot.privmsg('NICKSERV',MSG)
#######################################################################################
#######################################################################################
###########################################################################################
###########################################################################################
@cron('*/1 * * * *')
def cron_auth(bot):
if not bot.nick==bot.original_nick:
MSG=f"identify {NICKSERV_USERNAME} {NICKSERV_PASSWORD}"
bot.privmsg('NICKSERV',MSG)
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
from irc3.utils import IrcString
import irc3
@ -10,12 +12,21 @@ import functools
from random import shuffle
import string
from irc3.plugins.cron import cron
###########################################################################################
###########################################################################################
USER_STRING_MATCH = re.compile('(.+)!(.+)@(.+)')
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
###########################################################################################
#######################################################################################
#######################################################################################
def __init__(self,bot):
self.bot=bot
staff_set=set()
@ -34,7 +45,10 @@ class Plugin:
for hostname in self.bot.staff_list:
if not current_masks.get(hostname):
self.bot.config['irc3.plugins.command.masks'][hostname] = "staff"
#######################################################################################
#######################################################################################
@irc3.extend
def check_if_ignored(self, hostmask):
global_hostmask = hostmask.replace(hostmask.nick, ".+")
@ -47,19 +61,10 @@ class Plugin:
if nick_pattern.match(mask):
return True
return False
#######################################################################################
@irc3.event(irc3.rfc.CONNECTED)
def _add_hostmask(self, *args, **kwargs):
def handle_who(self, response):
result = response.result()
self.bot.hostmask = result.get('mask')
task = self.bot.who(self.bot.get_nick())
task.add_done_callback(functools.partial(handle_who, self))
opper_password = self.bot.config.get("opper_password")
opper_username = self.bot.config.get("opper_username")
self.bot.send_line(f"GOD {opper_username} {opper_password}")
self.bot.privmsg("nickserv", f"IDENTIFY {self.bot.nick} {opper_password}")
#######################################################################################
@irc3.event(irc3.rfc.JOIN)
def auto_kick_handler(self, mask, channel, **kw):
msg = "g1mp'n ain't easy unless you're maple"
@ -67,30 +72,41 @@ class Plugin:
cmd = f"MODE {channel} +b {mask.nick}!*@*"
self.bot.send(cmd)
self.bot.kick(channel, mask.nick, msg)
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def mdeban(self, mask, target, args):
"""removes all present bans from channel
%%mdeban
"""
self.target=target
###############################################################################
###############################################################################
def handle_bans(self, response):
result = response.result()
[ self.bot.send(f'MODE {self.target} -b {x["mask"]}') for x in result['bans'] ]
###############################################################################
###############################################################################
try:
task = self.bot.channel_bans(self.target)
task.add_done_callback(functools.partial(handle_bans, self))
except Exception as e:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def lockdown(self, mask, target, args):
"""lockdown channel
%%lockdown
"""
###############################################################################
try:
yek=list(string.ascii_letters+string.digits)
shuffle(yek)
@ -98,13 +114,15 @@ class Plugin:
self.mv(mask,target,args)
except Exception as e:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def unlockdown(self, mask, target, args):
"""unlockdown channel
%%unlockdown
"""
###############################################################################
try:
self.bot.send(f'MODE {target} -mik')
except Exception as e:
@ -117,48 +135,68 @@ class Plugin:
"""
channel=args.get('<channel>')
hostmask=args.get('<hostmask>')
###############################################################################
try:
self.bot.send(f'MODE {channel} -b {hostmask}')
except Exception as e:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def ban(self, mask, target, args):
"""bans user from channel
%%ban <nick>
"""
self.target=target
###############################################################################
###############################################################################
def handle_who(self, response):
result = response.result()
self.bot.send(f"MODE {self.target} +b *!{result['user']}@*")
###############################################################################
###############################################################################
try:
USER=args['<nick>']
task = self.bot.who(USER)
task.add_done_callback(functools.partial(handle_who, self))
except Exception as e:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def mban(self, mask, target, args):
"""Bans all present users from channel
%%mban
"""
self.target=target
###############################################################################
###############################################################################
def handle_who(self, response):
result = response.result()
self.bot.send(f"MODE {self.target} +b *!{result['user']}@*")
###############################################################################
###############################################################################
try:
for USER in self.bot.channels[target]:
task = self.bot.who(USER)
task.add_done_callback(functools.partial(handle_who, self))
except Exception as e:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def mkick(self, mask, target, args):
"""Kicks all present users from channel
@ -169,7 +207,10 @@ class Plugin:
[self.bot.kick(target,x,self.bot.emo(msg)) for x in self.bot.channels[target]]
except Exception as e:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def kick(self, mask, target, args):
"""Kicks user from channel
@ -181,7 +222,10 @@ class Plugin:
self.bot.kick(target,nick,self.bot.emo(msg))
except Exception as e:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def mv(self, mask, target, args):
"""Voices all present users in channel
@ -191,7 +235,10 @@ class Plugin:
[ self.bot.send(f'MODE {target} +v {x}') for x in self.bot.channels[target]]
except Exception as e:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def mdv(self, mask, target, args):
"""DeVoices all present users in channel
@ -201,7 +248,10 @@ class Plugin:
[ self.bot.send(f'MODE {target} -v {x}') for x in self.bot.channels[target]]
except:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def v(self, mask, target, args):
"""Voices user in channel
@ -212,7 +262,10 @@ class Plugin:
self.bot.send(f'MODE {target} +v {nick}')
except Exception as e:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def dv(self, mask, target, args):
"""DeVoices user in channel
@ -223,7 +276,10 @@ class Plugin:
self.bot.send(f'MODE {target} -v {nick}')
except:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def mop(self, mask, target, args):
"""Ops all present users in channel
@ -233,7 +289,10 @@ class Plugin:
[ self.bot.send(f'MODE {target} +o {x}') for x in self.bot.channels[target]]
except Exception as e:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def mdeop(self, mask, target, args):
"""DeOps all present users in channel
@ -243,7 +302,10 @@ class Plugin:
[ self.bot.send(f'MODE {target} -o {x}') for x in self.bot.channels[target]]
except:
pass
###########################################################################################
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def op(self, mask, target, args):
"""Ops user
@ -254,7 +316,10 @@ class Plugin:
self.bot.send(f'MODE {target} +o {nick}')
except:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def deop(self, mask, target, args):
"""Deops user
@ -265,7 +330,10 @@ class Plugin:
self.bot.send(f'MODE {target} -o {nick}')
except:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def mhop(self, mask, target, args):
"""Hops all present users in channel
@ -275,7 +343,10 @@ class Plugin:
[ self.bot.send(f'MODE {target} +h {x}') for x in self.bot.channels[target]]
except Exception as e:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def mdehop(self, mask, target, args):
"""DeHops all present users in channel
@ -285,7 +356,10 @@ class Plugin:
[ self.bot.send(f'MODE {target} -h {x}') for x in self.bot.channels[target]]
except:
pass
###########################################################################################
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def hop(self, mask, target, args):
"""Hops user
@ -296,7 +370,10 @@ class Plugin:
self.bot.send(f'MODE {target} +h {nick}')
except:
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def dehop(self, mask, target, args):
"""Dehops user
@ -307,7 +384,10 @@ class Plugin:
self.bot.send(f'MODE {target} -h {nick}')
except:
pass
#######################################################################################
#######################################################################################
@command(permission="admin", show_in_help_list=False)
def stats(self, mask, target, args):
"""Stats
@ -320,37 +400,61 @@ class Plugin:
for mode, nicknames in sorted(channel.modes.items()):
message += f' - {mode}({len(nicknames)})'
self.bot.privmsg(target, message)
#######################################################################################
@command(permission='admin', public=False, show_in_help_list=False)
def restart(self, mask, target, args):
"""restart
%%restart
#######################################################################################
@command(permission='admin', show_in_help_list=False)
def reload(self, mask, target, args):
"""reload
%%reload <noise>
"""
self.bot.privmsg(target, 'BOT RESTARTING')
time.sleep(1)
os.execl(sys.executable, sys.executable, *sys.argv)
noise = f"plugins.{args.get('<noise>')}_plugin"
self.bot.privmsg(target, f'reloading plugin: {noise}')
try:
self.bot.reload(noise)
except:
self.bot.privmsg(target, f'error: reloading plugin: {noise} failed')
#######################################################################################
#######################################################################################
@command(permission='admin', public=False, show_in_help_list=False)
def uptime(self, mask, target, args):
pass
#######################################################################################
#######################################################################################
@command(permission='admin', public=False, show_in_help_list=False)
def ping(self, mask, target, args):
pass
#######################################################################################
#######################################################################################
@command(permission='staff', public=True, show_in_help_list=False)
def staff(self, mask, target, args):
"""staff
%%staff <noise>...
"""
###################################################################################
###################################################################################
def __staff_list(self, mask, target, args):
current_masks = self.bot.config.get("irc3.plugins.command.masks", "")
current_staff_list = [k for k,v in current_masks.items() if v in ["all_permissions", "staff"]]
self.bot.privmsg(target, "\x02༺Staff List༻\x0F\x02\x0303 > \x0F\x0302{}".format(", ".join(current_staff_list)))
###################################################################################
###################################################################################
def __staff_del(self, mask, target, args):
###############################################################################
###############################################################################
def del_hostmask(self, host_string):
current_masks = self.bot.config.get("irc3.plugins.command.masks", "")
if host_string in current_masks.keys():
@ -368,14 +472,20 @@ class Plugin:
pass # pass for brevarity
else:
self.bot.privmsg(target, f'{host_string} is not a staff member')
###############################################################################
###############################################################################
def handle_who(self, response):
result = response.result()
nick = result.get("nick")
mask = result.get('mask')
host_string = mask.replace(nick,"*")
del_hostmask(self, host_string)
###############################################################################
###############################################################################
nick = args.get("<nick>")
match_list = USER_STRING_MATCH.findall(nick)
if match_list and len(match_list[0]) == 3:
@ -385,9 +495,15 @@ class Plugin:
task = self.bot.who(nick)
task.add_done_callback(functools.partial(handle_who, self))
return
###################################################################################
###################################################################################
def __staff_add(self, mask, target, args):
###############################################################################
###############################################################################
def add_hostmask(self, host_string):
current_masks = self.bot.config.get("irc3.plugins.command.masks", "")
if host_string in current_masks.keys():
@ -400,17 +516,26 @@ class Plugin:
self.bot.staff_list.add(host_string)
self.bot.db.setlist("staff_list", self.bot.staff_list)
self.bot.privmsg(target, f'{host_string} added to staff')
###############################################################################
###############################################################################
def handle_who(self, response):
result = response.result()
nick = result.get("nick")
mask = result.get('mask')
host_string = mask.replace(nick,"*")
add_hostmask(self, host_string)
###############################################################################
###############################################################################
nick = args.get("<nick>")
match_list = USER_STRING_MATCH.findall(nick)
###############################################################################
###############################################################################
if match_list and len(match_list[0]) == 3:
add_hostmask(self, nick)
return
@ -418,10 +543,16 @@ class Plugin:
task = self.bot.who(nick)
task.add_done_callback(functools.partial(handle_who, self))
return
###################################################################################
###################################################################################
cmd = ' '.join(args['<noise>'])[0]
args = ' '.join(args['<noise>'])[1:]
###################################################################################
###################################################################################
if not cmd:
self.bot.privmsg(target, "please specify add/del/list")
elif cmd in ["d","del","delete","remove"]:
@ -430,5 +561,6 @@ class Plugin:
__staff_list(self, mask, target, args)
elif cmd in ["w", "write","a", "add"]:
__staff_add(self, mask, target, args)
###################################################################################
####################################################################################### EOF
###########################################################################################
####################################################################################### EOF

File diff suppressed because it is too large Load Diff

@ -1,27 +1,44 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
???DISCORD???
???TELEGRAM???
???MATRIX???
###########################################################################################
###########################################################################################
import asyncio
###########################################################################################
###########################################################################################
import irc3
from irc3.plugins.command import command
###########################################################################################
###########################################################################################
from plugins.tool_bus_plugin import BUS
from plugins.tool_colors_plugin import colorform as print
from plugins.tool_dims_plugin import dims
from plugins.tool_guds_plugin import guds
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@irc3.extend
@command(permission='admin', public=False, show_in_help_list=False)
async def listrooms(self,sender_netroomchan,sender_user,target,):
@ -31,19 +48,46 @@ class Plugin:
results=[]
result=dims.list_channels()
for _ in result:
#########################################
if SERVICES_MATRIX and _.startswith('!'):
#########################################
room=f'__matrix: {_}'
#######################
elif _.startswith('#'):
#######################
room=f'_____irc: {_}'
#############################################
elif SERVICES_TELEGRAM and _.startswith('$'):
#############################################
room=f'telegram: {_}'
############################################
elif SERVICES_DISCORD and _.startswith('^'):
############################################
room=f'_discord: {_}'
###############################################################################
###############################################################################
msg=f'<<< _____cmd_irc_plugin >>> [ ({sender_netroomchan})({sender_user})(listrooms)->({target}) ] - {room}'
print(msg)
results.append(room)
###################################################################################
###################################################################################
return results
#######################################################################################
#######################################################################################
@irc3.extend
@command(permission='admin', public=False, show_in_help_list=False)
async def listbridges(self,sender_netroomchan,sender_user,target,):
@ -76,7 +120,10 @@ class Plugin:
else:
results.append(f"{channel}")
return results
#######################################################################################
#######################################################################################
@irc3.extend
@command(permission='admin', public=False, show_in_help_list=False)
async def addbridge(self,mask,target,args):
@ -96,7 +143,10 @@ class Plugin:
msg=f'<<< ________dims_plugin >>> [ addbridge ] - {src_outbound} -> {dest_inbound} - {status}'
print(msg)
return results
#######################################################################################
#######################################################################################
@irc3.extend
@command(permission='admin', public=False, show_in_help_list=False)
async def delbridge(self,mask,target,args):
@ -116,7 +166,10 @@ class Plugin:
msg=f'<<< ________dims_plugin >>> [ addbridge ] - {src_outbound} -> {dest_inbound} - {status}'
print(msg)
return results
#######################################################################################
#######################################################################################
@irc3.extend
@command(permission='admin', public=False, show_in_help_list=False)
async def blackhole(self,mask,target,args):
@ -134,6 +187,9 @@ class Plugin:
self.blackhole.append(entry)
return self.blackhole
###################################################################################
###################################################################################
src_blackhole=noise.split()[0]
command=noise.split()[1]
results=[]
@ -142,30 +198,47 @@ class Plugin:
msg=f'<<< ________dims_plugin >>> [ addblackhole ] - {src_blackhole}'
print(msg)
return results
#######################################################################################
#######################################################################################
@irc3.extend
@command(permission='admin', public=False, show_in_help_list=False)
async def purgebridges(self, mask=None, target=None, data=None, sender_user=None, sender_netroomchan=None, **kw):
"""purgebridges - erases channel/room message history across nets
%%purgebridges
"""
####################
if SERVICES_DISCORD:
####################
msg=f'<<< _____cmd_irc_plugin >>> [ ({mask.nick}{target}).purgebridges()->({target}) ] - purging'
print(msg)
from plugins.net_discord_plugin import d_discord_cmd
d_discord_cmd(target,"purgebridges")
#####
else:
#####
msg=f'<<< _____cmd_irc_plugin >>> [ ({mask.nick}{target}).purgebridges()->({target}) ] - command disabled, not servicing discord atm'
print(msg)
###################################################################### NET IRC - MAIN [4/4]
###################################################################### NET IRC - MAIN [4/4]
async def _d_cmd_irc(sender_netroomchan,sender_user,target,cmd,) -> None:
#######################################################################################
result=(await eval(f"guds.memory('ircbot').{cmd}")(sender_netroomchan=sender_netroomchan,sender_user=sender_user,target=target,cmd=cmd,))
#######################################################################################
bridgedbus=(BUS(['#b0tsh0p','!OftXgmqAFOPEatmvLU:pcriot.org'])) # hardcoded channel, audit - maybe from debugging
await bridgedbus.output([sender_netroomchan,sender_user],result) # hardcoded channel, audit - maybe from debugging
###########################################################################################
###########################################################################################
def d_cmd_irc(sender_netroomchan,sender_user,target,cmd,):
self=guds.memory('ircbot')
asyncio.run_coroutine_threadsafe(_d_cmd_irc(sender_netroomchan,sender_user,target,cmd,),self.loop)
####################################################################################### EOF#.[d].
###########################################################################################
####################################################################################### EOF

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.compat import asyncio
from irc3 import utils
from collections import defaultdict
@ -11,6 +13,10 @@ import shlex
import irc3
import sys
import re
###########################################################################################
###########################################################################################
__doc__ = '''
==========================================
:mod:`irc3.plugins.command` Command plugin
@ -164,31 +170,46 @@ be called via all three names.
'''
###########################################################################################
###########################################################################################
class free_policy:
"""Default policy"""
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.context = bot
#######################################################################################
#######################################################################################
def __call__(self, predicates, meth, client, target, args, **kwargs):
return meth(client, target, args)
###########################################################################################
###########################################################################################
class mask_based_policy:
"""Allow only valid masks. Able to take care or permissions"""
key = __name__ + '.masks'
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.context = bot
self.log = logging.getLogger(__name__)
self.log.debug('Masks: %r', self.masks)
#######################################################################################
#######################################################################################
@property
def masks(self):
masks = self.context.config[self.key]
if hasattr(self.context, 'db'):
# update config with storage values
try:
value = self.context.db[self]
except KeyError:
@ -198,6 +219,9 @@ class mask_based_policy:
masks.update(value)
return masks
#######################################################################################
#######################################################################################
def has_permission(self, mask, permission):
if permission is None:
return True
@ -210,6 +234,9 @@ class mask_based_policy:
return True
return False
#######################################################################################
#######################################################################################
def __call__(self, predicates, meth, client, target, args, **kwargs):
if self.has_permission(client, predicates.get('permission')):
return meth(client, target, args)
@ -218,12 +245,15 @@ class mask_based_policy:
client.nick,
'You are not allowed to use the %r command' % cmd_name)
###########################################################################################
###########################################################################################
def attach_command(func, depth=2, **predicates):
commands = predicates.pop('commands',
'irc3.plugins.command.Commands')
category = predicates.pop('venusian_category',
'irc3.plugins.command')
commands = predicates.pop('commands','irc3.plugins.command.Commands')
category = predicates.pop('venusian_category','irc3.plugins.command')
#######################################################################################
#######################################################################################
def callback(context, name, ob):
obj = context.context
@ -244,9 +274,14 @@ def attach_command(func, depth=2, **predicates):
obj.log.debug('Register command %r %r', cmd_name, aliases)
else:
obj.log.debug('Register command %r', cmd_name)
info = venusian.attach(func, callback,
category=category, depth=depth)
#######################################################################################
#######################################################################################
info = venusian.attach(func, callback,category=category, depth=depth)
###########################################################################################
###########################################################################################
def command(*func, **predicates):
if func:
@ -259,6 +294,8 @@ def command(*func, **predicates):
return func
return wrapper
###########################################################################################
###########################################################################################
@irc3.plugin
class Commands(dict):
@ -271,6 +308,9 @@ class Commands(dict):
default_policy = free_policy
case_sensitive = False
#######################################################################################
#######################################################################################
def __init__(self, context):
self.context = context
module = self.__class__.__module__
@ -278,34 +318,42 @@ class Commands(dict):
self.log = logging.getLogger(module)
self.log.debug('Config: %r', config)
if 'cmd' in context.config: # in case of
if 'cmd' in context.config:
config['cmd'] = context.config['cmd']
context.config['cmd'] = self.cmd = config.get('cmd', '!')
context.config['re_cmd'] = re.escape(self.cmd)
self.use_shlex = self.config.get('use_shlex', True)
self.antiflood = self.config.get('antiflood', False)
self.case_sensitive = self.config.get('casesensitive',
self.case_sensitive)
self.case_sensitive = self.config.get('casesensitive',self.case_sensitive)
guard = utils.maybedotted(config.get('guard', self.default_policy))
self.log.debug('Guard: %s', guard.__name__)
self.guard = guard(context)
self.error_format = utils.maybedotted(config.get('error_format',
"Invalid arguments.".format))
self.error_format = utils.maybedotted(config.get('error_format',"Invalid arguments.".format))
self.handles = defaultdict(Done)
self.tasks = defaultdict(Done)
self.aliases = {}
#######################################################################################
#######################################################################################
def split_command(self, data, use_shlex=None):
if not data:
return []
return shlex.split(data) if use_shlex else data.split(' ')
#######################################################################################
#######################################################################################
@irc3.event((r'(@(?P<tags>\S+) )?:(?P<mask>\S+) PRIVMSG (?P<target>\S+) '
r':{re_cmd}(?P<cmd>[\w-]+)(\s+(?P<data>\S.*)|(\s*$))'))
r':{re_cmd}(?P<cmd>[\w-]+)(\s+(?P<data>\S.*)|(\s*$))'))
#######################################################################################
#######################################################################################
def on_command(self, cmd, mask=None, target=None, client=None, **kw):
if not self.case_sensitive:
cmd = cmd.lower()
@ -319,16 +367,18 @@ class Commands(dict):
else:
return self.do_command(predicates, meth, mask, target, **kw)
#######################################################################################
#######################################################################################
def do_command(self, predicates, meth, client, target, data=None, **kw):
nick = self.context.nick or '-'
to = client.nick if target == nick else target
doc = meth.__doc__ or ''
doc = [line.strip() for line in doc.strip().split('\n')]
doc = [nick + ' ' + line.strip('%%')
for line in doc if line.startswith('%%')]
doc = [nick + ' ' + line.strip('%%') for line in doc if line.startswith('%%')]
doc = 'Usage:' + '\n ' + '\n '.join(doc)
if data:
if not isinstance(data, str): # pragma: no cover
if not isinstance(data, str):
encoding = self.context.encoding
data = data.encode(encoding)
try:
@ -348,8 +398,7 @@ class Commands(dict):
if not predicates.get('quiet', False):
args = {'cmd': cmd_name, 'args': data,
'args_str': " ".join(data), 'exc': exc}
error_format = predicates.get('error_format',
self.error_format)
error_format = predicates.get('error_format',self.error_format)
self.context.privmsg(to, error_format(**args))
else:
uid = (cmd_name, to)
@ -364,9 +413,7 @@ class Commands(dict):
client if use_client else client.nick,
"Please be patient and don't flood me", nowait=True)
else:
# get command result
res = self.guard(predicates, meth, client, target, args=args)
callback = functools.partial(self.command_callback, uid, to)
if res is not None:
coros = (
@ -376,16 +423,17 @@ class Commands(dict):
if any(coros):
task = asyncio.ensure_future(
res, loop=self.context.loop)
# use a callback if command is a coroutine
task.add_done_callback(callback)
self.tasks[uid] = task
return task
else:
# no callback needed
callback(res)
#######################################################################################
#######################################################################################
def command_callback(self, uid, to, msgs):
if isinstance(msgs, asyncio.Future): # pragma: no cover
if isinstance(msgs, asyncio.Future):
msgs = msgs.result()
if msgs is not None:
def iterator(msgs):
@ -397,6 +445,9 @@ class Commands(dict):
if handle is not None:
self.handles[uid] = handle
#######################################################################################
#######################################################################################
@command
def help(self, mask, target, args):
"""Show help
@ -434,11 +485,11 @@ class Commands(dict):
yield 'Aliases: {0}'.format(','.join(sorted(aliases)))
else:
yield ('No such command. Try %shelp for an '
'overview of all commands.'
% self.context.config.cmd)
'overview of all commands.'
% self.context.config.cmd)
else:
cmds = sorted((k for (k, (p, m)) in self.items()
if p.get('show_in_help_list', True)))
if p.get('show_in_help_list', True)))
cmds_str = ', '.join([self.cmd + k for k in cmds])
lines = utils.split_message(
'Available commands: %s ' % cmds_str, 160)
@ -448,15 +499,22 @@ class Commands(dict):
if url:
yield 'Full help is available at ' + url
#######################################################################################
#######################################################################################
def __repr__(self):
return '<Commands %s>' % sorted([self.cmd + k for k in self.keys()])
###########################################################################################
###########################################################################################
class Done:
def done(self):
return True
###########################################################################################
###########################################################################################
@command(permission='admin', show_in_help_list=False, public=False)
def ping(bot, mask, target, args):
@ -466,6 +524,8 @@ def ping(bot, mask, target, args):
"""
bot.send('NOTICE %(nick)s :PONG %(nick)s!' % dict(nick=mask.nick))
###########################################################################################
###########################################################################################
@command(venusian_category='irc3.debug', show_in_help_list=False)
def quote(bot, mask, target, args):
@ -477,6 +537,8 @@ def quote(bot, mask, target, args):
bot.log.info('quote> %r', msg)
bot.send(msg)
###########################################################################################
###########################################################################################
@command(venusian_category='irc3.debug', show_in_help_list=False)
def reconnect(bot, mask, target, args):
@ -487,6 +549,8 @@ def reconnect(bot, mask, target, args):
plugin = bot.get_plugin(utils.maybedotted('irc3.plugins.core.Core'))
bot.loop.call_soon(plugin.reconnect)
###########################################################################################
###########################################################################################
@irc3.extend
def print_help_page(bot, file=sys.stdout):
@ -505,7 +569,6 @@ def print_help_page(bot, file=sys.stdout):
for name, (predicates, callback) in plugin.items():
commands = modules.setdefault(callback.__module__, [])
commands.append((name, callback, predicates))
for module in sorted(modules):
p(module)
p('=' * len(module))
@ -526,4 +589,6 @@ def print_help_page(bot, file=sys.stdout):
if predicates.get('public', True) is False:
p('*Only available in private.*')
p('')
#.[d].
###########################################################################################
####################################################################################### EOF

@ -1,42 +1,77 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
import sys
from irc3.plugins.command import command
import irc3,os,aiohttp, asyncio, async_timeout
from plugins.tool_log_plugin import FOG
###########################################################################################
###########################################################################################
def getenv(s):
try:
s = os.environ[s]
return s
except:
fog=FOG().fog
error_type="environmental variable error"
error_reason=f"exported {s} not found"
fog(f"{error_type}: {error_reason}")
sys.exit(1)
###########################################################################################
###########################################################################################
CRYPTOCOMPARE_KEY=getenv('CRYPTOCOMPARE_KEY')
###########################################################################################
###########################################################################################
headers = { 'authorization': f'Apikey {CRYPTOCOMPARE_KEY}' }
###########################################################################################
###########################################################################################
dir_path = os.path.dirname(os.path.realpath(__file__))
try:
CRYPTOCOMPARE_KEY = os.environ['CRYPTOCOMPARE_KEY']
headers = { 'authorization': f'Apikey {CRYPTOCOMPARE_KEY}' }
except:
pass
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@command(permission='view')
def cc(self, mask, target, args):
"""Show Crypto Value
%%cc <coin>
"""
###################################################################################
###################################################################################
coin = args['<coin>'].upper()
async def fetch(session, url):
async with async_timeout.timeout(10):
async with session.get(url) as response:
return await response.json()
###################################################################################
###################################################################################
async def grab_url(url):
async with aiohttp.ClientSession(headers=headers) as session:
json_response = await fetch(session, url)
return json_response
###################################################################################
###################################################################################
def parse_coin(response):
try:
task_result, _ = response.result()
@ -46,7 +81,6 @@ class Plugin:
price = rlist[1].get("USD")
price_multi = rlist[2].get("DISPLAY")[coin].get("USD", {})
daily_avg = rlist[0].get("USD")
elif rlist[2].get("USD"):
price_multi = rlist[1].get("DISPLAY")[coin].get("USD", {})
price = rlist[2].get("USD")
@ -57,7 +91,6 @@ class Plugin:
v = v.replace("$","").replace(" ","").replace(",","")
data_dict[k] = v
price_multi = data_dict
X = float(daily_avg) # AVERAGE OF THE DAY
P = float(price_multi.get('PRICE')) # PRICE CURRENTLY
H = float(price_multi.get('HIGHDAY')) # HIGH OF THE DAY
@ -65,7 +98,6 @@ class Plugin:
A = float(price) # AGGREGATED EXCHANGE
Y = float(price_multi.get('CHANGE24HOUR')) # PRICE PERCENT DIFFERENTIAL 24 HOURS AGO
C = float(price_multi.get('CHANGEPCT24HOUR'))
if C <= 0:
C = "\x0304{}\x0F".format(C)
else:
@ -74,7 +106,6 @@ class Plugin:
Y = "\x0304{}\x0F".format(Y)
else:
Y = "\x0303{}\x0F".format(Y)
symbol = price_multi.get('FROMSYMBOL')
msg = "\x02\x0302[ {coin:}/{symbol:} ]\x0F @\x0303${p:,}\x0F ::: H\x0303${h:,}\x0F L\x0303${l:,}\x0F ::: Y${y:} @ %{c:} ::: X\x0303${x:,}\x0F A\x0303${a:,}\x0F".format(coin=coin, symbol=symbol, p=P, h=H, l=L, y=Y,c=C, x=X, a=A)
msg = self.bot.emo(msg)
@ -82,8 +113,10 @@ class Plugin:
except Exception as e:
msg = self.bot.emo('their api is glitching: check back later')
self.bot.privmsg(target, msg)
###################################################################################
###################################################################################
def process_lookups(response):
try:
html = response.result()
@ -100,15 +133,17 @@ class Plugin:
price_multi_url = "https://min-api.cryptocompare.com/data/pricemultifull?fsyms={}&tsyms=USD&api_key=94e50805f19646893ee16424918998caad5ec6accff539a23ffee8e546eda4e3".format(coin)
price_url = "https://min-api.cryptocompare.com/data/price?fsym={}&tsyms=USD&api_key=94e50805f19646893ee16424918998caad5ec6accff539a23ffee8e546eda4e3".format(coin)
tasks = [asyncio.ensure_future(grab_url(day_avg_url)),
asyncio.ensure_future(grab_url(price_multi_url)),
asyncio.ensure_future(grab_url(price_url))]
asyncio.ensure_future(grab_url(price_multi_url)),
asyncio.ensure_future(grab_url(price_url))]
task = self.bot.create_task(asyncio.wait(tasks))
task.add_done_callback(parse_coin)
###################################################################################
###################################################################################
url = "https://min-api.cryptocompare.com/data/all/coinlist"
asyncio.ensure_future(grab_url(url), loop=self.bot.loop).add_done_callback(process_lookups)
#######################################################################################
#######################################################################################
asyncio.ensure_future(grab_url(url), \
loop=self.bot.loop).add_done_callback(process_lookups)
###########################################################################################
####################################################################################### EOF#.[d].
####################################################################################### EOF

@ -0,0 +1,53 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
from datetime import datetime as dt
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@classmethod
def reload(cls, old):
return cls(old.bot)
#######################################################################################
#######################################################################################
def before_reload(self):
pass
#######################################################################################
#######################################################################################
def after_reload(self):
pass
#######################################################################################
#######################################################################################
@command(permission='view')
def time(self, mask, target, args):
"""Show local server datetime info
%%time
"""
msg = "LOCAL SERVER TIME: {HOUR}:{MINUTE} {MONTH}/{DAY}/{YEAR}"
TIME = dt.now()
msg = msg.format(HOUR=TIME.hour,MINUTE=TIME.minute,MONTH=TIME.month,DAY=TIME.day,YEAR=TIME.year)
self.bot.privmsg(target,self.bot.emo(msg))
###########################################################################################
####################################################################################### EOF

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*- ########################################################################################### SOF
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
"""# MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ####
#### MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMh+MMMMMMMMMMMMMMhsMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ####
#### MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMm/ oMMMMMMMMMMMMMMm +NMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ####
@ -31,6 +33,9 @@
#### MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNs. -hMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ####
#### MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMdyymMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM #"""
###########################################################################################
###########################################################################################
import os
import re
import subprocess
@ -43,7 +48,8 @@ from irc3.plugins.cron import cron
from plugins.tool_guds_plugin import guds
#######################################################################################################################
###########################################################################################
###########################################################################################
global REASSEMBLY
global iCount
@ -59,29 +65,34 @@ ANSI_HOME='databases/ansi'
if not os.path.exists(ANSI_HOME):
os.mkdir(ANSI_HOME)
###########################################################################################
###########################################################################################
COLOR_SET_A = "\x1b[38;2;196;0;255m"
COLOR_SET_B = "\x1b[38;2;128;64;255m"
COLOR_SET_C = "\x1b[38;2;128;0;255m"
COLOR_SET_D = "\x1b[2;35m"
COLOR_SET_E = "\x1b[2;31m"
#######################################################################################################################
###########################################################################################
###########################################################################################
############
@irc3.plugin
############ ##########################################################################################################
############# #########################################################################################################
###########################################################################################
###########################################################################################
class Plugin:
#############
########################### #######################################################################################
#######################################################################################
#######################################################################################
class HYDRA_FILE_HANDLER():
###########################
###################
###################################################################################
###################################################################################
def __init__(self):
###################
self.txt=[]
self.ans=[]
@ -89,15 +100,17 @@ class Plugin:
self.ptr=[]
########################### #######################################################################################
#######################################################################################
#######################################################################################
class DR1P_STATE_MACHINE():
###########################
FLAGS = ['ESCAPED']
###################
###################################################################################
###################################################################################
def __init__(self):
###################
self.ESCAPED = False
self.ASSEMBLY = False
@ -110,48 +123,51 @@ class Plugin:
self.attr_last = False
self.attr_reset = False
#################
def fog(self, s):
#################
###################################################################################
###################################################################################
def dog(self, s):
if DEBUGGING:
print(s)
##################
###################################################################################
###################################################################################
def flip(self, b):
##################
FLIP = ({'03': '1B5B'})
fog = self.fog
dog = self.dog
if b in FLIP:
fog(f'flp:{b}>{FLIP[b]}')
dog(f'flp:{b}>{FLIP[b]}')
return FLIP[b]
else:
return b
#################
###################################################################################
###################################################################################
def seq(self, b):
#################
global REASSEMBLY
fog = self.fog
fog(f'\033[38;2;0;255;0mseq:{b}')
dog = self.dog
dog(f'\033[38;2;0;255;0mseq:{b}')
if b == "1B5B":
self.ack(flag="ESCAPED")
REASSEMBLY += str(b)
self.ASSEMBLY = False
self.stack = []
if self.interrupt:
if DEBUGGING: fog(f'\033[38;2;255;0;0minterrupted')
if DEBUGGING: dog(f'\033[38;2;255;0;0minterrupted')
if int("30", 16) <= int(str(b), 16) <= int("39", 16):
if DEBUGGING: fog('\n\033[38;2;255;255;255m<<< <<< BINGO - CODES >>> >>>\x1b[\x1b[92m')
if DEBUGGING: dog('\n\033[38;2;255;255;255m<<< <<< BINGO - CODES >>> >>>\x1b[\x1b[92m')
self.stack.append(b)
if DEBUGGING:
fog('')
dog('')
elif b == "2C":
if DEBUGGING: fog('\n\033[38;2;0;255;255m<<< <<< BINGO - DELIMITER >>> >>>\x1b[\x1b[92m')
if DEBUGGING: dog('\n\033[38;2;0;255;255m<<< <<< BINGO - DELIMITER >>> >>>\x1b[\x1b[92m')
self.stack.append(b)
if DEBUGGING: fog('')
if DEBUGGING: dog('')
else:
if self.interrupt == True and len(self.stack) >= 1:
if not b == "1B" or not int("30", 16) <= int(str(b), 16) <= int("39", 16) or not b == "2C":
@ -205,7 +221,7 @@ class Plugin:
except:
self.ASSEMBLY = False
if DEBUGGING:
fog('')
dog('')
if self.ASSEMBLY:
self.stack.append(b)
REASSEMBLY += b
@ -223,11 +239,12 @@ class Plugin:
REASSEMBLY += "1B5B306D0D0A"
return
###############################
def ack(self, flag="", cmd=""):
###############################
###################################################################################
###################################################################################
fog = self.fog
def ack(self, flag="", cmd=""):
dog = self.dog
if cmd == "escaped":
if flag == "ESCAPED":
return 1
@ -237,51 +254,53 @@ class Plugin:
for i, _ in enumerate(self.FLAGS):
if eval(f"self.{self.FLAGS[i]}"):
if DEBUGGING:
fog(f'\033[38;2;0;0;255m{_} FLAG IS {str(eval(f"self.{self.FLAGS[i]}")).upper()}')
dog(f'\033[38;2;0;0;255m{_} FLAG IS {str(eval(f"self.{self.FLAGS[i]}")).upper()}')
else:
if flag in self.FLAGS:
if flag == "ESCAPED":
self.ESCAPED = not self.ESCAPED
if DEBUGGING:
fog(f"ESCAPED flag set {self.ESCAPED}")
dog(f"ESCAPED flag set {self.ESCAPED}")
if self.ESCAPED:
self.interrupt = 1
else:
self.interrupt = 0
#################
###################################################################################
###################################################################################
def fmt(self, b):
#################
b = hex(int(b, 16))[2:].upper().zfill(2)
return b
#################
###################################################################################
###################################################################################
def asm(self, b):
#################
b = self.fmt(b)
b = self.flip(b)
self.seq(b)
##################
###################################################################################
###################################################################################
def push(self, b):
##################
fog = self.fog
dog = self.dog
global iCount
iCount += 1
fog = self.fog
if DEBUGGING: fog(f'{COLOR_SET_B}{str(iCount).zfill(8)} {hex(iCount)[2:].zfill(8).upper()}{COLOR_SET_A}')
dog = self.dog
if DEBUGGING: dog(f'{COLOR_SET_B}{str(iCount).zfill(8)} {hex(iCount)[2:].zfill(8).upper()}{COLOR_SET_A}')
asm = self.asm
self.ack()
asm(b)
########################### #######################################################################################
##################################### #############################################################################
#######################################################################################
#######################################################################################
class ESCAPE_CODE_DETECTION_SYSTEM():
#####################################
###################
def __init__(self):
@ -306,12 +325,13 @@ class Plugin:
self.STRINCREMENT = f"{str(INDEX)}".zfill(8)
self.FILENAME = f"{ANSI_HOME}/{FILE_PREFIX}{self.STRINCREMENT}.txt"
self.f1 = open(self.FILENAME, "w") # file handle f1
self.f1 = open(self.FILENAME, "w")
###################################################################################
###################################################################################
#################################################
def push(self,nick,channel,dataline,hexdataline):
#################################################
if not self.buffering:
self.sorting.append([nick,True,channel,[datetime.now().timestamp()],[dataline],[hexdataline]])
self.sorting[0][3].pop()
@ -328,12 +348,11 @@ class Plugin:
x[5].append(hexdataline)
except Exception as e:
pass
##################################### #############################################################################
######################## ##########################################################################################
#######################################################################################
#######################################################################################
def __init__(self, bot):
########################
self.bot = bot
self.bot.hfh = self.HYDRA_FILE_HANDLER()
@ -346,11 +365,11 @@ class Plugin:
self.DELIMIT=False
self.hexdataline=None
############
#######################################################################################
#######################################################################################
@irc3.extend
###################### ######################################################################################### find every instance of a string within a string
def depumper_reset(self):
######################
self.bot.hfh = guds.memory('HYDRA_FILE_HANDLER')()
self.bot.ecds = guds.memory('ESCAPE_CODE_DETECTION_SYSTEM')()
@ -362,25 +381,25 @@ class Plugin:
global iCount
REASSEMBLY="1B5B306D"
iCount=-1
############
#######################################################################################
#######################################################################################
@irc3.extend
###################### ######################################################################################### find every instance of a string within a string
def findall(self,s,w):
######################
result=[i for i in range(len(s)) if s.startswith(w, i)]
#############
return result
#############
############
#######################################################################################
#######################################################################################
@irc3.extend
####################### ######################################################################################## used to strip a string of escape codes
def stripcodes(self,s):
#######################
codes=[]
buffer=s
@ -402,11 +421,12 @@ class Plugin:
return buffer
#############
############
#######################################################################################
#######################################################################################
@irc3.extend
################################################################################################################ used to make sure a string fits into a space
def padding(self,s,n):
######################
pad=n-len(self.stripcodes(s))
padding=(" "*pad)
@ -416,12 +436,12 @@ class Plugin:
return s
########
############
#######################################################################################
#######################################################################################
@irc3.extend
############################ ######################################################################################
def process_irc_codes(self,ecds):
############################
# self.bot = self
self.ecds = ecds
dsm=self.DR1P_STATE_MACHINE()
@ -430,9 +450,10 @@ class Plugin:
for i in range(0,len(self.ecds.l)):
#########################
# REQUIRES MOTION FROM CRONJOB
#########################
################################
# REQUIRES MOTION FROM CRONJOB #
################################
DYTE=hex(self.ecds.l[i])[2:].zfill(2).upper()
DINT=hex(self.ecds.l[i])
self.processing_byte.append(DYTE)
@ -491,12 +512,11 @@ class Plugin:
return self.ecds.l
#####################
#############################
@irc3.event(irc3.rfc.PRIVMSG)
########################################################################## ########################################
def on_privmsg(self, mask=None, event=None, target=None, data=None, **kw):
##########################################################################
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg(self, mask=None, event=None, target=None, data=None, **kw):
if mask.nick == self.bot.nick: return
self.hexdataline = ''
inverse = self.bot.ecds.REGEX.sub("", data)
@ -505,17 +525,11 @@ class Plugin:
self.hexdataline += hex(ord(c))[2:].upper()
self.bot.ecds.push(mask.nick, target, data, self.hexdataline)
################################################################################################################### DMZ
# DMZ #################################################################################################################
################################################################################################################### DMZ
###########################################################################################
###########################################################################################
######################
@cron('* * * * * */1')
###################### ################################################################################################
###################### ################################################################################################
def ecds_cronjob(bot):
######################
ecds = bot.ecds
@ -548,7 +562,7 @@ def ecds_cronjob(bot):
ecds.sorting.remove(ecds.sorting[z])
ecds_sorted = ecds.sorted[-1]
for dataline in ecds_sorted[2]:
ecds.f1.write(f"{dataline}\n") # file handle f1
ecds.f1.write(f"{dataline}\n")
# bot.privmsg(hydrachan,dataline)
########################
@ -576,15 +590,15 @@ def ecds_cronjob(bot):
ecds.buffering = False
bot.ecds.f1.close() # file handle f1
bot.ecds.f1.close()
print('\x1b[36m'+''*16+'\n\x1b[32mDEPUMPER █\n'+''*16)
try:
ecds.IN__FILE__UTF8_IRC_ARTWORK_TXT = ecds.FILENAME
ecds.OUT_FILE_CP437_ANS_ARTWORK_BIN = ecds.IN__FILE__UTF8_IRC_ARTWORK_TXT+".ans"
ecds.f2 = open(ecds.IN__FILE__UTF8_IRC_ARTWORK_TXT, "rb") # file handle f2
ecds.l = ecds.f2.read() # file handle f2
ecds.f2.close() # file handle f2
ecds.f2 = open(ecds.IN__FILE__UTF8_IRC_ARTWORK_TXT, "rb")
ecds.l = ecds.f2.read()
ecds.f2.close()
except:
print('\n\x1b[31mERROR: NO INPUT BUFFER/FILE')
@ -593,18 +607,16 @@ def ecds_cronjob(bot):
print(chr(27)+"[2J")
print(f'\x1b[36mPROCESSING: {ecds.IN__FILE__UTF8_IRC_ARTWORK_TXT}')
#################################
#################################printhex(main(DR1P_STATE_MACHINE))
#################################
# printhex(main(DR1P_STATE_MACHINE))
###########################
bot.process_irc_codes(ecds)
#################################
#################################
#################################
###########################
irc_bytes = []
for i in range(len(REASSEMBLY)//2):
irc_bytes.append(int(REASSEMBLY[i*2:i*2+2], 16))
bot.ecds.f3 = open(bot.ecds.OUT_FILE_CP437_ANS_ARTWORK_BIN, 'wb') # file handle f3
bot.ecds.f3 = open(bot.ecds.OUT_FILE_CP437_ANS_ARTWORK_BIN, 'wb')
bad_byte_seq = [226, 150, 172]
good_byte_seq = []
rebuilt_bytes = []
@ -634,11 +646,11 @@ def ecds_cronjob(bot):
try:
irc_bytes = bytes(irc_bytes).decode().encode('cp437')
bot.ecds.f3.write(irc_bytes) # file handle f3
bot.ecds.f3.write(irc_bytes)
except Exception as e:
print(f"error: post-codec-conversion: {e}")
bot.ecds.f3.close() # file handle f3
bot.ecds.f3.close()
MSG=f'\x1b[32mSUCCESS:\n'
MSG+=f'\x1b[35mIN < PROCESSED: {bot.ecds.IN__FILE__UTF8_IRC_ARTWORK_TXT}\n'
@ -704,10 +716,12 @@ def ecds_cronjob(bot):
del bot.ecds;
bot.ecds = guds.memory('ESCAPE_CODE_DETECTION_SYSTEM')()
bot.depumper_reset()
###########################################################
###########################################################
################################################################################################################### EOF
###########################################################################################
###########################################################################################
"""# MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMmyydMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ####
#### MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMh- .sNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ####
@ -740,3 +754,6 @@ def ecds_cronjob(bot):
#### MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN+ mMMMMMMMMMMMMMMo /mMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ####
#### MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMshMMMMMMMMMMMMMM+hMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ####
#### MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM #"""
###########################################################################################
####################################################################################### EOF

@ -1,17 +1,29 @@
# -*- coding: utf-8 -*-
####################################################################################### SOF
####################################################################################### SOF
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
"""
- spelling - `alternate ircnicks - direct reference` - done
- messages in instances - right now only a record of 1 is indicated and that is incorrect it's only referencing last_msg
- activity timestamps - `floored to hour so there are no morethan 24 per user per day`
"""
###########################################################################################
###########################################################################################
from irc3.plugins.command import command
import asyncio
import irc3
from plugins.tool_colors_plugin import colorform as print
import os
import re
from datetime import datetime, timedelta
import timeago
from irc3.plugins.cron import cron
from time import sleep
###########################################################################################
###########################################################################################
D="\x02\x0315"
G="\x02\x0314"
S="\x02\x0304"
@ -19,11 +31,15 @@ P="\x02\x0305"
X="\x02\x0307"
R="\x02\x0302"
B="\x02\x0312"
###########################################################################################
###########################################################################################
class DBIO():
#######################################################################################
#######################################################################################
history_threshold=1
idle_threshold=1
faded_threshold=14
@ -39,44 +55,79 @@ class DBIO():
users=[]
scanning=False
scanning_operation=False
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self,bot):
self.bot=bot
self.bot.dbio=DBIO()
###################################################################################
###################################################################################
try:
self.bot.dbio.hardchatters=self.bot.db.getlist("hardchatters", [])
print('<<< loaded database >>> hardchatters')
print(f'<<< _________dsa_plugin >>> [ loaded database ] - hardchatters')
except Exception as e:
print(f'error: dsa_plugin > __init__ > hardchatter storage database: {e}')
print(f'<<< _________dsa_plugin >>> [ __init__ ] - hardchatter storage database: {e}')
self.bot.dbio.hardchatters=[]
###################################################################################
###################################################################################
try:
self.bot.dbio.lurkers=self.bot.db.getlist("lurkers", [])
print('<<< loaded database >>> lurkers')
print(f'<<< _________dsa_plugin >>> [ loaded database ] - lurkers')
except Exception as e:
print(f'error: dsa_plugin > __init__ > lurkers storage database: {e}')
print(f'<<< _________dsa_plugin >>> [ __init__ ] - lurkers storage database: {e}')
self.bot.dbio.lurkers=[]
#######################################################################################
#######################################################################################
@classmethod
def reload(cls, old):
return cls(old.bot)
#######################################################################################
#######################################################################################
def before_reload(self):
pass
#######################################################################################
#######################################################################################
def after_reload(self):
pass
#######################################################################################
#######################################################################################
def log(self,s):
print(s)
self.bot.dbio.LOG.append(s)
#######################################################################################
#######################################################################################
@irc3.extend
def log_play(self,target):
for _ in self.bot.dbio.LOG:
self.bot.privmsg(target,_);
print(_)
self.bot.dbio.LOG=[]
#######################################################################################
#######################################################################################
def dbentry_add(self,database,record):
buffer=self.bot.db.getlist(database,[])
buffer.append(record)
@ -85,8 +136,10 @@ class Plugin:
exec(f'self.bot.dbio.{database}=buffer')
self.bot.db.setlist(database,buffer)
self.bot.privmsg("#PalletTown",f'{X}[ {G}added {record} entry to {database} database {X}]')
#######################################################################################
#######################################################################################
def dbentry_remove(self,database,record):
buffer=self.bot.db.getlist(database,[])
status=False
@ -98,8 +151,10 @@ class Plugin:
exec(f'self.bot.dbio.{database}=buffer')
self.bot.db.setlist(database,buffer)
self.bot.privmsg("#PalletTown",f'{X}[ {G}removed {record} entry from {database} database - status: {status} {X}]')
#######################################################################################
#######################################################################################
async def epochtimestamp(self,timestamp):
year,month,day=timestamp.split('T')[0].split('-')
hour,minute,second=timestamp.split('T')[1].split(':')
@ -107,8 +162,10 @@ class Plugin:
year,month,day,hour,minute,second,millisecond=[int(x) for x in [year,month,day,hour,minute,second,millisecond]]
epoch_timestamp_past=datetime(year,month,day,hour,minute,second,millisecond).timestamp()
return epoch_timestamp_past
#######################################################################################
#######################################################################################
async def epochdelta(self,timestamp):
year,month,day=timestamp.split('T')[0].split('-')
hour,minute,second=timestamp.split('T')[1].split(':')
@ -119,29 +176,36 @@ class Plugin:
epochdelta=epoch_timestamp_present-epoch_timestamp_past
distance=timeago.format(timedelta(seconds=epochdelta),datetime.now())
return distance
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.NEW_NICK)
def on_nick_change_for_dsa_hardchatradar(self, nick, new_nick):
for _ in self.bot.channels.keys():
if _[0]=="#":
USER=str(new_nick).lower()
self.dsa_hardchatradar(USER,_)
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.JOIN)
def on_channel_join_for_dsa_hardchatradar(self,mask,channel,**kw):
USER=str(mask.nick).lower
self.dsa_hardchatradar(mask.nick,channel)
#######################################################################################
#######################################################################################
def dsa_hardchatradar(self, USER, channel):
"""radar for hardchatters who join a channel"""
###############################################################################
###############################################################################
###################################################################################
###################################################################################
try:
if not USER == self.bot.nick:
#######################################################################
self.bot.dbio.LOG=[]
asyncio.set_event_loop(self.bot.loop)
asyncio.run_coroutine_threadsafe(self.bot._dsa_scan(USER,channel),self.bot.loop)
@ -150,8 +214,10 @@ class Plugin:
except Exception as e:
msg=f'error: dsa_plugin:hardchat_radar - {e}'
print(msg); #self.bot.privmsg(channel,self.bot.emo(msg))
#######################################################################################
#######################################################################################
@command(permission='view')
def dsa_add_hardchatter(self, mask, target, args):
"""dsa_add_hardchatter
@ -177,8 +243,10 @@ class Plugin:
except Exception as e:
msg=f'error: dsa_plugin:dsa_add_hardchatter > {e}'
print(msg); #self.bot.privmsg(target,self.bot.emo(msg))
#######################################################################################
#######################################################################################
@command(permission='view')
def dsa_del_hardchatter(self, mask, target, args):
"""dsa_del_hardchatter
@ -204,8 +272,10 @@ class Plugin:
except Exception as e:
msg=f'error: dsa_plugin:dsa_del_hardchatter > {e}'
print(msg); #self.bot.privmsg(target,self.bot.emo(msg))
#######################################################################################
#######################################################################################
@command(permission='view')
def dsa_list_hardchatters(self, mask, target, args):
"""dsa_list_hardchatters
@ -232,8 +302,10 @@ class Plugin:
except Exception as e:
msg=f'error: dsa_plugin:hardchatters > {e}'
print(msg); #self.bot.privmsg(target,self.bot.emo(msg))
#######################################################################################
#######################################################################################
@command(permission='view')
def dsa_list_lurkers(self, mask, target, args):
"""dsa_list_lurkers
@ -255,31 +327,34 @@ class Plugin:
self.bot.privmsg(target, self.bot.emo(_))
else:
self.bot.privmsg(target, self.bot.emo(f"{R}no lurkers"))
###########################################################################
except Exception as e:
msg=f'error: dsa_plugin:dsa_list_lurkers > {e}'
print(msg); #self.bot.privmsg(target,self.bot.emo(msg))
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def dsa_analyze(self,mask,target,args):
"""dsa_analyze
%%dsa_analyze <message>...
"""
data=''.join(args['<message>']).strip()
###################################################################################
db_info=self.bot.config['storage']
base_dir=f"{os.getcwd()}/{db_info.split('/')[-2]}"
db_pathname=f"{base_dir}/{db_info.split('/')[-1]}"
f=open(db_pathname,'r');l=f.read();f.close()
###################################################################################
db=l.splitlines()
for _ in db:
if not _.find('last_msg_for_')==-1:
self.bot.dbio.seen_users.append(_.split('last_msg_for_')[1].split('"')[0])
###################################################################################
###################################################################################
nicks=[]; key=''; USER=data.lower(); SEARCH_FLAG=False
###################################################################################
###################################################################################
try:
key=self.bot.db.getlist(f'last_msg_for_{USER}')
except Exception as e:
@ -287,10 +362,8 @@ class Plugin:
if len(USER) > 1:
if not key:
SEARCH_FLAG=True
###################################################################################
self.bot.dbio.search_users=[]
IS_RUNNING=True
###################################################################################
LOOP=1
if SEARCH_FLAG:
for _ in db:
@ -298,7 +371,6 @@ class Plugin:
if not _.find(USER)==-1:
self.bot.dbio.search_users.append(_.split('last_msg_for_')[-1].split('":')[0])
LOOP=len(self.bot.dbio.search_users)
###################################################################################
for i in range(0,LOOP):
if SEARCH_FLAG:
try:
@ -308,9 +380,13 @@ class Plugin:
IS_RUNNING=False
msg=f"{B}< {R}no {G}{USER} {R}ircnick(s) or similar were found {B}>"
self.bot.privmsg(target,msg)
###############################################################################
###############################################################################
newnicks=0; privmsgs=0; lastmsg=[]; lasttime=[]
###############################################################################
###############################################################################
try:
for _ in key:
if _['type']=='newnick':
@ -321,17 +397,13 @@ class Plugin:
lasttime.append(_['time'])
except Exception as e:
print(f'error: dsa:nicks:search -> no items of a key means no db operation: {e}')
###############################################################################
self.bot.privmsg("#PalletTown",f'{"#"*69}')
###############################################################################
if newnicks>0 or privmsgs>0:
self.bot.privmsg("#PalletTown",f"{D}<<< {G}{USER} {B}- {G}ircnicks{B}: {D}{int(newnicks)+1} {B}- {G}messages{B}: {G}{privmsgs} {D}>>>")
###############################################################################
if privmsgs>0:
for i in range(0,privmsgs):
self.bot.privmsg("#PalletTown",f'{"#"*69}')
self.bot.privmsg("#PalletTown",f'{G}{lasttime[i]} {B}> {R}{USER} {B}> {D}{lastmsg[i]}')
###############################################################################
if newnicks==0:
self.bot.privmsg("#PalletTown",f'{"#"*69}');
self.bot.privmsg("#PalletTown",f"!!! no alternate ircnicks !!!")
@ -342,43 +414,33 @@ class Plugin:
elif i==LOOP and SEARCH_FLAG:
IS_RUNNING=False
return
###############################################################################
self.bot.privmsg("#PalletTown",f'{"#"*69}')
###############################################################################
while IS_RUNNING:
###########################################################################
if not SEARCH_FLAG:
msg=f"{D}<<< {R}near region{D} >>>"
else:
msg=f"{D}<<< {R}near region - issues{D} >>>"
self.bot.privmsg("#PalletTown",msg); self.bot.privmsg("#PalletTown",f'{"#"*69}')
###########################################################################
for _ in key:
if _['type']=='newnick':
f,t=_['msg'].split(' changed nick to ')
self.bot.privmsg("#PalletTown",f'{D}{_["time"]} {B}> {R}from ircnick {G}{f} {R}to ircnick {G}{t}')
nicks.append(f)
###########################################################################
nicks=list(set(nicks))
###########################################################################
if len(nicks)>0:
self.bot.privmsg("#PalletTown",f'{"#"*69}')
#######################################################################
if not SEARCH_FLAG:
msg=f'{D}[ {G}{USER} {D}- {R}alternate ircnicks - direct referfence{D}]{B}: {R}{" ".join(nicks)}'
msg=f'{D}[ {G}{USER} {D}- {R}alternate ircnicks - direct reference{D}]{B}: {R}{" ".join(nicks)}'
else:
msg=f'{D}[ {G}{USER} {D}- {R}alternate ircnicks - keyworded{D}]{B}: {R}{" ".join(nicks)}'
###########################################################################
self.bot.privmsg("#PalletTown",msg); self.bot.privmsg("#PalletTown",f'{"#"*69}'); self.bot.privmsg("#PalletTown",f"{D}<<< {R}distant region{D} >>>"); self.bot.privmsg("#PalletTown",f'{"#"*69}')
for _ in nicks:
self.bot.privmsg("#PalletTown",f'{B}[ {R}{_} {B}]')
try:
key=self.bot.db.getlist(f'last_msg_for_{_}')
for __ in key:
###############################################################
if __['type']=='privmsg':
self.bot.privmsg("#PalletTown",f'{D}{__["time"]} {B}> {R}{_} {B}> {D}{__["msg"]}"')
###############################################################
elif __['type']=='newnick':
f,t=__['msg'].split(' changed nick to ')
self.bot.privmsg("#PalletTown",f'{D}{__["time"]} {B}> {R}to ircnick {B}{t} {R}from ircnick {G}{f}')
@ -399,11 +461,9 @@ class Plugin:
except Exception as e:
IS_OK=False
print(f'error: dsa:dirties:IS_OK -> pulling db key for last_msg_for_{f}: {e}')
###############################################################
except Exception as e:
self.bot.privmsg("#PalletTown",f'{D}<{R}none{D}>')
print(f'error: dsa:dirties -> pulling db key for last_msg_for_{_}: {e}')
###########################################################################
if SEARCH_FLAG:
self.bot.privmsg("#PalletTown",f'{B}<<< {R}total instances found{X}: {R}{LOOP} {B}>>>')
#self.log_play(target)
@ -416,11 +476,16 @@ class Plugin:
IS_RUNNING=False
else:
IS_RUNNING=False
#######################################################################################
#######################################################################################
@irc3.extend
async def _dsa_scan(self,NICK,target):
###############################################################################
###############################################################################
###################################################################################
###################################################################################
self.bot.privmsg("#PalletTown",f'{"#"*69}');
msg=f'{G}<<< {S}analyzing {NICK} {G}>>>'
self.bot.privmsg("#PalletTown",msg)
@ -459,8 +524,6 @@ class Plugin:
cmd=f"MODE {target} +v {USER}"
self.bot.send(cmd)
else:
###################################################################
###################################################################
self.bot.privmsg("#PalletTown",f'{"#"*69}')
records=len(key)
records_timestamps=[]
@ -501,8 +564,6 @@ class Plugin:
timestamp=await self.epochdelta(_key['time'])
records_timestamps.append(_key['time'])
records_newnicks.append(timestamp)
###################################################################
###################################################################
records_timestamps.sort()
faded_timestamp=await self.epochtimestamp(records_timestamps[-1])
newest_timestamp=await self.epochdelta(records_timestamps[-1])
@ -510,8 +571,6 @@ class Plugin:
oldest_timestamp=await self.epochdelta(records_timestamps[-1])
oldest_timestamp_epoch=await self.epochtimestamp(records_timestamps[-1])
history_timestamp=datetime.now().timestamp()-oldest_timestamp_epoch
###################################################################
###################################################################
faded_status=False
idle_status=False
idler_status=False
@ -533,8 +592,6 @@ class Plugin:
hardchat_status=True
if USER in self.bot.dbio.lurkers:
lurker_status=True
###################################################################
###################################################################
if records_privmsgs==0:
self.dbentry_add('lurkers',USER)
lurker_status=True
@ -619,15 +676,14 @@ class Plugin:
except Exception as e:
msg=f'error: dsa_plugin:hardchattting > {e}'
self.bot.privmsg("#PalletTown",msg)
#######################################################################
#######################################################################
except Exception as e:
msg=f'error: dsa:lurkers > {e}'
print(msg)
self.bot.privmsg("#PalletTown",msg)
###############################################################################
###############################################################################
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
@irc3.extend
def dsa_scan(self,mask,target,args):
@ -650,8 +706,6 @@ class Plugin:
if OP_FLAG:
msg=f'{G}<<< {S}analyzing {CHANNEL} users {G}>>>'
self.bot.privmsg("#PalletTown",msg)
###############################################################################
###############################################################################
if not target in self.bot.dbio.channel:
self.bot.dbio.channel.append(target)
self.bot.dbio.channel_users.append(channel)
@ -665,62 +719,54 @@ class Plugin:
asyncio.run_coroutine_threadsafe(asyncio.sleep(0.5),self.bot.loop)
# while len(self.bot.dbio.LOG) > 0:
# self.bot.log_play("#pallettown")
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=True)
def dsa_set_threshold_history(self,mask,target,args):
"""dsa_set_threshold_history - sets a threshold by distance in days - if there is no record within that amount of time then they fall below this threshold and will be marked with no history, this is used to indicate if a user is a rando or a known user. default value is 30 days. 90 day threshold example: ?dsa_set_threshold_history 90
%%dsa_set_threshold_history <message>...
"""
###################################################################################
###################################################################################
data=''.join(args['<message>']).strip()
###################################################################################
###################################################################################
try:
self.bot.dbio.history_threshold=int(data)
msg=f'{R}{mask.nick}{B}: {R}dsa_plugin:dsa_history_threshold set to {B}{data} days'
except Exception as e:
msg=f'{mask.nick}: error - dsa_plugin:dsa_history_threshold > {e}'
print(msg); self.bot.privmsg(target,self.bot.emo(msg))
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=True)
def dsa_set_threshold_faded(self,mask,target,args):
"""dsa_set_threshold_faded - sets a threshold by distance in days to mark a user awol - if there is no record within that amount of time then they fall below this threshold and will be marked awol. default value is 14 days. 90 day threshold example: ?dsa_set_threshold_faded 90
%%dsa_set_threshold_faded <message>...
"""
###################################################################################
###################################################################################
data=''.join(args['<message>']).strip()
###################################################################################
###################################################################################
try:
self.bot.dbio.faded_threshold=int(data)
msg=f'{R}{mask.nick}{B}: {R}dsa_plugin:dsa_faded_threshold set to {B}{data} days'
except Exception as e:
msg=f'{mask.nick}: error - dsa_plugin:dsa_faded_threshold > {e}'
print(msg); self.bot.privmsg(target,self.bot.emo(msg))
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=True)
def dsa_set_threshold_idle(self,mask,target,args):
"""dsa_set_threshold_idle - sets a threshold by distance in hours - if there is no record within that amount of time then they fall below this threshold and will be marked idle. default value is 1 hour. 3 hour threshold example: ?dsa_set_threshold_idle 3
%%dsa_set_threshold_idle <message>...
"""
###################################################################################
###################################################################################
data=''.join(args['<message>']).strip()
###################################################################################
###################################################################################
try:
self.bot.dbio.history_threshold=int(data)
msg=f'{R}{mask.nick}{B}: {R}dsa_plugin:dsa_history_threshold set to {B}{data} days'
except Exception as e:
msg=f'{mask.nick}: error - dsa_plugin:dsa_history_threshold > {e}'
print(msg); self.bot.privmsg(target,self.bot.emo(msg))
#######################################################################################
#######################################################################################
#### EOF CLASS INSTANCE EOF CLASS INSTANCE EOF CLASS INSTANCE EOF CLASS INSTANCE
#### EOF CLASS INSTANCE EOF CLASS INSTANCE EOF CLASS INSTANCE EOF CLASS INSTANCE
###########################################################################################
####################################################################################### EOF

@ -1,19 +1,31 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
import random
import os
###########################################################################################
###########################################################################################
dir_path = os.path.dirname(os.path.realpath(__file__))
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@irc3.extend
def emo(self,s):
emote_db = '%s/../databases/emote.db' % dir_path
@ -25,8 +37,10 @@ class Plugin:
emoj = "\x0303{}\x0F".format(emoj)
s = s + '\x0303 > ' + emoj
return s
#######################################################################################
#######################################################################################
@command(permission='view',show_in_help_list=False)
def emote(self, mask, target, args):
"""Show Emotion
@ -37,6 +51,6 @@ class Plugin:
return random.choice(list(open(emote_db)))
emoj = __random_line()
self.bot.privmsg(target, "%s" % emoj)
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,14 +1,26 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
import os
import irc3
from stat import S_ISFIFO
###########################################################################################
###########################################################################################
@irc3.plugin
class Fifo:
#######################################################################################
#######################################################################################
BLOCK_SIZE = 1024
MAX_BUFFER_SIZE = 800
#######################################################################################
#######################################################################################
def __init__(self, context):
self.context = context
self.config = self.context.config
@ -20,7 +32,10 @@ class Fifo:
self.fifos = {}
self.buffers = {}
self.create_fifo(None)
#######################################################################################
#######################################################################################
@classmethod
def read_fd(cls, fd):
while True:
@ -30,7 +45,10 @@ class Fifo:
continue
except BlockingIOError:
return b""
#######################################################################################
#######################################################################################
def handle_line(self, line, channel):
if not line:
return
@ -41,7 +59,10 @@ class Fifo:
self.context.send_line(line)
else:
self.context.privmsg(channel, line)
#######################################################################################
#######################################################################################
def data_received(self, data, channel):
if not data:
return
@ -61,7 +82,10 @@ class Fifo:
self.buffers[channel] = b""
else:
self.buffers[channel] = last
#######################################################################################
#######################################################################################
def watch_fd(self, fd, channel):
reading = True
@ -69,7 +93,10 @@ class Fifo:
data = self.read_fd(fd)
reading = len(data) == self.BLOCK_SIZE
self.data_received(data, channel)
#######################################################################################
#######################################################################################
def create_fifo(self, channel):
if channel is None:
path = os.path.join(self.runpath, ':raw')
@ -89,14 +116,17 @@ class Fifo:
os.mkfifo(path)
fd = os.open(path, os.O_RDWR | os.O_NONBLOCK)
self.loop.add_reader(fd, self.watch_fd, fd, channel)
self.context.log.debug("%s's fifo is %s %r",
channel or ':raw', path, fd)
self.context.log.debug("%s's fifo is %s %r",channel or ':raw', path, fd)
return fd
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.JOIN)
def join(self, mask=None, channel=None, **kwargs):
if mask.nick == self.context.nick:
if channel not in self.fifos:
self.fifos[channel] = self.create_fifo(channel)
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,21 +1,35 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
import pyfiglet
import random
###########################################################################################
###########################################################################################
fig = pyfiglet.Figlet(width=100)
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
self.fig_fonts = set(self.bot.db.getlist("fig_font_list", []))
if not self.fig_fonts:
self.fig_fonts = ['poison','isometric2', 'puffy', 'standard', 'nancyj-fancy', 'chunky', 'broadway', 'cosmike', 'mirror', 'gradient', 'banner3-D', 'isometric4', 'ogre', 'smisome1', 'starwars', 'lean', 'whimsy', 'dotmatrix', 'cricket', 'isometric1', 'caligraphy', 'pawp', 'univers', 'cosmic', 'graceful', 'thin', 'rozzo', 'defleppard', 'marquee', 'rowancap', 'stop', 'shimrod', 'fuzzy', 'coinstak', 'fraktur', 'shadow', 'doh', 'charact1', 'big', 'roman', 'rev', 'cybersmall', 'rounded', 'stacey', 'ascii___', 'nancyj', 'smslant', 'doom']
self.bot.db.setlist("fig_font_list", self.fig_fonts)
#######################################################################################
#######################################################################################
@irc3.extend
def fig(self, text=None, font=None, width=None):
if font in self.fig_fonts:
@ -26,7 +40,10 @@ class Plugin:
fig.width=width
if not text: return
return fig.renderText(text)
#######################################################################################
#######################################################################################
@command(permission='view', name="fig", public=True, show_in_help_list=True)
def figcmd(self, mask, target, args):
"""Print figlet Text
@ -77,11 +94,9 @@ class Plugin:
newfont = random.choice(list(self.fig_fonts))
msg = self.bot.emo(newfont)
self.bot.privmsg(target, msg)
fig_text = self.fig(text=text, font=newfont, width=width) # Cause weird command format
fig_text = self.fig(text=text, font=newfont, width=width)
for line in fig_text.split("\n"):
self.bot.privmsg(target, line)
###########################################################################################
####################################################################################### EOF
#.[d].
#
# MY PREFERENCE OF FONTS TO REMOVE FROM OPTIONS LIST
#

@ -1,20 +1,34 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
from lxml.html import fromstring
from googlesearch import search
import irc3,os,sys,requests
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
def __get_tiny_url(self, url):
tiny_url = 'http://tinyurl.com/api-create.php?url=%s' % url
r = requests.get(tiny_url)
return r.text
#######################################################################################
#######################################################################################
@command(permission='view', public=True, show_in_help_list=True)
def g(self, mask, target, args):
"""Google Query
@ -52,5 +66,6 @@ class Plugin:
except Exception as e:
print("%s" % e)
pass
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,16 +1,26 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
import random
import os
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot=bot
#######################################################################################
#######################################################################################
def __color(self,c):
try:
c=str(c.lower())
@ -37,18 +47,19 @@ class Plugin:
except:
print('_color: error')
return '\x0f'
#######################################################################################
#######################################################################################
@command(permission='view',public=True,show_in_help_list=True)
def hl(self, mask, target, args):
"""hl - use a chosen or random color palette that will iterate a message to whichever ircnick you pick.
c1,c2,c3,c4,s1,s2,s3,s4,s5,s6 accept a color range of 0-15 and symbol range of 0-30. usage: ?hl c1,c2,c3,c4,s1,s2,s3,s4,s5,s6 ircnick n message.
uses specified colors & symbols, tags ircnick dr1p with hello message 10 times. example 1: ?hl 8,12,9,13,3,4 dr1p 10 hello.
uses a random color palette, tags ircnick dr1p with hello message 10 times. example 2: ?hl dr1p 10 hello.
uses a random color palette, tags ircnick dr1p with hello message 1 time. example 3: ?hl dr1p hello.
%%hl <message>...
c1,c2,c3,c4,s1,s2,s3,s4,s5,s6 accept a color range of 0-15 and symbol range of 0-30. usage: ?hl c1,c2,c3,c4,s1,s2,s3,s4,s5,s6 ircnick n message.
uses specified colors & symbols, tags ircnick dr1p with hello message 10 times. example 1: ?hl 8,12,9,13,3,4 dr1p 10 hello.
uses a random color palette, tags ircnick dr1p with hello message 10 times. example 2: ?hl dr1p 10 hello.
uses a random color palette, tags ircnick dr1p with hello message 1 time. example 3: ?hl dr1p hello.
%%hl <message>...
"""
###################################################################################
try:
message=' '.join(args['<message>']).strip()
channel=self.bot.channels[target]
@ -64,7 +75,6 @@ class Plugin:
GOT_PALETTE=''; palette=''
GOT_IRCNICK=''; ircnick=mask.nick
GOT_ITERATIONS=''; iterations=1
###############################################################################
for palette in message.split():
try:
if len(palette.split(','))==10:
@ -72,7 +82,6 @@ class Plugin:
break
except:
pass
###############################################################################
for ircnick in message.split():
try:
if ircnick in channel:
@ -80,7 +89,6 @@ class Plugin:
break
except:
pass
###############################################################################
for iterations in message.split():
try:
if int(iterations)>0:
@ -88,7 +96,6 @@ class Plugin:
break
except:
pass
###############################################################################
if GOT_IRCNICK:
message=message.replace(GOT_IRCNICK,'')
ircnick=GOT_IRCNICK
@ -110,7 +117,6 @@ class Plugin:
iterations=GOT_ITERATIONS
else:
iterations=1
###############################################################################
message=message.strip()
for i in range(int(iterations)):
h1=self.__color(hex(c1)[2:])
@ -120,10 +126,9 @@ class Plugin:
msg=f'{h1}{s1[0]} {h2}{ircnick} {h1}{s1[1]} {h3}{s2[0]} {h4}{message} {h3}{s2[1]} {h1}{s1[0]} {h2}{ircnick} {h1}{s1[1]}\x20'
if not GOT_PALETTE: msg+=f"{h1}{str(c1).zfill(2)},{h2}{str(c2).zfill(2)},{h3}{str(c3).zfill(2)},{h4}{str(c4).zfill(2)},{h1}{str(n1[0]).zfill(2)},{str(n1[1]).zfill(2)},{str(n1[2]).zfill(2)},{h3}{str(n2[0]).zfill(2)},{str(n2[1]).zfill(2)},{str(n2[2]).zfill(2)}"
self.bot.privmsg(target,self.bot.emo(msg))
###############################################################################
###################################################################################
except Exception as e:
msg=f"{mask.nick}: highlight_plugin:hl - error: {e}"
self.bot.privmsg(target,self.bot.emo(msg))
###########################################################################################
####################################################################################### EOF
#.[d].

@ -0,0 +1,58 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
import requests
import socket
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
###################################################################################
###################################################################################
def __init__(self, bot):
self.bot = bot
###################################################################################
###################################################################################
@classmethod
def reload(cls, old):
return cls(old.bot)
###################################################################################
###################################################################################
def before_reload(self):
pass
###################################################################################
###################################################################################
def after_reload(self):
pass
###################################################################################
###################################################################################
@command(permission='view')
def ip(self, mask, target, args):
"""Show ip info
%%ip <ip>
"""
ip = args.get('<ip>')
try:
ip = socket.gethostbyname(ip)
except:
return
msg = "ip: {IP}"
msg = msg.format(IP=ip)
self.bot.privmsg(target,self.bot.emo(msg))
###########################################################################################
####################################################################################### EOF

@ -1,18 +1,26 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
def isup_check(self, domain_or_ip):
msg=''
try:
@ -51,8 +59,10 @@ class Plugin:
msg=f'up -> https://{domain_or_ip} is communicating'
finally:
return msg
#######################################################################################
#######################################################################################
@command(permission='view')
def isup(self, mask, target, args):
"""isup domain
@ -81,5 +91,6 @@ class Plugin:
self.bot.privmsg(target,self.bot.emo("{}: doesn't sanitize towards a valid domain/ip".format(domain)))
return
self.bot.privmsg(target,self.bot.emo("{}".format(self.isup_check(domain))))
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,21 +1,27 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
###########################################################################################
###########################################################################################
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot=bot
self.site_url="https://icanhazdadjoke.com"
#######################################################################################
#######################################################################################
def urlget(self,url):
USER_AGENT_CURL="curl/7.78.0"
ACCEPT_MODES="text/plain"
@ -27,8 +33,10 @@ class Plugin:
except HTTPError as e: return STATUS_BAD_CODE.format(e.code)
except URLError as e: return STATUS_BAD_REASON.format(e.reason)
else: return STATUS_OK + response
#######################################################################################
#######################################################################################
@irc3.extend
@command(permission='view')
def joke(self, mask, target, args):
@ -39,5 +47,6 @@ class Plugin:
for msg in response.splitlines():
if len(msg) > 1:
self.bot.privmsg(target, self.bot.emo(msg))
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
import asyncio
import configparser
import io
@ -10,7 +12,16 @@ from difflib import SequenceMatcher
from glob import glob
from time import time
###########################################################################################
###########################################################################################
import irc3
from plugins.tool_colors_plugin import colorform as print
###########################################################################################
###########################################################################################
import sklearn
import numpy as np
import requests
import torch
@ -19,53 +30,73 @@ from tqdm import tqdm
from transformers import GPT2Config, GPT2LMHeadModel, GPT2Tokenizer
###########################################################################################
###########################################################################################
global message_history
class MESSAGE_HISTORY():
#######################################################################################
#######################################################################################
maple_messages = []
user_messages = []
user_users = []
last_message = ''
maple_message = ''
#######################################################################################
#######################################################################################
def __init__(self):
self.processing=0
self.bounce=False
self.loopcount=0
#######################################################################################
#######################################################################################
def push_maple_messages(self,data):
self.maple_messages = self.maple_messages[-1:] + self.maple_messages[:-1]
self.maple_messages[0] = data
#######################################################################################
#######################################################################################
def push_user_messages(self,user,data):
self.user_users.append(user)
self.user_messages.append(data)
#######################################################################################
#######################################################################################
def similar(self,a,b):
return SequenceMatcher(None,a,b).ratio()
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
terminate=False
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger=logging.getLogger(__name__)
#######################################################################################
CONFIG_FILE={
'small':'https://convaisharables.blob.core.windows.net/lsp/117M/config.json',
'medium':'https://convaisharables.blob.core.windows.net/lsp/345M/config.json'
}
#######################################################################################
VOCAB_FILE={
'small':'https://convaisharables.blob.core.windows.net/lsp/117M/vocab.json',
'medium':'https://convaisharables.blob.core.windows.net/lsp/345M/vocab.json'
}
#######################################################################################
MERGE_FILE={
'small':'https://convaisharables.blob.core.windows.net/lsp/117M/merges.txt',
'medium':'https://convaisharables.blob.core.windows.net/lsp/345M/merges.txt'
}
#######################################################################################
LSP_MODEL_URL={
'multiref':{
'medium_fs':'https://convaisharables.blob.core.windows.net/lsp/multiref/medium_fs.pkl',
@ -77,18 +108,15 @@ class Plugin:
'small_ft':'https://convaisharables.blob.core.windows.net/lsp/DSTC/medium_ft.pkl'
}
}
#######################################################################################
REVERSE_MODEL_URL='https://convaisharables.blob.core.windows.net/lsp/multiref/small_reverse.pkl'
OPINION="""
"""
#######################################################################################
WISDOM="""
"""
#######################################################################################
PERSONALITY="""
[model]
data_folder=models
model_size=medium
model_size=small
dataset=multiref
from_scratch=True
no_cuda=False
@ -102,15 +130,16 @@ class Plugin:
num_samples=1
max_turns_history=-1
"""
#######################################################################################
#######################################################################################
def __init__(self,bot):
self.bot=bot
self.bot.history=MESSAGE_HISTORY()
message_history=self.bot.history
#############################################
for _ in range(5):
self.bot.history.maple_messages.append("")
#############################################
self.mode=0
self.span=0
self.epoch_time_last=0
@ -131,7 +160,10 @@ class Plugin:
else:
self.mmi_model=None
self.mmi_tokenizer=None
#######################################################################################
#######################################################################################
def http_get(self,url,temp_file):
req=requests.get(url,stream=True)
content_length=req.headers.get('Content-Length')
@ -142,7 +174,10 @@ class Plugin:
progress.update(len(chunk))
temp_file.write(chunk)
progress.close()
#######################################################################################
#######################################################################################
def download_file(self,url,folder):
if not os.path.exists(folder):
os.makedirs(folder,exist_ok=True)
@ -153,7 +188,10 @@ class Plugin:
return
with open(os.path.join(folder,file_name),'wb') as f:
self.http_get(url,f)
#######################################################################################
#######################################################################################
def download_model_folder(self,config):
data_folder=config.get('model','data_folder')
model_size=config.get('model','model_size')
@ -163,7 +201,7 @@ class Plugin:
os.makedirs(data_folder, exist_ok=True)
target_folder_name=model_size+"_"+dataset+("_fs" if from_scratch else "_ft")
target_folder=os.path.join(data_folder,target_folder_name)
self.logger.info(f"Downloading model files to {target_folder_name}...")
print(f'<<< _______maple_plugin >>> [ downloading model files ] - path: {target_folder_name}')
self.download_file(self.CONFIG_FILE[model_size],target_folder)
self.download_file(self.VOCAB_FILE[model_size],target_folder)
self.download_file(self.MERGE_FILE[model_size],target_folder)
@ -173,7 +211,10 @@ class Plugin:
raise ValueError(f"'{model_train_type}' not exist for dataset '{dataset}', please choose from [{k}]")
self.download_file(self.LSP_MODEL_URL[dataset][model_train_type],target_folder)
return target_folder_name
#######################################################################################
#######################################################################################
def download_reverse_model_folder(self,config):
data_folder=config.get('model','data_folder')
model_size='medium'
@ -181,18 +222,21 @@ class Plugin:
os.makedirs(data_folder,exist_ok=True)
target_folder_name=model_size+'_reverse'
target_folder=os.path.join(data_folder,target_folder_name)
self.logger.info(f"Downloading model files to {target_folder_name}...")
print(f'<<< _______maple_plugin >>> [ downloading model files ] - path: {target_folder_name}')
self.download_file(self.CONFIG_FILE[model_size],target_folder)
self.download_file(self.VOCAB_FILE[model_size],target_folder)
self.download_file(self.MERGE_FILE[model_size],target_folder)
self.download_file(self.REVERSE_MODEL_URL,target_folder)
return target_folder_name
#######################################################################################
#######################################################################################
def load_model(self,target_folder_name,config):
data_folder=config.get('model','data_folder')
model_size=config.get('model','model_size')
no_cuda=config.getboolean('model', 'no_cuda')
self.logger.info(f"Loading model from {target_folder_name}...")
print(f'<<< _______maple_plugin >>> [ downloading model files ] - path: {target_folder_name}')
device=torch.device("cuda" if torch.cuda.is_available() and not no_cuda else "cpu")
target_folder=os.path.join(data_folder,target_folder_name)
tokenizer=GPT2Tokenizer(os.path.join(target_folder, 'vocab.json'), os.path.join(target_folder,'merges.txt'))
@ -209,12 +253,18 @@ class Plugin:
model.to(device)
model.eval()
return model,tokenizer
#######################################################################################
#######################################################################################
def set_seed(self,seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
#######################################################################################
#######################################################################################
def top_k_top_p_filtering(self,logits,top_k=0,top_p=0.0,filter_value=-float('Inf')):
top_k=min(top_k,logits.size(-1))
if top_k>0:
@ -229,7 +279,10 @@ class Plugin:
indices_to_remove=sorted_indices_to_remove.scatter(dim=1,index=sorted_indices,src=sorted_indices_to_remove)
logits[indices_to_remove]=filter_value
return logits
#######################################################################################
#######################################################################################
def sample_sequence(self,model,tokenizer,context_ids,config):
no_cuda=config.getboolean('model','no_cuda')
num_samples=config.getint('decoder','num_samples')
@ -257,7 +310,10 @@ class Plugin:
if generated.shape[1]-len(context_ids)>=max_length:
break
return generated
#######################################################################################
#######################################################################################
def select_using_mmi(self,mmi_model,mmi_tokenizer,candidates,config):
no_cuda=config.getboolean('model','no_cuda')
device=torch.device("cuda" if torch.cuda.is_available() and not no_cuda else "cpu")
@ -274,7 +330,10 @@ class Plugin:
scores=torch.stack(scores, dim=0)
winner=torch.multinomial(F.softmax(scores,dim=0),num_samples=1).item()
return winner
#######################################################################################
#######################################################################################
def generate_response(self,model,tokenizer,context,config,mmi_model=None,mmi_tokenizer=None):
use_mmi=config.getboolean('model','use_mmi')
num_samples=config.getint('decoder','num_samples')
@ -297,10 +356,12 @@ class Plugin:
best_i=self.select_using_mmi(mmi_model,mmi_tokenizer,candidates,config)
return [texts[best_i]]
return texts
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg_search_for_maple(self, mask=None, target=None, data=None, **kw):
##############################################
if mask.nick.lower()=='nickserv': return
if target!=self.bot.config['nick'] and mask.nick==self.bot.nick: return
if mask.nick == self.bot.config["nick"]:
@ -310,27 +371,23 @@ class Plugin:
mask.nick=data.split('[')[1].split(']')[0]
else:
return
##############################################
if self.epoch_time_boolean==True:
print('[ checking flood protection status ]')
epoch_time_now=int(str(time()).split('.')[0])
if epoch_time_now-self.epoch_time_last>=30:
self.epoch_time_boolean=False
print('[ turned off flood protection ]')
print(f'<<< _______maple_plugin >>> [ turned off flood protection ]')
else:
print('[ flood protection still on ]')
print(f'<<< _______maple_plugin >>> [ flood protection still on ]')
return
##############################################
data=data.strip().lower()
self.bot.history.last_message=data
##############################################
self.span=0
for _ in data.split():
for __ in self.OPINION.split():
if _ == __:
self.span=1
break
##############################################
if not data.lower().find('joke')==-1:
self.bot.joke(mask,target,'')
if mask.nick == "d":
@ -338,19 +395,18 @@ class Plugin:
if data.find('hang with us')>-1:
msg="ok, i'll hang out for a bit"
self.bot.privmsg(target,self.bot.emo(msg))
print(f'<<< _______maple_plugin >>> [ maple is hanging out with us ]')
self.mode=1
if data.find('leave us alone')>-1:
msg="ok, gotta go"
self.bot.privmsg(target,self.bot.emo(msg))
print(f'<<< _______maple_plugin >>> [ maple is no longer hanging out with us ]')
self.mode=0
##############################################
if self.mode==0:
if not data.find(self.bot.config["nick"])>-1:
if self.span==0:
return
##############################################
self.span=0
##############################################
self.maple_io.append({'user':mask.nick,'message':f'{data}','target':target})
self.main()
if len(self.maple_io) > 5:
@ -359,29 +415,29 @@ class Plugin:
self.epoch_time_last=self.epoch_time_now
self.epoch_time_boolean=True
msg=f"kind of busy at the moment {mask.nick}, i'll be right back"
print('[ turned on flood protection ]')
print(f'<<< _______maple_plugin >>> [ turned on flood protection ]')
self.bot.privmsg(target,msg)
#######################################################################################
#######################################################################################
@irc3.extend
async def indirect_maple(self, net=None, data=None, **kw):
##############################################
net_user=net[0]
net_src=net[1]
net_dest=net[2]
##############################################
if self.epoch_time_boolean==True:
print('[ checking flood protection status ]')
print(f'<<< _______maple_plugin >>> [ checking flood protection status ]')
epoch_time_now=int(str(time()).split('.')[0])
if epoch_time_now-self.epoch_time_last>=30:
self.epoch_time_boolean=False
print('[ turned off flood protection ]')
print(f'<<< _______maple_plugin >>> [ turned off flood protection ]')
else:
print('[ flood protection still on ]')
print(f'<<< _______maple_plugin >>> [ flood protection still on ]')
return
##############################################
data=data.strip().lower()
self.bot.history.last_message=data
##############################################
self.maple_io.append({'user':net_user,'message':f'{data}','target':net_src})
self.main()
if len(self.maple_io) > 5:
@ -390,13 +446,16 @@ class Plugin:
self.epoch_time_last=self.epoch_time_now
self.epoch_time_boolean=True
msg=f"kind of busy at the moment {net_user}, i'll be right back"
print('[ turned on flood protection ]')
print(f'<<< _______maple_plugin >>> [ turned on flood protection ]')
from plugins.tool_bus_plugin import BUS
from plugins.tool_dims_plugin import dims
netschanlist=dims.list_channels_bridged(netsrc=net_src)
bridgedbus=(BUS(netschanlist))
await bridgedbus.input(net_src,net_user,msg,True)
#######################################################################################
#######################################################################################
def run_chat(self,model,tokenizer,config,mmi_model=None,mmi_tokenizer=None):
num_samples=config.getint('decoder','num_samples')
max_turns_history=config.getint('decoder','max_turns_history')
@ -405,7 +464,7 @@ class Plugin:
config.set('decoder','seed',f'{datetime.now().microsecond}')
try:
if not type(self.bot.history.bounce)==bool:
print('<received bounce message>')
print(f'<<< _______maple_plugin >>> [ received bounce message ]')
USER=self.bot.history.bounce['user']
MESSAGE=self.bot.history.bounce['message']
TARGET=self.bot.history.bounce['target']
@ -422,7 +481,7 @@ class Plugin:
TARGET=maple_io['target']
except:
return True
print(f'human > {MESSAGE}')
print(f'<<< _______maple_plugin >>> [ human > {MESSAGE} ] - {USER}{TARGET}')
self.bot.history.maple_message=MESSAGE
if max_turns_history==0:
@ -463,41 +522,48 @@ class Plugin:
else:
maple_message=random.choice(maple_messages)
turn['maple_messages'].append(maple_message)
################################################################################### REPROCESSOR SOF
################################################################### REPROCESSOR SOF
# SIMILARITY
for i in range(len(self.bot.history.maple_messages)):
if self.bot.history.similar(maple_message,str(self.bot.history.maple_messages[i]))>0.9:
self.maple_io.append({'user':USER,'message':f'{MESSAGE}','target':TARGET})
print(f'maple - logic ! rejected // maple similarity - repeat of previous response')
print(f'<<< _______maple_plugin >>> [ maple - logic ! rejected ] - maple similarity - repeat of previous response')
self.bot.history.loopcount+=1
return False
###################################################################################
# MOCK / DUPE
if self.bot.history.similar(maple_message,MESSAGE)>0.9:
self.maple_io.append({'user':USER,'message':f'{MESSAGE}','target':TARGET})
print(f'maple - logic ! rejected // human mock - maple response same as human')
print(f'<<< _______maple_plugin >>> [ maple - logic ! rejected ] - human mock - maple response same as human')
self.bot.history.loopcount+=1
return False
###################################################################################
# GPT LOOP GLITCH
n=len(maple_message.split())
i=len(set(maple_message.split()))
if i<int(n/2):
self.maple_io.append({'user':USER,'message':f'{MESSAGE}','target':TARGET})
print(f'maple - logic ! rejected // gpt loop glitch - reiterating same thing in multiples')
print(f'<<< _______maple_plugin >>> [ maple - logic ! rejected ] - gpt loop glitch - reiterating same thing in multiples')
self.bot.history.loopcount+=1
return False
###################################################################################
# LIMITED RESPONSE
n=len(maple_message.split())
if i<3:
self.maple_io.append({'user':USER,'message':f'{MESSAGE}','target':TARGET})
print(f'maple - logic ! rejected // limited response - skip an unfinished token chain')
print(f'<<< _______maple_plugin >>> [ maple - logic ! rejected ] - limited response - skip an unfinished token chain')
self.bot.history.loopcount+=1
return False
###################################################################################
self.bot.history.push_maple_messages(maple_message)
print(f'maple > {maple_message}')
print(f'<<< _______maple_plugin >>> [ maple > {maple_message} ]')
MAPLE_MESSAGE=maple_message.replace('lt 3','<3')
msg=f'{MAPLE_MESSAGE}'
from plugins.tool_bus_plugin import BUS
@ -508,11 +574,12 @@ class Plugin:
async def truss(self,TARGET,USER,msg):
await bridgedbus.input(TARGET,USER,msg,True)
asyncio.run_coroutine_threadsafe( bridgedbus.input("👻"+TARGET,USER,msg,True), asyncio.get_event_loop() )
# asyncio.run_coroutine_threadsafe(self.truss(TARGET,USER,msg),self.bot.loop)
# self.bot.privmsg(TARGET,msg)
self.bot.history.loopcount=0
return True
#######################################################################################
#######################################################################################
def main(self):
FLAG_OK=False
while not FLAG_OK:
@ -521,5 +588,6 @@ class Plugin:
self.bot.history.loopcount=0
self.maple_io=[]
FLAG_OK=True
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,42 +1,93 @@
#-*- coding: utf-8 -*- ################################################################ SOF
###########################################################################################
???DISCORD???
###########################################################################################
###########################################################################################
####################
if SERVICES_DISCORD:
####################
import asyncio
import os
import re
###########################################################################################
import sys
#######################################################################################
#######################################################################################
import discord
###########################################################################################
#######################################################################################
#######################################################################################
from plugins.tool_colors_plugin import colorform as print
import irc3
###########################################################################################
if SERVICES_DISCORD:
from discord import Client
from discord.ext import commands, tasks
###########################################################################################
#######################################################################################
#######################################################################################
from discord import Client
from discord.ext import commands, tasks
#######################################################################################
#######################################################################################
from irc3.plugins.command import command
###########################################################################################
#######################################################################################
#######################################################################################
from plugins.tool_bus_plugin import BUS
from plugins.tool_dims_plugin import dims
from plugins.tool_guds_plugin import guds
###########################################################################################
if SERVICES_DISCORD:
DISCORD__SCHAN=int(os.environ['DISCORD__SCHAN'])
DISCORD__TOKEN=str(os.environ['DISCORD__TOKEN'])
###########################################################################################
from plugins.tool_log_plugin import FOG
#######################################################################################
#######################################################################################
def getenv(s):
try:
s = os.environ[s]
return s
except:
fog=FOG().fog
error_type="environmental variable error"
error_reason=f"exported {s} not found"
fog(f"{error_type}: {error_reason}")
sys.exit(1)
#######################################################################################
#######################################################################################
DISCORD__SCHAN=int(getenv('DISCORD__SCHAN'))
DISCORD__TOKEN=getenv('DISCORD__TOKEN')
#######################################################################################
#######################################################################################
global client
###########################################################################################
#######################################################################################
#######################################################################################
async def _d_bnc_msg(netsrc,usernick,netdest,data):
netsrc="^{}".format(netsrc)
bridgedbus=(BUS(netdest))
await bridgedbus.input(netsrc,usernick,data,True)
###########################################################################################
#######################################################################################
#######################################################################################
def d_bnc_msg(netsrc,usernick,netdest,data,):
ircbot=guds.memory('ircbot')
asyncio.run_coroutine_threadsafe(_d_bnc_msg(netsrc,usernick,netdest,data),ircbot.loop)
###########################################################################################
#######################################################################################
#######################################################################################
def start_discordbot(self):
print(f'<<< _net_discord_plugin >>> [ discordbot started ]')
self.discordbot=DISCORDBOT()
@ -44,9 +95,16 @@ if SERVICES_DISCORD:
asyncio.set_event_loop(self.loop)
asyncio.run_coroutine_threadsafe(self.discordbot.client.start(DISCORD__TOKEN),self.loop)
return self
#######################################################################################
#######################################################################################
class DISCORDBOT:
####################
if SERVICES_DISCORD:
#######################################################################################
####################
intents=discord.Intents.default()
intents.members = True
intents.messages = True
@ -58,11 +116,17 @@ if SERVICES_DISCORD:
self.dbname="discordchat"
self.db=self.ircbot.db.getlist(self.dbname)
if not self.db: self.db=[]
#######################################################################################
###############################################################################
###############################################################################
@client.event
async def on_ready():
print(f'<<< _net_discord_plugin >>> [ discordbot connection made as {globals()["DISCORDBOT"].client.user.name} ]')
#######################################################################################
###############################################################################
###############################################################################
async def listchannels(self):
print(f"<<< _net_discord_plugin >>> [ event: scanning channels ] - started")
discordchannels=list(globals()['DISCORDBOT'].client.get_all_channels())
@ -74,7 +138,10 @@ if SERVICES_DISCORD:
dims.__create__('discord',channel_name)
print(f"<<< _net_discord_plugin >>> [ event: new channel ] - dims.__create__(discord,{channel_name}) - active channel record created")
globals()['DISCORDBOT'].push(channel.id,channel.name)
#######################################################################################
###############################################################################
###############################################################################
async def clear():
discordbot=guds.memory('discordbot')
client=discordbot.client
@ -92,7 +159,10 @@ if SERVICES_DISCORD:
msg=f'<<< _net_discord_plugin >>> [ purging bridge ] - completed'
print(msg)
TRAP_FLAG=False
#######################################################################################
###############################################################################
###############################################################################
def push(id,name):
class discordchat:
def __init__(self,id,name):
@ -109,10 +179,12 @@ if SERVICES_DISCORD:
self.db.append([dc.id,f"^{dc.name}"])
self.ircbot.db.setlist(self.dbname,self.db)
print(f'<<< _net_discord_plugin >>> [ new database entry ] > [{dc.id},^{dc.name}]')
########################################################################################
###############################################################################
###############################################################################
@client.event
async def on_message(message):
###################################################################################
discordbot=guds.memory('discordbot')
client=discordbot.client
if message.author.name == client.user.name:
@ -132,20 +204,31 @@ if SERVICES_DISCORD:
asyncio.run_coroutine_threadsafe(bridgedbus.input(TARGET,USER,message.content,True),ircbot.loop)
msg=f'<<< _net_discord_plugin >>> [ (d)({message.channel.id})({channel_name}) ] > {str(message.author)}: {message.content}'
print(msg)
###################################################################################
###############################################################################
###############################################################################
async def _d_discord_msg(self,target,msg):
discordbot=guds.memory('discordbot')
client=discordbot.client
if [x.id for x in list(client.get_all_channels()) if x.name==target[1:]][0]:
channel=client.get_channel([x.id for x in list(client.get_all_channels()) if x.name==target[1:]][0])
await channel.send(msg)
###########################################################################################
#######################################################################################
#######################################################################################
def d_discord_cmd(target,cmd,):
discordbot=guds.memory('discordbot')
if cmd=="purgebridges":
asyncio.run_coroutine_threadsafe(discordbot.clear(),discordbot.client.loop)
###########################################################################################
#######################################################################################
#######################################################################################
def d_discord_msg(target,msg,):
discordbot=guds.memory('discordbot')
asyncio.run_coroutine_threadsafe(discordbot._d_discord_msg(target,msg),discordbot.client.loop)
####################################################################################### EOF#.[d].
###########################################################################################
####################################################################################### EOF

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
from irc3.plugins.cron import cron
from irc3.plugins import core
@ -8,7 +10,10 @@ from random import randint as rint
from random import shuffle
from datetime import datetime
import socket
###########################################################################################
###########################################################################################
class dr1p:
def __init__():
dr1p.designation=""
@ -17,10 +22,12 @@ class dr1p:
dr1p.color=""
dr1p.keyid=""
dr1p.home=""
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
def generate_keyid_token(self,mode=1):
if mode:
token=""
@ -38,7 +45,10 @@ class Plugin:
shuffle(keyid)
keyid=''.join(keyid)
return keyid
#######################################################################################
#######################################################################################
def __init__(self,bot):
self.bot=bot
dr1p.color=""
@ -55,7 +65,10 @@ class Plugin:
dr1p.color="\x0304"
dr1p.keyid=self.generate_keyid_token(0)
dr1p.token=self.generate_keyid_token(1)
#######################################################################################
#######################################################################################
def server_ready(self):
if not dr1p.designation=='core':
dr1p.token=self.generate_keyid_token()
@ -64,45 +77,57 @@ class Plugin:
dr1p.keyid=self.generate_keyid_token(0)
dr1p.token=self.generate_keyid_token(1)
self.bot.privmsg("maple",f"[{dr1p.keyid}] - [{dr1p.token}] - purpose: {dr1p.purpose} - core - connected")
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.ERR_NICK)
def on_errnick(self,srv=None,retcode=None,me=None,nick=None,data=None):
###################################################################################
if not dr1p.designation=='core': return
msg=f'err_nick - srv:{srv} - retcode:{retcode} - me:{me} - nick:{nick} - data:{data}'
self.bot.privmsg("maple",msg.lower())
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.NEW_NICK)
def on_newnick(self,nick=None,new_nick=None):
###################################################################################
if not dr1p.designation=='core': return
if nick==self.bot.config['nick'] or new_nick==self.bot.config['nick']:
msg=f'new_nick - nick:{nick} - new_nick:{new_nick}'
self.bot.privmsg("maple",msg.lower())
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.CTCP)
def on_ctcp(self,mask=None,event=None,target=None,ctcp=None):
###################################################################################
if not dr1p.designation=='core': return
msg=f'ctcpd - mask:{mask} - event:{event} - target:{target} - ctcp:{ctcp}'
self.bot.privmsg("maple",msg.lower())
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.INVITE)
def on_invite(self,mask=None,channel=None):
###################################################################################
if not dr1p.designation=='core': return
msg=f'invited - mask:{mask} - channel:{channel}'
self.bot.privmsg("maple",msg.lower())
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.KICK)
def on_kick(self,mask=None,event=None,channel=None,target=None,data=None):
###################################################################################
msg=f'kicked - mask:{mask} - event:{event} - target:{target} - data:{data}'
self.bot.privmsg(dr1p.home,msg)
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg(self,mask=None,event=None,target=None,data=None,**kw):
###################################################################################
if mask.nick=='d' and 'maple' in data and 'list' in data and 'hydra' in data:
msg=f"{dr1p.color}[hydra:{dr1p.keyid}] - purpose: {dr1p.purpose}"
self.bot.privmsg(target,msg)
@ -112,7 +137,6 @@ class Plugin:
msg=f"{dr1p.color}[hydra:{dr1p.keyid}] - hostname: {socket.gethostname()} - plugin: {_}"
self.bot.privmsg(target,msg)
return
###################################################################################
if target!=self.bot.config['nick'] and mask.nick==self.bot.nick:
data=""
return
@ -152,18 +176,21 @@ class Plugin:
if keyid1==keyid2: self.bot.privmsg(dr1p.home,msg.lower())
except:
self.bot.privmsg(dr1p.home,"exception - "+msg.lower())
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.MY_PRIVMSG)
def on_my_privmsg(self,mask=None,event=None,target=None,data=None,**kw):
###################################################################################
pass
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.JOIN_PART_QUIT)
def on_join_part_quit(self,mask=None,target=None,data=None,**kw):
target=kw['channel']
###################################################################################
if mask.nick==self.bot.config['nick']:
###############################################################################
if kw['event']=='JOIN':
self.bot.privmsg("maple",f"[{dr1p.keyid}] - [{dr1p.token}] - joined {target}".lower())
if target!=dr1p.home:
@ -183,5 +210,6 @@ class Plugin:
else:
msg=f"[hydra:{dr1p.keyid}] -"
self.bot.privmsg("maple",msg+f"quit {target} - {data}")
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,16 +1,40 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
???MATRIX???
###########################################################################################
###########################################################################################
import irc3,os,asyncio,re
from irc3.testing import ini2config
from irc3.plugins.command import command
###########################################################################################
###########################################################################################
###################
if SERVICES_MATRIX:
###################
from nio import AsyncClient, MatrixRoom, RoomMessageText
###########################################################################################
###########################################################################################
from plugins.tool_dims_plugin import dims
from plugins.tool_guds_plugin import guds
from plugins.tool_bus_plugin import BUS
from plugins.tool_colors_plugin import colorform as print
###########################################################################################
###########################################################################################
regex=re.compile("\x03(?:\d{1,2}(?:,\d{1,2})?)?",re.UNICODE)
################################################################ NET IRC - BOT CONFIG [2/4]
###########################################################################################
###########################################################################################
def config_ircbot():
config=ini2config("""
[bot]
@ -25,7 +49,59 @@ def config_ircbot():
ssl_verify = CERT_NONE
includes =
irc3.plugins.command
irc3.plugins.asynchronious
irc3.plugins.uptime
irc3.plugins.ctcp
irc3.plugins.cron
irc3.plugins.log
irc3.plugins.logger
irc3.plugins.userlist
plugins.tool_dims_plugin
plugins.tool_guds_plugin
plugins.tool_bus_plugin
plugins.sasl_custom_plugin
plugins.net_hydra_plugin
plugins.net_irc_plugin
plugins.net_matrix_plugin
plugins.storage_plugin
plugins.base_plugin
plugins.emote_plugin
plugins.fifo_plugin
plugins.url_grabber_plugin
plugins.youtube_plugin
plugins.net_discord_plugin
plugins.net_telegram_plugin
plugins.cmd_irc_plugin
plugins.crypto_plugin
plugins.notes_plugin
plugins.quote_plugin
plugins.ratesex_plugin
plugins.remind_plugin
plugins.timezonediff_plugin
plugins.sed_plugin
plugins.seen_plugin
plugins.strain_plugin
plugins.tell_plugin
plugins.twitter_plugin
plugins.ud_plugin
plugins.figlet_plugin
plugins.soundcloud_plugin
plugins.isup_plugin
plugins.tcpac_plugin
plugins.google_plugin
plugins.highlight_plugin
plugins.boombox_plugin
plugins.whoami_plugin
plugins.joke_plugin
plugins.maple_plugin
plugins.tool_colors_plugin
plugins.dsa_plugin
plugins.openai_plugin
plugins.ip_plugin
plugins.datetime_plugin
plugins.ping_plugin
#plugins.ansi_plugin
autojoins =
'#b0tsh0p'
@ -35,7 +111,7 @@ def config_ircbot():
flood_burst = 0
flood_rate = 1
flood_rate_delay = 1
storage = json://databases/maple_db.json
storage = sqlite://databases/maple_db.sqlite
[irc3.plugins.command]
cmd = ?
@ -77,39 +153,62 @@ def config_ircbot():
for i,_ in enumerate(config['autojoins']):
config['autojoins'][i]=_.replace("'","")
return ircbot
############################################################### NET IRC - BOT STARTUP [3/4]
###########################################################################################
###########################################################################################
def start_ircbot(self):
print(f'<<< _____net_irc_plugin >>> [ ircbot started ]')
self.ircbot.loop=self.loop
self.ircbot.run(forever=True)
return self
###################################################################### NET IRC - MAIN [4/4]
###########################################################################################
###########################################################################################
async def _d_irc_msg(target,msg,) -> None:
ircbot=guds.memory('ircbot')
await ircbot.privmsg(target,msg,)
###########################################################################################
###########################################################################################
def d_irc_msg(target,msg,):
self=guds.memory('ircbot')
asyncio.run_coroutine_threadsafe(_d_irc_msg(target,msg),self.loop)
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
###########################################################################################
def __init__(self,bot):
self.bot=bot
print(f'<<< _____net_irc_plugin >>> [ plugin loaded ]')
globals()['guds'].memories.append([self.bot,'net_irc_plugin:start_ircbot.self'])
self.dbname="ircchat"
#######################################################################################
#######################################################################################
def connection_made(self):
print(f'<<< _____net_irc_plugin >>> [ event: ircbot connection made ]')
#######################################################################################
#######################################################################################
def server_ready(self):
print(f'<<< _____net_irc_plugin >>> [ event: ircbot server ready ]')
#######################################################################################
#######################################################################################
def connection_lost(self):
print(f'<<< _____net_irc_plugin >>> [ event: ircbot connection lost ]')
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
async def on_privmsg(self, mask=None, target=None, data=None, **kw):
msg=f"<<< _____net_irc_plugin >>> [ (i)({self.bot.config['host']})({target}) ] > {mask.nick}: {regex.sub('',data)}"
@ -121,10 +220,14 @@ class Plugin:
await bridgedbus.input(target,mask.nick,data,True)
else: # bot
pass
#######################################################################################
#######################################################################################
def push(self,channel):
self.db=self.bot.db.getlist(self.dbname)
if not self.db: self.db=[]
if not self.db:
self.db=[]
class ircchat:
def __init__(self,channel):
self.channel=channel
@ -138,19 +241,19 @@ class Plugin:
self.db.append([ircc.channel])
self.bot.db.setlist(self.dbname,self.db)
print(f'<<< _____net_irc_plugin >>> [ new database entry ] > [{ircc.channel}]')
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.JOIN_PART_QUIT)
def on_join_part_quit(self,mask=None,target=None,data=None,**kw):
target=kw['channel']
###################################################################################
if not mask.nick==self.bot.config['nick']: # this section is the user
msg=f'<<< _____net_irc_plugin >>> [ event: join_part_quit ] - nick: {mask.nick} - target: {target} - event: {kw["event"]} - data: {data}'
print(msg)
###################################################################################
else: # this section is the bot
###############################################################################
else:
if kw['event']=='JOIN':
result=dims.isircchannel(channel=target,return_index=True)
result,i=dims.isircchannel(channel=target,return_index=True)
guds.mask=mask
if not result:
msg=f'<<< _____net_irc_plugin >>> [ event: join_part_quit ] - nick: {mask.nick} - target: {target} - event: {kw["event"]} - data: {data}'
@ -158,37 +261,40 @@ class Plugin:
dims.__create__('irc',target)
print(f"<<< ___tool_dims_plugin >>> [ event: join ] - dims.__create__(irc,{target}) - active channel record created")
self.push(target)
###############################################################################
elif kw['event']=='PART':
###########################################################################
result=dims.isircchannel(channel=target,return_index=True)
###########################################################################
result,i=dims.isircchannel(channel=target,return_index=True)
msg=f'<<< _____net_irc_plugin >>> [ event: join_part_quit ] - nick: {mask.nick} - target: {target} - event: {kw["event"]} - data: {data}'
print(msg)
dims.__delete__('irc',i)
print(f"<<< ___tool_dims_plugin >>> [ event: part ] - dims.__delete__(irc,{target}) - active channel record deleted")
###############################################################################
elif kw['event']=='QUIT':
###########################################################################
result=dims.isircchannel(target)
###########################################################################
result,i=dims.isircchannel(target)
msg=f'<<< _____net_irc_plugin >>> [ event: join_part_quit ] - nick: {mask.nick} - target: {target} - event: {kw["event"]} - data: {data}'
print(msg)
dims.__delete__('irc',i)
print(f"<<< ___tool_dims_plugin >>> [ event: quit ] - dims.__delete__(irc,{target}) - active channel record deleted")
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.TOPIC)
def on_topic(self,mask=None,target=None,data=None,**kw):
if not mask.nick==self.bot.config['nick']:
msg=f"{mask.nick}: target: {target} - event: topic - data: {data}"
print("<<< _____net_irc_plugin >>> [ "+msg+" ]")
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.INVITE)
def on_invite(self,mask=None,target=None,data=None,**kw):
if not mask.nick==self.bot.config['nick']:
msg=f"{mask.nick}: target: {target} - event: invite - data: {data}"
print("<<< _____net_irc_plugin >>> [ "+msg+" ]")
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.KICK)
def on_kick(self,mask=None,target=None,data=None,**kw):
try:
@ -197,7 +303,10 @@ class Plugin:
print("<<< _____net_irc_plugin >>> [ "+msg+" ]")
except:
pass
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.MODE)
def on_mode(self,mask=None,target=None,data=None,**kw):
try:
@ -206,7 +315,10 @@ class Plugin:
print("<<< _____net_irc_plugin >>> [ "+msg+" ]")
except:
pass
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.NEW_NICK)
def on_new_kick(self,mask=None,target=None,data=None,**kw):
try:
@ -215,7 +327,10 @@ class Plugin:
print("<<< _____net_irc_plugin >>> [ "+msg+" ]")
except:
pass
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.CTCP)
def on_ctcp(self,mask=None,target=None,data=None,**kw):
try:
@ -224,4 +339,6 @@ class Plugin:
print("<<< _____net_irc_plugin >>> [ "+msg+" ]")
except:
pass
####################################################################################### EOF
###########################################################################################
####################################################################################### EOF

@ -1,10 +1,16 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
???MATRIX???
###############################################################################################
###########################################################################################
###########################################################################################
###################
if SERVICES_MATRIX:
import irc3,asyncio,os,re,aiofiles.os
#import magic
# from PIL import Image
###################
import irc3, asyncio, os, re, sys, aiofiles.os
from nio import AsyncClient, MatrixRoom, RoomMessageText, UploadResponse
from plugins.tool_dims_plugin import dims
from plugins.tool_guds_plugin import guds
@ -12,33 +18,57 @@ if SERVICES_MATRIX:
from plugins.tool_bus_plugin import BUS
from datetime import datetime
from plugins.tool_colors_plugin import colorform as print
###########################################################################################
try:
MATRIX_HOMESERVER=os.environ['MATRIX_HOMESERVER']
MATRIX___USERNAME=os.environ['MATRIX___USERNAME']
MATRIX___PASSWORD=os.environ['MATRIX___PASSWORD']
###########################################################################################
except:
pass
###########################################################################################
from plugins.tool_log_plugin import FOG
#######################################################################################
#######################################################################################
def getenv(s):
try:
s = os.environ[s]
return s
except:
fog=FOG().fog
error_type="environmental variable error"
error_reason=f"exported {s} not found"
fog(f"{error_type}: {error_reason}")
sys.exit(1)
#######################################################################################
#######################################################################################
MATRIX_HOMESERVER=getenv('MATRIX_HOMESERVER')
MATRIX___USERNAME=getenv('MATRIX___USERNAME')
MATRIX___PASSWORD=getenv('MATRIX___PASSWORD')
#######################################################################################
#######################################################################################
matrix_bot_credentials=[]
###########################################################################################
#######################################################################################
#######################################################################################
def add_credentials(credential):
matrix_bot_credentials.append(credential)
print(f'<<< __net_matrix_plugin >>> [ add_credentials ] - added {credential} credentials to net_matrix_plugin.matrix_bot_credentials')
###########################################################################################
#######################################################################################
#######################################################################################
def check_credentials(self,against_credential):
flag_match=False
for credential in matrix_bot_credentials:
if not credential.find(against_credential):
flag_match=True
print(f'<<< __net_matrix_plugin >>> [ check_credentials ] - found {credential} against {against_credential}')
#######################################################################################
if not flag_match:
print(f'<<< __net_matrix_plugin >>> [ check_credentials ] - no credentials found matching {against_credential}')
#######################################################################################
return flag_match
###########################################################################################
#######################################################################################
#######################################################################################
def start_matrixbot(self):
print(f'<<< __net_matrix_plugin >>> [ matrixbot started ]')
add_credentials("@maple.or.g1mp:matrix.org")
@ -49,7 +79,10 @@ if SERVICES_MATRIX:
asyncio.run_coroutine_threadsafe(self.matrixbot.main(),self.loop)
self.matrixbot.client=AsyncClient(MATRIX_HOMESERVER, MATRIX___USERNAME)
return self
###########################################################################################
#######################################################################################
#######################################################################################
async def _d_matrix_msg(target,msg,) -> None:
matrixbot=guds.memory('matrixbot')
await matrixbot.client.room_send(
@ -57,11 +90,16 @@ if SERVICES_MATRIX:
message_type="m.room.message",
content={"msgtype":"m.text","body":msg},
)
###########################################################################################
#######################################################################################
#######################################################################################
def d_matrix_msg(target,msg,):
matrixbot=guds.memory('matrixbot')
asyncio.run_coroutine_threadsafe(_d_matrix_msg(target,msg),matrixbot.loop)
###########################################################################################
#######################################################################################
#######################################################################################
class MATRIXBOT:
def __init__(self):
self.ircbot=guds.memory('ircbot')
@ -71,7 +109,8 @@ if SERVICES_MATRIX:
print(f'<<< __net_matrix_plugin >>> [ plugin loaded ]')
globals()['guds'].memories.append([self,'net_matrix_plugin:start_matrixbot.self'])
#######################################################################################
###################################################################################
###################################################################################
async def message_callback(self,room: MatrixRoom, event: RoomMessageText) -> None:
if guds.timestamp_check('matrix_boot')==False:
return
@ -83,7 +122,6 @@ if SERVICES_MATRIX:
bridgedbus=(BUS(netschanlist))
await bridgedbus.input(room.room_id,user_src,event.body,True)
if not event.body.lower().find("maple")==-1:
#######################################################################################
self.blackhole=[]
ircbot=guds.memory('ircbot')
dbname="blackhole"
@ -101,7 +139,10 @@ if SERVICES_MATRIX:
d_cmd_irc(room.room_id,event.sender,'!OftXgmqAFOPEatmvLU:pcriot.org','listrooms','')
elif not event.body.find('purgebridges')==-1:
d_cmd_irc(room.room_id,event.sender,'!OftXgmqAFOPEatmvLU:pcriot.org','purgebridges','')
#######################################################################################
###################################################################################
###################################################################################
def push(self,room_id):
class matrixchat:
def __init__(self,room_id):
@ -116,7 +157,10 @@ if SERVICES_MATRIX:
self.db.append([mc.room_id])
self.ircbot.db.setlist(self.dbname,self.db)
print(f'<<< __net_matrix_plugin >>> [ new database entry ] > [{mc.room_id}]')
#######################################################################################
###################################################################################
###################################################################################
async def main(self,) -> None:
self.client.add_event_callback(self.message_callback,RoomMessageText)
await self.client.login(MATRIX___PASSWORD)
@ -130,7 +174,8 @@ if SERVICES_MATRIX:
dims.__create__('matrix',_room)
print(f"<<< ___tool_dims_plugin >>> [ event: join ] - dims.__create__(matrix,{_room}) - active room record created")
self.push(_room)
###################################################################################
print(f'<<< __net_matrix_plugin >>> [ await client.sync_forever(timeout=5000) ]')
await self.client.sync_forever(timeout=5000) # milliseconds
####################################################################################### EOF#.[d].
###########################################################################################
####################################################################################### EOF

@ -1,42 +1,73 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
???TELEGRAM???
###########################################################################################
#####################
if SERVICES_TELEGRAM:
#####################
import asyncio
import configparser
import logging
import os
import sys
import random
import re
from functools import wraps
###########################################################################################
#######################################################################################
#######################################################################################
import irc3
import telegram
from irc3.plugins.command import command
from telegram import ChatAction, ParseMode
from telegram.ext import (ChatJoinRequestHandler, CommandHandler, Filters,
MessageHandler, Updater)
###########################################################################################
#######################################################################################
#######################################################################################
from plugins.tool_bus_plugin import BUS
from plugins.tool_dims_plugin import dims
from plugins.tool_guds_plugin import guds
###########################################################################################
from plugins.tool_colors_plugin import colorform as print
###########################################################################################
try:
TELEGRAM_TOKEN=os.environ['TELEGRAM_TOKEN']
except:
pass
###########################################################################################
from plugins.tool_log_plugin import FOG
#######################################################################################
#######################################################################################
def getenv(s):
try:
s = os.environ[s]
return s
except:
fog=FOG().fog
error_type="environmental variable error"
error_reason=f"exported {s} not found"
fog(f"{error_type}: {error_reason}")
sys.exit(1)
#######################################################################################
#######################################################################################
TELEGRAM_TOKEN=getenv('TELEGRAM_TOKEN')
#######################################################################################
#######################################################################################
def start_telegrambot(self):
print(f'<<< net_telegram_plugin >>> [ telegrambot started ]')
self.telegrambot=TELEGRAMBOT()
globals()['guds'].memories.append([self.telegrambot,'net_telegram_plugin:start_telegrambot.self'])
self.telegrambot.main()
return self
###########################################################################################
#######################################################################################
#######################################################################################
class TELEGRAMBOT:
#######################################################################################
def __init__(self):
self.ircbot=guds.memory('ircbot')
self.dbname="telegramchat"
@ -45,21 +76,36 @@ if SERVICES_TELEGRAM:
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger=logging.getLogger(__name__)
#######################################################################################
###################################################################################
###################################################################################
def start(self,update,context):
update.message.reply_text('Hi!')
#######################################################################################
###################################################################################
###################################################################################
def help(self,update,context):
update.message.reply_text('Help!')
#######################################################################################
###################################################################################
###################################################################################
async def _t_bnc_msg(self,netsrc,usernick,netdest,data,):
bridgedbus=(BUS(netdest))
await bridgedbus.input(f"${netsrc}",usernick,data,True)
###########################################################################################
###################################################################################
###################################################################################
def t_bnc_msg(self,netsrc,usernick,netdest,data,):
ircbot=guds.memory('ircbot')
asyncio.run_coroutine_threadsafe(self._t_bnc_msg(netsrc,usernick,netdest,data),ircbot.loop)
#######################################################################################
###################################################################################
###################################################################################
def push(self,chat_id):
class telegramchat:
def __init__(self,id,type,title):
@ -77,7 +123,10 @@ if SERVICES_TELEGRAM:
self.db.append([tgc.id,f"${tgc.title}",tgc.type])
self.ircbot.db.setlist(self.dbname,self.db)
print(f'<<< net_telegram_plugin >>> [ new database entry ] > [{tgc.id},${tgc.title},{tgc.type}]')
#######################################################################################
###################################################################################
###################################################################################
def echo(self,update,context):
from plugins.tool_bus_plugin import BUS
from plugins.tool_dims_plugin import dims
@ -96,10 +145,16 @@ if SERVICES_TELEGRAM:
netschanlist.append(TARGET)
bridgedbus=(BUS(netschanlist))
asyncio.run_coroutine_threadsafe(bridgedbus.input(TARGET,USER,msg,True),self.ircbot.loop)
#######################################################################################
###################################################################################
###################################################################################
def error(self,update,context):
self.logger.warning('Update "%s" caused error "%s"',update,context.error)
#######################################################################################
###################################################################################
###################################################################################
def main(self):
self.updater=Updater(TELEGRAM_TOKEN,use_context=True)
self.api=self.updater.bot
@ -109,7 +164,10 @@ if SERVICES_TELEGRAM:
self.dp.add_handler(MessageHandler(Filters.text,self.echo))
self.dp.add_error_handler(self.error)
self.updater.start_polling()
###########################################################################################
#######################################################################################
#######################################################################################
def d_telegram_msg(target,msg):
ircbot=guds.memory('ircbot')
telegram_groups=ircbot.db.getlist('telegramchat')
@ -118,4 +176,6 @@ if SERVICES_TELEGRAM:
group=_group[0]
telegrambot=guds.memory('telegrambot')
telegrambot.api.send_message(group,msg)
####################################################################################### EOF#.[d].
###########################################################################################
####################################################################################### EOF

@ -1,28 +1,38 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
from datetime import datetime
import dateutil.parser
import timeago
import uuid
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=True)
def notes(self, *args, **kwargs):
"""list/write/del notes
%%notes [<cmd>] [<operation>]
"""
return self.note(*args)
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def note(self, mask, target, args):
"""list/write/del notes
@ -42,8 +52,10 @@ class Plugin:
elif cmd in ["r", "read"]:
self.note_read(mask, target, args)
return
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def note_del(self, mask, target, args):
"""Delete Note or * for all notes
@ -73,8 +85,10 @@ class Plugin:
msg = "{} Removed".format(note_uuid_hash)
msg = self.bot.emo(msg)
self.bot.privmsg(target, msg)
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def note_list(self, mask, target, args):
"""List All Note Names
@ -94,8 +108,10 @@ class Plugin:
note_msg = note.get("note_msg")
msg = "<{}> {} | {} | {}".format(note_from, note_time, note_msg, note_uuid)
self.bot.privmsg(target, msg)
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def note_read(self, mask, target, args):
"""Display Note
@ -138,8 +154,10 @@ class Plugin:
msg = "<{}> {} | {} | {}".format(note_from, note_time, note_msg, note_uuid)
msg = self.bot.emo(msg)
self.bot.privmsg(target, msg)
#######################################################################################
#######################################################################################
@command(permission='admin', public=True, show_in_help_list=False)
def note_write(self, mask, target, args):
"""Add Note
@ -159,7 +177,6 @@ class Plugin:
msg = "Note Added! {}".format(note_uuid)
msg = self.bot.emo(msg)
self.bot.privmsg(target, msg)
#######################################################################################
#######################################################################################
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,6 +1,9 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
import os
import re
import sys
from difflib import SequenceMatcher
import urllib.parse
import irc3
@ -9,48 +12,90 @@ import requests
from irc3.plugins.command import command
from random import randint as rint
from random import choices
dir_path = os.path.dirname(os.path.realpath(__file__))
from glob import glob
from plugins.tool_log_plugin import FOG
###########################################################################################
OPENAI_KEY = os.environ['OPENAI_KEY']
###########################################################################################
dir_path = os.path.dirname(os.path.realpath(__file__))
###########################################################################################
###########################################################################################
def getenv(s):
try:
s = os.environ[s]
return s
except:
fog=FOG().fog
error_type="environmental variable error"
error_reason=f"exported {s} not found"
fog(f"{error_type}: {error_reason}")
sys.exit(1)
###########################################################################################
###########################################################################################
OPENAI_KEY = getenv('OPENAI_KEY')
###########################################################################################
###########################################################################################
DREY="\x02\x0315"
GREY="\x02\x0314"
DRED="\x02\x0302"
LRED="\x02\x0312"
###########################################################################################
###########################################################################################
class OPENAI_MESSAGE_HISTORY():
#######################################################################################
#######################################################################################
openai_messages = []
user_messages = []
user_users = []
#######################################################################################
#######################################################################################
def __init__(self):
self.processing=0
#######################################################################################
#######################################################################################
def push_openai_messages(self,data):
self.openai_messages = self.openai_messages[-1:] + self.openai_messages[:-1]
self.openai_messages[0] = data
#######################################################################################
#######################################################################################
def push_user_messages(self,user,data):
self.user_users.append(user)
self.user_messages.append(data)
#######################################################################################
#######################################################################################
def similar(self,a,b):
return SequenceMatcher(None,a,b).ratio()
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
self.bot.openai_history=OPENAI_MESSAGE_HISTORY()
#############################################
for _ in range(5):
self.bot.openai_history.openai_messages.append("")
#############################################
self.openai_io=[]
self.start_chat_log=""
self.lastterm=""
@ -63,8 +108,10 @@ class Plugin:
self.presence_penalty=0.0
self.flipcolor=False
self.default_load()
#######################################################################################
#######################################################################################
@command(permission='view')
def ai(self, mask, target, args):
"""OpenAi Question A Term
@ -72,10 +119,8 @@ class Plugin:
"""
term=' '.join(args['<term>'])
if not term[-1] == ".": term+="."
openai.api_key = OPENAPI_KEY
######################################################################################
openai.api_key = OPENAI_KEY
print(f"<<< openai: processing {target} {mask.nick.lower()} message: {term.lower()}")
######################################################################################
MESSAGE_OK=True
TRAP_OK=True
LOOP_COUNT_LIMIT=5
@ -95,66 +140,12 @@ class Plugin:
presence_penalty=self.presence_penalty
)
self.lastresponse=response
##################################################################################
openai_message=response.choices[0].text
USER=mask.nick
MESSAGE=term
# ################################################################################### REPROCESSOR SOF
# # SIMILARITY - QUERY SENT VS QUERY ANSWER
# if MESSAGE_OK:
# if self.bot.openai_history.similar(openai_message.lower(),term.lower())>0.4:
# self.openai_io.append({'user':USER,'message':MESSAGE,'target':target})
# print(f'openai - logic ! rejected // openai similarity - response too similar to query')
# TRAP_OK=False
# ################################################################################### REPROCESSOR SOF
# # SIMILARITY - QUERY ANSWER VS PERSONALITY PROFILE DATABASE
# if MESSAGE_OK:
# if self.bot.openai_history.similar(openai_message.lower().strip(),' '.join(self.start_chat_log.strip().splitlines())[:len(openai_message.strip())])>0.4:
# self.openai_io.append({'user':USER,'message':MESSAGE,'target':target})
# print(f'openai - logic ! rejected // openai similarity - response too similar to persoanlity profile database')
# TRAP_OK=False
# ###################################################################################
# # SIMILARITY - HISTORY
# if MESSAGE_OK:
# for i in range(len(self.bot.openai_history.openai_messages)):
# if self.bot.openai_history.similar(openai_message,str(self.bot.openai_history.openai_messages[i]))>0.8:
# self.openai_io.append({'user':USER,'message':MESSAGE,'target':target})
# print(f'openai - logic ! rejected // openai similarity - repeat of previous response')
# TRAP_OK=False
# ###################################################################################
# # MOCK / DUPE
# if MESSAGE_OK:
# if self.bot.openai_history.similar(openai_message,MESSAGE)>0.8:
# self.openai_io.append({'user':USER,'message':MESSAGE,'target':target})
# print(f'openai - logic ! rejected // human mock - openai response same as human')
# TRAP_OK=False
# ###################################################################################
# # GPT LOOP GLITCH
# if MESSAGE_OK:
# n=len(openai_message.split())
# i=len(set(openai_message.split()))
# if i<int(n/2):
# self.openai_io.append({'user':USER,'message':MESSAGE,'target':target})
# print(f'openai - logic ! rejected // gpt loop glitch - reiterating same thing in multiples')
# TRAP_OK=False
# ###################################################################################
# # LIMITED RESPONSE
# if MESSAGE_OK:
# n=len(openai_message.split())
# if i<3:
# self.openai_io.append({'user':USER,'message':MESSAGE,'target':target})
# print(f'openai - logic ! rejected // limited response - skip an unfinished token chain')
# TRAP_OK=False
###################################################################################
if MESSAGE_OK and TRAP_OK:
self.bot.openai_history.push_openai_messages(openai_message)
_msg = re.findall(r'.{1,400}(?:\s+|$)', openai_message)
#if len(_msg) > 1:
# if len(_msg[0]) < len(_msg[1])//2:
# print(f'openai - discovered and removed a preface glitch: {_msg[0].strip()}')
# _msg.reverse()
# _msg.pop()
# _msg.reverse()
COLOR=""
self.flipcolor = not self.flipcolor
if self.flipcolor:
@ -168,20 +159,22 @@ class Plugin:
self.bot.privmsg(target, f"{COLOR}{_.strip()}\x0F")
MESSAGE_OK=False
print('<<< openai finished >>>')
###################################################################################
if LOOP_COUNT > LOOP_COUNT_LIMIT:
print(f"<<< openai failed: bouncing to mapleai >>>")
self.bot.history.bounce={'user':USER,'message':term,'target':target}
#MESSAGE=f"{GREY}<<< {DRED}i got nothing to say {GREY}>>>"
#self.bot.privmsg(target, f"{USER}: {MESSAGE}")
break
################################################################################### REPROCESSOR EOF
#######################################################################################
#######################################################################################
def random_float(self,n):
i=float(rint(0,n))
i/=10
return i
#######################################################################################
#######################################################################################
def print_response_properties(self,target):
self.bot.privmsg(target, f"{DRED} model{GREY}: {LRED}{self.default_model}")
self.bot.privmsg(target, f"{DRED} temperature{GREY}: {LRED}{self.temperature}")
@ -189,7 +182,10 @@ class Plugin:
self.bot.privmsg(target, f"{DRED} top_p{GREY}: {LRED}{self.top_p}")
self.bot.privmsg(target, f"{DRED}frequency_penalty{GREY}: {LRED}{self.frequency_penalty}")
self.bot.privmsg(target, f"{DRED} presence_penalty{GREY}: {LRED}{self.presence_penalty}")
#######################################################################################
#######################################################################################
@command(permission='admin')
def airand(self, mask, target, args):
"""OpenAi Randomize Response Properties
@ -208,7 +204,10 @@ class Plugin:
self.presence_penalty=self.random_float(20)
self.bot.privmsg(target, self.bot.emo(f"{GREY}<<< {DRED}randomizing personality properties {GREY}>>>"))
self.print_response_properties(target)
#######################################################################################
#######################################################################################
def default_load(self):
FILE='%s/../personalities/default.db' % dir_path
f=open(FILE,'r')
@ -216,7 +215,10 @@ class Plugin:
if self.start_chat_log.find('\n')==0:
self.start_chat_log=self.start_chat_log[1:]
f.close()
#######################################################################################
#######################################################################################
@command(permission='admin')
def airead(self, mask, target, args):
"""OpenAi Read Current Personality
@ -230,7 +232,10 @@ class Plugin:
msg = re.findall(r'.{1,400}(?:\s+|$)', _)
for __ in msg:
self.bot.privmsg(target, f'{__.strip()}')
#######################################################################################
#######################################################################################
@command(permission='admin')
def aishow(self, mask, target, args):
"""OpenAi Show Current Personality Properties and Values.
@ -238,7 +243,10 @@ class Plugin:
"""
self.bot.privmsg(target, self.bot.emo(f"{GREY}<<< {DRED}showing current personality properties {GREY}>>>"))
self.print_response_properties(target)
#######################################################################################
#######################################################################################
@command(permission='admin')
def aiterm(self, mask, target, args):
"""OpenAi Show Last Term.
@ -249,7 +257,10 @@ class Plugin:
msg = re.findall(r'.{1,400}(?:\s+|$)', _)
for __ in msg:
self.bot.privmsg(target, f'{__.strip()}')
#######################################################################################
#######################################################################################
@command(permission='admin')
def airesponse(self, mask, target, args):
"""OpenAi Show Last Server Response.
@ -267,11 +278,9 @@ class Plugin:
PROMPT_TOKENS=MODEL=self.lastresponse['usage']['prompt_tokens']
TOTAL_TOKENS=MODEL=self.lastresponse['usage']['total_tokens']
_TEXT=re.findall(r'.{1,400}(?:\s+|$)', TEXT)
#msg.append(f'{GREY}[{DRED}usage{GREY}]')
msg.append(f'{DRED}completion_tokens{GREY}: {LRED}{COMPLETION_TOKENS}')
msg.append(f' {DRED}prompt_tokens{GREY}: {LRED}{PROMPT_TOKENS}')
msg.append(f' {DRED}total_tokens{GREY}: {LRED}{TOTAL_TOKENS}')
#msg.append(f'{GREY}[{DRED}choices{GREY}]')
msg.append(f' {DRED}index{GREY}: {LRED}{INDEX}')
msg.append(f' {DRED}logprobs{GREY}: {LRED}{LOGPROBS}')
if len(_TEXT) > 1:
@ -287,7 +296,10 @@ class Plugin:
msg.append(f'{LRED}{_.strip()}')
for _ in msg:
self.bot.privmsg(target, _)
#######################################################################################
#######################################################################################
@command(permission='admin')
def ailist(self, mask, target, args):
"""OpenAi List Personalities
@ -299,7 +311,10 @@ class Plugin:
for i,_ in enumerate(FILES):
FILE=_.split('/')[-1].replace('.db','')
self.bot.privmsg(target, f'{DRED}{i}{GREY}: {LRED}{FILE}')
#######################################################################################
#######################################################################################
@command(permission='admin')
def aiload(self, mask, target, args):
"""OpenAi Load Personalities
@ -325,7 +340,10 @@ class Plugin:
except:
self.bot.privmsg(target, self.bot.emo(f'{GREY}<<< {DRED}error{GREY}: {LRED}could not load this personality database, maybe invalid index number {GREY}>>>'))
return
#######################################################################################
#######################################################################################
@command(permission='admin')
def aiwrite(self, mask, target, args):
"""OpenAi List Personalities
@ -344,7 +362,10 @@ class Plugin:
f.write(f'{self.start_chat_log}\n')
f.close()
self.bot.privmsg(target, self.bot.emo(f"{GREY}<<< {DRED}created {msg} personality database {GREY}>>>"))
#######################################################################################
#######################################################################################
@command(permission='admin')
def aitrain(self, mask, target, args):
"""OpenAi Question A Term
@ -359,7 +380,10 @@ class Plugin:
f.close()
self.start_chat_log=f'{self.start_chat_log}\n{term}'
self.bot.privmsg(target, self.bot.emo(f"{GREY}<<< {DRED}trained {GREY}>>>"))
#######################################################################################
#######################################################################################
@command(permission='admin')
def aidefault(self, mask, target, args):
"""OpenAi Return to Defaults
@ -373,7 +397,10 @@ class Plugin:
self.presence_penalty=0.0
self.bot.privmsg(target, self.bot.emo(f"{GREY}<<< {DRED}setting personality and properties to defaults {GREY}>>>"))
self.print_response_properties(target)
#######################################################################################
#######################################################################################
@command(permission='admin')
def aiset(self, mask, target, args):
"""OpenAi Set Response Properties. Properties are default_model, temperature, max_tokens, top_p, frequency_penalty, presence_penalty. Example Usage: ?aiset top_p 1.0
@ -384,7 +411,6 @@ class Plugin:
MODELS=["text-davinci-002","text-curie-001","text-babbage-001","text-ada-001"]
prop=""
val=""
try:
prop=msg.split()[0].lower()
val=msg.split()[1].lower()
@ -457,7 +483,10 @@ class Plugin:
return
self.bot.privmsg(target, self.bot.emo(f"{GREY}<<< {DRED}{prop} property set to the value {val} {GREY}>>>"))
self.print_response_properties(target)
#######################################################################################
#######################################################################################
@command(permission='admin')
def aiclear(self, mask, target, args):
"""OpenAi Clear Term
@ -469,7 +498,6 @@ class Plugin:
f.close()
self.start_chat_log = ""
self.bot.privmsg(target, self.bot.emo(f"{GREY}<<< {DRED}cleared {GREY}>>>"))
#######################################################################################
###########################################################################################
###########################################################################################
#.[d].
####################################################################################### EOF

@ -1,18 +1,26 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
import random
import uuid
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self,bot):
self.bot=bot
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.JOIN)
def quote_user_join(self, mask, channel, **kw):
"""quote a user when they join"""
@ -31,8 +39,10 @@ class Plugin:
msg=self.bot.emo(msg)
print(f'\n{msg}\n')
self.bot.privmsg(channel,msg)
#######################################################################################
#######################################################################################
@command(permission='view')
def quote(self,mask,target, args):
"""quote user message
@ -62,8 +72,10 @@ class Plugin:
status=f"\x02\x0304error \x02\x0303>\x0F {e.message[0]['message']}'"
msg=self.bot.emo(status)
self.bot.privmsg(target,msg)
#######################################################################################
#######################################################################################
@command(permission='view',show_in_help_list=False)
def quotes(self, mask, target, args):
"""quotes user
@ -82,7 +94,6 @@ class Plugin:
msg=user+' \x02\x0303>\x0F '+quote_user[i]
msg=self.bot.emo(msg)
self.bot.privmsg(target,msg)
#######################################################################################
#######################################################################################
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,15 +1,23 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
from irc3.plugins.cron import cron
import irc3
###########################################################################################
###########################################################################################
import os
import sys
import re
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
from random import randint
###########################################################################################
###########################################################################################
__doc__ = '''#######################################################################################
####################################################################################################
@ -48,6 +56,8 @@ MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMdyymMMMMMMMMMMMMMMMMMMMMMMMMMMM
####################################################################################################
#################################################################################################'''
###########################################################################################
###########################################################################################
rgb2irc = { 52: '16', 94: '17', 100: '18', 58: '19', 22: '20', 29: '21', 23: '22', 24: '23', 17: '24', 54: '25', 53: '26', 89: '27',
88: '28', 130: '29', 142: '30', 64: '31', 28: '32', 35: '33', 30: '34', 25: '35', 18: '36', 91: '37', 90: '38', 125: '39',
@ -107,17 +117,22 @@ set2rgb = { 52: '#470000', 94: '#472100', 100: '#474700', 58: '#324700'
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
def ratesex_request(self,site,commands):
USER_AGENT_BROWSER="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
USER_AGENT_CURL="curl/7.29.0"
STATUS_BAD_CODE=":( - error code: {}"
STATUS_BAD_REASON=":( - failed reason: {}"
STATUS_OK=":)"
if site != 'rate':
url = f"https://{site}.rate.sx/{commands}"
else:
@ -133,34 +148,40 @@ class Plugin:
return STATUS_OK + response
#######################################################################################
#######################################################################################
def escape_ansi(self,line):
ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]')
return ansi_escape.sub('', str(line))
#######################################################################################
#######################################################################################
def invert_dict(self,d):
return {v: k for k, v in d.items()}
#######################################################################################
#######################################################################################
def enumerate_dict(self,d):
return list(zip(list(d),list(invert_dict(d)),range(len(d))))
#######################################################################################
#######################################################################################
def organize_dict(self,d):
_d=list(d.values())
return _d.sort()
#######################################################################################
#######################################################################################
def escape_ansi(self,line):
ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]')
return ansi_escape.sub('', str(line))
#######################################################################################
#######################################################################################
def hex2gravity(self,h):
r,g,b=int(h[1:3],16),int(h[3:5],16),int(h[5:7],16)
@ -203,6 +224,7 @@ class Plugin:
return str(f"\x03{rgb2irc[self.invert_dict(set2rgb)[nearest_color]]}")
#######################################################################################
#######################################################################################
def parse_control(self,s):
px=[]
@ -214,12 +236,14 @@ class Plugin:
return px,py
#######################################################################################
#######################################################################################
def findall(self,s,w):
return [i for i in range(len(s)) if s.startswith(w, i)]
#######################################################################################
#######################################################################################
def color_line(self,s,t):
codes=["\x1b[0m","\x1b[30m","\x1b[31m","\x1b[32m","\x1b[33m","\x1b[34m","\x1b[35m","\x1b[36m","\x1b[37m","\x1b[40m","\x1b[41m","\x1b[42m","\x1b[43m","\x1b[44m","\x1b[45m","\x1b[46m","\x1b[47m","\x1b(B","\x1b[m","\x1b[2m"]
@ -228,7 +252,6 @@ class Plugin:
p=[]
for _ in range(len(t[0])):
r=self.findall(s[t[0][_]:t[1][_]],'\x1b')
for __ in range(len(r)):
if not __ == len(r)-1:
p.append(s[t[0][_]:t[1][_]][r[__]:r[__+1]])
@ -250,14 +273,13 @@ class Plugin:
farthest_color_hex = rgb2set['ef{}'.format(gravity)]
result = self.hex2gravity(farthest_color_hex)
c.append(result)
r=self.findall(_s,'{}')
for _ in range(len(r)):
_s=_s.replace('{}',c[_],1)
return _s
#######################################################################################
#######################################################################################
@command(permission='view')
def ratesex(self, mask, target, args):
@ -294,6 +316,7 @@ class Plugin:
self.bot.privmsg(target, msg)
#######################################################################################
#######################################################################################
__doc__ = ''':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::.
@ -346,5 +369,6 @@ __doc__ = ''':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-ymNNNNNNNNNNNNNNNNNNNNNNNNdo-` +NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNmy.
............................ .-...............................`
`````` ````````` `````````````` `````````` ```'''
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,29 +1,43 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
from irc3.plugins.cron import cron
import irc3
from datetime import datetime
from time import time
import re
###########################################################################################
###########################################################################################
REMIND_RE = re.compile('maple.remind\s(.+?)\s(.+)')
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
def __triggered(i):
time_now = int(str(time()).split('.')[0])
if i <= time_now:
print('triggered')
else:
print('not triggered')
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
@irc3.extend
def on_privmsg_search_for_remind(self, mask=None, target=None, data=None, **kw):
@ -81,10 +95,10 @@ class Plugin:
self.bot.db.setlist("remind_%s" % tell_nick.lower(), message_list)
irc_message = "TCPDIRECT/REMIND: {} < {} > reminding < {} > {}".format(new_message.get("time"),new_message.get("from"),tell_nick,new_message.get("message"))
self.bot.privmsg(target, self.bot.emo(irc_message))
#######################################################################################
#######################################################################################
###########################################################################################
###########################################################################################
@cron('* * * * *')
def _reminding(bot):
nicks = ','.join(bot.db.context.nicks.keys()).split(',')
@ -104,6 +118,6 @@ def _reminding(bot):
else:
_keys.append(__)
bot.db.setlist("remind_{}".format(_),_keys)
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,13 +1,39 @@
# -*- coding: utf-8 -*- ########################################################## SOF
import irc3,os,base64
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
import irc3,os,sys,base64
from plugins.tool_colors_plugin import colorform as print
######################################################################################
BOT_SASL_USERNAME=os.environ['BOT_SASL_USERNAME']
BOT_SASL_PASSWORD=os.environ['BOT_SASL_PASSWORD']
######################################################################################
from plugins.tool_log_plugin import FOG
###########################################################################################
###########################################################################################
def getenv(s):
try:
s = os.environ[s]
return s
except:
fog=FOG().fog
error_type="environmental variable error"
error_reason=f"exported {s} not found"
fog(f"{error_type}: {error_reason}")
sys.exit(1)
###########################################################################################
###########################################################################################
BOT_SASL_USERNAME=getenv('BOT_SASL_USERNAME')
BOT_SASL_PASSWORD=getenv('BOT_SASL_PASSWORD')
###########################################################################################
###########################################################################################
@irc3.plugin
class DR1PSASL:
##################################################################################
#######################################################################################
#######################################################################################
def __init__(self, bot):
print('<<< _sasl_custom_plugin >>> [ custom sasl initiated ]')
self.bot=bot
@ -20,31 +46,46 @@ class DR1PSASL:
irc3.event(r'AUTHENTICATE +', self.authenticate),
irc3.event(r'^:\S+ 903 \S+ :Authentication successful',self.cap_end),
]
##################################################################################
#######################################################################################
#######################################################################################
def connection_ready(self, *args, **kwargs):
print('<<< _sasl_custom_plugin >>> [ CAP LS ]')
self.bot.send('CAP LS\r\n')
self.bot.attach_events(*self.events)
##################################################################################
#######################################################################################
#######################################################################################
def cap_ls(self, data=None, **kwargs):
print('<<< _sasl_custom_plugin >>> [ CAP REQ :sasl ]')
if 'sasl' in data.lower():
self.bot.send_line('CAP REQ :sasl')
else:
self.cap_end()
##################################################################################
#######################################################################################
#######################################################################################
def cap_ack(self, **kwargs):
print('<<< _sasl_custom_plugin >>> [ AUTHENTICATE PLAIN ]')
self.bot.send_line('AUTHENTICATE PLAIN')
##################################################################################
#######################################################################################
#######################################################################################
def authenticate(self, **kwargs):
print(f'<<< _sasl_custom_plugin >>> [ AUTHENTICATE {self.auth} ]')
self.bot.send_line(f'AUTHENTICATE {self.auth}\n')
##################################################################################
#######################################################################################
#######################################################################################
def cap_end(self, **kwargs):
print('<<< _sasl_custom_plugin >>> [ CAP END ]')
self.bot.send_line('CAP END\r\n')
self.bot.detach_events(*self.events)
##################################################################################
################################################################################## EOF
#.[d].
###########################################################################################
####################################################################################### EOF

@ -1,42 +1,54 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
import irc3
import os
import random
from string import ascii_lowercase as alpha
SED1_RE = "s/"
SED2_RE = "j/"
###########################################################################################
###########################################################################################
class TCPSED():
buffer_text=[]
buffer_nick=[]
#######################################################################################
#######################################################################################
def __init__(self):
return
#######################################################################################
#######################################################################################
def push(self,data,nick):
self.buffer_text=self.buffer_text[-1:]+self.buffer_text[:-1]
self.buffer_text[0]=data
self.buffer_nick=self.buffer_nick[-1:]+self.buffer_nick[:-1]
self.buffer_nick[0]=nick
#######################################################################################
#######################################################################################
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.d=TCPSED()
for _ in range(2000):
self.d.buffer_text.append('')
self.d.buffer_nick.append('')
self.bot = bot
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg_search_for_sed(self, mask=None, target=None, data=None, **kw):
if self.bot.config.nick == mask.nick:
@ -70,14 +82,14 @@ class Plugin:
count=0
for i,_ in enumerate(self.d.buffer_text):
if not _ == '':
itwist=i
count = len([_i for _i in range(len(_)) if _.startswith(_from, _i)])
if count == 1:
self.d.buffer_text[i] = self.d.buffer_text[i].replace(_from,_to)
break
elif count > 1:
self.d.buffer_text[i] = self.d.buffer_text[i].replace(_from,_to,1)
break
itwist=i
count = len([_i for _i in range(len(_)) if _.startswith(_from, _i)])
if count == 1:
self.d.buffer_text[i] = self.d.buffer_text[i].replace(_from,_to)
break
elif count > 1:
self.d.buffer_text[i] = self.d.buffer_text[i].replace(_from,_to,1)
break
if count != 0:
irc_message = "{}: {}".format(self.d.buffer_nick[itwist],self.d.buffer_text[itwist])
else:
@ -91,7 +103,6 @@ class Plugin:
self.bot.privmsg(target,self.bot.emo(irc_message))
except:
self.bot.privmsg(target,self.bot.emo(irc_message))
#######################################################################################
#######################################################################################
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,29 +1,39 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
from datetime import datetime
import operator
import irc3
import timeago
import dateutil.parser
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
return
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.NEW_NICK)
def on_nick_change_for_seen(self, nick, new_nick):
# record of nickchanges, these are kept
# "5": {
# "msg": "_d changed nick to d",
# "time": "2021-10-03T00:24:03.040916",
# "type": "newnick"
# },
new_key = "last_msg_for_{}".format(new_nick).lower()
msg_list = self.bot.db.getlist(new_key)
if not msg_list:
@ -34,8 +44,10 @@ class Plugin:
msg_list.append(seen_msg)
self.bot.db.setlist(new_key, msg_list)
return
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg_for_seen(self, mask=None, target=None, data=None, **kw):
if data.startswith("?"): return # no ?
@ -87,8 +99,10 @@ class Plugin:
messages.append(priv_msg)
self.bot.db.setlist(key, messages)
return
#######################################################################################
#######################################################################################
@command(permission='view')
def seen(self, mask, target, args):
"""Display last time user was seen
@ -123,7 +137,6 @@ class Plugin:
msg = self.bot.emo(msg)
self.bot.privmsg(target, msg)
return
#######################################################################################
#######################################################################################
###########################################################################################
###########################################################################################
####################################################################################### EOF

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
from urllib.request import Request, urlopen
@ -7,16 +9,22 @@ from urllib.parse import quote_plus
import html
import requests
from lxml.html import fromstring
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
def __soundcloud__request(self,command,query):
USER_AGENT_CURL="curl/7.29.0"
STATUS_BAD_CODE=":( - error code: {}"
@ -35,8 +43,10 @@ class Plugin:
return STATUS_BAD_REASON.format(e.reason)
else:
return STATUS_OK+response
#######################################################################################
#######################################################################################
@command(permission='view')
def sc(self, mask, target, args):
"""Soundcloud artist/song search.. example: ?sc yung innanet nano tapes cronjob
@ -72,9 +82,15 @@ class Plugin:
URL=f'https://soundcloud.com/{_path[0]}'
TITLE=title.split('|')[0].split('by')[-1].strip()
NAME=html.unescape(_name[0]);
######## SOUNDCLOUD <-> BOOMBOX_PLUGIN HOOK ######## SOUNDCLOUD <-> BOOMBOX_PLUGIN HOOK ########
######## SOUNDCLOUD <-> BOOMBOX_PLUGIN HOOK <-> SOUNDCLOUD ####################
######## SOUNDCLOUD <-> BOOMBOX_PLUGIN HOOK <-> SOUNDCLOUD ####################
self.bot.bbs.enter(NICK,URL,TITLE)
######## SOUNDCLOUD <-> BOOMBOX_PLUGIN HOOK ######## SOUNDCLOUD <-> BOOMBOX_PLUGIN HOOK ########
######## SOUNDCLOUD <-> BOOMBOX_PLUGIN HOOK <-> SOUNDCLOUD ####################
######## SOUNDCLOUD <-> BOOMBOX_PLUGIN HOOK <-> SOUNDCLOUD ####################
msg=f"\x02\x0302{NICK}\x0F\x02\x0304 > "
msg+=f"\x0F\x02\x0313{NAME}\x0F\x02\x0304 > "
msg+=f"\x0F\x02\x0312{URL}\x0F\x02\x0313\x0F\x02\x0304 > "
@ -84,6 +100,6 @@ class Plugin:
msg=f"\x02\x0302{NICK}\x0F\x02\x0304 > "
msg+=f"\x0F\x02\x0313{MSG}\x0F\x02\x0304 "
self.bot.privmsg(target,self.bot.emo(f"{msg}"))
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
import os
try:
import ujson as json
@ -6,34 +8,65 @@ except ImportError:
import json
import irc3
import shelve
###########################################################################################
###########################################################################################
class Shelve:
#######################################################################################
#######################################################################################
def __init__(self, uri=None, **kwargs):
self.filename = uri[9:]
self.db = shelve.open(self.filename)
#######################################################################################
#######################################################################################
def set(self, key, value):
self.db[key] = value
self.db.sync()
#######################################################################################
#######################################################################################
def get(self, key):
return self.db[key]
#######################################################################################
#######################################################################################
def delete(self, key):
del self.db[key]
self.sync()
#######################################################################################
#######################################################################################
def contains(self, key):
return key in self.db
#######################################################################################
#######################################################################################
def sync(self):
self.db.sync()
#######################################################################################
#######################################################################################
def close(self):
self.db.close()
###########################################################################################
###########################################################################################
class JSON:
#######################################################################################
#######################################################################################
def __init__(self, uri=None, **kwargs):
self.filename = uri[7:]
if os.path.isfile(self.filename): # pragma: no cover
@ -41,39 +74,70 @@ class JSON:
self.db = json.load(fd)
else:
self.db = {}
#######################################################################################
#######################################################################################
def set(self, key, value):
self.db[key] = value
self.sync()
#######################################################################################
#######################################################################################
def get(self, key):
return self.db[key]
#######################################################################################
#######################################################################################
def delete(self, key):
del self.db[key]
self.sync()
#######################################################################################
#######################################################################################
def contains(self, key):
return key in self.db
#######################################################################################
#######################################################################################
def sync(self):
with open(self.filename, 'w') as fd:
json.dump(self.db, fd, indent=2, sort_keys=True)
#######################################################################################
#######################################################################################
def close(self):
self.sync()
###########################################################################################
###########################################################################################
class Redis:
#######################################################################################
#######################################################################################
def __init__(self, uri=None, **kwargs):
ConnectionPool = irc3.utils.maybedotted(
'redis.connection.ConnectionPool')
pool = ConnectionPool.from_url(uri)
StrictRedis = irc3.utils.maybedotted('redis.client.StrictRedis')
self.db = StrictRedis(connection_pool=pool)
#######################################################################################
#######################################################################################
def set(self, key, value):
self.db.hmset(key, value)
#######################################################################################
#######################################################################################
def get(self, key):
keys = self.db.hkeys(key)
if not keys:
@ -83,22 +147,40 @@ class Redis:
values = [v.decode('utf8') for v in values]
values = dict(zip(keys, values))
return values
#######################################################################################
#######################################################################################
def delete(self, key):
self.db.delete(key)
#######################################################################################
#######################################################################################
def contains(self, key):
return self.db.exists(key)
#######################################################################################
#######################################################################################
def flushdb(self):
self.db.flushdb()
#######################################################################################
#######################################################################################
def sync(self):
self.db.save()
#######################################################################################
#######################################################################################
def close(self):
self.sync()
###########################################################################################
###########################################################################################
class SQLite:
CREATE_TABLE = """
CREATE TABLE IF NOT EXISTS
@ -111,7 +193,10 @@ class SQLite:
UPSERT = """
INSERT OR REPLACE INTO irc3_storage(key,value) VALUES(?, ?);
"""
#######################################################################################
#######################################################################################
def __init__(self, uri=None, **kwargs):
self.sqlite = irc3.utils.maybedotted('sqlite3')
self.uri = uri.split('://')[-1]
@ -120,7 +205,10 @@ class SQLite:
cursor.execute(self.CREATE_TABLE)
conn.commit()
conn.close()
#######################################################################################
#######################################################################################
def set(self, key, value):
conn = self.sqlite.connect(self.uri)
cursor = conn.cursor()
@ -128,7 +216,10 @@ class SQLite:
cursor.fetchall()
conn.commit()
conn.close()
#######################################################################################
#######################################################################################
def get(self, key):
value = None
conn = self.sqlite.connect(self.uri)
@ -142,7 +233,10 @@ class SQLite:
if value is None:
raise KeyError(key)
return value
#######################################################################################
#######################################################################################
def delete(self, key):
conn = self.sqlite.connect(self.uri)
cursor = conn.cursor()
@ -150,7 +244,10 @@ class SQLite:
cursor.close()
conn.commit()
conn.close()
#######################################################################################
#######################################################################################
def contains(self, key):
conn = self.sqlite.connect(self.uri)
cursor = conn.cursor()
@ -161,7 +258,10 @@ class SQLite:
cursor.close()
conn.close()
return res
#######################################################################################
#######################################################################################
def flushdb(self):
conn = self.sqlite.connect(self.uri)
cursor = conn.cursor()
@ -170,13 +270,22 @@ class SQLite:
cursor.close()
conn.commit()
conn.close()
#######################################################################################
#######################################################################################
def sync(self):
pass
#######################################################################################
#######################################################################################
def close(self):
pass
###########################################################################################
###########################################################################################
@irc3.plugin
class Storage:
backends = {
@ -187,7 +296,10 @@ class Storage:
'rediss': Redis,
'sqlite': SQLite,
}
#######################################################################################
#######################################################################################
def __init__(self, context):
uri = context.config.storage
name = uri.split('://', 1)[0]
@ -198,7 +310,10 @@ class Storage:
self.backend = factory(uri)
self.context = context
self.context.db = self
#######################################################################################
#######################################################################################
def setdefault(self, key_, **kwargs):
"""Update storage value for key with kwargs iif the keys doesn't
exist. Return stored values"""
@ -213,14 +328,20 @@ class Storage:
if changed:
self[key_] = stored
return kwargs
#######################################################################################
#######################################################################################
def get(self, key_, default=None):
"""Get storage value for key or return default"""
if key_ not in self:
return default
else:
return self[key_]
#######################################################################################
#######################################################################################
def getlist(self, key_, default=None):
"""Get storage value (as list) for key or return default"""
if key_ not in self:
@ -229,7 +350,10 @@ class Storage:
value = self[key_]
value = [(int(i), v) for i, v in value.items()]
return [v for k, v in sorted(value)]
#######################################################################################
#######################################################################################
def set(self, key_, **kwargs):
"""Update storage value for key with kwargs"""
stored = self.get(key_, dict())
@ -240,14 +364,20 @@ class Storage:
changed = True
if changed:
self[key_] = stored
#######################################################################################
#######################################################################################
def setlist(self, key_, value):
"""Update storage value (as list)"""
value = dict([(str(i), v) for i, v in enumerate(value)])
if key_ in self:
del self[key_]
self.set(key_, **value)
#######################################################################################
#######################################################################################
def __setitem__(self, key, value):
"""Set storage value for key"""
key = getattr(key, '__module__', key)
@ -258,7 +388,10 @@ class Storage:
except Exception as e: # pragma: no cover
self.context.log.exception(e)
raise
#######################################################################################
#######################################################################################
def __getitem__(self, key):
"""Get storage value for key"""
key = getattr(key, '__module__', key)
@ -269,7 +402,10 @@ class Storage:
except Exception as e: # pragma: no cover
self.context.log.exception(e)
raise
#######################################################################################
#######################################################################################
def __delitem__(self, key):
"""Delete key in storage"""
key = getattr(key, '__module__', key)
@ -278,7 +414,10 @@ class Storage:
except Exception as e: # pragma: no cover
self.context.log.exception(e)
raise
#######################################################################################
#######################################################################################
def __contains__(self, key):
"""Return True if storage contains key"""
key = getattr(key, '__module__', key)
@ -287,8 +426,12 @@ class Storage:
except Exception as e: # pragma: no cover
self.context.log.exception(e)
raise
#######################################################################################
#######################################################################################
def SIGINT(self):
self.backend.close()
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,17 +1,25 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
import requests
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
def _get_weed(self,t,s):
try:
url=""
@ -28,8 +36,10 @@ class Plugin:
return r.json()
except:
return -1
#######################################################################################
#######################################################################################
@command(permission='view')
def strain(self, mask, target, args):
"""strain
@ -85,7 +95,6 @@ class Plugin:
except:
msg = "strain: not found"
self.bot.privmsg(target, msg)
#######################################################################################
#######################################################################################
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,15 +1,26 @@
# -*- coding: utf-8 -*- ############################################################################# SOF
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
from irc3.plugins.cron import cron
import irc3
import socket
#########################################################################################################
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#########################################################################################################
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#####################################################################################################
#######################################################################################
#######################################################################################
@command(permission='view')
def tcpac(self, mask, target, args):
"""tcpac - the irc version of `cat file - | nc tcp.ac 9999`, usage: ?tcpac message
@ -28,6 +39,6 @@ class Plugin:
self.bot.privmsg(target,msg)
msg=f"{mask.nick}: irc version of `cat file - | nc tcp.ac 9999` -> del: {delmsg}"
self.bot.privmsg(mask.nick,msg)
#####################################################################################################
##################################################################################################### EOF
#.[d].
###########################################################################################
####################################################################################### EOF

@ -1,18 +1,26 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from datetime import datetime
import irc3
import re
TELL_RE = re.compile('maple.tell\s(.+?)\s(.+)')
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg_search_to_tell(self, mask=None, target=None, data=None, **kw):
if mask.nick.lower() == "maple":
@ -23,8 +31,10 @@ class Plugin:
irc_message = "TCPDIRECT/TOLD: {} <{}> told <{}> {}".format(msg.get("time"),msg.get("from"),mask.nick,msg.get("message"))
self.bot.privmsg(target, self.bot.emo(irc_message))
self.bot.db.setlist("tell_%s" % mask.nick.lower(), messages_to_send[1:])
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg_search_for_tell(self, mask=None, target=None, data=None, **kw):
match_list = TELL_RE.findall(data)
@ -40,7 +50,7 @@ class Plugin:
self.bot.db.setlist("tell_%s" % tell_nick.lower(), message_list)
irc_message = "TCPDIRECT/TELL: {} <{}> telling <{}> {}".format(new_message.get("time"),new_message.get("from"),tell_nick,new_message.get("message"))
self.bot.privmsg(target, self.bot.emo(irc_message))
#######################################################################################
#######################################################################################
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
from datetime import datetime
@ -7,12 +9,21 @@ from pytz import common_timezones
from pytz import timezone
import re
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@command(permission='view')
def timezonediff(self, mask, target, args):
"""timezonediff - '?timezonediff yourzone theirzone calendar_date theirzone_event_time message' or '?timezonediff yourzone theirzone theirzone_event_time message'
@ -32,6 +43,9 @@ class Plugin:
self.bot.privmsg(target,self.bot.emo(msg))
return
###################################################################################
###################################################################################
try:
zone2=timezone(noise.split()[1])
except:
@ -43,6 +57,9 @@ class Plugin:
self.bot.privmsg(target,self.bot.emo(msg))
return
###################################################################################
###################################################################################
FLAG_DATE=False
try:
date=noise.split()[2].replace("/","")
@ -74,6 +91,9 @@ class Plugin:
except:
pass #with no date set we presume it is implied as an event today from now into the time of then
###################################################################################
###################################################################################
if not FLAG_DATE:
try:
stime=noise.split()[2]
@ -95,6 +115,9 @@ class Plugin:
self.bot.privmsg(target,self.bot.emo(msg))
return
###################################################################################
###################################################################################
if not FLAG_DATE:
try:
smessage=' '.join(noise.split()[3:])
@ -121,6 +144,9 @@ class Plugin:
self.bot.privmsg(target,self.bot.emo(msg))
return
###################################################################################
###################################################################################
dtf=datetime(int(year),int(month),int(day),int(hour),int(minute))
dtn=datetime.now()
# zone1=timezone('us/central')
@ -133,6 +159,9 @@ class Plugin:
tsz2b=z3.timestamp()
timedistance=timeago.format(tsz2b-delta.seconds,tsz2a)
###################################################################################
###################################################################################
if str(timedistance).startswith('in'):
msg = f'i will remind in you {timedistance} in your local timezone of {zone1} about {smessage}'
self.bot.privmsg(target, msg)
@ -148,4 +177,6 @@ class Plugin:
else:
msg = f'sorry, this time of event is in the past now {timedistance}'
self.bot.privmsg(target, self.bot.emo(msg))
#.[d].
###########################################################################################
####################################################################################### EOF

@ -1,84 +1,179 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
???DISCORD???
???TELEGRAM???
???MATRIX???
###########################################################################################
###########################################################################################
if SERVICES_MATRIX:
global matrixbot
###########################################################################################
###########################################################################################
global bus, dims, ircbot
from plugins.tool_dims_plugin import dims
from plugins.tool_guds_plugin import guds
from plugins.tool_colors_plugin import colorform as print
from random import randint as rint
import re
regex=re.compile("\x03(?:\d{1,2}(?:,\d{1,2})?)?",re.UNICODE)
###########################################################################################
###########################################################################################
regex=re.compile("\x03(?:\d{1,2}(?:,\d{1,2})?)?",re.UNICODE)
###########################################################################################
###########################################################################################
class BUS:
#######################################################################################
#######################################################################################
results=[]
#######################################################################################
#######################################################################################
def __init__(self,bridged_network_roomchans=[]):
self.bridged_network_roomchans=bridged_network_roomchans
###################################################################################
###################################################################################
###################
if SERVICES_MATRIX:
###################
self.matrixbot=guds.memory('matrixbot')
###################################################################################
###################################################################################
self.ircbot=guds.memory('ircbot')
#######################################################################################
#######################################################################################
def sortnet(self,s):
if s.startswith('!'):
return '(m)'
elif s.startswith('#'):
return '(i)'
#######################################################################################
#######################################################################################
async def output(self,netschanroom_src,data):
from plugins.net_irc_plugin import d_irc_msg
if SERVICES_MATRIX:
from plugins.net_matrix_plugin import d_matrix_msg
###################################################################################
###################################################################################
###################
if SERVICES_MATRIX:
###################
from plugins.net_matrix_plugin import d_matrix_msg
###################################################################################
###################################################################################
chanroom=netschanroom_src[0]; usernick=netschanroom_src[1]
if type(self.bridged_network_roomchans)==list:
targets=self.bridged_network_roomchans
for target in targets:
if type(data)==list:
##############################################
if SERVICES_MATRIX and target.startswith('!'):
##############################################
for _data in data:
d_matrix_msg(target,regex.sub("",_data))
msg=f"<<< ____tool_bus_plugin >>> [ BUS.output ] - {self.sortnet(chanroom)}({chanroom})({usernick})->{self.sortnet(target)}({target}) > {regex.sub('',_data)}"
############################
elif target.startswith('#'):
############################
for _data in data:
d_irc_msg(target,_data)
msg=f'<<< ____tool_bus_plugin >>> [ BUS.output ] - {self.sortnet(chanroom)}({chanroom})({usernick})->{self.sortnet(target)}({target}) > {_data}'
###########################################################################
else:
##############################################
if SERVICES_MATRIX and target.startswith('!'):
##############################################
d_matrix_msg(target,regex.sub('',data))
msg=f"<<< ____tool_bus_plugin >>> [ BUS.output ] - {self.sortnet(chanroom)}({chanroom})({usernick})->{self.sortnet(target)}({target}) > {regex.sub('',data)}"
############################
elif target.startswith('#'):
############################
d_irc_msg(target,data)
msg=f'<<< ____tool_bus_plugin >>> [ BUS.output ] - {self.sortnet(chanroom)}({chanroom})({usernick})->{self.sortnet(target)}({target}) > {data}'
###########################################################################
###########################################################################
print(msg)
###########################################################################
###########################################################################
else:
target=self.bridged_network_roomchans
if type(data)==list:
##############################################
if SERVICES_MATRIX and target.startswith('!'):
##############################################
for _data in data:
d_matrix_msg(target,regex.sub('',_data))
msg=f"<<< ____tool_bus_plugin >>> [ BUS.output ] - {self.sortnet(chanroom)}({chanroom})({usernick})->{self.sortnet(target)}({target}) > {regex.sub('',_data)}"
############################
elif target.startswith('#'):
############################
for msg in data:
d_irc_msg(target,_data)
msg=f'<<< ____tool_bus_plugin >>> [ BUS.output ] - {self.sortnet(chanroom)}({chanroom})({usernick})->{self.sortnet(target)}({target}) > {_data}'
###############################################################################
###############################################################################
else:
##############################################
if SERVICES_MATRIX and target.startswith('!'):
##############################################
d_matrix_msg(target,regex.sub('',data))
msg=f"<<< ____tool_bus_plugin >>> [ BUS.output ] - {self.sortnet(chanroom)}({chanroom})({usernick})->{self.sortnet(target)}({target}) > {regex.sub('',data)}"
############################
elif target.startswith('#'):
############################
d_irc_msg(target,data)
msg=f'<<< ____tool_bus_plugin >>> [ BUS.output ] - {self.sortnet(chanroom)}({chanroom})({usernick})->{self.sortnet(target)}({target}) > {data}'
###############################################################################
###############################################################################
print(msg)
#######################################################################################
#######################################################################################
async def input(self,network_chanroom_user_src,user_src,data,verbose_bridge):
prefix_src=""; maple_dispatch=False
network_chanroom_dest=network_chanroom_user_src
@ -90,20 +185,43 @@ class BUS:
elif network_chanroom_user_src.startswith('$'): prefix_src="" #"$t"
elif network_chanroom_user_src.startswith('^'): prefix_src="" #"^d"
netsrc=network_chanroom_user_src
#if prefix_src=="": return
for network_chanroom_dest in self.bridged_network_roomchans:
from plugins.net_irc_plugin import d_irc_msg
###################
if SERVICES_MATRIX:
###################
from plugins.net_matrix_plugin import d_matrix_msg
####################
if SERVICES_DISCORD:
####################
from plugins.net_discord_plugin import d_discord_msg
#####################
if SERVICES_TELEGRAM:
#####################
from plugins.net_telegram_plugin import d_telegram_msg
#################################################################### ROUTER
#################################################################### ROUTER
if type(data)==list:
for _data in data:
########################################################### TELEGRAM
########################################################### TELEGRAM
#####################
if SERVICES_TELEGRAM:
#####################
if network_chanroom_dest.startswith('$'):
if verbose_bridge:
_data=regex.sub("",_data)
@ -115,8 +233,14 @@ class BUS:
else:
msg=regex.sub("",data)
d_telegram_msg(network_chanroom_dest,msg)
########################################################### DISCORD
########################################################### DISCORD
####################
if SERVICES_DISCORD:
####################
if network_chanroom_dest.startswith('^'):
if verbose_bridge:
_data=regex.sub("",_data)
@ -128,8 +252,14 @@ class BUS:
else:
msg=regex.sub("",data)
d_discord_msg(network_chanroom_dest,msg)
############################################################ MATRIX
############################################################ MATRIX
###################
if SERVICES_MATRIX:
###################
if network_chanroom_dest.startswith('!'):
if verbose_bridge:
_data=regex.sub("",_data)
@ -141,7 +271,10 @@ class BUS:
else:
msg=regex.sub("",data)
d_matrix_msg(network_chanroom_dest,msg)
############################################################### IRC
############################################################### IRC
if network_chanroom_dest.startswith('#'):
if verbose_bridge:
_data=regex.sub("",_data)
@ -153,10 +286,19 @@ class BUS:
else:
msg=f'{_data.strip()}'
d_irc_msg(network_chanroom_dest,msg)
############################################################# LOCAL
############################################################# LOCAL
else:
############################################################### TELEGRAM
############################################################### DISCORD
############################################################### DISCORD
#####################
if SERVICES_TELEGRAM:
#####################
if network_chanroom_dest.startswith('$'):
if verbose_bridge:
data=regex.sub("",data)
@ -168,8 +310,14 @@ class BUS:
else:
msg=regex.sub("",data)
d_telegram_msg(network_chanroom_dest,msg)
############################################################### DISCORD
############################################################### DISCORD
####################
if SERVICES_DISCORD:
####################
if network_chanroom_dest.startswith('^'):
if verbose_bridge:
data=regex.sub("",data)
@ -181,8 +329,14 @@ class BUS:
else:
msg=regex.sub("",data)
d_discord_msg(network_chanroom_dest,msg)
################################################################ MATRIX
################################################################ MATRIX
###################
if SERVICES_MATRIX:
###################
if network_chanroom_dest.startswith('!'):
if verbose_bridge:
data=regex.sub("",data)
@ -194,7 +348,10 @@ class BUS:
else:
msg=regex.sub("",data)
d_matrix_msg(network_chanroom_dest,msg)
################################################################### IRC
################################################################### IRC
if network_chanroom_dest.startswith('#'):
if verbose_bridge:
data=regex.sub("",data)
@ -206,4 +363,6 @@ class BUS:
else:
msg=f'{data.strip()}'
d_irc_msg(network_chanroom_dest,msg)
####################################################################################### EOF#.[d].
###########################################################################################
####################################################################################### EOF

@ -1,18 +1,31 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
def rgb(r=0,g=0,b=0):return f"\033[38;2;{r};{g};{b}m"
###########################################################################################
###########################################################################################
def rgbe():return f"\033[38;2;255;255;255m"
###########################################################################################
###########################################################################################
def rgbt(t='',r=0,g=0,b=0):return f"\033[38;2;{r};{g};{b}m{t}\033[38;2;255;255;255m"
###########################################################################################
###########################################################################################
def colorform(s):
#######################################################################################
#######################################################################################
try:
between_gtlts=s.split(' >>> ')[0].split('<<< ')[1]
except:
pass
try:
between_brackets=s.split(' >>> [ ')[1].split(' ]')[0]
if s[:-2].endswith(between_brackets):
@ -21,18 +34,25 @@ def colorform(s):
FLAG_A=True
except:
FLAG_A=True
try:
if FLAG_A:
everything_past_brackets=s.split(' >>> [ ')[1].split(' ] ')[1]
except:
pass
#######################################################################################
#######################################################################################
s=f"{rgb(b=255)}<<<{rgb(g=255,b=255)} {between_gtlts} {rgb(b=255)}>>> {rgb(r=255)}"
if between_brackets.startswith('('):
s+=f"[{rgb(b=255)} {between_brackets} {rgb(r=255)}]"
else:
s+=f"[{rgb(r=255,g=255)} {between_brackets} {rgb(r=255)}]"
#######################################################################################
#######################################################################################
maybe_delimited=""
try:
if maybe_delimited=="":
@ -56,5 +76,6 @@ def colorform(s):
except:
print(s)
return
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,29 +1,51 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
???DISCORD???
???MATRIX???
???TELEGRAM???
###########################################################################################
###########################################################################################
from irc3.plugins.command import command
from plugins.tool_guds_plugin import guds
import asyncio
global dims
###########################################################################################
###########################################################################################
class DIMS:
###################
if SERVICES_MATRIX:
###################
###################################################################################
###################################################################################
class __INIT_MATRIX__:
###############################################################################
###############################################################################
class __INIT_ROOM__:
###########################################################################
###########################################################################
class __INIT_BRIDGE_MATRIX__:
#######################################################################
#######################################################################
def __init__(self,room):
self.inbound=[]
#self.matrix_rooms_inbound=[]
self.outbound=[]
#self.irc_channels_inbound=[]
###########################################################################
###########################################################################
def __init__(self,room):
room_flag=False
if len(dir(room))>1:
@ -41,19 +63,28 @@ class DIMS:
'typing_users','unread_highlights','unread_notifications','users']:
if room_flag:
exec(f'self.{_}=room.{_}')
# print(f"room.{_}->{eval(f'self.{_}')}")
self.bridge=self.__INIT_BRIDGE_MATRIX__(room.room_id)
else:
exec(f'self.{_}=""')
self.room_id=room
self.bridge=self.__INIT_BRIDGE_MATRIX__(room)
###############################################################################
###############################################################################
def __init__(self,room):
self.rooms=[]
self.rooms.append(self.__INIT_ROOM__(room))
#######################################################################################
#######################################################################################
def __update_matrix__(self,index,room,bridge=""):
###################
if SERVICES_MATRIX:
###################
for _ in ['canonical_alias','creator','display_name','encrypted',
'federate','fully_read_marker','gen_avatar_url','history_visibility',
'invited_count','invited_users','is_group','is_named','join_rule',
@ -68,63 +99,111 @@ class DIMS:
cmdf=f"room.{_}"
cmdt=f"self.matrix[{index}].rooms[0].{_}"
print(f"literal: room.{_}->self.matrix[{index}].rooms[0].{_} - explicit: {eval(cmdf)}->{eval(cmdt)}")
#######################################################################################
#######################################################################################
def ismatrixroom(self,room):
###################
if SERVICES_MATRIX:
###############################################################################
###################
try:
for index_server,_matrix in enumerate(self.matrix):
for index_room,_room in enumerate(_matrix.rooms):
if _room.room_id==room:
return True
###############################################################################
except: pass
###############################################################################
return False
#######################################################################################
#######################################################################################
class __INIT_DISCORD__:
if SERVICES_DISCORD:
####################
if SERVICES_DISCORD:
####################
###############################################################################
###############################################################################
class __INIT_CHANNEL__:
###########################################################################
###########################################################################
class __INIT_BRIDGE_DISCORD__:
#######################################################################
#######################################################################
def __init__(self,channel):
self.inbound=[]
self.outbound=[]
###########################################################################
###########################################################################
def __init__(self,channel):
self.channel=channel
self.bridge=self.__INIT_BRIDGE_DISCORD__(channel)
###############################################################################
###############################################################################
def __init__(self,channel):
self.channels=[]
self.channels.append(self.__INIT_CHANNEL__(channel))
#######################################################################################
#######################################################################################
def isdiscordchannel(self,channel):
####################
if SERVICES_DISCORD:
###############################################################################
####################
try:
for index_server,_discord in enumerate(self.discord):
for index_channel,_channel in enumerate(_discord.channels):
if _channel.channel==channel:
return True
###############################################################################
except: pass
###############################################################################
return False
#######################################################################################
#######################################################################################
class __INIT_TELEGRAM__:
###################################################################################
###################################################################################
#####################
if SERVICES_TELEGRAM:
#####################
class __INIT_GROUP__:
###########################################################################
###########################################################################
class __INIT_BRIDGE_TELEGRAM__:
#######################################################################
#######################################################################
def __init__(self,group):
self.inbound=[]
self.outbound=[]
###########################################################################
###########################################################################
def __init__(self,group):
self.group=group
self.bridge=self.__INIT_BRIDGE_TELEGRAM__(group)
@ -132,45 +211,70 @@ class DIMS:
def __init__(self,group):
self.groups=[]
self.groups.append(self.__INIT_GROUP__(group))
#######################################################################################
#######################################################################################
def istelegramgroup(self,group):
###################################################################################
#####################
if SERVICES_TELEGRAM:
#####################
try:
for index_server,_telegram in enumerate(self.telegram):
for index_group,_group in enumerate(_telegram.groups):
if _group.group==group:
return True
###############################################################################
except: pass
###############################################################################
return False
#######################################################################################
#######################################################################################
class __INIT_IRC__:
###################################################################################
###################################################################################
class __INIT_CHANNEL__:
###############################################################################
###############################################################################
class __INIT_BRIDGE_IRC__:
###########################################################################
###########################################################################
def __init__(self,channel):
self.inbound=[]
#self.irc_channels_inbound=[]
self.outbound=[]
#self.matrix_rooms_inbound=[]
###############################################################################
###############################################################################
def __init__(self,channel):
self.channel=channel
self.bridge=self.__INIT_BRIDGE_IRC__(channel)
###################################################################################
###################################################################################
def __init__(self,channel):
self.channels=[]
self.channels.append(self.__INIT_CHANNEL__(channel))
#######################################################################################
#######################################################################################
def __update_irc__(self,index,channel,bridge=""):
self.irc[index].channels[0].channel=channel
#######################################################################################
#######################################################################################
def isircchannel(self,channel=None,return_index=False):
###################################################################################
try:
for index_server,_irc in enumerate(self.irc):
for index_channel,_channel in enumerate(_irc.channels):
@ -178,38 +282,46 @@ class DIMS:
if return_index:
return True,index_server
else:
return True
###################################################################################
return True,-1
except: pass
###################################################################################
return False
return False,-1
#######################################################################################
#######################################################################################
matrix=[]; irc=[]; telegram=[]; discord=[]; netschanroom=[]; netschanroom_bridged=[];
#######################################################################################
#######################################################################################
def __init__(self,net="",chanroom=""):
###################################################################################
if not net or not chanroom: return
###################################################################################
net=net.lower()
dupe_flag=False
###################################################################################
#####################################
if SERVICES_MATRIX and net=='matrix':
#####################################
for i in range(len(self.matrix)):
if self.matrix[i].rooms[0].room_id==chanroom.room_id:
# print(f'<<< ________dims_plugin >>> [ updating pre-existing matrix room data ]')
dupe_flag=True; index=i; self.__update_matrix__(index,chanroom)
if not dupe_flag:
# print(f'<<< ________dims_plugin >>> [ new matrix room data entry ]')
self.matrix.append(self.__INIT_MATRIX__(chanroom))
###################################################################################
###################################################################################
elif net=='irc':
for i in range(len(self.irc)):
if self.irc[i].channels[0].channel==chanroom:
# print(f'<<< ________dims_plugin >>> [ updating pre-existing irc channel data ]')
dupe_flag=True; index=i; self.__update_irc__(index,chanroom)
if not dupe_flag:
# print(f'<<< ________dims_plugin >>> [ new irc channel data entry ]')
self.irc.append(self.__INIT_IRC__(chanroom))
#######################################################################################
#######################################################################################
def __boot__(self):
ircbot=guds.memory('ircbot')
dbnames=["matrixchat","telegramchat","discordchat","ircchat"]
@ -217,13 +329,25 @@ class DIMS:
dbdata=ircbot.db.getlist(dbname)
if dbdata:
for entry in dbdata:
##########################################
if SERVICES_MATRIX and dbname==dbnames[0]:
##########################################
if not dims.ismatrixroom(entry[0]):
self.matrix.append(self.__INIT_MATRIX__(entry[0]))
##############################################
elif SERVICES_TELEGRAM and dbname==dbnames[1]:
##############################################
if not dims.istelegramgroup(entry[1]):
self.telegram.append(self.__INIT_TELEGRAM__(entry[1]))
#############################################
elif SERVICES_DISCORD and dbname==dbnames[2]:
#############################################
if not dims.isdiscordchannel(entry[1]):
self.discord.append(self.__INIT_DISCORD__(entry[1]))
discordbot=guds.memory('discordbot')
@ -231,6 +355,10 @@ class DIMS:
elif dbname==dbnames[3]:
if not dims.isircchannel(entry[0]):
self.irc.append(self.__INIT_IRC__(entry[0]))
###################################################################################
###################################################################################
dbname="chatbridges"
dbdata=ircbot.db.getlist(dbname)
if dbdata:
@ -238,55 +366,108 @@ class DIMS:
chanroom=entry[0]
src_outbound=entry[1]
dest_inbound=entry[2]
################################################
if SERVICES_MATRIX and chanroom.startswith('!'):
################################################
for _matrix in self.matrix:
for _rooms in _matrix.rooms:
if _rooms.room_id==chanroom:
_rooms.bridge.inbound=src_outbound
_rooms.bridge.outbound=dest_inbound
##############################
elif chanroom.startswith('#'):
##############################
for _irc in self.irc:
for _channels in _irc.channels:
if _channels.channel==chanroom:
_channels.bridge.inbound=src_outbound
_channels.bridge.outbound=dest_inbound
####################################################
elif SERVICES_TELEGRAM and chanroom.startswith('$'):
####################################################
for _telegram in self.telegram:
for _groups in _telegram.groups:
if _groups.group==chanroom:
_groups.bridge.inbound=src_outbound
_groups.bridge.outbound=dest_inbound
###################################################
elif SERVICES_DISCORD and chanroom.startswith('^'):
###################################################
for _discord in self.discord:
for _channels in _discord.channels:
if _channels.channel==chanroom:
_channels.bridge.inbound=src_outbound
_channels.bridge.outbound=dest_inbound
#######################################################################################
#######################################################################################
def __create__(self,net="",chanroom=""):
###################################################################################
#####################################
if SERVICES_MATRIX and net=='matrix':
#####################################
self.matrix.append(self.__INIT_MATRIX__(chanroom))
###################################################################################
################
elif net=='irc':
################
self.irc.append(self.__INIT_IRC__(chanroom))
###################################################################################
#########################################
elif SERVICES_DISCORD and net=='discord':
#########################################
self.discord.append(self.__INIT_DISCORD__(chanroom))
###################################################################################
###########################################
elif SERVICES_TELEGRAM and net=='telegram':
###########################################
self.telegram.append(self.__INIT_TELEGRAM__(chanroom))
#######################################################################################
#######################################################################################
def __delete__(self,net="",chanroom_index=-1):
###################################################################################
if SERVICES_MATRIX and net=='matrix': self.matrix.remove(self.matrix[chanroom_index])
###################################################################################
elif net=='irc': self.irc.remove(self.irc[chanroom_index])
###################################################################################
elif SERVICES_DISCORD and net=='discord': self.discord.remove(self.discord[chanroom_index])
###################################################################################
elif SERVICES_TELEGRAM and net=='telegram': self.telegram.remove(self.telegram[chanroom_index])
#####################################
if SERVICES_MATRIX and net=='matrix':
#####################################
self.matrix.remove(self.matrix[chanroom_index])
################
elif net=='irc':
################
self.irc.remove(self.irc[chanroom_index])
#########################################
elif SERVICES_DISCORD and net=='discord':
#########################################
self.discord.remove(self.discord[chanroom_index])
###########################################
elif SERVICES_TELEGRAM and net=='telegram':
###########################################
self.telegram.remove(self.telegram[chanroom_index])
#######################################################################################
#######################################################################################
@command(permission='admin', public=False, show_in_help_list=False)
def blackholes(self,src_blackhole,cmd=None):
self.blackhole=[]
@ -311,7 +492,10 @@ class DIMS:
except:
pass
return self.blackhole
#######################################################################################
#######################################################################################
@command(permission='admin', public=False, show_in_help_list=False)
def bridge_routes(self,src_outbound,dest_inbound,cmd=None):
err_chan="bot is not in this channel/room/group: {}"
@ -319,7 +503,6 @@ class DIMS:
err_cmds="wrong command given to bridge_routes: {}"
err_flow="wrong flow direction given: {}"
err_same="src_outbound: {} and dest_inbound: {} are the same route"
###################################################################################
if src_outbound==dest_inbound: return False,err_same.format(src_outbound,dest_inbound)
try:
for flow in ["out","in"]:
@ -327,8 +510,11 @@ class DIMS:
flow_direction=src_outbound
elif flow=="in":
flow_direction=dest_inbound
###############################################################################
######################################################
if SERVICES_MATRIX and flow_direction.startswith('!'):
######################################################
if not dims.ismatrixroom(flow_direction): return False,err_chan.format(flow_direction)
for _matrix in self.matrix:
for _rooms in _matrix.rooms:
@ -353,8 +539,11 @@ class DIMS:
return False,err_flow
else:
return False,err_cmds
###################################################################################
####################################
elif flow_direction.startswith('#'):
####################################
if not dims.isircchannel(flow_direction): return False,err_chan.format(flow_direction)
for _irc in self.irc:
for _channels in _irc.channels:
@ -379,8 +568,11 @@ class DIMS:
return False,err_flow
else:
return False,err_cmds
###################################################################################
##########################################################
elif SERVICES_TELEGRAM and flow_direction.startswith('$'):
##########################################################
if not dims.istelegramgroup(flow_direction): return False,err_chan.format(flow_direction)
for _telegram in self.telegram:
for _groups in _telegram.groups:
@ -405,8 +597,11 @@ class DIMS:
return False,err_flow
else:
return False,err_cmds
###################################################################################
#########################################################
elif SERVICES_DISCORD and flow_direction.startswith('^'):
#########################################################
if not dims.isdiscordchannel(flow_direction): return False,err_chan.format(flow_direction)
for _discord in self.discord:
for _channels in _discord.channels:
@ -431,7 +626,10 @@ class DIMS:
return False,err_flow
else:
return False,err_cmds
###################################################################################
###################################################################################
self.ircbot=guds.memory('ircbot')
self.dbname="chatbridges"
self.db=self.ircbot.db.getlist(self.dbname)
@ -475,7 +673,10 @@ class DIMS:
return True,None
except Exception as e:
return False,e
#######################################################################################
#######################################################################################
@command(permission='admin', public=False, show_in_help_list=False)
def list_channels_bridged(self,netsrc=False):
self.netschanroom_bridged=[]
@ -486,7 +687,11 @@ class DIMS:
[self.netschanroom_bridged.append(x) for x in _channels.bridge.outbound]
else:
self.netschanroom_bridged.append([_channels.channel,_channels.bridge.inbound,_channels.bridge.outbound])
###################
if SERVICES_MATRIX:
###################
for _matrix in self.matrix:
for _rooms in _matrix.rooms:
if netsrc:
@ -494,7 +699,11 @@ class DIMS:
[self.netschanroom_bridged.append(x) for x in _rooms.bridge.outbound]
else:
self.netschanroom_bridged.append([_rooms.room_id,_rooms.bridge.inbound,_rooms.bridge.outbound])
#####################
if SERVICES_TELEGRAM:
#####################
for _telegram in self.telegram:
for _groups in _telegram.groups:
if netsrc:
@ -502,7 +711,11 @@ class DIMS:
[self.netschanroom_bridged.append(x) for x in _groups.bridge.outbound]
else:
self.netschanroom_bridged.append([_groups.group,_groups.bridge.inbound,_groups.bridge.outbound])
####################
if SERVICES_DISCORD:
####################
for _discord in self.discord:
for _channels in _discord.channels:
if netsrc:
@ -511,25 +724,39 @@ class DIMS:
else:
self.netschanroom_bridged.append([_channels.channel,_channels.bridge.inbound,_channels.bridge.outbound])
return self.netschanroom_bridged
#######################################################################################
#######################################################################################
@command(permission='admin', public=False, show_in_help_list=False)
def list_channels(self):
###################################################################################
self.netschanroom=[]
ircbot=guds.memory('ircbot')
###################
if SERVICES_MATRIX:
###################
dbname="matrixchat"
db=ircbot.db.getlist(dbname)
if db:
for entry in db:
self.netschanroom.append(entry[0])
#####################
if SERVICES_TELEGRAM:
#####################
dbname="telegramchat"
db=ircbot.db.getlist(dbname)
if db:
for entry in db:
self.netschanroom.append(entry[1])
####################
if SERVICES_DISCORD:
####################
dbname="discordchat"
db=ircbot.db.getlist(dbname)
if db:
@ -540,8 +767,16 @@ class DIMS:
if db:
for entry in db:
self.netschanroom.append(entry[0])
###################################################################################
###################################################################################
return self.netschanroom
###########################################################################################
###########################################################################################
dims=DIMS()
####################################################################################### EOF
###########################################################################################
####################################################################################### EOF

@ -1,17 +1,31 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from datetime import datetime
from datetime import timedelta
import timeago
from plugins.tool_colors_plugin import colorform as print
global guds # global unified data system 2 move instantiated data between processes/threads
###########################################################################################
###########################################################################################
class GUDS:
#######################################################################################
#######################################################################################
push_index=0; memories=[]; timestamped_alarm=[];
#######################################################################################
#######################################################################################
def __init__(self):
pass
#######################################################################################
#######################################################################################
def timestamp_alarm(self,reason,seconds):
try:
iseconds=int(seconds)
@ -21,7 +35,10 @@ class GUDS:
print(f'<<< ________guds_plugin >>> [ timestamp_alarm ] - active: {reason} - alarm: {timestamp} - now: {datetime.now().timestamp()}')
except:
print('<<< ________guds_plugin >>> [ timestamp_alarm ] - error')
#######################################################################################
#######################################################################################
def timestamp_check(self,reason):
try:
REASON_FLAG=True
@ -48,16 +65,27 @@ class GUDS:
except:
print('<<< ________guds_plugin >>> [ timestamp_check ] timestamp_check error')
return -1
#######################################################################################
#######################################################################################
def memory(self,data):
for _ in self.memories:
if not _[1].find(data)==-1:
return _[0]
#######################################################################################
#######################################################################################
def push(self,data):
self.push_index+=1
self.memories.append(data)
print(f'<<< ________guds_plugin >>> [ data pushed into guds.memories[{str(self.push_index)}]={guds.memories[-1]} ]')
###########################################################################################
###########################################################################################
guds=GUDS()
####################################################################################### EOF#.[d].
###########################################################################################
####################################################################################### EOF

@ -0,0 +1,92 @@
# -*- coding: utf-8 -*- ################################################ SOF - HYDRA LOGGER
###########################################################################################
import sys,inspect
###########################################################################################
###########################################################################################
class FOG:
#######################################################################################
###################################### - RGB // RETURNS RGB TERMINAL ESCAPE COLOR CODES
def rgb(self,r=0,g=0,b=0):return f"\033[38;2;{r};{g};{b}m"
#######################################################################################
##################################################### - FOG // RETURNS FORMATTED STRING
def fog(self=None,data=None,caller=None,self_name=None):
frame = inspect.currentframe().f_back
try:
codeobj = frame.f_code
try:
self_name = codeobj.co_varnames[0]
except IndexError:
caller = None
raise Exception()
try:
self_obj = frame.f_locals[self_name]
except KeyError:
caller = None
raise Exception()
self_type = type(self_obj)
func_name = codeobj.co_name
for cls in self_type.__mro__:
try:
method = vars(cls)[func_name]
except KeyError:
continue
try:
method = inspect.unwrap(method)
except ValueError:
pass
if getattr(method, '__code__', None) is codeobj:
caller = self_type.__name__
raise Exception()
caller = None
raise Exception()
except:
pass
finally:
del frame
###################################################################################
###################################################################################
PATHFILENAME=sys._getframe().f_code.co_filename
filename=PATHFILENAME.split('/')[-1].split('.')[0]
renamed="_"*(19-len(filename))+filename
the_origin=origin=renamed
the_caller=sys._getframe(1).f_code.co_name
the_function=sys._getframe().f_code.co_name
msg=f'{self.rgb(b=255)}<<<{self.rgb(g=255,b=255)} {the_origin} {self.rgb(b=255)}>>> '
if self and data and caller:
the_class=""
the_class=type(self).__name__
if codeobj.co_filename==PATHFILENAME:
msg+=f'{self.rgb(r=255)}[ {self.rgb(r=255,b=255)}{caller}.{the_class}.{the_caller} {self.rgb(r=255)}]'
else:
origin=codeobj.co_filename.split('/')[-1].replace('.py','')
msg+=f'{self.rgb(r=255)}[ {self.rgb(r=255,b=255)}{origin}.{the_caller}.{caller}.{__name__}.{the_class}.{the_function} {self.rgb(r=255)}]'
msg+=f'{self.rgb(b=255)} - '
msg+=f'{self.rgb(g=128,b=128,r=128)}{data}'
else:
caller=str(self).split(f'<{__name__}.')[1].split()[0]
if not self_name and the_caller=="<module>":
if codeobj.co_filename==PATHFILENAME:
msg+=f'{self.rgb(r=255)}[ {self.rgb(r=255,b=255)}{__name__}.{caller}.{the_function} {self.rgb(r=255)}]'
else:
origin=codeobj.co_filename.split('/')[-1].replace('.py','')
msg+=f'{self.rgb(r=255)}[ {self.rgb(r=255,b=255)}{origin}.{__name__}.{caller}.{the_function} {self.rgb(r=255)}]'
else:
if codeobj.co_filename==PATHFILENAME:
msg+=f'{self.rgb(r=255)}[ {self.rgb(r=255,b=255)}{self_name}.{the_caller}.{caller}.{the_function} {self.rgb(r=255)}]'
else:
pass
msg+=f'{self.rgb(b=255)} - '
msg+=f'{self.rgb(g=128,b=128,r=128)}{data}'
print(msg)
###########################################################################################
####################################################################################### EOF

@ -1,56 +1,95 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
???YOUTUBE???
###########################################################################################
###########################################################################################
import irc3
from datetime import datetime
import twitter
import re
import os
import sys
import time
import timeago
import os
import requests
from lxml.html import fromstring
from difflib import SequenceMatcher
from plugins.tool_log_plugin import FOG
###########################################################################################
###########################################################################################
try:
TWITTER_CONSUMER_KEY = os.environ['TWITTER_CONSUMER_KEY']
TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS_TOKEN_KEY = os.environ['TWITTER_ACCESS_TOKEN_KEY']
TWITTER_ACCESS_TOKEN_SECRET = os.environ['TWITTER_ACCESS_TOKEN_SECRET']
except:
pass
TOO_LONG = 2000
###########################################################################################
###########################################################################################
####################
if SERVICES_YOUTUBE:
####################
YOUTUBE_REGEX = re.compile('http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?', re.IGNORECASE)
###########################################################################################
###########################################################################################
try:
TWITTER_REGEX = re.compile('https?:\/\/twitter\.com\/(?:#!\/)?(\w+)\/status(es)?\/(\d+)$', re.IGNORECASE)
URL_REGEX = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', re.IGNORECASE)
def getenv(s):
try:
s = os.environ[s]
return s
except:
fog=FOG().fog
error_type="environmental variable error"
error_reason=f"exported {s} not found"
fog(f"{error_type}: {error_reason}")
sys.exit(1)
###########################################################################################
###########################################################################################
TWITTER_CONSUMER_KEY = getenv('TWITTER_CONSUMER_KEY')
TWITTER_CONSUMER_SECRET = getenv('TWITTER_CONSUMER_SECRET')
TWITTER_ACCESS_TOKEN_KEY = getenv('TWITTER_ACCESS_TOKEN_KEY')
TWITTER_ACCESS_TOKEN_SECRET = getenv('TWITTER_ACCESS_TOKEN_SECRET')
###########################################################################################
###########################################################################################
twitter = twitter.Api(consumer_key=TWITTER_CONSUMER_KEY, consumer_secret=TWITTER_CONSUMER_SECRET,
access_token_key=TWITTER_ACCESS_TOKEN_KEY, access_token_secret=TWITTER_ACCESS_TOKEN_SECRET)
except:
pass
access_token_key=TWITTER_ACCESS_TOKEN_KEY, access_token_secret=TWITTER_ACCESS_TOKEN_SECRET)
###########################################################################################
###########################################################################################
TWITTER_REGEX = re.compile('https?:\/\/twitter\.com\/(?:#!\/)?(\w+)\/status(es)?\/(\d+)$', re.IGNORECASE)
URL_REGEX = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', re.IGNORECASE)
###########################################################################################
###########################################################################################
TOO_LONG = 2000
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@irc3.extend
def _similar(self, a, b):
return SequenceMatcher(None, a, b).ratio()
#######################################################################################
#######################################################################################
@irc3.extend
def _check_for_url(self, og_tweet, d_nick, d_url, d_unrolled, d_text, d_target):
match_list = URL_REGEX.findall(d_unrolled)
@ -119,8 +158,10 @@ class Plugin:
self.bot.privmsg("_debug_check_for_url_error: {}".format(e))
print("original: {} nick: {} url: {} unrolled: {} text: {} error: {}".format(og_tweet,d_nick,d_url,d_unrolled,d_text,e))
pass
#######################################################################################
#######################################################################################
def _check_for_twitter(self, mask=None, data=None, target=None, **kw):
match_list = TWITTER_REGEX.findall(data)
if match_list:
@ -161,17 +202,18 @@ class Plugin:
except:
print('cant remove from matchlist, does not exist')
t_eurl = tweet.urls[y].expanded_url
###################################################
###################################################
####################
if SERVICES_YOUTUBE:
####################
yt_match_list = YOUTUBE_REGEX.findall(t_eurl)
if SERVICES_YOUTUBE and yt_match_list:
d_video_id = t_eurl.split('=')[1]
self.bot.madjust = "{}:UNROLLED".format(user)
self.bot.yt(mask,target,{'<keyword>': [d_video_id],'yt': True})
self.bot.madjust = ""
###################################################
###################################################
if yt_match_list:
d_video_id = t_eurl.split('=')[1]
self.bot.madjust = "{}:UNROLLED".format(user)
self.bot.yt(mask,target,{'<keyword>': [d_video_id],'yt': True})
self.bot.madjust = ""
else:
if not str(tweet.id) == t_eurl.split('/')[-1]:
self.bot._check_for_url(tweet,user,t_turl,t_eurl,tweet_text,target)
@ -199,13 +241,15 @@ class Plugin:
msg = self.bot.emo(msg)
self.bot.privmsg(target, msg)
pass
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg_search_for_twitter(self, mask=None, target=None, data=None, **kw):
if data.startswith("?"): return
if mask.nick.lower() not in self.bot.ignore_list:
self._check_for_twitter(mask, data, target)
#######################################################################################
#######################################################################################
####################################################################################### EOF#.[d].
###########################################################################################
####################################################################################### EOF

@ -1,71 +1,109 @@
# -*- coding: utf-8 -*- ###############################################################MMMMMMMMMMMMMMMMMMM## SOF
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
import pdb
###########################################################################################
###########################################################################################
import json
import os
import re
###########################################################################################
###########################################################################################
import irc3
import subprocess
import requests
###########################################################################################
###########################################################################################
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from random import shuffle
###########################################################################################
###########################################################################################
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
import base64
import io
###########################################################################################
###########################################################################################
from irc3.plugins.command import command
from irc3.plugins.cron import cron
from PIL import Image, PngImagePlugin
from plugins.tool_log_plugin import cog, dog
################################################################################################################
###########################################################################################
###########################################################################################
#ansi_home=os.environ['ANSI_HOME']
#hydrachan=home=os.environ['HYDRA_TEST_CHANNEL']
################################################################################################################ . GLOBALS PROTOS
###########################################################################################
###########################################################################################
#global REASSEMBLY
################################################################################################################ . GLOBALS DATA
###########################################################################################
###########################################################################################
#REASSEMBLY="1B5B306D"
#regex=re.compile("\x03(?:\d{1,2}(?:,\d{1,2})?)?",re.UNICODE)
################################################################################################################ . FORMATTING STRING COLORS
###########################################################################################
###########################################################################################
DREY="\x02\x0315"
GREY="\x02\x0314"
DRED="\x02\x0302"
LRED="\x02\x0312"
################################################################################################################ . DEBUGGING - TEST FILE DATA
###########################################################################################
###########################################################################################
DIRPATH=os.path.dirname(os.path.realpath(__file__))
#IN__FILE__UTF8_IRC_ARTWORK_TXT="" # f"{DIRPATH}/art.txt"
#OUT_FILE_CP437_ANS_ARTWORK_BIN="" # f"{DIRPATH}/art.ans"
################################################################################################################ deconcatenation of as tring by specific widths
def chunk(s,n): # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
###############
###########################################################################################
###########################################################################################
def chunk(s,n):
result=[s[i:i+n] for i in range(0,len(s),n)]
#############
return result
################################################################################################################ find every instance of a string within a string
def findall(s,w): # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#################
###########################################################################################
###########################################################################################
def findall(s,w):
result=[i for i in range(len(s)) if s.startswith(w, i)]
#############
return result
################################################################################################################ used to make sure a string fits into a space
def padding(s,n): # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#################
###########################################################################################
###########################################################################################
def padding(s,n):
pad=n-len(s);
padding=(" "*pad);
s+=padding;
########
return s
################################################################################################################
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
############################################################################################################
############################################################################################################
#######################################################################################
#######################################################################################
def __init__(self, bot):
########################
self.bot = bot
self.url = "https://saizer:7860"
self.models=[]
@ -79,11 +117,12 @@ class Plugin:
self.height=768
self.restore_faces=True
self.running=False
############################################################################################################
#######################################################################################
#######################################################################################
@command(permission='view',show_in_help_list=True,error_format="{cmd} error - usage: ?{cmd} clear,default,list,show,set,run - example: ?{cmd} set prompt neon female hacker".format)
###################################################
def txt2img(self, mask, target, args):
####################################
"""txt2img
%%txt2img [<noise>] [<param>] [<paramvalue>]...
"""
@ -93,9 +132,7 @@ class Plugin:
msg="error - usage: ^txt2img default,list,show,set,run - example: ?txt2img set prompt neon female hacker"
self.bot.privmsg(target,msg)
return
#noise=' '.join(args['<noise>']).strip().lower()
url=self.url
#pdb.set_trace()
if noise.split()[0]=="list":
# LIST
self.models=[]
@ -107,12 +144,10 @@ class Plugin:
self.bot.privmsg(target,MODEL)
if noise.split()[0]=="set":
#import pdb
# SET
PARAMS=[' model', 'prompt','negative_prompt','prompt+','negative_prompt+','steps','cfg_scale','seed','width','height','restore_faces']
TARAMS=[ [str,int], [str], [str], [str], [str], [int], [float], [int], [int], [int], [bool]]
try:
#pdb.set_trace()
PARAM=args.get('<param>')
try:
assert PARAM in PARAMS
@ -261,4 +296,5 @@ class Plugin:
self.bot.privmsg(target, self.bot.emo(f"{GREY}<<< error {GREY}>>>"))
self.running=False
############################################################################################################ EOF
###########################################################################################
####################################################################################### EOF

@ -1,18 +1,26 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
import requests
import urllib.parse
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@command(permission='view')
def ud(self, mask, target, args):
"""Urban Dictonary A Term
@ -28,7 +36,9 @@ class Plugin:
except:
msg = "{} Term Not Found".format(term)
self.bot.privmsg(target,msg)
#######################################################################################
#######################################################################################
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,8 +1,12 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
???TWITTER???
???YOUTUBE???
###########################################################################################
###########################################################################################
from irc3.plugins.command import command
import irc3
import re
@ -10,24 +14,40 @@ import requests
from lxml.html import fromstring
TOO_LONG = 2000
URL_REGEX = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', re.IGNORECASE)
###########################################################################################
###########################################################################################
####################
if SERVICES_YOUTUBE:
####################
YOUTUBE_REGEX = re.compile('http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?', re.IGNORECASE)
###########################################################################################
###########################################################################################
####################
if SERVICES_TWITTER:
####################
TWITTER_REGEX = re.compile('https?:\/\/twitter\.com\/(?:#!\/)?(\w+)\/status(es)?\/(\d+)$', re.IGNORECASE)
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg(self, mask=None, target=None, data=None, **kw):
if not data.find('reacted with :') == -1: return
@ -35,25 +55,39 @@ class Plugin:
if self.bot.check_if_ignored(mask): return
if mask.nick == '[0]' or mask.nick == '[0]_': return
self.__check_for_url(data,target,mask)
#######################################################################################
#######################################################################################
def __check_for_url(self,msg,target,mask):
match_list = URL_REGEX.findall(msg)
read_size = 0
if match_list:
url = match_list.pop()
##########################################
if not url.lower().find('wp-login') == -1:
##########################################
msg = 'pre-fetch aborted -> hell nah nigga'
msg = self.bot.emo(msg)
self.bot.privmsg(target, msg)
return
####################
if SERVICES_YOUTUBE:
####################
y_match = YOUTUBE_REGEX.findall(url)
if y_match:
y_match = y_match.pop()
if len(y_match) == 3:
return
####################
if SERVICES_TWITTER:
####################
t_match = TWITTER_REGEX.findall(url)
if t_match:
t_match = t_match.pop()
@ -90,9 +124,15 @@ class Plugin:
msg = "\x02\x0302{nick:}\x0F\x02\x0304 > \x0F\x1D\x0314{title:}\x0F".format(nick=mask.nick,title=title)
msg = self.bot.emo(msg)
self.bot.privmsg(target, msg)
######## URL_GRABBER <-> BOOMBOX_PLUGIN HOOK ######## URL_GRABBER <-> BOOMBOX_PLUGIN HOOK ########
########### URL_GRABBER <-> BOOMBOX_PLUGIN HOOK <-> URL_GRABBER
########### URL_GRABBER <-> BOOMBOX_PLUGIN HOOK <-> URL_GRABBER
self.bot.bbs.enter(mask.nick,url,title)
######## URL_GRABBER <-> BOOMBOX_PLUGIN HOOK ######## URL_GRABBER <-> BOOMBOX_PLUGIN HOOK ########
########### URL_GRABBER <-> BOOMBOX_PLUGIN HOOK <-> URL_GRABBER
########### URL_GRABBER <-> BOOMBOX_PLUGIN HOOK <-> URL_GRABBER
return
read_size = read_size + 2000
except Exception as e:
@ -100,6 +140,7 @@ class Plugin:
pass
#######################################################################################
#######################################################################################
@irc3.extend
def prefetch_title(self,msg,target,mask):
match_list = URL_REGEX.findall(msg)
@ -128,6 +169,6 @@ class Plugin:
except Exception as e:
print("%s" % e)
pass
#######################################################################################
#######################################################################################
####################################################################################### EOF#.[d].
###########################################################################################
####################################################################################### EOF

@ -1,13 +1,24 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
from irc3.plugins.command import command
import irc3
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@command(permission='view')
def whoami(self, mask, target, args):
"""whoami - plugin to give some identity information. usage: ?whoami
@ -15,6 +26,6 @@ class Plugin:
"""
msg = f'{mask.nick}: mask: {mask} channel: {target}'
self.bot.privmsg(target, self.bot.emo(msg))
#######################################################################################
###########################################################################################
####################################################################################### EOF
#.[d].

@ -1,38 +1,81 @@
# -*- coding: utf-8 -*- ############################################################### SOF
###########################################################################################
???YOUTUBE???
from irc3.plugins.command import command
import irc3
import os
import re
import datetime
import dateutil.parser
import timeago
import isodate
from apiclient.discovery import build
dir_path = os.path.dirname(os.path.realpath(__file__))
try:
if SERVICES_YOUTUBE:
YOUTUBE_DEVELOPER_KEY = os.environ['YOUTUBE_DEVELOPER_KEY']
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
YOUTUBE_REGEX = re.compile('http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?', re.IGNORECASE)
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=YOUTUBE_DEVELOPER_KEY)
except:
pass
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
####################
if SERVICES_YOUTUBE:
####################
from irc3.plugins.command import command
import irc3
import os
import re
import sys
import datetime
import dateutil.parser
import timeago
import isodate
from apiclient.discovery import build
from plugins.tool_log_plugin import FOG
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
self.bot.channel_live = []
dir_path = os.path.dirname(os.path.realpath(__file__))
#######################################################################################
#######################################################################################
@irc3.extend
def youtube_search(self, q=None, eventType=None, max_results=1, order="relevance", channelId=None, token=None, location=None, location_radius=None):
if SERVICES_YOUTUBE:
def getenv(s):
try:
s = os.environ[s]
return s
except:
fog=FOG().fog
error_type="environmental variable error"
error_reason=f"exported {s} not found"
fog(f"{error_type}: {error_reason}")
sys.exit(1)
#######################################################################################
#######################################################################################
YOUTUBE_DEVELOPER_KEY = getenv('YOUTUBE_DEVELOPER_KEY')
#######################################################################################
#######################################################################################
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=YOUTUBE_DEVELOPER_KEY)
#######################################################################################
#######################################################################################
YOUTUBE_REGEX = re.compile('http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?', re.IGNORECASE)
#######################################################################################
#######################################################################################
@irc3.plugin
class Plugin:
###################################################################################
###################################################################################
def __init__(self, bot):
self.bot = bot
self.bot.channel_live = []
###################################################################################
###################################################################################
@irc3.extend
def youtube_search(self, q=None, eventType=None, max_results=1, order="relevance", channelId=None, token=None, location=None, location_radius=None):
search_response = youtube.search().list(
q=q,
channelId=channelId,
@ -48,18 +91,20 @@ class Plugin:
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
return(search_result)
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg_search_for_youtube(self, mask=None, target=None, data=None, **kw):
if SERVICES_YOUTUBE:
#######################################################################################
#######################################################################################
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg_search_for_youtube(self, mask=None, target=None, data=None, **kw):
if data.startswith("?"): return
if self.bot.check_if_ignored(mask): return
self.__check_for_youtube(mask, data, target)
#######################################################################################
#######################################################################################
def __check_for_youtube(self, mask, msg, target):
if SERVICES_YOUTUBE:
#######################################################################################
#######################################################################################
def __check_for_youtube(self, mask, msg, target):
match_list = YOUTUBE_REGEX.findall(msg)
if match_list:
video_id = match_list.pop()
@ -81,7 +126,10 @@ class Plugin:
topics[:] = [i.replace("https://en.wikipedia.org/wiki/", "").replace("_"," ").title() for i in topics]
except:
topics = []
######## YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 1 of 2 ######## YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 1 of 2 ########
################### YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 1 of 2 <-> YOUTUBE
################### YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 1 of 2 <-> YOUTUBE
MUSIC_FOUND=False
for topic in topics:
if topic.lower().find('music'):
@ -89,7 +137,10 @@ class Plugin:
if MUSIC_FOUND:
url = "https://youtu.be/{}".format(video_id)
self.bot.bbs.enter(mask.nick,url,title)
######## YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 1 of 2 ######## YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 1 of 2 ########
################### YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 1 of 2 <-> YOUTUBE
################### YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 1 of 2 <-> YOUTUBE
duration = isodate.parse_duration(video_info.get("contentDetails").get("duration"))
msg = "\x02\x0302{nick:}\x0F\x02\x0304 >> \x02\x0303\x1D\x1F{title:}\x0F".format(nick=mask.nick, title=title)
msg = msg + "\x02\x1D\x0304 > \x0F\x1D\x0314Duration: \x0F\x1D{duration:} \x0F".format(duration=duration)
@ -101,33 +152,36 @@ class Plugin:
msg = msg +" \x0304> \x0F\x02\x0312"+ url
msg = self.bot.emo(msg)
self.bot.privmsg(target,msg)
#######################################################################################
#######################################################################################
@irc3.extend
def videos_list_by_id(self, id):
if SERVICES_YOUTUBE:
###################################################################################
###################################################################################
@irc3.extend
def videos_list_by_id(self, id):
search_response = youtube.videos().list(part="id,snippet,statistics,topicDetails,contentDetails", id=id).execute()
for search_result in search_response.get("items", []):
if search_result["kind"] == "youtube#video":
return(search_result)
#######################################################################################
#######################################################################################
@command(permission='view', public=True, show_in_help_list=False)
def y(self, *args, **kwargs):
"""Search for youtube video
%%y <keyword>...
"""
if SERVICES_YOUTUBE:
###################################################################################
###################################################################################
@command(permission='view', public=True, show_in_help_list=False)
def y(self, *args, **kwargs):
"""Search for youtube video
%%y <keyword>...
"""
return self.yt(*args)
#######################################################################################
#######################################################################################
@irc3.extend
@command(permission='view')
def yt(self, mask, target, args):
"""Search for youtube video
%%yt <keyword>...
"""
if SERVICES_YOUTUBE:
###################################################################################
###################################################################################
@irc3.extend
@command(permission='view')
def yt(self, mask, target, args):
"""Search for youtube video
%%yt <keyword>...
"""
keyword = ' '.join(args['<keyword>'])
video = self.youtube_search(q=keyword)
if video:
@ -150,7 +204,10 @@ class Plugin:
except:
topics = []
duration = isodate.parse_duration(video_info.get("contentDetails").get("duration"))
######## YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 2 of 2 ######## YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 2 of 2 ########
####################### YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 2 of 2 <-> YOUTUBE
####################### YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 2 of 2 <-> YOUTUBE
MUSIC_FOUND=False
for topic in topics:
if topic.lower().find('music'):
@ -158,7 +215,10 @@ class Plugin:
if MUSIC_FOUND:
url = "https://youtu.be/{}".format(video_id)
self.bot.bbs.enter(mask.nick,url,title)
######## YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 2 of 2 ######## YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 2 of 2 ########
####################### YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 2 of 2 <-> YOUTUBE
####################### YOUTUBE <-> BOOMBOX_PLUGIN HOOK: 2 of 2 <-> YOUTUBE
_nick = ""
try:
if len(self.bot.madjust) > 0:
@ -177,7 +237,6 @@ class Plugin:
msg = msg + url
msg = self.bot.emo(msg)
self.bot.privmsg(target, msg)
#######################################################################################
#######################################################################################
###########################################################################################
####################################################################################### EOF
#.[d].

@ -2,3 +2,4 @@ irc3
aiocron
timeago
ipdb
sqlite3

@ -8,3 +8,4 @@ lxml
aiocron
ipdb
pytz
sqlite3

@ -23,3 +23,5 @@ transformers==2.3.0
googletrans==2.4.0
textblob==0.15.3
matplotlib
sqlite3
sklearn