Update irc.py

This commit is contained in:
therealvorteckz 2023-10-12 10:25:19 -07:00
parent d60395c76f
commit 81a6d8e315
1 changed files with 327 additions and 331 deletions

658
irc.py
View File

@ -1,331 +1,327 @@
from config import config from config import config
import time import time
import ssl import ssl
import argparse import logging
import logging import logging.handlers
import logging.handlers import asyncio
import asyncio import time
import importlib import functions
import time import sqlite3
import sys
import functions # Formatting Control Characters / Color Codes
from functions import shop, buyweapon, buyammo, buybandages, shoot, reload, ammo, heal, revive, getmoney, getbandages, removeweapon, createuser, profile, removeuser, setlevel, createuser, punch, checkexist bold = '\x02'
import sqlite3 italic = '\x1D'
underline = '\x1F'
# Formatting Control Characters / Color Codes reverse = '\x16'
bold = '\x02' reset = '\x0f'
italic = '\x1D' white = '00'
underline = '\x1F' black = '01'
reverse = '\x16' blue = '02'
reset = '\x0f' green = '03'
white = '00' red = '04'
black = '01' brown = '05'
blue = '02' purple = '06'
green = '03' orange = '07'
red = '04' yellow = '08'
brown = '05' light_green = '09'
purple = '06' cyan = '10'
orange = '07' light_cyan = '11'
yellow = '08' light_blue = '12'
light_green = '09' pink = '13'
cyan = '10' grey = '14'
light_cyan = '11' light_grey = '15'
light_blue = '12'
pink = '13' conn = sqlite3.connect('data.db')
grey = '14' c = conn.cursor()
light_grey = '15'
def color(msg: str, foreground: str, background: str='') -> str:
conn = sqlite3.connect('data.db') '''
c = conn.cursor() Color a string with the specified foreground and background colors.
def color(msg: str, foreground: str, background: str='') -> str: :param msg: The string to color.
''' :param foreground: The foreground color to use.
Color a string with the specified foreground and background colors. :param background: The background color to use.
'''
:param msg: The string to color. return f'\x03{foreground},{background}{msg}{reset}' if background else f'\x03{foreground}{msg}{reset}'
:param foreground: The foreground color to use.
:param background: The background color to use.
''' def ssl_ctx() -> ssl.SSLContext:
return f'\x03{foreground},{background}{msg}{reset}' if background else f'\x03{foreground}{msg}{reset}' '''Create a SSL context for the connection.'''
ctx = ssl.create_default_context()
#ctx.verify_mode = ssl.CERT_NONE # Comment out this line to verify hosts
def ssl_ctx() -> ssl.SSLContext: #ctx.load_cert_chain('/path/to/cert', password='loldongs')
'''Create a SSL context for the connection.''' return ctx
ctx = ssl.create_default_context() class Bot(object):
#ctx.verify_mode = ssl.CERT_NONE # Comment out this line to verify hosts def __init__(self):
#ctx.load_cert_chain('/path/to/cert', password='loldongs') self.nickname = config.irc.nickname
return ctx self.username = config.irc.username
class Bot(object): self.realname = config.irc.realname
def __init__(self): self.channel = config.irc.channel
self.nickname = config.irc.nickname self.channelkey = config.irc.channelkey
self.username = config.irc.username self.reader = None
self.realname = config.irc.realname self.writer = None
self.channel = config.irc.channel
self.channelkey = config.irc.channelkey #createtable()
self.reader = None
self.writer = None async def action(self, chan: str, msg: str):
'''
#createtable() Send an ACTION to the IRC server.
async def action(self, chan: str, msg: str): :param chan: The channel to send the ACTION to.
''' :param msg: The message to send to the channel.
Send an ACTION to the IRC server. '''
await self.sendmsg(chan, f'\x01ACTION {msg}\x01')
:param chan: The channel to send the ACTION to.
:param msg: The message to send to the channel. async def raw(self, data: str):
''' '''
await self.sendmsg(chan, f'\x01ACTION {msg}\x01') Send raw data to the IRC server.
async def raw(self, data: str): :param data: The raw data to send to the IRC server. (512 bytes max including crlf)
''' '''
Send raw data to the IRC server. self.writer.write(data[:510].encode('utf-8') + b'\r\n')
:param data: The raw data to send to the IRC server. (512 bytes max including crlf) async def sendmsg(self, target: str, msg: str):
''' '''
self.writer.write(data[:510].encode('utf-8') + b'\r\n') Send a PRIVMSG to the IRC server.
async def sendmsg(self, target: str, msg: str): :param target: The target to send the PRIVMSG to. (channel or user)
''' :param msg: The message to send to the target.
Send a PRIVMSG to the IRC server. '''
try:
:param target: The target to send the PRIVMSG to. (channel or user) await self.raw(f'PRIVMSG {target} :{msg}')
:param msg: The message to send to the target.
''' time.sleep(config.throttle.msg)
try: except:
await self.raw(f'PRIVMSG {target} :{msg}') await bot.sendmsg(config.irc.channel, "Slow down homie!!")
time.sleep(config.throttle.msg) async def connect(self):
except: '''Connect to the IRC server.'''
await bot.sendmsg(config.irc.channel, "Slow down homie!!") while True:
try:
async def connect(self): options = {
'''Connect to the IRC server.''' 'host' : config.irc.server,
while True: 'port' : config.irc.port if config.irc.port else 6697 if config.irc.ssl else 6667,
try: 'limit' : 1024, # Buffer size in bytes (don't change this unless you know what you're doing)
options = { 'ssl' : ssl_ctx() if config.irc.ssl else None,
'host' : config.irc.server, 'family' : 2, # 10 = AF_INET6 (IPv6), 2 = AF_INET (IPv4)
'port' : config.irc.port if config.irc.port else 6697 if config.irc.ssl else 6667, 'local_addr' : None # Can we just leave this as args.vhost?
'limit' : 1024, # Buffer size in bytes (don't change this unless you know what you're doing) }
'ssl' : ssl_ctx() if config.irc.ssl else None, self.reader, self.writer = await asyncio.wait_for(asyncio.open_connection(**options), 15) # 15 second timeout
'family' : 2, # 10 = AF_INET6 (IPv6), 2 = AF_INET (IPv4) if config.irc.password:
'local_addr' : None # Can we just leave this as args.vhost? await self.raw('PASS ' + config.irc.password) # Rarely used, but IRCds may require this
} await self.raw(f'USER {self.username} 0 * :{self.realname}') # These lines must be sent upon connection
self.reader, self.writer = await asyncio.wait_for(asyncio.open_connection(**options), 15) # 15 second timeout await self.raw('NICK ' + self.nickname) # They are to identify the bot to the server
if config.irc.password: while not self.reader.at_eof():
await self.raw('PASS ' + config.irc.password) # Rarely used, but IRCds may require this data = await asyncio.wait_for(self.reader.readuntil(b'\r\n'), 300) # 5 minute ping timeout
await self.raw(f'USER {self.username} 0 * :{self.realname}') # These lines must be sent upon connection await self.handle(data.decode('utf-8').strip()) # Handle the data received from the IRC server
await self.raw('NICK ' + self.nickname) # They are to identify the bot to the server except Exception as ex:
while not self.reader.at_eof(): logging.error(f'failed to connect to {config.irc.server} ({str(ex)})')
data = await asyncio.wait_for(self.reader.readuntil(b'\r\n'), 300) # 5 minute ping timeout finally:
await self.handle(data.decode('utf-8').strip()) # Handle the data received from the IRC server await asyncio.sleep(30) # Wait 30 seconds before reconnecting
except Exception as ex:
logging.error(f'failed to connect to {config.irc.server} ({str(ex)})') async def handle(self, data: str):
finally: '''
await asyncio.sleep(30) # Wait 30 seconds before reconnecting Handle the data received from the IRC server.
async def handle(self, data: str): :param data: The data received from the IRC server.
''' '''
Handle the data received from the IRC server. try:
logging.info(data)
:param data: The data received from the IRC server. args = data.split()
''' if data.startswith('ERROR :Closing Link:'):
try: raise Exception('Cannot Connect')
logging.info(data) if args[0] == 'PING':
args = data.split() await self.raw('PONG ' + args[1]) # Respond to the server's PING request with a PONG to prevent ping timeout
if data.startswith('ERROR :Closing Link:'): elif args[1] == '001': # RPL_WELCOME
raise Exception('Cannot Connect') await self.raw(f'MODE {self.nickname} +B') # Set user mode +B (Bot)
if args[0] == 'PING': await asyncio.sleep(10) # Wait 10 seconds before joining the channel (required by some IRCds to wait before JOIN)
await self.raw('PONG ' + args[1]) # Respond to the server's PING request with a PONG to prevent ping timeout await self.raw(f'JOIN {self.channel} {self.channelkey}')
elif args[1] == '001': # RPL_WELCOME elif args[1] == '433': # ERR_NICKNAMEINUSE
await self.raw(f'MODE {self.nickname} +B') # Set user mode +B (Bot) self.nickname += '_' # If the nickname is already in use, append an underscore to the end of it
await asyncio.sleep(10) # Wait 10 seconds before joining the channel (required by some IRCds to wait before JOIN) await self.raw('NICK ' + self.nickname) # Send the new nickname to the server
await self.raw(f'JOIN {self.channel} {self.channelkey}') elif args[1] == 'KICK':
elif args[1] == '433': # ERR_NICKNAMEINUSE chan = args[2]
self.nickname += '_' # If the nickname is already in use, append an underscore to the end of it kicked = args[3]
await self.raw('NICK ' + self.nickname) # Send the new nickname to the server if kicked == self.nickname:
elif args[1] == 'KICK': await asyncio.sleep(3)
chan = args[2] await self.raw(f'JOIN {chan}')
kicked = args[3] elif args[1] == 'PRIVMSG':
if kicked == self.nickname: ident = args[0][1:]
await asyncio.sleep(3) nick = args[0].split('!')[0][1:].lower()
await self.raw(f'JOIN {chan}') target = args[2]
elif args[1] == 'PRIVMSG': msg = ' '.join(args[3:])[1:]
ident = args[0][1:] arguments = msg.split()
nick = args[0].split('!')[0][1:].lower() bandageamount = '0'
target = args[2] if target == self.nickname:
msg = ' '.join(args[3:])[1:] pass # Handle private messages here
arguments = msg.split() if target.startswith('#'): # Channel message
bandageamount = '0' if msg.startswith('!'):
if target == self.nickname: try:
pass # Handle private messages here if time.time() - config.throttle.last < config.throttle.cmd and config.throttle.lastnick == nick:
if target.startswith('#'): # Channel message if not config.throttle.slow:
if msg.startswith('!'): config.throttle.slow = True
try: await bot.sendmsg(config.irc.channel, color("Slow down homie!!", red))
if time.time() - config.throttle.last < config.throttle.cmd and config.throttle.lastnick == nick:
if not config.throttle.slow: else:
config.throttle.slow = True config.throttle.slow = False
await bot.sendmsg(config.irc.channel, color("Slow down homie!!", red)) config.throttle.lastnick = nick
else: if arguments[0] == '!hug':
config.throttle.slow = False await bot.sendmsg(target, f'[XOXO Hugger9000... {nick} hugs {arguments[1]}]')
config.throttle.lastnick = nick if arguments[0] == '!admins':
for i in config.irc.admins:
if arguments[0] == '!hug': await bot.sendmsg(target, f'[Admins: ' + color(i, red) + ']')
await bot.sendmsg(target, f'[XOXO Hugger9000... {nick} hugs {arguments[1]}]') if arguments[0] == '!shop':
if arguments[0] == '!admins': await bot.sendmsg(config.irc.channel, f'[Shop Accessories]')
for i in config.irc.admins: await bot.sendmsg(config.irc.channel, f'[!buy weapon - purchase a 3-round burst gun (note: weapon has a quality of 300 trigger limit)]')
await bot.sendmsg(target, f'[Admins: ' + color(i, red) + ']') await bot.sendmsg(config.irc.channel, f'[!buy ammo - buy ammunition (+60 rounds) for your weapon]')
if arguments[0] == '!shop': await bot.sendmsg(config.irc.channel, f'[!buy bandages <amount>]')
await bot.sendmsg(config.irc.channel, f'[Shop Accessories]') if arguments[0] == '!buy' and arguments[1] != None:
await bot.sendmsg(config.irc.channel, f'[!buy weapon - purchase a 3-round burst gun (note: weapon has a quality of 300 trigger limit)]') if arguments[1] == 'weapon':
await bot.sendmsg(config.irc.channel, f'[!buy ammo - buy ammunition (+60 rounds) for your weapon]') value = await functions.buyweapon(nick)
await bot.sendmsg(config.irc.channel, f'[!buy bandages <amount>]') await bot.sendmsg(config.irc.channel, f'{value}')
if arguments[0] == '!buy' and arguments[1] != None:
if arguments[1] == 'weapon': elif arguments[1] == 'ammo':
value = await functions.buyweapon(nick) value = await functions.buyammo(nick)
await bot.sendmsg(config.irc.channel, f'{value}') await bot.sendmsg(config.irc.channel, f'{value}')
elif arguments[1] == 'bandages':
elif arguments[1] == 'ammo': if len(arguments) <= 2 or int(arguments[2]) == 0:
value = await functions.buyammo(nick) await bot.sendmsg(config.irc.channel, '[You must specify amount of bandages (greater than 0) to purchase]')
await bot.sendmsg(config.irc.channel, f'{value}') else:
elif arguments[1] == 'bandages': value = await functions.buybandages(nick, int(arguments[2]))
if len(arguments) <= 2 or int(arguments[2]) == 0: await bot.sendmsg(config.irc.channel, f'{value}')
await bot.sendmsg(config.irc.channel, '[You must specify amount of bandages (greater than 0) to purchase]') if arguments[0] == '!test':
else: value = await functions.testfunction(nick)
value = await buybandages(nick, int(arguments[2])) await bot.sendmsg(config.irc.channel, f'{value}')
await bot.sendmsg(config.irc.channel, f'{value}')
if arguments[0] == '!test': if arguments[0] == '!shoot':
value = await functions.testfunction(nick) await functions.shoot(arguments[1].lower(), nick)
await bot.sendmsg(config.irc.channel, f'{value}') #await bot.sendmsg(config.irc.channel, f'{value}')
if arguments[0] == '!reload':
if arguments[0] == '!shoot': value = await functions.reload(nick)
await functions.shoot(arguments[1].lower(), nick) if value != None:
#await bot.sendmsg(config.irc.channel, f'{value}') await bot.sendmsg(config.irc.channel, f'{value}')
if arguments[0] == '!reload': if arguments[0] == '!ammo':
value = await functions.reload(nick) ammovalue = await functions.ammo(nick)
if value != None: await bot.sendmsg(config.irc.channel, f'{ammovalue}')
await bot.sendmsg(config.irc.channel, f'{value}') if arguments[0] == '!heal':
if arguments[0] == '!ammo': value = await functions.heal(nick)
ammovalue = await ammo(nick) await bot.sendmsg(config.irc.channel, f'{value}')
await bot.sendmsg(config.irc.channel, f'{ammovalue}') if arguments[0] == '!revive':
if arguments[0] == '!heal': value = await functions.revive(nick)
value = await functions.heal(nick) await bot.sendmsg(config.irc.channel, f'{value}')
await bot.sendmsg(config.irc.channel, f'{value}') if arguments[0] == '!help':
if arguments[0] == '!revive': await bot.sendmsg(config.irc.channel, '[Command List]')
value = await functions.revive(nick) await bot.sendmsg(config.irc.channel, '[!help - shows commands]')
await bot.sendmsg(config.irc.channel, f'{value}') await bot.sendmsg(config.irc.channel, '[!register - Register your player]')
if arguments[0] == '!help': await bot.sendmsg(config.irc.channel, '[!profile - Shows Profile Stats [!profile username]')
await bot.sendmsg(config.irc.channel, '[Command List]') await bot.sendmsg(config.irc.channel, '[!punch <enemy> - Fight [!punch username]')
await bot.sendmsg(config.irc.channel, '[!help - shows commands]') await bot.sendmsg(config.irc.channel, '[!shoot <enemy> - Shoot if you own a weapon]')
await bot.sendmsg(config.irc.channel, '[!register - Register your player]') await bot.sendmsg(config.irc.channel, '[!bank - Returns Bank Balance]')
await bot.sendmsg(config.irc.channel, '[!profile - Shows Profile Stats [!profile username]') await bot.sendmsg(config.irc.channel, '[!buy <item> [weapon, ammo, bandages <amount>]')
await bot.sendmsg(config.irc.channel, '[!punch <enemy> - Fight [!punch username]') await bot.sendmsg(config.irc.channel, '[!reload - Reloads Weapon]')
await bot.sendmsg(config.irc.channel, '[!shoot <enemy> - Shoot if you own a weapon]') await bot.sendmsg(config.irc.channel, '[!ammo - Show Ammunition Amounts]')
await bot.sendmsg(config.irc.channel, '[!bank - Returns Bank Balance]') await bot.sendmsg(config.irc.channel, '[!bandages - Shows Bandage Amounts]')
await bot.sendmsg(config.irc.channel, '[!buy <item> [weapon, ammo, bandages <amount>]') await bot.sendmsg(config.irc.channel, '[!revive - Brings you back to health if dead]')
await bot.sendmsg(config.irc.channel, '[!reload - Reloads Weapon]') await bot.sendmsg(config.irc.channel, '[!heal - Use bandages to regain health]')
await bot.sendmsg(config.irc.channel, '[!ammo - Show Ammunition Amounts]') await bot.sendmsg(config.irc.channel, ' ')
await bot.sendmsg(config.irc.channel, '[!bandages - Shows Bandage Amounts]') await bot.sendmsg(config.irc.channel, '[Admin Command List]')
await bot.sendmsg(config.irc.channel, '[!revive - Brings you back to health if dead]') await bot.sendmsg(config.irc.channel, '[!setlevel - !setlevel username Level (1 to 5)]')
await bot.sendmsg(config.irc.channel, '[!heal - Use bandages to regain health]') await bot.sendmsg(config.irc.channel, '[!adduser <user> - Force create a user]')
await bot.sendmsg(config.irc.channel, ' ') await bot.sendmsg(config.irc.channel, '[!remove <user> - Removes a player]')
await bot.sendmsg(config.irc.channel, '[Admin Command List]') await bot.sendmsg(config.irc.channel, '[!removeweapon <user> - Remove user weapon]')
await bot.sendmsg(config.irc.channel, '[!setlevel - !setlevel username Level (1 to 5)]') if arguments[0] == '!bank':
await bot.sendmsg(config.irc.channel, '[!adduser <user> - Force create a user]') value = await functions.getmoney(nick)
await bot.sendmsg(config.irc.channel, '[!remove <user> - Removes a player]') await bot.sendmsg(config.irc.channel, f'{value}')
await bot.sendmsg(config.irc.channel, '[!removeweapon <user> - Remove user weapon]') if arguments[0] == '!bandages':
if arguments[0] == '!bank': value = await functions.getbandages(nick)
value = await functions.getmoney(nick) await bot.sendmsg(config.irc.channel, f'{value}')
await bot.sendmsg(config.irc.channel, f'{value}') if nick in config.irc.admins:
if arguments[0] == '!bandages': #await self.sendmsg(target, f'{nick} is an ' + color('Admin!', red))
value = await functions.getbandages(nick) if arguments[0] == '!removeweapon':
await bot.sendmsg(config.irc.channel, f'{value}') value = await functions.removeweapon(nick)
if nick in config.irc.admins: await bot.sendmsg(config.irc.channel, f'{value}')
#await self.sendmsg(target, f'{nick} is an ' + color('Admin!', red)) if arguments[0] == '!adduser':
if arguments[0] == '!removeweapon': name = arguments[1].lower()
value = await functions.removeweapon(nick)
await bot.sendmsg(config.irc.channel, f'{value}') c.execute(f"SELECT rowid FROM users WHERE name = (:name)", {'name': name})
if arguments[0] == '!adduser':
name = arguments[1].lower() data=c.fetchone()
if data is None:
c.execute(f"SELECT rowid FROM users WHERE name = (:name)", {'name': name}) await bot.sendmsg(config.irc.channel, '[Registering Player: %s]'%name)
await functions.createuser(name)
data=c.fetchone() await functions.profile(name)
if data is None: else:
await bot.sendmsg(config.irc.channel, '[Registering Player: %s]'%name) await bot.sendmsg(config.irc.channel, f'{color("[Player already exists!]", red)}')
await createuser(name)
await profile(name) if arguments[0] == '!remove':
else: logging.debug('remove user')
await bot.sendmsg(config.irc.channel, f'{color("[Player already exists!]", red)}') name = arguments[1].lower()
c.execute(f"SELECT rowid FROM users WHERE name= (:name)", {'name': name})
if arguments[0] == '!remove':
logging.debug('remove user') data=c.fetchone()
name = arguments[1].lower() if data != None:
c.execute(f"SELECT rowid FROM users WHERE name= (:name)", {'name': name}) await bot.sendmsg(config.irc.channel, f'[Removing {color(name, red)} from database]')
await functions.removeuser(name)
data=c.fetchone() else:
if data != None: await bot.sendmsg(config.irc.channel, f'[User does not exist]')
await bot.sendmsg(config.irc.channel, f'[Removing {color(name, red)} from database]')
await functions.removeuser(name) if arguments[0] == '!setlevel':
else: value = await functions.setlevel(arguments[1].lower(), arguments[2])
await bot.sendmsg(config.irc.channel, f'[User does not exist]') await bot.sendmsg(config.irc.channel, f'{value}')
if arguments[0] == '!register':
if arguments[0] == '!setlevel': c.execute(f"SELECT rowid FROM users WHERE name = (:name)", {'name': nick})
value = await functions.setlevel(arguments[1].lower(), arguments[2])
await bot.sendmsg(config.irc.channel, f'{value}') data=c.fetchone()
if arguments[0] == '!register': if data is None:
c.execute(f"SELECT rowid FROM users WHERE name = (:name)", {'name': nick}) await bot.sendmsg(config.irc.channel, f'[Registering Player: %s]'%nick)
await functions.createuser(nick)
data=c.fetchone() await functions.profile(nick)
if data is None: else:
await bot.sendmsg(config.irc.channel, f'[Registering Player: %s]'%nick) await bot.sendmsg(config.irc.channel, f'{color("[Player already exists!]", red)}')
await createuser(nick) if arguments[0] == '!profile':
await profile(nick) try:
else: value = await functions.profile(arguments[1].lower())
await bot.sendmsg(config.irc.channel, f'{color("[Player already exists!]", red)}') await bot.sendmsg(config.irc.channel, f'{value}')
if arguments[0] == '!profile': except:
try: value = await functions.profile(nick)
value = await profile(arguments[1].lower()) await bot.sendmsg(config.irc.channel, f'{value}')
await bot.sendmsg(config.irc.channel, f'{value}') if arguments[0] == '!punch':
except: await functions.punch(arguments[1].lower(), nick)
value = await profile(nick) config.throttle.last = time.time()
await bot.sendmsg(config.irc.channel, f'{value}') except Exception as ex:
if arguments[0] == '!punch': if time.time() - config.throttle.last < config.throttle.cmd:
await functions.punch(arguments[1].lower(), nick) if not config.throttle.slow:
config.throttle.last = time.time() await bot.sendmsg(config.irc.channel, color('Slow down homie!', red))
except Exception as ex: config.throttle.slow = True
if time.time() - config.throttle.last < config.throttle.cmd: config.throttle.last = time.time()
if not config.throttle.slow:
await bot.sendmsg(config.irc.channel, color('Slow down homie!', red))
config.throttle.slow = True #except (UnicodeDecodeError, UnicodeEncodeError):
config.throttle.last = time.time() except (UnicodeDecodeError, UnicodeEncodeError):
pass # Some IRCds allow invalid UTF-8 characters, this is a very important exception to catch
except Exception as ex:
#except (UnicodeDecodeError, UnicodeEncodeError): logging.exception(f'Unknown error has occured! ({ex})')
except (UnicodeDecodeError, UnicodeEncodeError):
pass # Some IRCds allow invalid UTF-8 characters, this is a very important exception to catch
except Exception as ex: def setup_logger(log_filename: str, to_file: bool = False):
logging.exception(f'Unknown error has occured! ({ex})') '''
Set up logging to console & optionally to file.
def setup_logger(log_filename: str, to_file: bool = False): :param log_filename: The filename of the log file
''' '''
Set up logging to console & optionally to file. sh = logging.StreamHandler()
sh.setFormatter(logging.Formatter('%(asctime)s | %(levelname)9s | %(message)s', '%I:%M %p'))
:param log_filename: The filename of the log file if to_file:
''' fh = logging.handlers.RotatingFileHandler(log_filename+'.log', maxBytes=250000, backupCount=3, encoding='utf-8') # Max size of 250KB, 3 backups
sh = logging.StreamHandler() fh.setFormatter(logging.Formatter('%(asctime)s | %(levelname)9s | %(filename)s.%(funcName)s.%(lineno)d | %(message)s', '%Y-%m-%d %I:%M %p')) # We can be more verbose in the log file
sh.setFormatter(logging.Formatter('%(asctime)s | %(levelname)9s | %(message)s', '%I:%M %p')) logging.basicConfig(level=logging.NOTSET, handlers=(sh,fh))
if to_file: else:
fh = logging.handlers.RotatingFileHandler(log_filename+'.log', maxBytes=250000, backupCount=3, encoding='utf-8') # Max size of 250KB, 3 backups logging.basicConfig(level=logging.NOTSET, handlers=(sh,))
fh.setFormatter(logging.Formatter('%(asctime)s | %(levelname)9s | %(filename)s.%(funcName)s.%(lineno)d | %(message)s', '%Y-%m-%d %I:%M %p')) # We can be more verbose in the log file
logging.basicConfig(level=logging.NOTSET, handlers=(sh,fh))
else: bot = Bot()
logging.basicConfig(level=logging.NOTSET, handlers=(sh,)) def run():
functions.createtable()
setup_logger('skeleton', to_file=True) # Optionally, you can log to a file, change to_file to False to disable this.
bot = Bot() asyncio.run(bot.connect())
def run():
functions.createtable()
setup_logger('skeleton', to_file=True) # Optionally, you can log to a file, change to_file to False to disable this.
asyncio.run(bot.connect())