Replaced multiple instances of double quotes with single quotes.

This commit is contained in:
ComputerTech312 2024-02-20 09:32:48 +01:00
parent a683fcffea
commit c0f8606715
7 changed files with 73 additions and 57 deletions

3
.gitignore vendored
View file

@ -1,4 +1,5 @@
__pycache__ __pycache__
data data
logs logs
test.json test.json
elitebot

View file

@ -1,4 +1,5 @@
{ {
"VERSION": "1.0.0",
"Connection": { "Connection": {
"Hostname": "irc.example.net", "Hostname": "irc.example.net",
"Port": "+6697", "Port": "+6697",
@ -18,4 +19,4 @@
"Database": { "Database": {
"ConnectionString": "mysql://user:password@host:port/database" "ConnectionString": "mysql://user:password@host:port/database"
} }
} }

View file

@ -1,14 +1,15 @@
VERSION: 1.0.0
Connection: Connection:
Hostname: irc.rizon.net Hostname: irc.rizon.net
Port: "+6697" Port: '+6697'
Nick: EliteBot Nick: EliteBot
Ident: EliteBot Ident: EliteBot
Name: EliteBot Name: EliteBot
BindHost: 0.0.0.0 BindHost: 0.0.0.0
SASL: SASL:
UseSASL: true UseSASL: false
SASLNick: EliteBot SASLNick: EliteBot
SASLPassword: 789abc// SASLPassword: password
Logging: Logging:
Console: true Console: true
Database: Database:

View file

@ -1,3 +1,7 @@
import random
import time
from datetime import datetime
from sqlalchemy import Table, Column, Integer, String, MetaData, insert, select from sqlalchemy import Table, Column, Integer, String, MetaData, insert, select
from src.channel_manager import ChannelManager from src.channel_manager import ChannelManager
@ -23,27 +27,44 @@ class Plugin(PluginBase):
self.channel_manager = ChannelManager() self.channel_manager = ChannelManager()
if parts[0].lower() == '!cookie': if parts[0].lower() == '!cookie':
if len(parts) == 1: # !cookie if len(parts) == 1:
self.insert_user(source_nick) self.insert_user(source_nick)
self.bot.ircsend(f'PRIVMSG {channel} :Nooooo~~')
c_db.set(source_nick, {'cookies': 1, 'last': '1999/01/01 00:00:01'}) cookies = c_db.get(source_nick, 2)
elif len(parts) == 2: # !cookie USER rnd = random.randint(1, 10)
last = datetime.strptime(c_db.get(source_nick, 3), '%Y/%m/%d %H:%M:%S')
current = datetime.strptime(datetime.now().strftime('%Y/%m/%d %H:%M:%S'), '%Y/%m/%d %H:%M:%S')
diff = round((current - last).total_seconds() / 60.0)
if diff >= 30:
c1 = 'no cookies' if rnd == 0 \
else f'{rnd} cookie' if rnd == 1 \
else f'{rnd} cookies'
c2 = 'no cookies' if (cookies + rnd) == 0 \
else f'{(cookies + rnd)} cookie' if (cookies + rnd) == 1 \
else f'{(cookies + rnd)} cookies'
self.bot.ircsend(f'PRIVMSG {channel} :\x01ACTION gives {c1} to {source_nick}.\x01')
self.bot.ircsend(f'PRIVMSG {channel} :You now have a total of {c2}.')
c_db.set(source_nick, {
'cookies': (cookies + rnd),
'last': current.strftime('%Y/%m/%d %H:%M:%S')
})
else:
rem = self.remaining_time(last.strftime('%Y/%m/%d %H:%M:%S'), 30 * 60000)
self.bot.ircsend(f'PRIVMSG {channel} :Remaining time: {rem}')
elif len(parts) == 2:
cookies = c_db.get(parts[1], 2) cookies = c_db.get(parts[1], 2)
if cookies == -1: if cookies == -1:
self.bot.ircsend(f'PRIVMSG {channel} :I\'ve looked everywhere for {parts[1]}, but I couldn\'t ' self.bot.ircsend(f'PRIVMSG {channel} :I\'ve looked everywhere for {parts[1]}, but I couldn\'t '
f'find them.') f'find them.')
else: else:
c = 'cookie' c = 'no cookies' if cookies == 0 \
if cookies == 0: else f'{cookies} cookie' if cookies == 1 \
c = 'no cookies.' else f'{cookies} cookies'
elif cookies == 1: self.bot.ircsend(f'PRIVMSG {channel} :{parts[1]} currently has {c}.')
c = f'{cookies} cookie.'
else:
c = f'{cookies} cookies.'
self.bot.ircsend(f'PRIVMSG {channel} :{parts[1]} currently has {c}')
def insert_user(self, user: str): def insert_user(self, user: str):
with c_db.engine.connect() as conn: with c_db.engine.connect() as conn:
@ -56,3 +77,24 @@ class Plugin(PluginBase):
values({'name': user}) values({'name': user})
)) ))
conn.commit() conn.commit()
def remaining_time(self, date: str, timeout: int):
diff = (int(time.mktime(
datetime.strptime(datetime.now().strftime('%Y/%m/%d %H:%M:%S'), '%Y/%m/%d %H:%M:%S').timetuple()) * 1000) -
int(time.mktime(datetime.strptime(date, '%Y/%m/%d %H:%M:%S').timetuple()) * 1000))
h = int((timeout - diff) / (60 * 60 * 1000) % 24)
m = int((timeout - diff) / (60 * 1000) % 60)
s = int((timeout - diff) / 1000 % 60)
hms = ''
if h == 0 and m == 0 and s == 0:
return 0
if h != 0:
hms += f'{h}h '
if m != 0:
hms += f'{m}m '
if s != 0:
hms += f'{s}s '
return f'{hms[:-1]}.'

View file

@ -1,25 +0,0 @@
from src.plugin_base import PluginBase
class WhoisPlugin(PluginBase):
def __init__(self, bot):
super().__init__(bot)
self.pending_whois = {}
def handle_message(self, source_nick, channel, message):
message_parts = message.split()
if message_parts[0] == '@whois':
self.bot.ircsend(f'WHOIS {source_nick}')
self.pending_whois[source_nick] = channel
print(f"Sent WHOIS for {source_nick}")
elif ' | ' in message:
parts = message.split(' | ')
command = parts[2].split(': ')[1]
if command == '311':
args = parts[3].split(': ')[1].strip('[]').split(', ')
nick = args[1].strip('\'')
hostmask = args[3].strip('\'')
if nick in self.pending_whois:
channel = self.pending_whois[nick]
self.bot.ircsend(f'PRIVMSG {channel} :pew')
print(f"Sent 'pew' to {channel}")
del self.pending_whois[nick]

View file

@ -8,7 +8,6 @@ import socket
import ssl import ssl
import sys import sys
import time import time
import yaml import yaml
from src.channel_manager import ChannelManager from src.channel_manager import ChannelManager
@ -32,18 +31,17 @@ class Bot:
def validate_config(self, config): def validate_config(self, config):
required_fields = [ required_fields = [
["Connection", "Port"], ['Connection', 'Port'],
["Connection", "Hostname"], ['Connection' 'Hostname'],
["Connection", "Nick"], ['Connection', 'Nick'],
["Connection", "Ident"], ['Connection', 'Ident'],
["Connection", "Name"], ['Connection', 'Name'],
# ["SASL", "UseSASL"], ['Database', 'ConnectionString']
["Database", "ConnectionString"]
] ]
for field in required_fields: for field in required_fields:
if not self.get_nested_config_value(config, field): if not self.get_nested_config_value(config, field):
raise ValueError(f'Missing required config field: {" -> ".join(field)}') raise ValueError(f'Missing required config field: {' -> '.join(field)}')
def get_nested_config_value(self, config, keys): def get_nested_config_value(self, config, keys):
value = config value = config
@ -92,7 +90,7 @@ class Bot:
except UnicodeDecodeError: except UnicodeDecodeError:
continue continue
self.logger.error('Could not decode byte string with any known encoding') self.logger.error('Could not decode byte string with any known encoding')
return bytes.decode('utf-8', 'ignore') # Ignore errors and return as much as possible return bytes.decode('utf-8', 'ignore')
def ircsend(self, msg): def ircsend(self, msg):
try: try:
@ -143,7 +141,7 @@ class Bot:
if self.config['SASL'].get('UseSASL'): if self.config['SASL'].get('UseSASL'):
self.ircsend('CAP REQ :sasl') self.ircsend('CAP REQ :sasl')
except Exception as e: except Exception as e:
self.logger.error(f"Error establishing connection: {e}") self.logger.error(f'Error establishing connection: {e}')
self.connected = False self.connected = False
return return
@ -168,13 +166,11 @@ class Bot:
source, command, args = self.parse_message(ircmsg) source, command, args = self.parse_message(ircmsg)
self.logger.debug(f'Received: source: {source} | command: {command} | args: {args}') self.logger.debug(f'Received: source: {source} | command: {command} | args: {args}')
# Handle PING requests immediately
if command == 'PING': if command == 'PING':
nospoof = args[0][1:] if args[0].startswith(':') else args[0] nospoof = args[0][1:] if args[0].startswith(':') else args[0]
self.ircsend(f'PONG :{nospoof}') self.ircsend(f'PONG :{nospoof}')
continue continue
# Process other messages
if command == 'PRIVMSG': if command == 'PRIVMSG':
channel, message = args[0], args[1] channel, message = args[0], args[1]
source_nick = source.split('!')[0] source_nick = source.split('!')[0]

View file

@ -25,7 +25,7 @@ class Logger:
case 'error': case 'error':
print(f'\033[91m[{asctime}] - {message}\033[39m') print(f'\033[91m[{asctime}] - {message}\033[39m')
case _: case _:
pass # just ignore it. pass
def debug(self, message): def debug(self, message):
self.log('debug', message) self.log('debug', message)